momentic-mobile 0.0.26 → 0.0.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var cC=Object.defineProperty;var ke=(r,e)=>()=>(r&&(e=r(r=0)),e);var uC=(r,e)=>{for(var t in e)cC(r,t,{get:e[t],enumerable:!0})};var aE,sE=ke(()=>{"use strict";aE=typeof globalThis=="object"?globalThis:global});var lE=ke(()=>{"use strict";sE()});var cE=ke(()=>{"use strict";lE()});var Hr,pp=ke(()=>{"use strict";Hr="1.9.0"});function XL(r){var e=new Set([r]),t=new Set,n=r.match(uE);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(s){return t.add(s),!1}function a(s){return e.add(s),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var l=c.match(uE);if(!l)return i(c);var u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[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 uE,dE,pE=ke(()=>{"use strict";pp();uE=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;dE=XL(Hr)});function qo(r,e,t,n){var o;n===void 0&&(n=!1);var i=da[ua]=(o=da[ua])!==null&&o!==void 0?o:{version:Hr};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!==Hr){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Hr);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Hr+"."),!0}function Gr(r){var e,t,n=(e=da[ua])===null||e===void 0?void 0:e.version;if(!(!n||!dE(n)))return(t=da[ua])===null||t===void 0?void 0:t[r]}function Ko(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Hr+".");var t=da[ua];t&&delete t[r]}var JL,ua,da,pa=ke(()=>{"use strict";cE();pp();pE();JL=Hr.split(".")[0],ua=Symbol.for("opentelemetry.js.api."+JL),da=aE});function ma(r,e,t){var n=Gr("diag");if(n)return t.unshift(e),n[r].apply(n,QL([],ZL(t),!1))}var ZL,QL,mE,gE=ke(()=>{"use strict";pa();ZL=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},QL=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},mE=function(){function r(e){this._namespace=e.namespace||"DiagComponentLogger"}return r.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ma("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ma("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ma("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ma("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ma("verbose",this._namespace,e)},r}()});var Pe,wl=ke(()=>{"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"})(Pe||(Pe={}))});function hE(r,e){r<Pe.NONE?r=Pe.NONE:r>Pe.ALL&&(r=Pe.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",Pe.ERROR),warn:t("warn",Pe.WARN),info:t("info",Pe.INFO),debug:t("debug",Pe.DEBUG),verbose:t("verbose",Pe.VERBOSE)}}var fE=ke(()=>{"use strict";wl()});var eN,tN,rN,xr,ga=ke(()=>{"use strict";gE();fE();wl();pa();eN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},tN=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))},rN="diag",xr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=Gr("diag");if(s)return s[o].apply(s,tN([],eN(i),!1))}}var t=this,n=function(o,i){var a,s,c;if(i===void 0&&(i={logLevel:Pe.INFO}),o===t){var l=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=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof i=="number"&&(i={logLevel:i});var u=Gr("diag"),d=hE((s=i.logLevel)!==null&&s!==void 0?s:Pe.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 qo("diag",d,t,!0)};t.setLogger=n,t.disable=function(){Ko(rN,t)},t.createComponentLogger=function(o){return new mE(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 SE,yE=ke(()=>{"use strict";SE=Symbol("BaggageEntryMetadata")});function mp(r){return typeof r!="string"&&(nN.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:SE,toString:function(){return r}}}var nN,bE=ke(()=>{"use strict";ga();yE();nN=xr.instance()});function gp(r){return Symbol.for(r)}var oN,hp,fp=ke(()=>{"use strict";oN=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}(),hp=new oN});function bp(){return yp}var Jn,iN,Rl,aN,sN,lN,cN,Sp,uN,dN,pN,yp,mN,gN,hN,fN,SN,yN,bN,Ep=ke(()=>{"use strict";Jn=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),iN=function(){function r(){}return r.prototype.createGauge=function(e,t){return gN},r.prototype.createHistogram=function(e,t){return hN},r.prototype.createCounter=function(e,t){return mN},r.prototype.createUpDownCounter=function(e,t){return fN},r.prototype.createObservableGauge=function(e,t){return yN},r.prototype.createObservableCounter=function(e,t){return SN},r.prototype.createObservableUpDownCounter=function(e,t){return bN},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),Rl=function(){function r(){}return r}(),aN=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Rl),sN=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Rl),lN=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Rl),cN=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Rl),Sp=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),uN=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Sp),dN=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Sp),pN=function(r){Jn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Sp),yp=new iN,mN=new aN,gN=new lN,hN=new cN,fN=new sN,SN=new uN,yN=new dN,bN=new pN});var Nt,EE=ke(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(Nt||(Nt={}))});var EN,TN,TE,vE=ke(()=>{"use strict";fp();EN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},TN=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))},TE=function(){function r(){}return r.prototype.active=function(){return hp},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,TN([n],EN(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var vN,AN,Tp,wN,AE,wE=ke(()=>{"use strict";vE();pa();ga();vN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},AN=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))},Tp="context",wN=new TE,AE=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return qo(Tp,e,xr.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,AN([e,t,n],vN(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Gr(Tp)||wN},r.prototype.disable=function(){this._getContextManager().disable(),Ko(Tp,xr.instance())},r}()});var Yo,RE=ke(()=>{"use strict";wE();Yo=AE.getInstance()});var j,CE=ke(()=>{"use strict";ga();j=xr.instance()});var RN,xE,_E=ke(()=>{"use strict";Ep();RN=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return yp},r}(),xE=new RN});var vp,ME,PE=ke(()=>{"use strict";_E();pa();ga();vp="metrics",ME=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return qo(vp,e,xr.instance())},r.prototype.getMeterProvider=function(){return Gr(vp)||xE},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){Ko(vp,xr.instance())},r}()});var Cl,IE=ke(()=>{"use strict";PE();Cl=ME.getInstance()});var ve=ke(()=>{"use strict";bE();fp();wl();Ep();EE();RE();CE();IE()});import{Argument as Lg,Command as xz,Option as _z}from"@commander-js/extra-typings";import hC from"appium";import{tmpdir as fC}from"os";import{remote as SC}from"webdriverio";import{createInstanceClient as dC}from"@limrun/api";import{execSync as pC}from"child_process";import{hostname as mC}from"os";import gC from"path";async function Ng(r){let{apiClient:e,logger:t,creationOpts:n,onStatusUpdate:o,logLevel:i}=r,{token:a,webRtcUrl:s,adbUrl:c,name:l,apkDownloadUrl:u,region:d}=await e.createAndroidEmulator({...n,hostname:mC()}),p;try{pC("adb --version"),p="adb"}catch{if(process.env.ANDROID_HOME)p=gC.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:l,apkToInstall:n.apkToInstall,region:d,apkDownloadUrl:u},"Android instance creation ok");let g=await dC({adbUrl:c,endpointUrl:s,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(S=>g.sendAsset(S))),o("Starting tunnel");let E=await g.startAdbTunnel();return{port:E.address.port,close:E.close,token:a,webRtcUrl:s,emulatorName:l}}async function os({onStatusUpdate:r,creationOpts:e,apiClient:t,logger:n,driverLogLevel:o,appiumPort:i,socket:a}){let s=Date.now(),{close:c,port:l,limbarToken:u,limbarUrl:d,emulatorName:p}=await EC({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 yC({logger:n,driverLogLevel:o,appiumPort:i,port:l,limbarStart:s,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:l,cleanup:m,appiumPort:i}}catch(f){throw await m(),new Error(`Failed to start Appium driver: ${f}`)}}async function yC({logger:r,driverLogLevel:e="warn",port:t,limbarStart:n,emulatorName:o,appiumPort:i}){let a=Date.now(),{close:s,logFile:c}=await bC({logger:r,logLevel:e,appiumPort:i}),l={platformName:"Android","appium:automationName":"UiAutomator2","appium:deviceName":"Android","appium:udid":`127.0.0.1:${t}`,"appium:adbExecTimeout":3e4,"appium:newCommandTimeout":600,"appium:skipDeviceInitialization":!0,"appium:skipServerInstallation":!0,"appium:androidInstallTimeout":6e4,"appium:autoWebview":!1,"appium:autoWebviewTimeout":0,"appium:clearDeviceLogsOnStart":!0},u={hostname:"localhost",port:i,logLevel:e,capabilities:l,connectionRetryTimeout:3e4,connectionRetryCount:2},d=Date.now(),p=await SC(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:l,emulatorName:o},"Started Appium driver"),{driver:p,appiumClose:s,appiumPort:i,appiumLogFile:c}}async function bC({logger:r,logLevel:e,appiumPort:t}){let n=`${fC()}/appium-port-${Date.now()}.log`,o=await hC.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 EC({apiClient:r,logger:e,onStatusUpdate:t,creationOpts:n}){let{close:o,port:i,token:a,webRtcUrl:s,emulatorName:c}=await Ng({apiClient:r,logger:e,creationOpts:n,onStatusUpdate:t});return{port:i,close:o,limbarToken:a,limbarUrl:s,emulatorName:c}}import kg from"crypto";import TC from"fs";async function is({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await TC.promises.readFile(t),a=kg.createHash("md5").update(i).digest("base64"),s=kg.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===s)){o.info({channel:e,tag:r,md5:a,md5Hex:s},`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 l=await fetch(c.uploadUrl,{headers:{"Content-Length":i.length.toString(),"Content-Type":"application/octet-stream"},method:"PUT",body:i});if(l.status!==200)throw new Error(`Got error response from emulator platform: ${l.status} ${await l.text()}`);o.info({channel:e,tag:r,md5:a},`Asset ${t} was uploaded successfully!`);return}catch(l){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:l},"Failed to upload asset"),l}}throw new Error(`No upload URL was given for asset ${t}`)}import{execSync as GS}from"child_process";import{existsSync as sI}from"fs";import{platform as jS}from"os";import{dirname as lI,join as cI,resolve as uI}from"path";import{z as Dg}from"zod";var Zz=Dg.object({input:Dg.string()});import{z as Ye}from"zod";var tH=Ye.object({srcs:Ye.array(Ye.string()),urls:Ye.array(Ye.string()),desiredSrc:Ye.string().optional(),desiredUrl:Ye.string().optional()}),Ug=Ye.object({srcRegex:Ye.string().optional(),urlRegex:Ye.string().optional()}),Fg=Ye.object({x:Ye.number(),y:Ye.number(),correlation:Ye.number()}),rH=Ye.object({searchImageBase64String:Ye.string(),pageImageBase64String:Ye.string(),id:Ye.string().uuid(),timeoutMs:Ye.number().max(1e4).min(0).optional()});import{z as O}from"zod";import*as U from"zod";import{extendZodWithOpenApi as vC}from"zod-openapi";vC(U);var Yr=(s=>(s.AI="AI",s.AI_HEALED="AI_HEALED",s.CLICK_TO_FIND="CLICK_TO_FIND",s.XY_PERCENT="XY_PERCENT",s.RECORDING="RECORDING",s.USER_CSS_SELECTOR="USER_CSS_SELECTOR",s.HEURISTIC_HEALED="HEURISTIC_HEALED",s))(Yr||{}),AC=U.object({mPathSelectorTokens:U.string().array(),frameSrcRegex:U.string().optional(),frameUrlRegex:U.string().optional(),indices:U.number().array()}),iu=U.object({result:U.number(),traceId:U.string()}).array(),as=U.object({type:U.literal("GCS_TRACES"),traces:iu}),Bg=U.object({text:U.string().optional(),attributes:U.record(U.string(),U.string()).optional(),boundingBox:U.object({x:U.number(),y:U.number(),width:U.number(),height:U.number()}).optional()}),wC=U.object({selectors:U.string().array(),requirements:Bg.optional()}),Xr=U.object({id:U.number().int(),dataMomenticId:U.number().int().optional(),selector:U.string().optional(),hybridSelector:U.object({textContent:U.string().nullish(),attributes:U.record(U.string(),U.string()),tagName:U.string(),expandShadowRoot:U.boolean().optional(),classNames:U.string().array(),nthChild:U.number()}).array().optional(),generatedSelectors:U.string().array().optional(),requirements:Bg.optional(),additionalElements:wC.array().optional(),role:U.string().optional(),name:U.string().optional(),numChildren:U.number().optional(),content:U.string().optional(),pathFromRoot:U.string().optional(),serializedHtml:U.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:U.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:U.string().url().optional(),boundingBox:U.object({x:U.number().optional(),y:U.number().optional(),width:U.number(),height:U.number()}).describe("css pixel bounding box").optional(),frameCache:AC.optional(),inputDescription:U.string().optional().describe("the description that generated this cache"),targetSource:U.nativeEnum(Yr).optional(),targetUpdateTime:U.string().optional(),targetUpdateLoggerTags:U.record(U.string(),U.string()).optional(),cacheResolutionUpdateSource:U.string().optional(),cacheResolutionUpdateTime:U.string().optional(),cacheResolutionUpdateLoggerTags:U.record(U.string(),U.string()).optional(),memory:as.optional()}).openapi({ref:"ElementTargetCache"});function ss(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}var RC=U.object({type:U.literal("description"),elementDescriptor:U.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),CC=U.object({x:U.number(),y:U.number()}),xC=U.object({type:U.literal("coordinates"),pixels:CC}).openapi({ref:"CoordinatesTarget"});function Jr(r){return r.type==="description"}function Sr(r){return r.type==="coordinates"}var pt=U.discriminatedUnion("type",[RC,xC]).openapi({ref:"ElementTarget"});function au(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function zg(r){return as.safeParse(r).success}import{v4 as me}from"uuid";import*as b from"zod";import{extendZodWithOpenApi as kC}from"zod-openapi";import{z as te}from"zod";import{extendZodWithOpenApi as _C}from"zod-openapi";import{z as Ai}from"zod";import Hg from"zod";var vi=Hg.object({updatedAt:Hg.coerce.date().optional()});var su=Ai.object({result:Ai.boolean(),traceId:Ai.string()}).array(),lu=Ai.object({type:Ai.literal("GCS_TRACES"),traces:su}),cu=vi.extend({memory:lu.optional()});_C(te);var Gg=te.object({plan:te.string().optional(),evidence:te.string().optional(),thoughts:te.string(),result:te.boolean(),relevantElements:te.array(te.number()).optional(),updatedMemory:su.optional()}),Zr=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Zr||{});var MC=te.object({type:te.literal("ELEMENT_NAME"),negated:te.boolean().optional(),operation:te.nativeEnum(Zr),value:te.string()}).openapi({ref:"ElementNameAssertion"}),PC=te.object({type:te.literal("ELEMENT_STYLE"),negated:te.boolean().optional(),operation:te.nativeEnum(Zr),property:te.string(),value:te.string()}).openapi({ref:"ElementStyleAssertion"}),IC=te.object({type:te.literal("ELEMENT_CONTENT"),negated:te.boolean().optional(),operation:te.nativeEnum(Zr),value:te.string()}).openapi({ref:"ElementContentAssertion"}),OC=te.object({type:te.literal("ELEMENT_ATTRIBUTE"),negated:te.boolean().optional(),operation:te.nativeEnum(Zr),attr:te.string(),value:te.string()}).openapi({ref:"ElementAttributeValueAssertion"}),bo=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(bo||{}),LC=te.object({type:te.literal("ELEMENT_EXISTENCE"),negated:te.boolean().optional(),condition:te.nativeEnum(bo).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),jg=te.discriminatedUnion("type",[IC,OC,LC,MC,PC]).openapi({ref:"ManualElementAssertion"});var NC=te.object({type:te.literal("CONTENT"),negated:te.boolean().optional(),value:te.string()}).openapi({ref:"PageContentAssertion"}),Vg=te.discriminatedUnion("type",[NC]).openapi({ref:"ManualPageAssertion"});import yt from"zod";var uu=yt.discriminatedUnion("type",[yt.object({type:yt.literal("SUBSTRING"),url:yt.string()}),yt.object({type:yt.literal("GLOB"),glob:yt.string()}),yt.object({type:yt.literal("REGEX"),regex:yt.string()}),yt.object({type:yt.literal("DOMAIN"),domain:yt.string()})]),wi=yt.object({urlMatcher:uu,method:yt.string().optional()});import{z as pe}from"zod";var Eo=pe.object({url:pe.string(),method:pe.union([pe.literal("GET"),pe.literal("POST"),pe.literal("PUT"),pe.literal("DELETE"),pe.literal("PATCH")]),headers:pe.record(pe.string(),pe.string()).optional(),params:pe.record(pe.string(),pe.string()).optional(),body:pe.string().optional(),timeout:pe.number().int().optional().describe("Max seconds to wait for the request to complete")}),$g=pe.object({url:pe.string(),headers:pe.record(pe.string(),pe.string()).optional(),query:pe.string(),variables:pe.string().optional(),timeout:pe.number().int().optional().describe("Max seconds to wait for the request to complete")}),ls=pe.object({code:pe.string(),fragment:pe.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:pe.union([pe.literal("NODE"),pe.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:pe.number().int().max(60).optional().describe("Max seconds for the code to complete")});var st=(K=>(K.AI_EXTRACT="AI_EXTRACT",K.AI_ASSERTION="AI_ASSERTION",K.AUTH_LOAD="AUTH_LOAD",K.AUTH_SAVE="AUTH_SAVE",K.BLUR="BLUR",K.CAPTCHA="CAPTCHA",K.CLICK="CLICK",K.COOKIE="COOKIE",K.COPY="COPY",K.DIALOG="DIALOG",K.DRAG="DRAG",K.ELEMENT_CHECK="ELEMENT_CHECK",K.FILE_UPLOAD="FILE_UPLOAD",K.FOCUS="FOCUS",K.GO_BACK="GO_BACK",K.GO_FORWARD="GO_FORWARD",K.HOVER="HOVER",K.JAVASCRIPT="JAVASCRIPT",K.LOCAL_STORAGE="LOCAL_STORAGE",K.MOUSE_DRAG="MOUSE_DRAG",K.NAVIGATE="NAVIGATE",K.NEW_TAB="NEW_TAB",K.PAGE_CHECK="PAGE_CHECK",K.PASTE="PASTE",K.PRESS="PRESS",K.KEY_DOWN="KEY_DOWN",K.KEY_UP="KEY_UP",K.REFRESH="REFRESH",K.REQUEST="REQUEST",K.GRAPHQL_REQUEST="GRAPHQL_REQUEST",K.SCROLL_DOWN="SCROLL_DOWN",K.SCROLL_UP="SCROLL_UP",K.SCROLL_LEFT="SCROLL_LEFT",K.SCROLL_RIGHT="SCROLL_RIGHT",K.SELECT_OPTION="SELECT_OPTION",K.SWITCH_TAB="TAB",K.TYPE="TYPE",K.VISUAL_DIFF="VISUAL_DIFF",K.WAIT="WAIT",K.WAIT_FOR_URL="WAIT_FOR_URL",K.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",K.AWAIT_LISTENER="AWAIT_LISTENER",K.RECORD_REQUESTS="RECORD_REQUESTS",K.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",K.SET_HEADER="SET_HEADER",K.MOCK_ROUTE="MOCK_ROUTE",K.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",K.OFFLINE_MODE="OFFLINE_MODE",K.SUCCESS="SUCCESS",K))(st||{});kC(b);var W=b.object({thoughts:b.string().optional(),id:b.string().uuid().describe("unique identifier to this step, used for step cache")}),Ht=b.object({useSelector:b.boolean().optional(),force:b.boolean().optional(),disableCache:b.boolean().optional().describe("disable element caching for this step"),iframeUrl:b.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Gt=vi.extend({target:Xr}).optional().openapi({ref:"SingleTargetCache"});function qg(r){return Gt.safeParse(r).success}var us=b.object({loadTimeout:b.number().int().max(60).optional().describe("Max seconds for the page to load")}),DC=W.merge(us).merge(b.object({type:b.literal("NAVIGATE"),url:b.string()})).openapi({ref:"NavigateCommand"}),ds=Ht.merge(b.object({cache:Gt})),To=W.merge(ds.merge(b.object({target:pt.optional(),type:b.literal("SCROLL_UP"),deltaY:b.number().optional()}))).openapi({ref:"ScrollUpCommand"}),vo=W.merge(ds.merge(b.object({target:pt.optional(),type:b.literal("SCROLL_DOWN"),deltaY:b.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Ao=W.merge(ds.merge(b.object({target:pt.optional(),type:b.literal("SCROLL_LEFT"),deltaX:b.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),wo=W.merge(ds.merge(b.object({target:pt.optional(),type:b.literal("SCROLL_RIGHT"),deltaX:b.number().optional()}))).openapi({ref:"ScrollRightCommand"}),OH=b.discriminatedUnion("type",[To,vo,Ao,wo]).openapi({ref:"AllScrollCommands"}),UC=W.merge(b.object({type:b.literal("DIALOG"),action:b.union([b.literal("ACCEPT"),b.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),FC=W.merge(b.object({type:b.literal("WAIT"),delay:b.number()})).openapi({ref:"WaitCommand"}),BC=b.object({caseInsensitive:b.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:b.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:b.number().int().optional().describe("Max seconds to wait for the URL to match")}),zC=W.extend({type:b.literal("WAIT_FOR_URL"),matcher:uu}).merge(BC).openapi({ref:"WaitUrlCommand"}),HC=W.merge(us).merge(b.object({type:b.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),GC=W.merge(b.object({type:b.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),jC=W.merge(b.object({type:b.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),VC=W.extend({type:b.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),$C=W.extend({type:b.literal("AUTH_LOAD"),storageState:b.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),du=W.merge(Ht).extend({type:b.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),WC=W.extend({type:b.literal("COPY"),value:b.string()}).openapi({ref:"CopyCommand"}),qC=W.extend({type:b.literal("PASTE")}).openapi({ref:"PasteCommand"}),KC=W.merge(ls).extend({type:b.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Ri=W.merge(Ht).extend({type:b.literal("CLICK"),target:pt,doubleClick:b.boolean().optional(),rightClick:b.boolean().optional(),waitForDownload:b.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:b.number().optional(),downloadTimeoutMs:b.number().optional(),cache:Gt,relativePosition:b.object({x:b.number(),y:b.number()}).optional()}).openapi({ref:"ClickCommand"}),Kg=vi.extend({fromTarget:Xr.optional(),toTarget:Xr.optional()}),Ci=W.merge(Ht).merge(b.object({type:b.literal("DRAG"),fromTarget:pt,toTarget:pt,steps:b.number().optional(),hoverSeconds:b.number().optional().describe("Seconds to hover the object before dropping"),cache:Kg.optional()})).openapi({ref:"DragCommand"}),xi=W.merge(Ht).merge(b.object({type:b.literal("MOUSE_DRAG"),target:pt.optional(),deltaX:b.string().describe("pixels to move horizontally, can be template"),deltaY:b.string().describe("pixels to move vertically, can be template"),steps:b.number().optional(),cache:Gt})).openapi({ref:"MouseDragCommand"}),_i=W.merge(Ht).merge(b.object({type:b.literal("HOVER"),target:pt,cache:Gt})).openapi({ref:"HoverCommand"}),Mi=W.merge(Ht).merge(b.object({type:b.literal("FOCUS"),target:pt,cache:Gt})).openapi({ref:"FocusCommand"}),Pi=W.merge(Ht).extend({type:b.literal("BLUR"),target:pt.optional(),cache:Gt}).openapi({ref:"BlurCommand"}),YC=b.object({type:b.literal("URL"),url:b.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),XC=b.object({type:b.literal("USER_FILE"),name:b.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),JC=W.extend({type:b.literal("FILE_UPLOAD"),fileSource:b.discriminatedUnion("type",[YC,XC]),filename:b.string().optional()}).openapi({ref:"FileUploadCommand"}),ZC=b.discriminatedUnion("type",[b.object({type:b.literal("VALUE"),value:b.string()}),b.object({type:b.literal("LABEL"),label:b.string()}),b.object({type:b.literal("INDEX"),index:b.coerce.string()})]),Ii=W.merge(Ht).extend({type:b.literal("SELECT_OPTION"),target:pt,cache:Gt,choice:ZC.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),pu=b.union([b.literal("MULTIMODAL"),b.literal("VISION_ONLY")]),ps=W.merge(b.object({type:b.literal("AI_ASSERTION"),assertion:b.string(),disableCache:b.boolean().optional(),iframeUrl:b.string().optional(),contextChoice:pu.optional(),timeout:b.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:cu.optional()})).openapi({ref:"AIAssertionCommand"}),Qr=5,mu=600,Oi=W.merge(Ht).extend({type:b.literal("ELEMENT_CHECK"),target:pt,assertion:jg,cache:Gt.or(cu).optional(),timeout:b.number().int().min(0).max(mu).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),QC=W.extend({type:b.literal("PAGE_CHECK"),assertion:Vg,iframeUrl:b.string().optional().describe("url or url regex for the iframe"),timeout:b.number().int().min(0).max(mu).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),ex=W.merge(b.object({type:b.literal("AI_EXTRACT"),goal:b.string(),schema:b.string().optional(),envKey:b.string().optional(),disableCache:b.boolean().optional(),iframeUrl:b.string().optional()})).openapi({ref:"AIExtractCommand"}),tx=b.object({clearContent:b.boolean().optional(),forceClearContent:b.boolean().optional(),delay:b.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:b.boolean().optional(),pressEnter:b.boolean().optional()}),Yg=25,Li=W.merge(Ht).merge(tx).extend({type:b.literal("TYPE"),target:pt.optional(),value:b.string(),cache:Gt}).openapi({ref:"TypeCommand"}),rx=W.merge(b.object({type:b.literal("PRESS"),value:b.string(),repeat:b.number().optional(),convertMeta:b.boolean().optional(),delayMs:b.number().optional()})).openapi({ref:"PressCommand"}),nx=W.merge(b.object({type:b.literal("KEY_DOWN"),value:b.string(),convertMeta:b.boolean().optional()})).openapi({ref:"KeyDownCommand"}),ox=W.merge(b.object({type:b.literal("KEY_UP"),value:b.string(),convertMeta:b.boolean().optional()})).openapi({ref:"KeyUpCommand"}),ix=b.object({type:b.literal("SUBSTRING"),substring:b.string()}),ax=b.object({type:b.literal("REGEX"),pattern:b.string()}),sx=b.object({type:b.literal("INDEX"),index:b.coerce.string()}),lx=b.discriminatedUnion("type",[ix,ax,sx]),cx=W.merge(us).merge(b.object({type:b.literal("TAB"),action:lx})).openapi({ref:"TabCommand"}),ux=W.merge(us).merge(b.object({type:b.literal("NEW_TAB"),url:b.string()})).openapi({ref:"NewTabCommand"}),dx=W.merge(b.object({type:b.literal("COOKIE"),value:b.string()})).openapi({ref:"CookieCommand"}),px=W.merge(b.object({type:b.literal("LOCAL_STORAGE"),key:b.string(),value:b.string()})).openapi({ref:"LocalStorageCommand"}),mx=W.extend({type:b.literal("REQUEST")}).merge(Eo).openapi({ref:"RequestCommand"}),gx=W.extend({type:b.literal("GRAPHQL_REQUEST")}).merge($g).openapi({ref:"GraphQLRequestCommand"}),hx=W.merge(b.object({type:b.literal("SUCCESS"),condition:ps.optional()})).openapi({ref:"SuccessCommand"}),fx=W.merge(b.object({type:b.literal("FAILURE")})).openapi({ref:"FailureCommand"}),Sx=b.object({data:b.string().describe("location at which to find a jpg"),width:b.number(),height:b.number()}),Ni=W.merge(Ht).merge(b.object({type:b.literal("VISUAL_DIFF"),threshold:b.number().optional().describe("default 0.1"),target:pt.optional(),screenshot:Sx.optional(),cache:Gt})).openapi({ref:"VisualDiffCommand"}),yx=W.merge(b.object({type:b.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:wi,key:b.string()})).openapi({ref:"RegisterRequestListenerCommand"}),bx=W.merge(b.object({type:b.literal("AWAIT_LISTENER"),key:b.string(),timeout:b.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),Ex=W.merge(b.object({type:b.literal("RECORD_REQUESTS"),requestMatcher:wi,key:b.string()})).openapi({ref:"RecordRequestsCommand"}),Tx=W.merge(b.object({type:b.literal("GET_RECORDED_REQUESTS"),key:b.string()})).openapi({ref:"GetRecordedRequestsCommand"}),vx=W.merge(b.object({type:b.literal("SET_HEADER"),name:b.string(),value:b.string(),requestMatcher:wi.optional()})).openapi({ref:"SetHeaderCommand"}),Ax=W.merge(b.object({type:b.literal("MOCK_ROUTE"),requestMatcher:wi,responseGenerator:b.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:b.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:b.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"})),wx=W.merge(b.object({type:b.literal("REMOVE_ROUTE_MOCK"),key:b.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),Rx=W.merge(b.object({type:b.literal("OFFLINE_MODE"),enable:b.boolean()})).openapi({ref:"OfflineModeCommand"}),Xg=b.discriminatedUnion("type",[Ri,Li,rx,nx,ox,Ii,DC,vo,To,ps,_i,FC,hx]),Cx=b.discriminatedUnion("type",[ex,$C,VC,du,dx,WC,UC,Ci,Oi,JC,GC,jC,KC,px,xi,ux,QC,qC,HC,mx,gx,Ao,wo,cx,Ni,Mi,Pi,zC,yx,bx,Ex,Tx,vx,Ax,wx,Rx]),Ro=b.discriminatedUnion("type",[...Xg.options,...Cx.options]).openapi({ref:"Command"}),ms=b.discriminatedUnion("type",[...Xg.options,fx]);function kr(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:me(),type:r};break;case"AUTH_LOAD":{e={id:me(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:me(),type:r,goal:""};break;case"DIALOG":e={id:me(),type:r,action:"DISMISS"};break;case"DRAG":e={id:me(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:me(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:me(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:me(),type:r,delay:1};break;case"BLUR":e={id:me(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:me(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:me(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:me(),type:r,value:""};break;case"SELECT_OPTION":e={id:me(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:me(),type:r,url:""};case"TAB":e={id:me(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:me(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:me(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:me(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:me(),type:r,code:""};break;case"AI_ASSERTION":e={id:me(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:me(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:me(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:me(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:me(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:me(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:me(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:me(),type:r,key:""};break}case"SET_HEADER":{e={id:me(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:me(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:me(),type:r};break}case"OFFLINE_MODE":{e={id:me(),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 Jg(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 xx}from"zod";var UH=xx.discriminatedUnion("type",[Pi,du,Ri,Ci,Mi,_i,xi,To,vo,Ao,wo,Ii,Li,Ni,Oi]);import{z as _x}from"zod";import{z as en}from"zod";function ki(r){return en.object({key:en.string(),testId:en.string().optional(),moduleId:en.string().optional(),organizationId:en.string(),value:r})}function Di(r){return ki(r).extend({uniqueKey:en.string()})}function gs(r){return en.record(en.string(),Di(r))}var bt={type:!0,cache:!0},Co=_x.discriminatedUnion("type",[ps.pick(bt),Pi.pick(bt),Ri.pick(bt),Ci.pick(bt),Oi.pick(bt),Mi.pick(bt),_i.pick(bt),xi.pick(bt),To.pick(bt),vo.pick(bt),Ao.pick(bt),wo.pick(bt),Ii.pick(bt),Li.pick(bt),Ni.pick(bt)]),gu=Object.values(st).filter(r=>Co.options.some(e=>e.shape.type.safeParse(r).success));Ro.options.forEach(r=>{if("target"in r.shape&&!gu.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function Zg(r){return gu.includes(r.type)}var Qg=ki(Co),eh=Di(Co),$H=gs(Co);import{z as hu}from"zod";import{extendZodWithOpenApi as Ix}from"zod-openapi";import{z as th}from"zod";import{extendZodWithOpenApi as Mx}from"zod-openapi";import{z as Mn}from"zod";var jt=Mn.object({index:Mn.number().optional().describe("global index within a test (in-order traversal)"),id:Mn.string(),skipped:Mn.boolean().optional(),envKey:Mn.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Mn.boolean().optional(),retries:Mn.number().optional()});Mx(th);var Px=jt.extend({type:th.literal("PRESET_ACTION")}),Vt=Px.extend({command:Ro}).openapi({ref:"PresetAction"});Ix(hu);var Pn=jt.extend({type:hu.literal("AI_ACTION"),text:hu.string(),steps:Vt.array().optional()}).openapi({ref:"AIAction"});import{z as Et}from"zod";import{z as hs}from"zod";import{extendZodWithOpenApi as Ox}from"zod-openapi";Ox(hs);var xo=jt.extend({type:hs.literal("AI_ACTION_DYNAMIC"),text:hs.string(),retries:hs.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as rh}from"zod";var fu=jt.extend({type:rh.literal("CONDITIONAL"),skipped:rh.boolean().optional()});import{z as se}from"zod";var Lx=se.object({cacheKey:se.string(),cacheExpiryMs:se.number()}),Su=jt.extend({id:se.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:se.record(se.string()).optional(),cacheConfig:Lx.optional()}),Dr=Su.extend({type:se.literal("MODULE"),moduleId:se.string().uuid()}),Nx=se.union([Dr.pick({type:!0,moduleId:!0}),se.record(se.unknown())]),kx=se.object({type:se.literal("URL_REGEX"),regex:se.string()}),Dx=se.object({type:se.literal("PAGE_CHECK"),substring:se.string()}),yu=se.object({cacheInvalidation:se.discriminatedUnion("type",[Dx,kx]).optional()}),$t=se.object({moduleId:se.string().uuid(),name:se.string(),description:se.string().nullish(),enabled:se.boolean().nullish(),parameters:se.string().array().nullish(),defaultParameters:se.record(se.string(),se.string()).nullish(),parameterEnums:se.record(se.string(),se.string().array()).nullish(),defaultCacheKey:se.string().nullish(),defaultCacheTtl:se.number().nullish(),defaultCacheAllInvocations:se.boolean().nullish(),autoAuth:se.boolean().nullish(),advanced:yu.nullish()});import{z as Wt}from"zod";var nh=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(nh||{});var Ux=Wt.discriminatedUnion("type",[Wt.object({type:Wt.literal("NAVIGATE_URL"),url:Wt.string().url()}),Wt.object({type:Wt.literal("GO_TO_SECTION_START")})]),Fx=Wt.object({trigger:Wt.nativeEnum(nh).optional(),attempts:Wt.number().int().optional(),restartBehavior:Ux}),Ui=jt.extend({type:Wt.literal("SECTION"),description:Wt.string().describe("user provided goal of what the section should accomplish"),plan:Wt.string().array().optional(),autohealingConfig:Fx.optional()});var oh=$t.merge(Su).extend({type:Et.literal("RESOLVED_MODULE"),steps:Et.lazy(()=>Je.array())}),Fi=$t.extend({steps:Et.lazy(()=>Je.array())}),bu=Ui.extend({steps:Et.lazy(()=>Tt.array())}),Bx=Ui.extend({steps:Et.lazy(()=>Je.array())}),_o=fu.extend({blocks:Et.object({assertion:Et.lazy(()=>Vt),steps:Et.lazy(()=>Tt.array())}).array(),elseSteps:Et.lazy(()=>Tt.array().optional())}),zx=fu.extend({blocks:Et.object({assertion:Et.lazy(()=>Vt),steps:Et.lazy(()=>Je.array())}).array(),elseSteps:Et.lazy(()=>Je.array().optional())}),Tt=Et.discriminatedUnion("type",[Vt,Pn,xo,Dr,_o,bu]),Je=Et.discriminatedUnion("type",[Vt,Pn,xo,oh,zx,Bx]);import{z as qt}from"zod";var Hx=qt.object({steps:Tt.array(),beforeSteps:Tt.array().nullish(),afterSteps:Tt.array().nullish()}),In=qt.object({steps:Je.array(),beforeSteps:Je.array().nullish(),afterSteps:Je.array().nullish()}),On=qt.object({steps:qt.record(qt.string(),qt.unknown()).array(),beforeSteps:qt.record(qt.string(),qt.unknown()).array().nullish(),afterSteps:qt.record(qt.string(),qt.unknown()).array().nullish()});var Ln="1.0.21",Eu="0.0.1";var ih=O.object({phrase:O.string()}),Tu=O.object({thoughts:O.string().optional(),result:O.union([O.literal("NOT_FOUND"),O.string(),O.number(),O.array(O.unknown()),O.record(O.unknown(),O.unknown()),O.unknown()])}),Pj=O.object({text:O.string()}),ah=O.object({attributes:O.array(O.string()).optional(),text:O.boolean().optional(),boundingBox:O.boolean().optional()}),Gx=O.object({id:O.number().int(),requirements:ah}),jx=Gx.array(),sh=O.object({thoughts:O.string(),review:O.string().optional(),id:O.number().int(),updatedMemory:iu.optional(),requirements:ah.optional(),additionalElements:jx.optional()});var vu=(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))(vu||{}),lh=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(lh||{});var ch=O.object({thoughts:O.string(),category:O.nativeEnum(vu)}),uh=O.object({thoughts:O.string(),category:O.nativeEnum(lh)}),Vx=O.discriminatedUnion("op",[O.object({op:O.literal("replace"),path:O.string(),value:O.string()}),O.object({op:O.literal("add"),path:O.string(),value:O.string()}),O.object({op:O.literal("remove"),path:O.string()})]),Ij=O.object({thoughts:O.string(),patches:Vx.array()}),$x=[O.literal("add"),O.literal("replace"),O.literal("remove")],Wx=O.object({op:O.union($x),path:O.string(),value:Je.optional()}),dh=O.object({patches:Wx.array(),thoughts:O.string()}),ph=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(ph||{}),mh=O.object({thoughts:O.string(),scenario:O.nativeEnum(ph),instructions:O.string().nullish()}),gh=O.object({reasoning:O.string(),scenario:O.string(),patch:O.null().optional()}),Oj=O.object({thoughts:O.string(),evaluation:O.number().min(0).max(10)}),Lj=O.object({observations:O.string(),reasoning:O.string(),command:ms});var Au=O.object({summary:O.string(),reasoning:O.string(),evaluation:O.discriminatedUnion("type",[O.object({type:O.literal("DONE")}),O.object({type:O.literal("RIGHT_TRACK")}),O.object({type:O.literal("WRONG_TRACK"),feedback:O.string()}),O.object({type:O.literal("IMPOSSIBLE")})])}),qx=O.object({startId:O.number().int(),endId:O.number().int()}),wu=(n=>(n.SIMPLE_CONTENT_BASED_LOCATOR="SIMPLE_CONTENT_BASED_LOCATOR",n.SIMPLE_CONTENT_BASED_ASSERTION="SIMPLE_CONTENT_BASED_ASSERTION",n.OTHER="OTHER",n))(wu||{}),hh=O.object({categoryThoughts:O.string(),category:O.nativeEnum(wu),relevantSections:qx.array()});import{z as I}from"zod";import*as re from"zod";var Bj=re.object({thoughts:re.string().optional().describe("only provided if a description was provided"),target:Xr.optional().describe("only provided if a description was provided"),pageState:re.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:re.object({label:re.string(),value:re.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:re.object({data:re.string(),height:re.number().int(),width:re.number().int()}).optional().describe("only provided if returnScreenshot is true")}),fh=re.union([re.literal("ELEMENT_CHECK"),re.literal("NEGATED_CHECK"),re.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),re.literal("SELECT_OPTION"),re.literal("TYPE")]);function Bi(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 zi=(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))(zi||{}),Mo=re.object({matched:re.boolean(),reason:re.string().optional().describe("Human understandable description"),logs:re.string().array().optional().describe("Logs for debugging")}),Kx=Mo.extend({type:re.literal("USER_SELECTOR")}),Yx=Mo.extend({type:re.literal("CSS_SELECTOR"),selectors:re.string().array()}),Xx=Mo.extend({type:re.literal("HYBRID_SELECTOR")}),Jx=Mo.extend({type:re.literal("HTML_DISTANCE"),distance:re.number().optional(),closestElement:re.string().optional(),savedElement:re.string().optional()}),Zx=Mo.extend({type:re.literal("TEMPLATE_MATCHING"),elementImageUrl:re.string().url()}),Qx=Mo.extend({type:re.literal("AUTO_FRAME"),logs:re.string().array().optional()}),Sh=re.discriminatedUnion("type",[Kx,Yx,Xx,Jx,Zx,Qx]);import{z as Vi}from"zod";import{z as u_}from"zod";import*as $ from"zod";import{extendZodWithOpenApi as r_}from"zod-openapi";import{cloneDeep as Xj}from"lodash-es";import Zj from"truncate-json";import*as Dn from"zod";import{extendZodWithOpenApi as e_}from"zod-openapi";import{z as mt}from"zod";import{z as ge}from"zod";var Ru=ge.object({autoFollowNewTabs:ge.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:ge.union([ge.boolean(),ge.literal("inputs-only")]).optional(),ignoreHrefForCaching:ge.boolean().optional(),disableSecondaryCacheResolution:ge.boolean().optional(),hybridSelectorMode:ge.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:ge.boolean().optional(),visualActions:ge.boolean().optional(),autoExpandIframes:ge.boolean().optional(),disableHtmlSnapshots:ge.boolean().optional(),importantAttributes:ge.string().array().optional(),importantClasses:ge.string().array().optional(),importantStyles:ge.string().array().optional()});var yh=1e4,bh=6e4,Nn=Ru.extend({pageLoadTimeoutMs:ge.number().optional().refine(r=>r===void 0||r<=bh&&r>=-1,{message:`Page load timeout must be between 0 and ${bh/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:ge.number().optional().refine(r=>r===void 0||r<=yh&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${yh/1e3} seconds`}),localChromeExtensionPaths:ge.string().array().optional(),extraHeaders:ge.record(ge.string(),ge.string()).optional().describe("HTTP headers to be sent on every request"),initialLocalStorage:ge.record(ge.string(),ge.record(ge.string(),ge.string())).optional().describe("Initial local storage key-value pairs to set per domain on browser startup"),userAgent:ge.string().optional(),disableGpu:ge.boolean().optional(),bustCacheOnBoundingBoxChange:ge.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:ge.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:ge.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 Cu="BASE_URL";var kn="ENV_NAME",Po="TEST_NAME",$j={[Cu]:"https://www.google.com"},Eh=mt.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Th=mt.object({name:mt.string(),variables:mt.record(mt.string().describe("variable name"),mt.string().describe("variable value"))}),vh=mt.object({name:mt.string(),variables:mt.record(mt.string().describe("variable name"),mt.unknown().describe("variable value")),browser:Nn.optional()});var Wj=mt.object({name:mt.string(),variables:mt.record(mt.string().describe("variable name"),mt.unknown().describe("variable value"))});e_(Dn);var xu=Dn.object({env:Dn.record(Dn.unknown())}).openapi({ref:"TestContextSnapshot"});var Ze=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Ze||{}),_u=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(_u||{});import{z as yr}from"zod";import{extendZodWithOpenApi as t_}from"zod-openapi";t_(yr);var Te=(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))(Te||{});var Mu=yr.object({reason:yr.nativeEnum(Te),previousStepsDescription:yr.array(yr.string()).optional(),summary:yr.string(),rootCause:yr.string().optional()}).openapi({ref:"TestResultClassification"}),fs=yr.object({errorMessage:yr.string(),errorStack:yr.string().optional(),classification:Mu.optional()}).openapi({ref:"TestFailureDetails"});r_($);var Pu=$.object({beforeUrl:$.string().optional(),afterUrl:$.string().optional(),message:$.string().optional(),beforeSnapshot:$.string().optional(),afterSnapshot:$.string().optional(),startedAt:$.coerce.date(),finishedAt:$.coerce.date()}),n_=Pu.extend({viewport:$.object({height:$.number(),width:$.number()}).nullish(),status:$.nativeEnum(_u),message:$.string().optional(),elementInteracted:$.string().optional()}),Un=Pu.extend({status:$.nativeEnum(Ze),message:$.string().optional(),data:$.unknown().optional(),beforeTestContext:xu.optional(),afterTestContext:xu.optional(),failureReason:$.nativeEnum(Te).optional(),details:$.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"}),Ah=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(Ah||{}),Ss=Un.merge(Vt).extend({results:n_.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:$.lazy(()=>rt.array()).optional(),failureRecoveryStatus:$.object({type:$.nativeEnum(Ah),message:$.string()}).optional()}),o_=Un.merge(Pn).extend({results:$.lazy(()=>Ss.array()),previousAttempts:$.lazy(()=>rt.array()).optional()}),i_=Un.merge(xo).extend({results:$.lazy(()=>Ss.array()),previousAttempts:$.lazy(()=>rt.array()).optional()}),a_=Un.merge(Dr).extend({moduleName:$.string().optional(),results:$.lazy(()=>rt.array()),previousAttempts:$.lazy(()=>rt.array()).optional()}),s_=Un.merge(_o).extend({assertion:Ss.optional(),results:$.lazy(()=>rt.array()).describe("results for the block actually executed"),previousAttempts:$.lazy(()=>rt.array()).optional()}),l_=Un.merge(Ui).extend({results:$.lazy(()=>rt.array()),healingAttempts:$.lazy(()=>rt.array().array()).optional(),previousAttempts:$.lazy(()=>rt.array()).optional()}),rt=$.discriminatedUnion("type",[o_,i_,Ss,a_,s_,l_]),SV=Un.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),c_=Pu.extend({index:$.number().optional(),description:$.string(),pageState:$.string().optional(),elementInteracted:$.string().optional(),startedAt:$.coerce.date().or($.string()).optional().catch(void 0),finishedAt:$.coerce.date().or($.string()).optional().catch(void 0)}),ys=c_.extend({beforeScreenshot:$.string().optional(),afterScreenshot:$.string().optional()});var Iu=u_.object({results:rt.array().describe("main results"),beforeResults:rt.array().optional(),afterResults:rt.array().optional()}),Hi=Iu.partial();import{z}from"zod";import{extendZodWithOpenApi as S_}from"zod-openapi";var Io=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(Io||{});import{isValidCron as d_}from"cron-validator";import{z as ne}from"zod";import{z as Ou}from"zod";var tn=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(tn||{});var bs=Ou.object({width:Ou.number().min(200).max(1e4),height:Ou.number().min(200).max(1e4)}),wh={"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}},wV=Object.keys(wh);var rn=wh["Desktop Large"],Rh="en-us",Ch="America/Los_Angeles";var xh={latitude:37.7749,longitude:-122.4194};var _h=["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 Mh=2e3,p_=Nn.extend({browserType:ne.nativeEnum(tn).optional(),slowMoMs:ne.number().optional().refine(r=>r===void 0||r<=Mh&&r>=-1,{message:`Slow motion must be between 0 and ${Mh} milliseconds`}),basicAuthorization:ne.object({username:ne.string().optional(),password:ne.string().optional()}).optional(),geolocation:ne.object({latitude:ne.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:ne.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:ne.boolean().optional(),locale:ne.string().optional(),timezone:ne.enum(_h).optional(),colorScheme:ne.enum(["light","dark"]).optional()});var Lu=ne.object({useMemory:ne.boolean().optional(),failureRecovery:ne.boolean().optional().describe("undefined means inherit org settings")}),m_=Lu.extend({disableAICaching:ne.boolean().optional(),failureRecoveryInstructions:ne.string().optional()}),g_=ne.object({viewport:bs.optional()}),Gi=g_.merge(m_).merge(p_),Oo=ne.object({cron:ne.string().refine(r=>d_(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:ne.boolean().default(!1),env:ne.string().optional(),timeZone:ne.string().default("America/Los_Angeles"),jobKey:ne.string().optional()}),Lo=ne.object({onSuccess:ne.boolean().default(!1),failureMessage:ne.string().optional(),onFailure:ne.boolean().default(!0),successMessage:ne.string().optional()}),h_=ne.object({name:ne.string(),required:ne.boolean().optional(),defaultValue:ne.string().describe("this is not optional because we need a value when the editor is first loaded")}),Es=h_.array(),f_=ne.object({name:ne.string(),value:ne.string()}),Ph=f_.array(),Ts=ne.object({name:ne.string(),default:ne.boolean().optional(),fixtures:Eh.array().optional()});S_(z);var Kt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},be=(s=>(s.PENDING="PENDING",s.RUNNING="RUNNING",s.PASSED="PASSED",s.FAILED="FAILED",s.CANCELLED="CANCELLED",s.RETRYING="RETRYING",s.WAITING_FOR_USER="WAITING_FOR_USER",s))(be||{}),vs=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(vs||{});var je=z.string().pipe(z.coerce.date()).or(z.date()),ji=z.object({id:z.string(),runKey:z.string(),organizationId:z.string(),executionType:z.nativeEnum(Io).optional().default("WEB"),createdAt:je,createdBy:z.string(),flake:z.boolean().nullish(),scheduledAt:je.or(z.null()),startedAt:je.or(z.null()),updatedAt:je.nullish(),finishedAt:je.or(z.null()),resolvedBaseUrl:z.string().nullish(),environmentName:z.string().nullish(),gitBranchName:z.string().nullish(),githubRepository:z.string().nullish(),gitlabProjectPath:z.string().nullish(),labels:z.array(z.string()).optional(),gitOriginUrl:z.string().nullish(),gitCommitSha:z.string().nullish(),gitCommitShaShort:z.string().nullish(),gitCommitAuthorName:z.string().nullish(),cliVersion:z.string().nullish(),section:z.nativeEnum(vs).nullish(),status:z.nativeEnum(be),trigger:z.nativeEnum(Kt),attempts:z.number(),runAttempts:z.array(z.object({id:z.string(),status:z.nativeEnum(be),startedAt:je.or(z.null()),finishedAt:je.or(z.null())})).optional(),videos:z.array(z.string()).optional(),failureReason:z.nativeEnum(Te).nullish(),failureDetails:fs.nullish(),failureRecoveryDetails:z.record(z.string(),z.unknown()).nullish(),pipelineId:z.string().nullish(),resolvedInputs:z.record(z.string(),z.string()).nullish(),quarantined:z.boolean().nullish().default(!1),quarantinedReason:z.string().nullish(),localTestId:z.string().nullish(),testId:z.string().nullish(),testName:z.string().nullish(),description:z.string().nullish(),test:z.object({name:z.string(),id:z.string()}).nullish().default(null),suiteId:z.string().nullish()}).openapi({ref:"RunMetadata"}),y_={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},As=ji.pick({...y_,test:!0}),Ih=ji.omit({failureReason:!0,failureDetails:!0,test:!0}),Nu=ji.extend({stepsSnapshot:z.array(z.record(z.unknown())).nullish(),resolvedInputs:z.record(z.string(),z.string()).nullish(),test:z.object({name:z.string(),id:z.string(),description:z.string().nullish(),baseUrl:z.string().nullish(),advanced:Gi.nullish()}).nullish()}).merge(Iu);var b_=Vi.object({id:Vi.string().uuid(),startedAt:je.or(Vi.null()),finishedAt:je.or(Vi.null()),status:Vi.nativeEnum(be)}).merge(Hi),WV=b_.array();import{z as Ve}from"zod";var E_=Ve.object({id:Ve.string(),status:Ve.nativeEnum(be),trigger:Ve.nativeEnum(Kt),createdAt:je,startedAt:je.nullish(),finishedAt:je.nullish(),gitCommitSha:Ve.string().nullish(),gitCommitShaShort:Ve.string().nullish(),gitCommitTimestamp:je.nullish(),gitBranchName:Ve.string().nullish(),gitOriginUrl:Ve.string().nullish(),gitCommitMessage:Ve.string().nullish(),gitCommitAuthorName:Ve.string().nullish(),githubRepository:Ve.string().nullish(),gitlabProjectPath:Ve.string().nullish(),pipelineId:Ve.string().nullish(),cliVersion:Ve.string().nullish(),labels:Ve.string().array().optional(),suite:Ve.object({id:Ve.string(),name:Ve.string()}).nullish(),runs:Ve.object({status:Ve.nativeEnum(be)}).array()}).openapi({ref:"RunGroup"}),Oh=E_.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:As.array()});import{z as nt}from"zod";var T_=nt.object({type:nt.literal("TARGETING"),name:nt.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:Sh.array(),pageState:nt.string().optional(),targetSource:nt.nativeEnum(Yr).optional(),targetUpdateTime:nt.string().optional()}),v_=nt.object({type:nt.literal("AI_LOCATION"),matched:nt.boolean(),pageState:nt.string().optional(),ragUsed:nt.boolean().optional(),thoughts:nt.string().optional()}),A_=nt.object({type:nt.literal("ASSERTION"),relevantElementsSerialized:nt.string().array().optional(),pageState:nt.string().optional(),ragUsed:nt.boolean().optional()}),w_=nt.discriminatedUnion("type",[T_,v_,A_]);import{z as Be}from"zod";var R_=Be.object({id:Be.string(),name:Be.string()}),a$=R_.merge(Be.object({createdAt:je,createdBy:Be.string(),schedule:Oo,notification:Lo,environment:Be.object({name:Be.string()}).nullish(),beforeTests:Be.object({id:Be.string()}).array().nullish(),afterTests:Be.object({id:Be.string()}).array().nullish()})),Lh=Be.object({id:Be.string().uuid(),orgId:Be.string(),createdAt:je,startedAt:je.or(Be.null()),finishedAt:je.or(Be.null()),status:Be.nativeEnum(be),trigger:Be.nativeEnum(Kt),suite:Be.object({id:Be.string(),name:Be.string()}).nullish(),runs:ji.array()}),s$=Lh.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),Nh=Lh.extend({runs:As.array()});import{z as Yt}from"zod";import{cloneDeep as u$}from"lodash-es";import{z as he}from"zod";var f$=he.object({thoughts:he.string(),subGoals:he.object({instruction:he.string()}).array()}),S$=he.object({thoughts:he.string(),newPlanMarkdown:he.string()}),y$=he.object({thoughts:he.string(),correct:he.boolean(),failedActionIndex:he.number().optional()}),C_=he.object({type:he.literal("PLANNING"),beforePlan:he.string(),goalDecision:he.string(),thoughts:he.string()}),x_=he.object({type:he.literal("RUNNING"),stepDisplayName:he.string(),status:he.nativeEnum(Ze),results:rt.array()}),__=he.object({type:he.literal("REVISING"),beforePlan:he.string(),afterPlan:he.string(),errString:he.string(),diffs:he.string(),thoughts:he.string()}),M_=he.object({type:he.literal("SYSTEM"),message:he.string()}),P_=he.discriminatedUnion("type",[C_,x_,__,M_]),kh=P_.array();var A$=Yt.object({id:Yt.string(),scheduledAt:Yt.coerce.date().nullable(),startedAt:Yt.coerce.date().nullable(),finishedAt:Yt.coerce.date().nullable(),status:Yt.nativeEnum(be),history:kh.nullable(),testPlan:Yt.object({id:Yt.string(),name:Yt.string()}).nullable(),test:Yt.object({id:Yt.string(),name:Yt.string()}).nullable()});import{z as vt}from"zod";var ku=vt.object({content:vt.string(),ids:vt.string().array(),tokenLength:vt.number()}),I_=vt.object({chunks:ku.array()}),z$=vt.object({ids:vt.string().array(),score:vt.number(),tokenLength:vt.number()}),H$=I_.extend({description:vt.string().describe("Input to pass to RAG engine"),tokenLimit:vt.number()}),Dh=vt.object({ids:vt.number().array()}),Uh=vt.object({indices:vt.number().array()});var gt=I.object({disableCache:I.boolean().optional(),useMemory:I.boolean().optional(),loggerTags:I.record(I.string(),I.string()).optional(),langfuseSessionId:I.string().optional(),agentConfigVersion:I.string().optional()}),Y$=gt.extend({chunks:ku.array(),description:I.string().describe("Input to pass to AI"),type:I.union([I.literal("locator"),I.literal("assertion"),I.literal("ai-action")]),softTokenLimit:I.number(),hardTokenLimit:I.number()}),O_=I.object({screenshotBase64AfterCommand:I.string(),urlAfterCommand:I.string(),serializedCommand:I.string(),elementInteracted:I.string().optional(),thoughts:I.string().optional()}),Fh=I.object({goal:I.string(),browserState:I.string(),screenshot:I.string(),source:fh.optional().catch(void 0),memory:I.discriminatedUnion("type",[as,I.object({type:I.literal("RESOLVED_TRACES"),traces:I.unknown().array()})]).optional()}),Bh=I.object({target:I.string().or(I.number()),browserState:I.string().optional(),screenshot:I.string().optional(),boundingBox:I.object({x:I.number(),y:I.number(),height:I.number(),width:I.number()}).optional()}),zh=I.object({goal:I.string(),browserState:I.string(),screenshot:I.string().optional(),returnSchema:I.string().optional()}),L_=I.literal("NEGATED_CHECK"),Hh=I.object({goal:I.string(),browserState:I.string(),screenshot:I.string(),url:I.string(),contextChoice:pu.optional(),memory:I.discriminatedUnion("type",[lu,I.object({type:I.literal("RESOLVED_TRACES"),traces:I.unknown().array()})]).optional(),source:L_.optional()}),Gh=I.object({command:Ro}),jh=I.object({message:I.string()}),Du=I.object({goal:I.string(),browserState:I.string(),startingScreenshot:I.string().optional(),screenshot:I.string(),url:I.string(),history:O_.array(),actionHint:I.string().optional(),lastError:I.string().optional()}),Vh=I.object({results:ys.array(),errorMessage:I.string(),errorStack:I.string().optional()}),$h=I.object({results:ys.array(),goal:I.string(),errorMessage:I.string()}),Wh=I.object({failedResults:ys.array(),nextStepsSerialized:I.string().array(),currentUrl:I.string(),currentPageState:I.string(),currentScreenshot:I.string(),customInstructions:I.string().optional(),testDescription:I.string().optional()}),X$=I.object({description:I.string(),type:I.union([I.literal("locator"),I.literal("assertion"),I.literal("ai-action")]),excerpt:I.string()}),qh=I.object({type:I.string(),browserContext:I.string(),currentStep:I.string(),screenshot:I.string()});import{z as $i}from"zod";var Q$=$i.object({goal:$i.string()}),Kh=$i.object({keywords:$i.array($i.string())});import{z as Uu}from"zod";var ws=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(ws||{}),rW=Uu.nativeEnum(ws),N_=Uu.enum(["v1","v2"]),nW=N_.or(Uu.string().describe("for people with special configurations"));import{z as Oe}from"zod";var Yh=Oe.object({attributesRequired:Oe.array(Oe.string()).optional(),textRequired:Oe.boolean().optional(),boundsRequired:Oe.boolean().optional()}),Xh=Oe.object({id:Oe.number(),thoughts:Oe.string(),inWebview:Oe.boolean().optional(),requirements:Yh.optional(),additionalElements:Oe.object({id:Oe.number(),requirements:Yh}).array().optional()}),Jh=Oe.object({description:Oe.string(),screenXml:Oe.string(),screenshot:Oe.string()}),Zh=Oe.object({assertion:Oe.string(),screenXml:Oe.string(),screenshot:Oe.string()}),Qh=Oe.object({thoughts:Oe.string(),result:Oe.boolean(),relevantElements:Oe.array(Oe.number()).optional()});import{z as Fn}from"zod";var ef=Fn.object({id:Fn.string().uuid(),skipped:Fn.boolean().optional(),envKey:Fn.string().optional().describe("key in the environment to save the result of this step to")}),Fu=ef.merge(Eo).extend({type:Fn.literal("REQUEST")}),Bu=ef.merge(ls).extend({type:Fn.literal("JAVASCRIPT")}),zu=Fn.discriminatedUnion("type",[Bu,Fu]);import{z as Xt}from"zod";import{z as Bn}from"zod";var k_=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,nn=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 Rs=Bn.string().min(1).max(255).superRefine((r,e)=>{try{Hu(r)}catch(t){return e.addIssue({code:Bn.ZodIssueCode.custom,message:t.message,fatal:!0}),Bn.NEVER}});function Hu(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(k_))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Cs=Bn.preprocess(r=>r===null?"":r,Bn.union([Bn.string().url(),Bn.literal("")])).optional();var tf=Xt.object({id:Xt.string(),name:Rs,description:Xt.string().optional().nullish(),baseUrl:Cs.nullish(),schemaVersion:Xt.string(),advanced:Xt.unknown().optional(),retries:Xt.number(),envs:Xt.array(Ts).nullish(),parameters:Es.nullish()}),D_=Xt.object({createdAt:Xt.coerce.date(),updatedAt:Xt.coerce.date(),schedule:Oo.nullish(),notification:Lo.nullish(),createdBy:Xt.string(),organizationId:Xt.string()}),U_=tf.merge(D_),MW=U_.extend({steps:zu.array()}),PW=tf.extend({steps:zu.array()});import{z as xt}from"zod";var rf=xt.object({startedAt:xt.coerce.date(),finishedAt:xt.coerce.date(),status:xt.nativeEnum(Ze),message:xt.string().optional(),data:xt.unknown().optional()}),F_=rf.merge(Bu).extend({type:xt.literal("JAVASCRIPT")}),B_=rf.merge(Fu).extend({type:xt.literal("REQUEST")}),z_=xt.discriminatedUnion("type",[F_,B_]),nf=xt.object({startedAt:xt.coerce.date(),finishedAt:xt.coerce.date().nullish(),status:xt.nativeEnum(be),results:z_.array(),failureReason:xt.string().nullish(),failureDetails:fs.nullish()});import{z as _t}from"zod";var H_=_t.object({id:_t.string(),organizationId:_t.string(),createdAt:_t.coerce.date(),updatedAt:_t.coerce.date(),createdBy:_t.string(),scheduledAt:_t.coerce.date().nullish(),startedAt:_t.coerce.date().nullish(),finishedAt:_t.coerce.date().nullish(),status:_t.nativeEnum(be),trigger:_t.nativeEnum(Kt),results:nf.array().nullish(),apiTestName:_t.string().nullish(),apiTestPath:_t.string().nullish(),apiTestId:_t.string().nullish()}),zW=H_.pick({status:!0,startedAt:!0,finishedAt:!0});var Wi=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(Wi||{}),of=3;function G_(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function Gu(r){if(!G_(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 ju(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return of;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 xs=class{trackStepExecution(){}async flush(){}};import{parseString as j_,splitCookiesString as V_}from"set-cookie-parser";import{z as Se}from"zod";var Vu=Se.object({name:Se.string(),value:Se.string(),url:Se.string().optional(),domain:Se.string().optional(),path:Se.string().optional(),expires:Se.number().default(Date.now()/1e3+60*60*24*365),httpOnly:Se.boolean().optional(),secure:Se.boolean().default(!0),sameSite:Se.union([Se.literal("Strict"),Se.literal("Lax"),Se.literal("None")]).default("None")});function _s(r,e){let t=[],n=V_(r);for(let o of n){let i=j_(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 s=Vu.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(s);let c=[s.name,...Object.keys(s)].map(u=>u.toLowerCase()),l=o.match(/\b(\S+)=([^;]*)/g);if(l)for(let u of l){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...s,name:d,value:p})}}return t}var $_=Se.object({origin:Se.string(),localStorage:Se.array(Se.object({name:Se.string(),value:Se.string()}))}),W_=Se.object({entries:Se.record(Se.string(),Se.array(Se.tuple([Se.unknown(),Se.unknown()]))),version:Se.number().optional()}),af=Se.object({cookies:Vu.array().optional(),origins:$_.array().optional(),idb:Se.record(Se.string(),W_).optional().describe("key is db name")});function Ms(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Vu.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 dM from"zod";import{v4 as cq}from"uuid";import{z as G}from"zod";import*as Ae from"zod";var sf=Ae.object({requiredText:Ae.string().optional(),requiredAttributes:Ae.record(Ae.string(),Ae.string()).optional(),requiredBounds:Ae.boolean().optional()}),q_=Ae.object({xPath:Ae.string(),requirements:sf.optional()}),K_=Ae.object({type:Ae.literal("NATIVE"),bounds:Ae.number().array(),resolvedDescription:Ae.string(),xPath:Ae.string(),elementOnlySerializedXml:Ae.string(),requirements:sf.optional(),requiredRelatedElements:q_.array().optional()}),Y_=Ae.object({type:Ae.literal("WEBVIEW"),resolvedDescription:Ae.string(),xPath:Ae.string(),browserCache:Xr.optional()}),Ps=Ae.discriminatedUnion("type",[K_,Y_]);var zn=(m=>(m.AI_CHECK="AI_CHECK",m.TAP="TAP",m.TYPE="TYPE",m.PRESS="PRESS",m.PRESS_KEYBOARD="PRESS_KEYBOARD",m.OPEN_APP="OPEN_APP",m.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",m.SWIPE="SWIPE",m.JAVASCRIPT="JAVASCRIPT",m.REQUEST="REQUEST",m.WAIT="WAIT",m.ADD_FILE="ADD_FILE",m.ADB="ADB",m.STATE="STATE",m))(zn||{}),$u=(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))($u||{}),Wu=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(Wu||{}),lf=G.object({type:G.literal("description"),description:G.string()}),X_=G.object({type:G.literal("coordinates"),xPercent:G.number(),yPercent:G.number()}),cf=G.discriminatedUnion("type",[lf,X_]),J_=G.object({updatedAt:G.coerce.date().optional()}),Mt=G.object({id:G.string().uuid(),disableCache:G.boolean().optional()}),Z_=Mt.extend({type:G.literal("STATE")}),uf=J_.extend({target:Ps}),Q_=Mt.extend({type:G.literal("AI_CHECK"),assertion:G.string(),timeoutSecs:G.number().optional()}),qu=Mt.extend({type:G.literal("TAP"),target:cf,cache:uf.optional(),longPress:G.boolean().optional(),longPressDurationMs:G.number().optional(),doubleTap:G.boolean().optional(),doubleTapDelayMs:G.number().optional(),relativePosition:G.object({x:G.number(),y:G.number()}).optional()}),Ku=Mt.extend({type:G.literal("TYPE"),target:cf.optional(),cache:uf.optional(),keyPressDelayMs:G.number().optional(),text:G.string(),clearContent:G.boolean().optional()}),eM=Mt.extend({type:G.literal("PRESS"),key:G.nativeEnum($u),longPress:G.boolean().optional()}),tM=Mt.extend({type:G.literal("PRESS_KEYBOARD"),key:G.nativeEnum(Wu)}),rM=Mt.extend({type:G.literal("OPEN_APP"),packageName:G.string(),activityName:G.string().optional()}),nM=Mt.extend({type:G.literal("OPEN_NOTIFICATION_DRAWER")}),oM=G.discriminatedUnion("type",[G.object({type:G.literal("SCREEN")}),G.object({type:G.literal("OPEN_APP")}),G.object({type:G.literal("CUSTOM"),target:lf})]),iM=Mt.extend({type:G.literal("SWIPE"),direction:G.enum(["up","down","left","right"]),scrollableElement:oM,viewportPercent:G.number().optional(),durationMs:G.number().optional()}),aM=Mt.extend({type:G.literal("JAVASCRIPT"),code:G.string(),timeout:G.number().int().max(60).optional().describe("Max seconds for the code to complete")}),sM=Mt.extend({type:G.literal("REQUEST")}).merge(Eo),lM=Mt.extend({type:G.literal("WAIT"),timeoutSecs:G.number()}),cM=Mt.extend({type:G.literal("ADB"),command:G.string(),jsonArgs:G.string().optional()}),uM=Mt.extend({type:G.literal("ADD_FILE"),file:G.string(),storageLocation:G.string()}),df=G.discriminatedUnion("type",[Q_,qu,Ku,eM,rM,nM,tM,iM,aM,sM,lM,uM,cM,Z_]);var Yu=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var pf={type:!0,cache:!0},on=dM.discriminatedUnion("type",[qu.pick(pf),Ku.pick(pf)]),pM=Object.values(zn).filter(r=>on.options.some(e=>e.shape.type.safeParse(r).success));function Is(r){return pM.includes(r.type)}var mf=ki(on),gf=Di(on),yq=gs(on);import{cloneDeep as qi}from"lodash-es";import hf from"truncate-json";var mM="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",gM=[kn,Po],ff=[kn,Po],No=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[kn],o=e.env[Po],i={};for(let[s,c]of Object.entries(e.env))ff.includes(s)||(t??{})[s]===void 0&&(i[s]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=qi(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){gM.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[kn]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return qi(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>ff.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,mM]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=hf(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=hf(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=qi(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable(kn,e.envName),e.testName&&this.setMomenticSystemVariable(Po,e.testName)}getDynamicVariablesCopy(){return qi(this.env)}getVariablesFromEnvironmentCopy(){return qi(this.varsFromMomenticEnvironment)}};var Ki=(t=>(t.USWest1="us-west1",t.EUNorth1="eu-north1",t))(Ki||{});import $e from"zod";import{z as sr}from"zod";import{z as Le}from"zod";var ar=Le.object({id:Le.string(),name:Rs,baseUrl:Cs,description:Le.string().optional().nullish(),schemaVersion:Le.string(),advanced:Gi,retries:Le.number(),envs:Le.array(Ts).nullish(),parameters:Es.nullish(),disabled:Le.boolean().optional(),labels:Le.array(Le.string()).optional().catch([])}),Mq=Le.enum(["INHERIT","ENABLED","DISABLED"]);var hM=Gi.extend({failureRecovery:Le.boolean().or(Le.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:Le.boolean().or(Le.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var Pq=ar.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:hM}),Iq=ar.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),fM=Le.object({labels:Le.array(Le.string()).optional(),outputs:Ph.nullish()}),ko=ar.merge(fM),SM=Le.object({createdAt:Le.coerce.date(),updatedAt:Le.coerce.date(),updatedBy:Le.string().nullable(),schedule:Oo,notification:Lo,createdBy:Le.string(),organizationId:Le.string(),folderId:Le.string().nullable().optional()}),yM=ar.merge(SM),Oq=yM.merge(In),Os=ar.merge(In),Lq=ar.merge(On);var bM="test",EM="module",TM="mobile-test",vM="mobile-module";var we=(o=>(o.TEST=`momentic/${bM}`,o.MODULE=`momentic/${EM}`,o.MOBILE_TEST=`momentic/${TM}`,o.MOBILE_MODULE=`momentic/${vM}`,o))(we||{}),zq=ar.merge(On),Sf=$t.extend({steps:sr.array(sr.record(sr.string(),sr.unknown())),schemaVersion:sr.string()}),Hq=Sf.extend({fileType:sr.literal(we.MODULE)}),Gq=sr.object({test:sr.string().describe("YAML for the test, including metadata and steps"),modules:sr.record(sr.string(),sr.string()).describe("Map of module name to YAML for the module")});var Xu=$e.object({parameterNames:$e.string().array(),defaultParameters:$e.record($e.string(),$e.string()).optional(),parameterEnums:$e.record($e.string(),$e.string().array()).optional()}),AM=$e.object({moduleId:$e.string().uuid(),name:$e.string(),description:$e.string().nullish(),parameters:Xu.optional(),enabled:$e.boolean().nullish(),schemaVersion:$e.string()}),Yi=AM.omit({name:!0}),Ls=Yi.extend({steps:$e.array($e.record($e.string(),$e.unknown()))}),wM=$e.object({fileType:$e.literal(we.MOBILE_MODULE)}).merge(Ls);import Pt from"zod";var lr=(t=>(t.PRESET="MOBILE_PRESET_STEP",t.MODULE="MOBILE_MODULE_STEP",t))(lr||{}),Ns=Pt.object({id:Pt.string().uuid(),envKey:Pt.string().optional(),skipped:Pt.boolean().optional()}),Xi=Ns.extend({type:Pt.literal("MOBILE_PRESET_STEP"),command:df,keyPressDelayMs:Pt.number().optional()}),Do=Pt.object({moduleId:Pt.string(),inputs:Pt.record(Pt.string(),Pt.string()).optional(),parameters:Xu.optional()}),Ji=Ns.merge(Do.extend({type:Pt.literal("MOBILE_MODULE_STEP")})),Xq=Do.extend({steps:Pt.lazy(()=>cr.array())}),cr=Pt.discriminatedUnion("type",[Xi,Ji]);import We from"zod";import ks from"zod";var Ur=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(Ur||{}),RM=Do.extend({steps:ks.lazy(()=>Zi.array()),name:ks.string().describe("name of the module")}),CM=Ns.merge(RM).extend({type:ks.literal("RESOLVED_MOBILE_MODULE")}),Zi=ks.discriminatedUnion("type",[CM,Xi]);function yf(r){return Object.values(Ur).includes(r)||Object.values(lr).includes(r)}var xM=We.object({disableMomenticAccessibilityTree:We.boolean().optional(),autoGrantPermissions:We.boolean().optional()}),Ju=xM.extend({region:We.nativeEnum(Ki).optional()}),Qi=We.object({retries:We.number().optional().describe("number of retries to run"),defaultChannel:We.string().optional().describe("default channel to use"),defaultTag:We.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:We.string().optional(),emulator:Ju.optional()}),br=We.object({id:We.string().uuid(),description:We.string(),schemaVersion:We.string(),settings:Qi.optional()}),_M=br.merge(We.object({steps:We.array(cr)})),Ds=We.object({fileType:We.literal(we.MOBILE_TEST)}).merge(_M),u2=We.object({name:We.string(),steps:We.array(cr).optional(),settings:Qi.optional()}),MM=br.extend({steps:Zi.array()});import ce from"zod";var an=ce.object({startTime:ce.number(),endTime:ce.number().optional(),durationMs:ce.number().optional(),error:ce.string().optional(),result:ce.unknown().optional(),attributes:ce.record(ce.string(),ce.unknown())});var PM=an.extend({type:ce.literal("SECTION"),name:ce.string(),subSpans:ce.lazy(()=>Zu.array())}),IM=an.extend({type:ce.literal("AI_LOCATOR_CALL"),result:ce.object({id:ce.number(),thoughts:ce.string()}).optional()}),OM=an.extend({type:ce.literal("AI_ASSERTION_CALL"),result:ce.object({thoughts:ce.string(),result:ce.boolean()}).optional()}),LM=an.extend({type:ce.literal("TARGET_RESOLUTION"),result:ce.object({serializedElement:ce.string()}).optional()}),NM=an.extend({type:ce.literal("WAIT_FOR_STABILITY"),reason:ce.string()}),kM=an.extend({type:ce.literal("EMULATOR_INTERACTION"),name:ce.string(),withinWebview:ce.boolean().optional()}),DM=an.extend({type:ce.literal("EMULATOR_READ_STATE"),name:ce.string()}),UM=an.extend({type:ce.literal("GENERIC"),name:ce.string()}),Zu=ce.discriminatedUnion("type",[PM,IM,OM,LM,NM,kM,DM,UM]);import ur from"zod";var bf=ur.object({message:ur.string().optional(),startTime:ur.number(),endTime:ur.number(),status:ur.nativeEnum(Ze),trace:ur.unknown(),beforeSnapshot:ur.string().optional(),afterSnapshot:ur.string().optional(),data:ur.unknown().optional().describe("output data from the step")}),FM=bf.merge(Xi),BM=bf.merge(Ji).extend({steps:ur.lazy(()=>dr.array())}),dr=ur.discriminatedUnion("type",[FM,BM]);var B2=new Set(Object.values(st));var zM={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"},z2={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:[]},H2={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."},G2={AI_CHECK:"AI check",RESOLVED_MOBILE_MODULE:"Module",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",SWIPE:"Swipe",OPEN_APP:"Open app",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",JAVASCRIPT:"JavaScript",REQUEST:"API request",WAIT:"Wait",ADD_FILE:"Add file",ADB:"ADB command",STATE:"Debug state"},j2={AI_CHECK:"Ask AI to verify whether something is true on the screen.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests.",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.",SWIPE:"Swipe on the screen.",OPEN_APP:"Open an app on the device.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a specified amount of time.",ADD_FILE:"Add a file to the device's disk.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device."};import HM from"semver";import{z as GM}from"zod";var q2=GM.string().refine(r=>HM.valid(r),{message:"must be a valid semver string"});import{Faker as X2,en as J2}from"@faker-js/faker";import{z as N}from"zod";var Q2=N.object({body:N.string(),to:N.string(),from:N.string()}),eK=N.object({from:N.string().optional(),to:N.string(),timeout:N.number().optional(),beforeDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional()}),tK=N.object({to:N.string().email(),from:N.string(),subject:N.string(),body:N.string(),html:N.string().optional()}),rK=N.object({inbox:N.string().transform(r=>r.toLowerCase()),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),timeout:N.number().optional(),trimWhitespace:N.boolean().optional()}),nK=N.object({inbox:N.string(),limit:N.number().optional(),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),trimWhitespace:N.boolean().optional()});var Us=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(Us||{}),Ef=N.object({body:N.string().nullish(),status:N.number().optional(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}),jM=N.object({url:N.string(),options:N.object({method:N.string(),body:N.string().nullish(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}).optional()}).optional(),VM=N.object({body:N.string().nullish(),options:N.object({status:N.number(),statusText:N.string().optional(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}).optional()}).optional(),Tf=N.object({result:N.unknown(),variableUpdates:N.record(N.string(),N.unknown()).optional(),persistentVariableUpdates:N.record(N.string(),N.unknown()).optional(),error:N.string().optional(),success:N.boolean()}),oK=N.object({id:N.string().optional(),orgId:N.string(),momenticLambdaAuthHash:N.string(),code:N.string(),fragment:N.boolean(),state:N.object({env:N.record(N.string(),N.unknown()),request:jM,response:VM,additionalBindings:N.record(N.string(),N.unknown()).optional()}),timeoutMs:N.number().optional(),disallowVariableUpdates:N.boolean().optional(),responseSerialization:N.nativeEnum(Us).optional()}),sn=15e3;import*as ht from"zod";import{extendZodWithOpenApi as $M}from"zod-openapi";$M(ht);var WM=ht.object({url:ht.string(),lineNumber:ht.number(),columnNumber:ht.number()}).openapi({ref:"CodeLocation"}),Fs=ht.object({timestamp:ht.number(),text:ht.string(),type:ht.string(),tabIndex:ht.number(),args:ht.unknown().array().optional(),url:ht.string().optional(),location:WM.optional()}).openapi({ref:"ConsoleLog"}),vf=Fs.array(),qM=vf.array();import*as Qu from"zod";import{extendZodWithOpenApi as mP}from"zod-openapi";import{z as M}from"zod";var KM=M.object({name:M.string(),version:M.string(),comment:M.string().optional()}),YM=M.object({name:M.string(),version:M.string(),comment:M.string().optional()}),XM=M.object({onContentLoad:M.number().optional(),onLoad:M.number().optional(),comment:M.string().optional()}),wf=M.object({startedDateTime:M.string(),id:M.string(),title:M.string().optional(),pageTimings:XM,comment:M.string().optional()}),JM=M.array(wf),ZM=M.object({name:M.string(),value:M.string(),path:M.string().optional(),domain:M.string().optional(),expires:M.string().optional(),httpOnly:M.boolean().optional(),secure:M.boolean().optional(),comment:M.string().optional()}),Rf=M.array(ZM),QM=M.object({name:M.string(),value:M.string(),comment:M.string().optional()}),Cf=M.array(QM),eP=M.object({name:M.string(),value:M.string(),comment:M.string().optional()}),tP=M.array(eP),rP=M.object({name:M.string(),value:M.string().optional(),fileName:M.string().optional(),contentType:M.string().optional(),comment:M.string().optional()}),nP=M.array(rP),oP=M.object({mimeType:M.string(),params:nP,text:M.string(),comment:M.string().optional()}),iP=M.object({method:M.string(),url:M.string(),httpVersion:M.string().optional(),cookies:Rf,headers:Cf,queryString:tP,postData:oP.optional(),headersSize:M.number().optional(),bodySize:M.number().optional(),comment:M.string().optional()}),aP=M.object({size:M.number().optional(),compression:M.number().optional(),mimeType:M.string().optional(),text:M.string().optional(),encoding:M.string().optional(),comment:M.string().optional()}),sP=M.object({status:M.number(),statusText:M.string(),httpVersion:M.string().optional(),cookies:Rf,headers:Cf,content:aP,redirectURL:M.string().optional(),headersSize:M.number().optional(),bodySize:M.number().optional(),comment:M.string().optional(),_mocked:M.boolean().optional()}),Af=M.object({expires:M.string().optional(),lastAccess:M.string(),eTag:M.string(),hitCount:M.number(),comment:M.string().optional()}),lP=M.object({beforeRequest:Af.optional(),afterRequest:Af.optional(),comment:M.string().optional()}),cP=M.object({blocked:M.number().optional(),dns:M.number().optional(),connect:M.number().optional(),send:M.number(),wait:M.number(),receive:M.number(),ssl:M.number().optional(),comment:M.string().optional()}),xf=M.object({pageref:M.string().optional(),startedDateTime:M.string(),time:M.number().optional(),request:iP,response:sP.optional(),cache:lP.optional(),timings:cP,serverIPAddress:M.string().optional(),connection:M.string().optional(),comment:M.string().optional(),_resourceType:M.string().optional()}),uP=M.array(xf),dP=M.object({version:M.string().default("1.1"),creator:KM.optional(),browser:YM.optional(),pages:JM.optional(),entries:uP,comment:M.string().optional()}),pP=M.object({log:dP}),_f=M.record(M.string(),wf),Mf=M.record(M.string(),xf);mP(Qu);var gP=Qu.object({logsPerPage:Fs.array().array(),harPages:_f.optional(),harEntries:Mf.optional()}).openapi({ref:"DebugData"});var _=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(Te))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}}},Uo=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},ln=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
|
|
2
|
+
var Sx=Object.defineProperty;var ze=(r,e)=>()=>(r&&(e=r(r=0)),e);var yx=(r,e)=>{for(var t in e)Sx(r,t,{get:e[t],enumerable:!0})};var mT,hT=ze(()=>{"use strict";mT=typeof globalThis=="object"?globalThis:global});var gT=ze(()=>{"use strict";hT()});var fT=ze(()=>{"use strict";gT()});var Jr,Up=ze(()=>{"use strict";Jr="1.9.0"});function O0(r){var e=new Set([r]),t=new Set,n=r.match(ST);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(s){return t.add(s),!1}function a(s){return e.add(s),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var l=c.match(ST);if(!l)return i(c);var u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[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 ST,yT,bT=ze(()=>{"use strict";Up();ST=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;yT=O0(Jr)});function ni(r,e,t,n){var o;n===void 0&&(n=!1);var i=Ca[Ra]=(o=Ca[Ra])!==null&&o!==void 0?o:{version:Jr};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!==Jr){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Jr);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Jr+"."),!0}function Zr(r){var e,t,n=(e=Ca[Ra])===null||e===void 0?void 0:e.version;if(!(!n||!yT(n)))return(t=Ca[Ra])===null||t===void 0?void 0:t[r]}function oi(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Jr+".");var t=Ca[Ra];t&&delete t[r]}var L0,Ra,Ca,xa=ze(()=>{"use strict";fT();Up();bT();L0=Jr.split(".")[0],Ra=Symbol.for("opentelemetry.js.api."+L0),Ca=mT});function _a(r,e,t){var n=Zr("diag");if(n)return t.unshift(e),n[r].apply(n,k0([],N0(t),!1))}var N0,k0,ET,TT=ze(()=>{"use strict";xa();N0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},k0=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))},ET=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 _a("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return _a("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return _a("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return _a("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return _a("verbose",this._namespace,e)},r}()});var Ne,zl=ze(()=>{"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"})(Ne||(Ne={}))});function vT(r,e){r<Ne.NONE?r=Ne.NONE:r>Ne.ALL&&(r=Ne.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",Ne.ERROR),warn:t("warn",Ne.WARN),info:t("info",Ne.INFO),debug:t("debug",Ne.DEBUG),verbose:t("verbose",Ne.VERBOSE)}}var AT=ze(()=>{"use strict";zl()});var D0,U0,F0,Dr,Ma=ze(()=>{"use strict";TT();AT();zl();xa();D0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},U0=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))},F0="diag",Dr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=Zr("diag");if(s)return s[o].apply(s,U0([],D0(i),!1))}}var t=this,n=function(o,i){var a,s,c;if(i===void 0&&(i={logLevel:Ne.INFO}),o===t){var l=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=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof i=="number"&&(i={logLevel:i});var u=Zr("diag"),d=vT((s=i.logLevel)!==null&&s!==void 0?s:Ne.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 ni("diag",d,t,!0)};t.setLogger=n,t.disable=function(){oi(F0,t)},t.createComponentLogger=function(o){return new ET(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 wT,RT=ze(()=>{"use strict";wT=Symbol("BaggageEntryMetadata")});function Fp(r){return typeof r!="string"&&(B0.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:wT,toString:function(){return r}}}var B0,CT=ze(()=>{"use strict";Ma();RT();B0=Dr.instance()});function Bp(r){return Symbol.for(r)}var z0,zp,Hp=ze(()=>{"use strict";z0=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}(),zp=new z0});function Vp(){return jp}var ao,H0,Hl,G0,j0,V0,$0,Gp,W0,q0,K0,jp,Y0,X0,J0,Z0,Q0,ek,tk,$p=ze(()=>{"use strict";ao=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)}}(),H0=function(){function r(){}return r.prototype.createGauge=function(e,t){return X0},r.prototype.createHistogram=function(e,t){return J0},r.prototype.createCounter=function(e,t){return Y0},r.prototype.createUpDownCounter=function(e,t){return Z0},r.prototype.createObservableGauge=function(e,t){return ek},r.prototype.createObservableCounter=function(e,t){return Q0},r.prototype.createObservableUpDownCounter=function(e,t){return tk},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),Hl=function(){function r(){}return r}(),G0=function(r){ao(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Hl),j0=function(r){ao(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Hl),V0=function(r){ao(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Hl),$0=function(r){ao(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Hl),Gp=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),W0=function(r){ao(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Gp),q0=function(r){ao(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Gp),K0=function(r){ao(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Gp),jp=new H0,Y0=new G0,X0=new V0,J0=new $0,Z0=new j0,Q0=new W0,ek=new q0,tk=new K0});var zt,xT=ze(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(zt||(zt={}))});var rk,nk,_T,MT=ze(()=>{"use strict";Hp();rk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},nk=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))},_T=function(){function r(){}return r.prototype.active=function(){return zp},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,nk([n],rk(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var ok,ik,Wp,ak,PT,IT=ze(()=>{"use strict";MT();xa();Ma();ok=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ik=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))},Wp="context",ak=new _T,PT=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return ni(Wp,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,ik([e,t,n],ok(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Zr(Wp)||ak},r.prototype.disable=function(){this._getContextManager().disable(),oi(Wp,Dr.instance())},r}()});var ii,OT=ze(()=>{"use strict";IT();ii=PT.getInstance()});var V,LT=ze(()=>{"use strict";Ma();V=Dr.instance()});var sk,NT,kT=ze(()=>{"use strict";$p();sk=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return jp},r}(),NT=new sk});var qp,DT,UT=ze(()=>{"use strict";kT();xa();Ma();qp="metrics",DT=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return ni(qp,e,Dr.instance())},r.prototype.getMeterProvider=function(){return Zr(qp)||NT},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){oi(qp,Dr.instance())},r}()});var Gl,FT=ze(()=>{"use strict";UT();Gl=DT.getInstance()});var Ce=ze(()=>{"use strict";CT();Hp();zl();$p();xT();OT();LT();FT()});import{Argument as ng,Command as nG,Option as oG}from"@commander-js/extra-typings";import Ax from"appium";import{tmpdir as wx}from"os";import{remote as Rx}from"webdriverio";import{createInstanceClient as bx}from"@limrun/api";import{execSync as Ex}from"child_process";import{hostname as Tx}from"os";import vx from"path";async function og(r){let{apiClient:e,logger:t,creationOpts:n,onStatusUpdate:o,logLevel:i}=r,{token:a,webRtcUrl:s,adbUrl:c,name:l,apkDownloadUrl:u,region:d}=await e.createAndroidEmulator({...n,hostname:Tx()}),p;try{Ex("adb --version"),p="adb"}catch{if(process.env.ANDROID_HOME)p=vx.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:l,apkToInstall:n.apkToInstall,region:d,apkDownloadUrl:u},"Android instance creation ok");let h=await bx({adbUrl:c,endpointUrl:s,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 g=n.apkToInstall?.channel,f=n.apkToInstall?.tag;o(`Installing APK${g?` with channel ${g}`:""}${f?` and tag ${f}`:""}`),await Promise.all(m.map(S=>h.sendAsset(S))),o("Starting tunnel");let E=await h.startAdbTunnel();return{port:E.address.port,close:E.close,token:a,webRtcUrl:s,emulatorName:l}}async function Ss({onStatusUpdate:r,creationOpts:e,apiClient:t,logger:n,driverLogLevel:o,appiumPort:i,socket:a}){let s=Date.now(),{close:c,port:l,limbarToken:u,limbarUrl:d,emulatorName:p}=await _x({apiClient:t,logger:n,creationOpts:e,onStatusUpdate:r}),h=[()=>t.deleteAndroidEmulator(p),c],m=async()=>{for(let f=h.length-1;f>=0;f-=1)try{await h[f]()}catch(E){if(E instanceof Error&&E.message.includes("ECONNREFUSED"))return;n.warn({err:E},"Error running cleanup task")}},g=async()=>{if(a&&!a.connected)throw await m(),new Error("Client disconnected before Appium driver could be started")};await g();try{let f=await Cx({logger:n,driverLogLevel:o,appiumPort:i,port:l,limbarStart:s,emulatorName:p,apiClient:t,onStatusUpdate:r,creationOpts:e});return h.push(f.appiumClose),h.push(async()=>f.driver.deleteSession()),await g(),{...f,emulatorName:p,limbarToken:u,limbarUrl:d,adbTunnelPort:l,cleanup:m,appiumPort:i}}catch(f){throw await m(),new Error(`Failed to start Appium driver: ${f}`)}}async function Cx({logger:r,driverLogLevel:e="warn",port:t,limbarStart:n,emulatorName:o,appiumPort:i}){let a=Date.now(),{close:s,logFile:c}=await xx({logger:r,logLevel:e,appiumPort:i}),l={platformName:"Android","appium:automationName":"UiAutomator2","appium:deviceName":"Android","appium:udid":`127.0.0.1:${t}`,"appium:adbExecTimeout":3e4,"appium:newCommandTimeout":600,"appium:skipDeviceInitialization":!0,"appium:skipServerInstallation":!0,"appium:androidInstallTimeout":6e4,"appium:autoWebview":!1,"appium:autoWebviewTimeout":0,"appium:clearDeviceLogsOnStart":!0},u={hostname:"localhost",port:i,logLevel:e,capabilities:l,connectionRetryTimeout:3e4,connectionRetryCount:2},d=Date.now(),p=await Rx(u);await p.updateSettings({enableMultiWindows:!0});let h=new Map;return p.on("command",m=>{h.set(m.command,Date.now())}),p.on("result",m=>{let g=h.get(m.command);if(!g)return;let f=Date.now()-g;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"),h.delete(m.command)}),r.info({timings:{limbarDuration:a-n,appiumDuration:d-a,wdioDuration:Date.now()-d},capabilities:l,emulatorName:o},"Started Appium driver"),{driver:p,appiumClose:s,appiumPort:i,appiumLogFile:c}}async function xx({logger:r,logLevel:e,appiumPort:t}){let n=`${wx()}/appium-port-${Date.now()}.log`,o=await Ax.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 _x({apiClient:r,logger:e,onStatusUpdate:t,creationOpts:n}){let{close:o,port:i,token:a,webRtcUrl:s,emulatorName:c}=await og({apiClient:r,logger:e,creationOpts:n,onStatusUpdate:t});return{port:i,close:o,limbarToken:a,limbarUrl:s,emulatorName:c}}import ig from"crypto";import Mx from"fs";async function ys({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await Mx.promises.readFile(t),a=ig.createHash("md5").update(i).digest("base64"),s=ig.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===s)){o.info({channel:e,tag:r,md5:a,md5Hex:s},`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 l=await fetch(c.uploadUrl,{headers:{"Content-Length":i.length.toString(),"Content-Type":"application/octet-stream"},method:"PUT",body:i});if(l.status!==200)throw new Error(`Got error response from emulator platform: ${l.status} ${await l.text()}`);o.info({channel:e,tag:r,md5:a},`Asset ${t} was uploaded successfully!`);return}catch(l){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:l},"Failed to upload asset"),l}}throw new Error(`No upload URL was given for asset ${t}`)}import{execSync as Xy}from"child_process";import{existsSync as GO}from"fs";import{platform as Jy}from"os";import{dirname as jO,join as VO,resolve as $O}from"path";import{z as ag}from"zod";var _G=ag.object({input:ag.string()});import{z as rt}from"zod";var IG=rt.object({srcs:rt.array(rt.string()),urls:rt.array(rt.string()),desiredSrc:rt.string().optional(),desiredUrl:rt.string().optional()}),sg=rt.object({srcRegex:rt.string().optional(),urlRegex:rt.string().optional()}),lg=rt.object({x:rt.number(),y:rt.number(),correlation:rt.number()}),OG=rt.object({searchImageBase64String:rt.string(),pageImageBase64String:rt.string(),id:rt.string().uuid(),timeoutMs:rt.number().max(1e4).min(0).optional()});import{z as L}from"zod";import*as F from"zod";import{extendZodWithOpenApi as Px}from"zod-openapi";Px(F);var nn=(s=>(s.AI="AI",s.AI_HEALED="AI_HEALED",s.CLICK_TO_FIND="CLICK_TO_FIND",s.XY_PERCENT="XY_PERCENT",s.RECORDING="RECORDING",s.USER_CSS_SELECTOR="USER_CSS_SELECTOR",s.HEURISTIC_HEALED="HEURISTIC_HEALED",s))(nn||{}),Ix=F.object({mPathSelectorTokens:F.string().array(),frameSrcRegex:F.string().optional(),frameUrlRegex:F.string().optional(),indices:F.number().array()}),Eu=F.object({result:F.number(),traceId:F.string()}).array(),bs=F.object({type:F.literal("GCS_TRACES"),traces:Eu}),cg=F.object({text:F.string().optional(),attributes:F.record(F.string(),F.string()).optional(),boundingBox:F.object({x:F.number(),y:F.number(),width:F.number(),height:F.number()}).optional()}),Ox=F.object({selectors:F.string().array(),requirements:cg.optional()}),on=F.object({id:F.number().int(),dataMomenticId:F.number().int().optional(),selector:F.string().optional(),hybridSelector:F.object({textContent:F.string().nullish(),attributes:F.record(F.string(),F.string().optional()),tagName:F.string(),expandShadowRoot:F.boolean().optional(),classNames:F.string().array(),nthChild:F.number()}).array().optional(),generatedSelectors:F.string().array().optional(),requirements:cg.optional(),additionalElements:Ox.array().optional(),role:F.string().optional(),name:F.string().optional(),numChildren:F.number().optional(),content:F.string().optional(),pathFromRoot:F.string().optional(),serializedHtml:F.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:F.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:F.string().url().optional(),boundingBox:F.object({x:F.number().optional(),y:F.number().optional(),width:F.number(),height:F.number()}).describe("css pixel bounding box").optional(),frameCache:Ix.optional(),inputDescription:F.string().optional().describe("the description that generated this cache"),targetSource:F.nativeEnum(nn).optional(),targetUpdateTime:F.string().optional(),targetUpdateLoggerTags:F.record(F.string(),F.string()).optional(),cacheResolutionUpdateSource:F.string().optional(),cacheResolutionUpdateTime:F.string().optional(),cacheResolutionUpdateLoggerTags:F.record(F.string(),F.string()).optional(),memory:bs.optional()}).openapi({ref:"ElementTargetCache"});function Es(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}var Lx=F.object({type:F.literal("description"),elementDescriptor:F.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),Nx=F.object({x:F.number(),y:F.number()}),kx=F.object({type:F.literal("coordinates"),pixels:Nx}).openapi({ref:"CoordinatesTarget"});function an(r){return r.type==="description"}function Rr(r){return r.type==="coordinates"}var ft=F.discriminatedUnion("type",[Lx,kx]).openapi({ref:"ElementTarget"});function Tu(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function ug(r){return bs.safeParse(r).success}import{v4 as ye}from"uuid";import*as b from"zod";import{extendZodWithOpenApi as jx}from"zod-openapi";import{z as ne}from"zod";import{extendZodWithOpenApi as Dx}from"zod-openapi";import{z as Ni}from"zod";import dg from"zod";var Li=dg.object({updatedAt:dg.coerce.date().optional()});var vu=Ni.object({result:Ni.boolean(),traceId:Ni.string()}).array(),Au=Ni.object({type:Ni.literal("GCS_TRACES"),traces:vu}),wu=Li.extend({memory:Au.optional()});Dx(ne);var pg=ne.object({plan:ne.string().optional(),evidence:ne.string().optional(),thoughts:ne.string(),result:ne.boolean(),relevantElements:ne.array(ne.number()).optional(),updatedMemory:vu.optional()}),Vr=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Vr||{});var Ux=ne.object({type:ne.literal("ELEMENT_NAME"),negated:ne.boolean().optional(),operation:ne.nativeEnum(Vr),value:ne.string()}).openapi({ref:"ElementNameAssertion"}),Fx=ne.object({type:ne.literal("ELEMENT_STYLE"),negated:ne.boolean().optional(),operation:ne.nativeEnum(Vr),property:ne.string(),value:ne.string()}).openapi({ref:"ElementStyleAssertion"}),Bx=ne.object({type:ne.literal("ELEMENT_CONTENT"),negated:ne.boolean().optional(),operation:ne.nativeEnum(Vr),value:ne.string()}).openapi({ref:"ElementContentAssertion"}),zx=ne.object({type:ne.literal("ELEMENT_ATTRIBUTE"),negated:ne.boolean().optional(),operation:ne.nativeEnum(Vr),attr:ne.string(),value:ne.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Un=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Un||{}),Hx=ne.object({type:ne.literal("ELEMENT_EXISTENCE"),negated:ne.boolean().optional(),condition:ne.nativeEnum(Un).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),mg=ne.discriminatedUnion("type",[Bx,zx,Hx,Ux,Fx]).openapi({ref:"ManualElementAssertion"});var Gx=ne.object({type:ne.literal("CONTENT"),negated:ne.boolean().optional(),value:ne.string()}).openapi({ref:"PageContentAssertion"}),hg=ne.discriminatedUnion("type",[Gx]).openapi({ref:"ManualPageAssertion"});import At from"zod";var Ru=At.discriminatedUnion("type",[At.object({type:At.literal("SUBSTRING"),url:At.string()}),At.object({type:At.literal("GLOB"),glob:At.string()}),At.object({type:At.literal("REGEX"),regex:At.string()}),At.object({type:At.literal("DOMAIN"),domain:At.string()})]),ki=At.object({urlMatcher:Ru,method:At.string().optional()});import{z as Se}from"zod";var _o=Se.object({url:Se.string(),method:Se.union([Se.literal("GET"),Se.literal("POST"),Se.literal("PUT"),Se.literal("DELETE"),Se.literal("PATCH")]),headers:Se.record(Se.string(),Se.string()).optional(),params:Se.record(Se.string(),Se.string()).optional(),body:Se.string().optional(),timeout:Se.number().int().optional().describe("Max seconds to wait for the request to complete")}),gg=Se.object({url:Se.string(),headers:Se.record(Se.string(),Se.string()).optional(),query:Se.string(),variables:Se.string().optional(),timeout:Se.number().int().optional().describe("Max seconds to wait for the request to complete")}),Ts=Se.object({code:Se.string(),fragment:Se.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:Se.union([Se.literal("NODE"),Se.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:Se.number().int().max(60).optional().describe("Max seconds for the code to complete")});var nt=(Y=>(Y.AI_EXTRACT="AI_EXTRACT",Y.AI_ASSERTION="AI_ASSERTION",Y.AUTH_LOAD="AUTH_LOAD",Y.AUTH_SAVE="AUTH_SAVE",Y.BLUR="BLUR",Y.CAPTCHA="CAPTCHA",Y.CLICK="CLICK",Y.COOKIE="COOKIE",Y.COPY="COPY",Y.DIALOG="DIALOG",Y.DRAG="DRAG",Y.ELEMENT_CHECK="ELEMENT_CHECK",Y.FILE_UPLOAD="FILE_UPLOAD",Y.FOCUS="FOCUS",Y.GO_BACK="GO_BACK",Y.GO_FORWARD="GO_FORWARD",Y.HOVER="HOVER",Y.JAVASCRIPT="JAVASCRIPT",Y.LOCAL_STORAGE="LOCAL_STORAGE",Y.MOUSE_DRAG="MOUSE_DRAG",Y.NAVIGATE="NAVIGATE",Y.NEW_TAB="NEW_TAB",Y.PAGE_CHECK="PAGE_CHECK",Y.PASTE="PASTE",Y.PRESS="PRESS",Y.KEY_DOWN="KEY_DOWN",Y.KEY_UP="KEY_UP",Y.REFRESH="REFRESH",Y.REQUEST="REQUEST",Y.GRAPHQL_REQUEST="GRAPHQL_REQUEST",Y.SCROLL_DOWN="SCROLL_DOWN",Y.SCROLL_UP="SCROLL_UP",Y.SCROLL_LEFT="SCROLL_LEFT",Y.SCROLL_RIGHT="SCROLL_RIGHT",Y.SELECT_OPTION="SELECT_OPTION",Y.SWITCH_TAB="TAB",Y.TYPE="TYPE",Y.VISUAL_DIFF="VISUAL_DIFF",Y.WAIT="WAIT",Y.WAIT_FOR_URL="WAIT_FOR_URL",Y.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",Y.AWAIT_LISTENER="AWAIT_LISTENER",Y.RECORD_REQUESTS="RECORD_REQUESTS",Y.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",Y.SET_HEADER="SET_HEADER",Y.MOCK_ROUTE="MOCK_ROUTE",Y.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",Y.OFFLINE_MODE="OFFLINE_MODE",Y.SUCCESS="SUCCESS",Y))(nt||{});jx(b);var q=b.object({thoughts:b.string().optional(),id:b.string().uuid().describe("unique identifier to this step, used for step cache")}),qt=b.object({useSelector:b.boolean().optional(),force:b.boolean().optional(),disableCache:b.boolean().optional().describe("disable element caching for this step"),iframeUrl:b.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Kt=Li.extend({target:on}).optional().openapi({ref:"SingleTargetCache"});function fg(r){return Kt.safeParse(r).success}var vs=b.object({loadTimeout:b.number().int().max(60).optional().describe("Max seconds for the page to load")}),Vx=q.merge(vs).merge(b.object({type:b.literal("NAVIGATE"),url:b.string()})).openapi({ref:"NavigateCommand"}),As=qt.merge(b.object({cache:Kt})),Mo=q.merge(As.merge(b.object({target:ft.optional(),type:b.literal("SCROLL_UP"),deltaY:b.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Po=q.merge(As.merge(b.object({target:ft.optional(),type:b.literal("SCROLL_DOWN"),deltaY:b.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Io=q.merge(As.merge(b.object({target:ft.optional(),type:b.literal("SCROLL_LEFT"),deltaX:b.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Oo=q.merge(As.merge(b.object({target:ft.optional(),type:b.literal("SCROLL_RIGHT"),deltaX:b.number().optional()}))).openapi({ref:"ScrollRightCommand"}),lj=b.discriminatedUnion("type",[Mo,Po,Io,Oo]).openapi({ref:"AllScrollCommands"}),$x=q.merge(b.object({type:b.literal("DIALOG"),action:b.union([b.literal("ACCEPT"),b.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),Wx=q.merge(b.object({type:b.literal("WAIT"),delay:b.number()})).openapi({ref:"WaitCommand"}),qx=b.object({caseInsensitive:b.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:b.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:b.number().int().optional().describe("Max seconds to wait for the URL to match")}),Sg=q.extend({type:b.literal("WAIT_FOR_URL"),matcher:Ru}).merge(qx).openapi({ref:"WaitUrlCommand"}),Kx=q.merge(vs).merge(b.object({type:b.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),Yx=q.merge(b.object({type:b.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),Xx=q.merge(b.object({type:b.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),Jx=q.extend({type:b.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),Zx=q.extend({type:b.literal("AUTH_LOAD"),storageState:b.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),xu=q.merge(qt).extend({type:b.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),Qx=q.extend({type:b.literal("COPY"),value:b.string()}).openapi({ref:"CopyCommand"}),e_=q.extend({type:b.literal("PASTE")}).openapi({ref:"PasteCommand"}),yg=q.merge(Ts).extend({type:b.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Ui=q.merge(qt).extend({type:b.literal("CLICK"),target:ft,doubleClick:b.boolean().optional(),rightClick:b.boolean().optional(),waitForDownload:b.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:b.number().optional(),downloadTimeoutMs:b.number().optional(),cache:Kt,relativePosition:b.object({x:b.number(),y:b.number()}).optional()}).openapi({ref:"ClickCommand"}),bg=Li.extend({fromTarget:on.optional(),toTarget:on.optional()}),Fi=q.merge(qt).merge(b.object({type:b.literal("DRAG"),fromTarget:ft,toTarget:ft,steps:b.number().optional(),hoverSeconds:b.number().optional().describe("Seconds to hover the object before dropping"),cache:bg.optional()})).openapi({ref:"DragCommand"}),Bi=q.merge(qt).merge(b.object({type:b.literal("MOUSE_DRAG"),target:ft.optional(),deltaX:b.string().describe("pixels to move horizontally, can be template"),deltaY:b.string().describe("pixels to move vertically, can be template"),steps:b.number().optional(),cache:Kt})).openapi({ref:"MouseDragCommand"}),zi=q.merge(qt).merge(b.object({type:b.literal("HOVER"),target:ft,cache:Kt})).openapi({ref:"HoverCommand"}),Hi=q.merge(qt).merge(b.object({type:b.literal("FOCUS"),target:ft,cache:Kt})).openapi({ref:"FocusCommand"}),Gi=q.merge(qt).extend({type:b.literal("BLUR"),target:ft.optional(),cache:Kt}).openapi({ref:"BlurCommand"}),t_=b.object({type:b.literal("URL"),url:b.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),r_=b.object({type:b.literal("USER_FILE"),name:b.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),n_=q.extend({type:b.literal("FILE_UPLOAD"),fileSource:b.discriminatedUnion("type",[t_,r_]),filename:b.string().optional()}).openapi({ref:"FileUploadCommand"}),Eg=b.discriminatedUnion("type",[b.object({type:b.literal("VALUE"),value:b.string()}),b.object({type:b.literal("LABEL"),label:b.string()}),b.object({type:b.literal("INDEX"),index:b.coerce.string()})]),ji=q.merge(qt).extend({type:b.literal("SELECT_OPTION"),target:ft,cache:Kt,choice:Eg.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),_u=b.union([b.literal("MULTIMODAL"),b.literal("VISION_ONLY")]),ws=q.merge(b.object({type:b.literal("AI_ASSERTION"),assertion:b.string(),disableCache:b.boolean().optional(),iframeUrl:b.string().optional(),contextChoice:_u.optional(),timeout:b.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:wu.optional()})).openapi({ref:"AIAssertionCommand"}),sn=5,Mu=600,Lo=q.merge(qt).extend({type:b.literal("ELEMENT_CHECK"),target:ft,assertion:mg,cache:Kt.or(wu).optional(),timeout:b.number().int().min(0).max(Mu).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),Tg=q.extend({type:b.literal("PAGE_CHECK"),assertion:hg,iframeUrl:b.string().optional().describe("url or url regex for the iframe"),timeout:b.number().int().min(0).max(Mu).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),vg=q.merge(b.object({type:b.literal("AI_EXTRACT"),goal:b.string(),schema:b.string().optional(),envKey:b.string().optional(),disableCache:b.boolean().optional(),iframeUrl:b.string().optional()})).openapi({ref:"AIExtractCommand"}),o_=b.object({clearContent:b.boolean().optional(),forceClearContent:b.boolean().optional(),delay:b.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:b.boolean().optional(),pressEnter:b.boolean().optional(),relativePosition:b.object({x:b.number(),y:b.number()}).optional()}),Ag=25,Vi=q.merge(qt).merge(o_).extend({type:b.literal("TYPE"),target:ft.optional(),value:b.string(),cache:Kt}).openapi({ref:"TypeCommand"}),i_=q.merge(b.object({type:b.literal("PRESS"),value:b.string(),repeat:b.number().optional(),convertMeta:b.boolean().optional(),delayMs:b.number().optional()})).openapi({ref:"PressCommand"}),a_=q.merge(b.object({type:b.literal("KEY_DOWN"),value:b.string(),convertMeta:b.boolean().optional()})).openapi({ref:"KeyDownCommand"}),s_=q.merge(b.object({type:b.literal("KEY_UP"),value:b.string(),convertMeta:b.boolean().optional()})).openapi({ref:"KeyUpCommand"}),l_=b.object({type:b.literal("SUBSTRING"),substring:b.string()}),c_=b.object({type:b.literal("REGEX"),pattern:b.string()}),u_=b.object({type:b.literal("INDEX"),index:b.coerce.string()}),d_=b.discriminatedUnion("type",[l_,c_,u_]),p_=q.merge(vs).merge(b.object({type:b.literal("TAB"),action:d_})).openapi({ref:"TabCommand"}),wg=q.merge(vs).merge(b.object({type:b.literal("NEW_TAB"),url:b.string()})).openapi({ref:"NewTabCommand"}),m_=q.merge(b.object({type:b.literal("COOKIE"),value:b.string()})).openapi({ref:"CookieCommand"}),h_=q.merge(b.object({type:b.literal("LOCAL_STORAGE"),key:b.string(),value:b.string()})).openapi({ref:"LocalStorageCommand"}),g_=q.extend({type:b.literal("REQUEST")}).merge(_o).openapi({ref:"RequestCommand"}),f_=q.extend({type:b.literal("GRAPHQL_REQUEST")}).merge(gg).openapi({ref:"GraphQLRequestCommand"}),S_=q.merge(b.object({type:b.literal("SUCCESS"),condition:ws.optional()})).openapi({ref:"SuccessCommand"}),Rg=q.merge(b.object({type:b.literal("FAILURE")})).openapi({ref:"FailureCommand"}),y_=b.object({data:b.string().describe("location at which to find a jpg"),width:b.number(),height:b.number()}),$i=q.merge(qt).merge(b.object({type:b.literal("VISUAL_DIFF"),threshold:b.number().optional().describe("default 0.1"),target:ft.optional(),screenshot:y_.optional(),cache:Kt})).openapi({ref:"VisualDiffCommand"}),b_=q.merge(b.object({type:b.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:ki,key:b.string()})).openapi({ref:"RegisterRequestListenerCommand"}),E_=q.merge(b.object({type:b.literal("AWAIT_LISTENER"),key:b.string(),timeout:b.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),T_=q.merge(b.object({type:b.literal("RECORD_REQUESTS"),requestMatcher:ki,key:b.string()})).openapi({ref:"RecordRequestsCommand"}),v_=q.merge(b.object({type:b.literal("GET_RECORDED_REQUESTS"),key:b.string()})).openapi({ref:"GetRecordedRequestsCommand"}),A_=q.merge(b.object({type:b.literal("SET_HEADER"),name:b.string(),value:b.string(),requestMatcher:ki.optional()})).openapi({ref:"SetHeaderCommand"}),w_=q.merge(b.object({type:b.literal("MOCK_ROUTE"),requestMatcher:ki,responseGenerator:b.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:b.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:b.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"})),R_=q.merge(b.object({type:b.literal("REMOVE_ROUTE_MOCK"),key:b.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),C_=q.merge(b.object({type:b.literal("OFFLINE_MODE"),enable:b.boolean()})).openapi({ref:"OfflineModeCommand"}),x_=b.discriminatedUnion("type",[Ui,Vi,i_,a_,s_,ji,Vx,Po,Mo,ws,Yx,zi,Wx]),Pu=b.discriminatedUnion("type",[...x_.options,S_]),Iu=b.discriminatedUnion("type",[...Pu.options,yg,Lo,Tg,wg,Sg,vg]),__=b.discriminatedUnion("type",[vg,Zx,Jx,xu,m_,Qx,$x,Fi,Lo,n_,Xx,yg,h_,Bi,wg,Tg,e_,Kx,g_,f_,Io,Oo,p_,$i,Hi,Gi,Sg,b_,E_,T_,v_,A_,w_,R_,C_]),No=b.discriminatedUnion("type",[...Pu.options,...__.options]).openapi({ref:"Command"}),Rs=b.discriminatedUnion("type",[...Pu.options,Rg]),cj=b.discriminatedUnion("type",[...Iu.options,Rg]);function $r(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:ye(),type:r};break;case"AUTH_LOAD":{e={id:ye(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:ye(),type:r,goal:""};break;case"DIALOG":e={id:ye(),type:r,action:"DISMISS"};break;case"DRAG":e={id:ye(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:ye(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:ye(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:ye(),type:r,delay:1};break;case"BLUR":e={id:ye(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:ye(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:ye(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:ye(),type:r,value:""};break;case"SELECT_OPTION":e={id:ye(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:ye(),type:r,url:""};case"TAB":e={id:ye(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:ye(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:ye(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:ye(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:ye(),type:r,code:""};break;case"AI_ASSERTION":e={id:ye(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:ye(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:ye(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:ye(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:ye(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:ye(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:ye(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:ye(),type:r,key:""};break}case"SET_HEADER":{e={id:ye(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:ye(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:ye(),type:r};break}case"OFFLINE_MODE":{e={id:ye(),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 Cg(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 M_}from"zod";var hj=M_.discriminatedUnion("type",[Gi,xu,Ui,Fi,Hi,zi,Bi,Mo,Po,Io,Oo,ji,Vi,$i,Lo]);import{z as P_}from"zod";import{z as ln}from"zod";function Wi(r){return ln.object({key:ln.string(),testId:ln.string().optional(),moduleId:ln.string().optional(),organizationId:ln.string(),value:r})}function qi(r){return Wi(r).extend({uniqueKey:ln.string()})}function Cs(r){return ln.record(ln.string(),qi(r))}var wt={type:!0,cache:!0},ko=P_.discriminatedUnion("type",[ws.pick(wt),Gi.pick(wt),Ui.pick(wt),Fi.pick(wt),Lo.pick(wt),Hi.pick(wt),zi.pick(wt),Bi.pick(wt),Mo.pick(wt),Po.pick(wt),Io.pick(wt),Oo.pick(wt),ji.pick(wt),Vi.pick(wt),$i.pick(wt)]),Ou=Object.values(nt).filter(r=>ko.options.some(e=>e.shape.type.safeParse(r).success));No.options.forEach(r=>{if("target"in r.shape&&!Ou.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function xg(r){return Ou.includes(r.type)}var _g=Wi(ko),Mg=qi(ko),vj=Cs(ko);import{v4 as vW}from"uuid";import{z as M}from"zod";var Ig=Symbol("Let zodToJsonSchema decide on which parser to use");var Pg={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Og=r=>typeof r=="string"?{...Pg,name:r}:{...Pg,...r};var Lg=r=>{let e=Og(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Lu(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function ue(r,e,t,n,o){r[e]=t,Lu(r,e,n,o)}var xs=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};import{ZodFirstPartyTypeKind as le}from"zod";function De(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?xs(e,r.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as I_}from"zod";function Ng(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==I_.ZodAny&&(t.items=X(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&ue(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&ue(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(ue(t,"minItems",r.exactLength.value,r.exactLength.message,e),ue(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function kg(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ue(t,"minimum",n.value,n.message,e):ue(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),ue(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ue(t,"maximum",n.value,n.message,e):ue(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),ue(t,"maximum",n.value,n.message,e));break;case"multipleOf":ue(t,"multipleOf",n.value,n.message,e);break}return t}function Dg(){return{type:"boolean"}}function _s(r,e){return X(r.type._def,e)}var Ug=(r,e)=>X(r.innerType._def,e);function Nu(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>Nu(r,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return O_(r,e)}}var O_=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":ue(t,"minimum",n.value,n.message,e);break;case"max":ue(t,"maximum",n.value,n.message,e);break}return t};function Fg(r,e){return{...X(r.innerType._def,e),default:r.defaultValue()}}function Bg(r,e){return e.effectStrategy==="input"?X(r.schema._def,e):De(e)}function zg(r){return{type:"string",enum:Array.from(r.values)}}var L_=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function Hg(r,e){let t=[X(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),X(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return t.forEach(i=>{if(L_(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:s,...c}=i;a=c}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function Gg(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}import{ZodFirstPartyTypeKind as Ki}from"zod";var ku,pr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ku===void 0&&(ku=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ku),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ms(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":ue(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":ue(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":mr(t,"email",n.message,e);break;case"format:idn-email":mr(t,"idn-email",n.message,e);break;case"pattern:zod":Rt(t,pr.email,n.message,e);break}break;case"url":mr(t,"uri",n.message,e);break;case"uuid":mr(t,"uuid",n.message,e);break;case"regex":Rt(t,n.regex,n.message,e);break;case"cuid":Rt(t,pr.cuid,n.message,e);break;case"cuid2":Rt(t,pr.cuid2,n.message,e);break;case"startsWith":Rt(t,RegExp(`^${Du(n.value,e)}`),n.message,e);break;case"endsWith":Rt(t,RegExp(`${Du(n.value,e)}$`),n.message,e);break;case"datetime":mr(t,"date-time",n.message,e);break;case"date":mr(t,"date",n.message,e);break;case"time":mr(t,"time",n.message,e);break;case"duration":mr(t,"duration",n.message,e);break;case"length":ue(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),ue(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Rt(t,RegExp(Du(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&mr(t,"ipv4",n.message,e),n.version!=="v4"&&mr(t,"ipv6",n.message,e);break}case"base64url":Rt(t,pr.base64url,n.message,e);break;case"jwt":Rt(t,pr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Rt(t,pr.ipv4Cidr,n.message,e),n.version!=="v4"&&Rt(t,pr.ipv6Cidr,n.message,e);break}case"emoji":Rt(t,pr.emoji(),n.message,e);break;case"ulid":{Rt(t,pr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{mr(t,"binary",n.message,e);break}case"contentEncoding:base64":{ue(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Rt(t,pr.base64,n.message,e);break}}break}case"nanoid":Rt(t,pr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Du(r,e){return e.patternStrategy==="escape"?k_(r):r}var N_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function k_(r){let e="";for(let t=0;t<r.length;t++)N_.has(r[t])||(e+="\\"),e+=r[t];return e}function mr(r,e,t,n){r.format||r.anyOf?.some(o=>o.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):ue(r,"format",e,t,n)}function Rt(r,e,t,n){r.pattern||r.allOf?.some(o=>o.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:jg(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):ue(r,"pattern",jg(e,n),t,n)}function jg(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,o="",i=!1,a=!1,s=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(t.i){if(a){if(n[c].match(/[a-z]/)){s?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),s=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],s=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(t.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
3
|
+
]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
|
|
4
|
+
]))`;continue}}if(t.s&&n[c]==="."){o+=a?`${n[c]}\r
|
|
5
|
+
`:`[${n[c]}\r
|
|
6
|
+
]`;continue}o+=n[c],n[c]==="\\"?i=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return o}function Ps(r,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&r.keyType?._def.typeName===Ki.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,o)=>({...n,[o]:X(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??De(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:X(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===Ki.ZodString&&r.keyType._def.checks?.length){let{type:n,...o}=Ms(r.keyType._def,e);return{...t,propertyNames:o}}else{if(r.keyType?._def.typeName===Ki.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(r.keyType?._def.typeName===Ki.ZodBranded&&r.keyType._def.type._def.typeName===Ki.ZodString&&r.keyType._def.type._def.checks?.length){let{type:n,...o}=_s(r.keyType._def,e);return{...t,propertyNames:o}}}return t}function Vg(r,e){if(e.mapStrategy==="record")return Ps(r,e);let t=X(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||De(e),n=X(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||De(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function $g(r){let e=r.values,n=Object.keys(r.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Wg(r){return r.target==="openAi"?void 0:{not:De({...r,currentPath:[...r.currentPath,"not"]})}}function qg(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Yi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Yg(r,e){if(e.target==="openApi3")return Kg(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in Yi&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((o,i)=>{let a=Yi[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===t.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:t.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return Kg(r,e)}var Kg=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,o)=>X(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function Xg(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:Yi[r.innerType._def.typeName],nullable:!0}:{type:[Yi[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=X(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=X(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function Jg(r,e){let t={type:"number"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"int":t.type="integer",Lu(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ue(t,"minimum",n.value,n.message,e):ue(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),ue(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ue(t,"maximum",n.value,n.message,e):ue(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),ue(t,"maximum",n.value,n.message,e));break;case"multipleOf":ue(t,"multipleOf",n.value,n.message,e);break}return t}function Zg(r,e){let t=e.target==="openAi",n={type:"object",properties:{}},o=[],i=r.shape();for(let s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let l=U_(c);l&&t&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=X(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});u!==void 0&&(n.properties[s]=u,l||o.push(s))}o.length&&(n.required=o);let a=D_(r,e);return a!==void 0&&(n.additionalProperties=a),n}function D_(r,e){if(r.catchall._def.typeName!=="ZodNever")return X(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function U_(r){try{return r.isOptional()}catch{return!0}}var Qg=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return X(r.innerType._def,e);let t=X(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:De(e)},t]}:De(e)};var ef=(r,e)=>{if(e.pipeStrategy==="input")return X(r.in._def,e);if(e.pipeStrategy==="output")return X(r.out._def,e);let t=X(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=X(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(o=>o!==void 0)}};function tf(r,e){return X(r.type._def,e)}function rf(r,e){let n={type:"array",uniqueItems:!0,items:X(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&ue(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&ue(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function nf(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>X(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:X(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>X(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function of(r){return{not:De(r)}}function af(r){return De(r)}var sf=(r,e)=>X(r.innerType._def,e);var lf=(r,e,t)=>{switch(e){case le.ZodString:return Ms(r,t);case le.ZodNumber:return Jg(r,t);case le.ZodObject:return Zg(r,t);case le.ZodBigInt:return kg(r,t);case le.ZodBoolean:return Dg();case le.ZodDate:return Nu(r,t);case le.ZodUndefined:return of(t);case le.ZodNull:return qg(t);case le.ZodArray:return Ng(r,t);case le.ZodUnion:case le.ZodDiscriminatedUnion:return Yg(r,t);case le.ZodIntersection:return Hg(r,t);case le.ZodTuple:return nf(r,t);case le.ZodRecord:return Ps(r,t);case le.ZodLiteral:return Gg(r,t);case le.ZodEnum:return zg(r);case le.ZodNativeEnum:return $g(r);case le.ZodNullable:return Xg(r,t);case le.ZodOptional:return Qg(r,t);case le.ZodMap:return Vg(r,t);case le.ZodSet:return rf(r,t);case le.ZodLazy:return()=>r.getter()._def;case le.ZodPromise:return tf(r,t);case le.ZodNaN:case le.ZodNever:return Wg(t);case le.ZodEffects:return Bg(r,t);case le.ZodAny:return De(t);case le.ZodUnknown:return af(t);case le.ZodDefault:return Fg(r,t);case le.ZodBranded:return _s(r,t);case le.ZodReadonly:return sf(r,t);case le.ZodCatch:return Ug(r,t);case le.ZodPipeline:return ef(r,t);case le.ZodFunction:case le.ZodVoid:case le.ZodSymbol:return;default:return(n=>{})(e)}};function X(r,e,t=!1){let n=e.seen.get(r);if(e.override){let s=e.override?.(r,e,n,t);if(s!==Ig)return s}if(n&&!t){let s=F_(n,e);if(s!==void 0)return s}let o={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,o);let i=lf(r,r.typeName,e),a=typeof i=="function"?X(i(),e):i;if(a&&B_(r,e,a),e.postProcess){let s=e.postProcess(a,r,e);return o.jsonSchema=a,s}return o.jsonSchema=a,a}var F_=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:xs(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),De(e)):e.$refStrategy==="seen"?De(e):void 0}},B_=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var Fn=(r,e)=>{let t=Lg(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:X(u._def,{...t,currentPath:[...t.basePath,t.definitionPath,l]},!0)??De(t)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=X(r._def,o===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,o]},!1)??De(t),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a),t.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[t.openAiAnyTypeName]||(n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));let s=o===void 0?n?{...i,[t.definitionPath]:n}:i:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,o].join("/"),[t.definitionPath]:{...n,[o]:i}};return t.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};import{z as Cr}from"zod";import{extendZodWithOpenApi as z_}from"zod-openapi";z_(Cr);var Re=(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))(Re||{});var Uu=Cr.object({reason:Cr.nativeEnum(Re),previousStepsDescription:Cr.array(Cr.string()).optional(),summary:Cr.string(),rootCause:Cr.string().optional()}).openapi({ref:"TestResultClassification"}),Is=Cr.object({errorMessage:Cr.string(),errorStack:Cr.string().optional(),classification:Uu.optional()}).openapi({ref:"TestFailureDetails"});var _=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(Re))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}}},Do=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},cn=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
|
|
3
7
|
Decisions:
|
|
4
8
|
${this.decisions.map(e=>e.toString()).join(`
|
|
5
|
-
`)}`}};function Pf(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function ed(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 Er=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},Bs=class extends Er{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},zs=class extends Er{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function td(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function rd(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 nd(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 ea=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};import{cloneDeep as hP}from"lodash-es";import{z as Tr}from"zod";var Of=(c=>(c.DisableClickhouseCaches="disable_clickhouse_caches",c.ShowZeroOpacityElements="show_zero_opacity_elements",c.VisualActions="visual_actions",c.RagV2="rag_v2",c.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",c.GlobalLocatorRedirect="global_locator_redirect",c.FakerConstantSeed="faker_constant_seed",c.AutoExpandIframes="auto_expand_iframes",c))(Of||{});var If=Tr.union([Tr.string(),Tr.number(),Tr.boolean(),Tr.null(),Tr.record(Tr.string(),Tr.lazy(()=>If)),Tr.array(Tr.lazy(()=>If))]),Hs=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=hP(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(Of).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")}},YK=new Hs({},{});var od={".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"},Lf=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],JK=Object.keys(od);import*as Nf from"zod";var QK=Nf.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as cn}from"zod";var rY=cn.object({id:cn.string(),name:cn.string(),createdAt:cn.coerce.date(),createdBy:cn.string(),updatedAt:cn.coerce.date(),updatedBy:cn.string().nullable(),organizationId:cn.string()});import{z as L}from"zod";import un from"zod";var Fo=un.object({platformSep:un.string(),fullPathSegments:un.string().array(),relativePathSegments:un.string().array(),relativePath:un.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:un.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:un.coerce.date(),createdAt:un.coerce.date()});var fP=L.array(Fo.extend({id:L.string(),name:L.string(),description:L.string().optional(),labels:L.string().array().optional()})),SP=L.array(Fo.extend({id:L.string(),name:L.string(),description:L.string().optional(),content:Fi})),hY=L.object({tests:fP,modules:SP,labels:L.string().array()}),fY=Os.merge(ko),SY=L.object({schemaVersion:L.string(),stepLists:In}),yY=ko.partial().merge(ar.pick({id:!0})),yP={name:L.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:L.string().optional(),baseUrl:L.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:L.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:L.nativeEnum(tn).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:bs.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:L.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},bY=L.object(yP),EY=Os.merge(L.object({relativeFilePath:L.string().describe("relative to project root")})),TY=L.object({name:L.string()}),vY=L.object({relativeFilePath:L.string()}),AY=L.object({name:L.string()}),wY=L.object({relativeFilePath:L.string()}),RY=L.object({name:L.string(),description:L.string(),enabled:L.boolean(),steps:L.lazy(()=>Je.array()),testFilePath:L.string().describe("relative to the project root"),folderPath:L.string().optional().describe("user selected folder path")}),CY=L.object({name:L.string(),description:L.string(),enabled:L.boolean()}).partial();var xY=L.array(vh),_Y=L.object({defaultEnv:L.string().optional().describe("name of the default env, or undefined to unset")}),MY=L.object({configFilePath:L.string().describe("full path on disk")}),PY=L.string().array(),IY=L.object({message:L.string(),newRelativeTestPath:L.string().optional()}),id=L.object({name:L.string(),absolutePath:L.string(),relativePath:L.string(),pathSegments:L.array(L.string()),isDirectory:L.boolean(),size:L.number(),createdAt:L.coerce.date(),modifiedAt:L.coerce.date(),accessedAt:L.coerce.date()}),kf=L.object({pathSegments:L.array(L.string())}),OY=L.object({absolutePath:L.string(),pathSegments:L.array(L.string()),contents:L.array(id)}),Df=L.object({pathSegments:L.array(L.string())}),Uf=L.object({pathSegments:L.array(L.string()),newPathSegments:L.array(L.string())}),Ff=L.object({pathSegments:L.array(L.string()),recursive:L.boolean().optional()}),LY=L.object({success:L.boolean(),message:L.string(),pathSegments:L.array(L.string()).optional()});var Gs=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],js=Gs.map(r=>`**/${r}/**`),Bf=!0,dn=!1;import vr from"chalk";import bP from"safe-stable-stringify";import EP from"truncate-json";import TP from"zod";var Bo=bP.configure({deterministic:!1});function zf(r){let e=Bo(r),{jsonString:t}=EP(e,1e4);return t}var vP=["app","version","env","namespace","host"];function ye(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!vP.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var $s=TP.enum(["debug","info","warn","error"]);var ta={debug:20,info:30,warn:40,error:50},Ws={20:"debug",30:"info",40:"warn",50:"error"},ad=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=ta[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[s,c]of a){let l=c;c instanceof Error?(l=c.message,console.log(t(` ${s}:`,l)),console.log(t(" stack:",c.stack))):typeof c=="object"?(l=Bo(c,void 0,2),l=l.split(`
|
|
9
|
+
`)}`}};function cf(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function Fu(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 xr=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},Os=class extends xr{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},Ls=class extends xr{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function Bu(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function zu(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 Hu(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 Xi=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};var H_={CLICK:"Click on an element on the page.",TYPE:"Type the specified text into an input on the page.",PRESS:"Press one or more keyboard keys.",KEY_DOWN:"Hold down one or more keyboard keys.",KEY_UP:"Release one or more keyboard keys.",SELECT_OPTION:"Choose an option from a native <select> component. Never use this command for non <select> elements. Instead, use a series of CLICK commands for those.",NAVIGATE:"Go to the specified fully qualified URL.",SCROLL_UP:"Scroll up.",SCROLL_DOWN:"Scroll down.",GO_BACK:"Go back to the previous page.",HOVER:"Hover over an element.",AI_ASSERTION:"Verify a statement about the current page, retrying until it is true. Only generate an assertion if the goal includes language like 'check that', 'verify that', etc..",WAIT:"Wait a fixed amount of seconds."},G_={...H_,JAVASCRIPT:"Execute JavaScript code in NODE or BROWSER environment.",ELEMENT_CHECK:"Perform a manual assertion on a specific element.",PAGE_CHECK:"Perform a manual assertion on the page.",NEW_TAB:"Open a new browser tab with the specified URL.",WAIT_FOR_URL:"Wait for the URL to match a pattern.",AI_EXTRACT:"Extract data from the page and optionally store it in an environment variable."};Iu.options.forEach(r=>{let e=r.shape.type.value;if(e!=="SUCCESS"&&!G_[e])throw new Error(`Command type ${e} is missing a description`)});var j_=M.object({type:M.literal("CLICK"),description:M.string().describe("Description of the element to click in the Current Page. Never click on <select> elements, see SELECT_OPTION."),doubleClick:M.boolean().or(M.null()),rightClick:M.boolean().or(M.null())}),V_=M.object({type:M.literal("TYPE"),description:M.string().describe("Description of the element to type into, which must be an <input>, <textarea>, or contenteditable element."),text:M.string().describe("The text to enter, truncated to 500 characters. If the PM provided text in the goals, use it exactly without modification."),pressEnter:M.boolean().or(M.null()).describe("Press enter after typing (useful for form submissions)."),clearContent:M.boolean().describe("Clear existing content before typing. Disable to append to the existing text.")}),$_=M.object({type:M.literal("GO_BACK")}),W_=M.object({type:M.literal("PRESS"),keys:M.array(M.string()).describe('The keys to press. Only use key names supported by the Playwright press method, such as "a", "ArrowLeft", "Meta", "Control", and "Enter". Multiple keys will be pressed together. Do not suggest platform-specific key combinations, such as CTRL+C.')}),q_=M.object({type:M.literal("SELECT_OPTION"),description:M.string().describe("Description of the <select> element to choose from. Only use this command to interact with native HTML <select> elements. You must use CLICK to select from any other HTML element, such as <input>, <div>, or custom elements."),option:M.discriminatedUnion("type",[M.object({type:M.literal("VALUE"),value:M.string()}),M.object({type:M.literal("LABEL"),label:M.string()}),M.object({type:M.literal("INDEX"),index:M.string().describe("Zero-based index of the option within the select.")})]).describe("Which option to select. Choose 1 of 3 strategies for selecting. By value is exactly matching the 'value' attribute. By label is exactly matching the 'label' attribute. By index is using the zero-based index of the option within the select.")}),K_=M.object({type:M.literal("NAVIGATE"),url:M.string().describe("The URL to navigate to. Only navigate to URLs relevant to the user goal.")}),Y_=M.object({type:M.literal("SCROLL"),y:M.number().describe("Scroll up or down by the specified pixels. Positive values scroll down.")}),X_=M.object({type:M.literal("WAIT"),timeout:M.number().describe("The number of seconds to wait.")}),J_=M.object({type:M.literal("AI_ASSERTION"),assertion:M.string().describe("The assertion to verify. This should be a statement verifiable based on the current page HTML or screenshot. Be specific enough that the assertion is not ambiguous or open to interpretation. Make sure the assertion aligns with what the user intends to verify."),timeout:M.number().describe("The max amount of seconds to wait for the assertion to be true. Respect user wishes but allow no more than 60. If unspecified, choose 5 for quick checks like form status, 10 for page loads, and 30 for actions that explicitly trigger a long time, like image generation.")}),Z_=M.object({type:M.literal("HOVER"),description:M.string().describe("Description of the element to hover over. Prefer elements that have visible bounding boxes according to the screenshot, element class attribute, or child contents.")}),Q_=M.object({type:M.literal("JAVASCRIPT"),code:M.string().describe("JavaScript code to execute. Defaults to NODE environment unless BROWSER is specified."),environment:M.union([M.literal("NODE"),M.literal("BROWSER")]).or(M.null()).describe("Execution environment. Default is NODE."),timeout:M.number().or(M.null()).describe("Max seconds for the code to complete. Max 60 seconds.")}),eM=M.object({type:M.literal("AI_EXTRACT"),goal:M.string().describe("Description of what data to extract from the page. Be specific about what you want to extract and where to find it."),schema:M.string().or(M.null()).describe("JSON schema defining the expected structure of the extracted data."),envKey:M.string().or(M.null()).describe("Environment variable name to store the extracted result in. If provided, the result will be stored and can be referenced later."),iframeUrl:M.string().or(M.null()).describe("URL or URL regex for the iframe to extract data from.")}),tM=M.object({type:M.literal("ELEMENT_CHECK"),description:M.string().describe("Description of the element to check."),assertionType:M.enum(["EXISTS","VISIBLE","CONTENT_CONTAINS","CONTENT_EQUALS"]).describe("The type of assertion. EXISTS checks if element exists, VISIBLE checks if visible, CONTENT_CONTAINS checks if text contains value, CONTENT_EQUALS checks if text equals value."),value:M.string().or(M.null()).describe("The value to check against (required for CONTENT assertions)."),negated:M.boolean().or(M.null()).describe("If true, asserts the opposite (e.g., does NOT exist)."),timeout:M.number().or(M.null()).describe("Max seconds to wait for the assertion to be true.")}),rM=M.object({type:M.literal("PAGE_CHECK"),value:M.string().describe("The text content to check for on the page."),negated:M.boolean().or(M.null()).describe("If true, checks that the content is NOT present."),timeout:M.number().or(M.null()).describe("Max seconds to wait for the assertion to be true.")}),nM=M.object({type:M.literal("NEW_TAB"),url:M.string().describe("The URL to open in the new tab.")}),oM=M.object({type:M.literal("WAIT_FOR_URL"),matcher:M.discriminatedUnion("type",[M.object({type:M.literal("SUBSTRING"),url:M.string()}),M.object({type:M.literal("GLOB"),glob:M.string()}),M.object({type:M.literal("REGEX"),regex:M.string()}),M.object({type:M.literal("DOMAIN"),domain:M.string()})]).describe("How to match the URL."),caseInsensitive:M.boolean().or(M.null()),negated:M.boolean().or(M.null()).describe("Wait for the URL to NOT match instead."),timeout:M.number().or(M.null()).describe("Max seconds to wait for the URL.")}),uf=M.object({type:M.literal("SUCCESS")}),Gu=M.object({type:M.literal("FAILURE")}),Ji=M.discriminatedUnion("type",[j_,V_,W_,q_,K_,Y_,X_,J_,Z_,$_]),PW=Fn(Ji),Ns=M.discriminatedUnion("type",[...Ji.options,Q_,tM,rM,nM,oM,eM]),IW=Fn(Ns),iM=M.discriminatedUnion("type",[...Ji.options,Gu]).describe("The command that will be executed next. This should naturally follow from your reasoning and be consistent with the goal."),OW=Fn(iM),aM=M.discriminatedUnion("type",[...Ji.options,uf,Gu]),LW=Fn(aM),NW=M.discriminatedUnion("type",[...Ns.options,uf,Gu]),sM=M.object({command:Ji,thoughts:M.string()}),kW=Fn(sM),DW=M.object({command:M.unknown(),thoughts:M.string()});import{z as ju}from"zod";import{extendZodWithOpenApi as uM}from"zod-openapi";import{z as df}from"zod";import{extendZodWithOpenApi as lM}from"zod-openapi";import{z as Bn}from"zod";var Yt=Bn.object({index:Bn.number().optional().describe("global index within a test (in-order traversal)"),id:Bn.string(),skipped:Bn.boolean().optional(),envKey:Bn.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Bn.boolean().optional(),retries:Bn.number().optional()});lM(df);var cM=Yt.extend({type:df.literal("PRESET_ACTION")}),Xt=cM.extend({command:No}).openapi({ref:"PresetAction"});uM(ju);var zn=Yt.extend({type:ju.literal("AI_ACTION"),text:ju.string(),steps:Xt.array().optional()}).openapi({ref:"AIAction"});import{z as Ct}from"zod";import{z as ks}from"zod";import{extendZodWithOpenApi as dM}from"zod-openapi";dM(ks);var Uo=Yt.extend({type:ks.literal("AI_ACTION_DYNAMIC"),text:ks.string(),retries:ks.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as pf}from"zod";var Vu=Yt.extend({type:pf.literal("CONDITIONAL"),skipped:pf.boolean().optional()});import{z as de}from"zod";var pM=de.object({cacheKey:de.string(),cacheExpiryMs:de.number()}),$u=Yt.extend({id:de.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:de.record(de.string()).optional(),cacheConfig:pM.optional()}),Wr=$u.extend({type:de.literal("MODULE"),moduleId:de.string().uuid()}),mM=de.union([Wr.pick({type:!0,moduleId:!0}),de.record(de.unknown())]),hM=de.object({type:de.literal("URL_REGEX"),regex:de.string()}),gM=de.object({type:de.literal("PAGE_CHECK"),substring:de.string()}),Wu=de.object({cacheInvalidation:de.discriminatedUnion("type",[gM,hM]).optional()}),Jt=de.object({moduleId:de.string().uuid(),name:de.string(),description:de.string().nullish(),enabled:de.boolean().nullish(),parameters:de.string().array().nullish(),defaultParameters:de.record(de.string(),de.string()).nullish(),parameterEnums:de.record(de.string(),de.string().array()).nullish(),defaultCacheKey:de.string().nullish(),defaultCacheTtl:de.number().nullish(),defaultCacheAllInvocations:de.boolean().nullish(),autoAuth:de.boolean().nullish(),advanced:Wu.nullish()});import{z as Zt}from"zod";var mf=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(mf||{});var fM=Zt.discriminatedUnion("type",[Zt.object({type:Zt.literal("NAVIGATE_URL"),url:Zt.string().url()}),Zt.object({type:Zt.literal("GO_TO_SECTION_START")})]),SM=Zt.object({trigger:Zt.nativeEnum(mf).optional(),attempts:Zt.number().int().optional(),restartBehavior:fM}),Zi=Yt.extend({type:Zt.literal("SECTION"),description:Zt.string().describe("user provided goal of what the section should accomplish"),plan:Zt.string().array().optional(),autohealingConfig:SM.optional()});var hf=Jt.merge($u).extend({type:Ct.literal("RESOLVED_MODULE"),steps:Ct.lazy(()=>ot.array())}),Qi=Jt.extend({steps:Ct.lazy(()=>ot.array())}),qu=Zi.extend({steps:Ct.lazy(()=>xt.array())}),yM=Zi.extend({steps:Ct.lazy(()=>ot.array())}),Fo=Vu.extend({blocks:Ct.object({assertion:Ct.lazy(()=>Xt),steps:Ct.lazy(()=>xt.array())}).array(),elseSteps:Ct.lazy(()=>xt.array().optional())}),bM=Vu.extend({blocks:Ct.object({assertion:Ct.lazy(()=>Xt),steps:Ct.lazy(()=>ot.array())}).array(),elseSteps:Ct.lazy(()=>ot.array().optional())}),xt=Ct.discriminatedUnion("type",[Xt,zn,Uo,Wr,Fo,qu]),ot=Ct.discriminatedUnion("type",[Xt,zn,Uo,hf,bM,yM]);import{z as Qt}from"zod";var EM=Qt.object({steps:xt.array(),beforeSteps:xt.array().nullish(),afterSteps:xt.array().nullish()}),Hn=Qt.object({steps:ot.array(),beforeSteps:ot.array().nullish(),afterSteps:ot.array().nullish()}),Gn=Qt.object({steps:Qt.record(Qt.string(),Qt.unknown()).array(),beforeSteps:Qt.record(Qt.string(),Qt.unknown()).array().nullish(),afterSteps:Qt.record(Qt.string(),Qt.unknown()).array().nullish()});var jn="1.0.21",Ku="0.0.1";import{z as St}from"zod";import{z as Vn}from"zod";var TM=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,un=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 Bo=Vn.string().min(1).max(255).superRefine((r,e)=>{try{Yu(r)}catch(t){return e.addIssue({code:Vn.ZodIssueCode.custom,message:t.message,fatal:!0}),Vn.NEVER}});function Yu(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(TM))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Ds=Vn.preprocess(r=>r===null?"":r,Vn.union([Vn.string().url(),Vn.literal("")])).optional();var vM=["AI_EXTRACT","JAVASCRIPT"],AM=St.object({id:St.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:Bo.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:St.string().optional().describe("The path of the entity to resolve.")}).describe("A selector for a single entity. Exactly one of id, name, or path must be provided. Id is recommended.").refine(r=>[r.id,r.name,r.path].filter(Boolean).length===1,"Exactly one of id, name, or path must be provided."),wM=St.object({selector:AM,inputs:St.record(St.string()).or(St.null())}),Jq=St.object({type:St.literal("PRESET_ACTION"),action:Ns,envKey:St.string().or(St.null()).describe(`key in the environment to save the result of this step to. Only use this for ${vM.join(" or ")} steps.`)}),Zq=St.object({type:St.literal("MODULE"),module:wM}),Qq=St.object({type:St.literal("AI_ACTION_DYNAMIC"),text:St.string().describe("The goal description for the AI action. Supports handlebars templates like {{env.VARIABLE_NAME}}.")});var gf=L.object({phrase:L.string()}),Xu=L.object({thoughts:L.string().optional(),result:L.union([L.literal("NOT_FOUND"),L.string(),L.number(),L.array(L.unknown()),L.record(L.unknown(),L.unknown()),L.unknown()])}),N2=L.object({text:L.string()}),ff=L.object({attributes:L.array(L.string()).optional(),text:L.boolean().optional(),boundingBox:L.boolean().optional()}),RM=L.object({id:L.number().int(),requirements:ff}),CM=RM.array(),Sf=L.object({thoughts:L.string(),review:L.string().optional(),id:L.number().int(),updatedMemory:Eu.optional(),requirements:ff.optional(),additionalElements:CM.optional()});var Ju=(h=>(h.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",h.FEW_WORDS="FEW_WORDS",h.STYLE_TAG="STYLE_TAG",h.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",h.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",h.NONE="NONE",h.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",h.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",h.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",h.PREFER_ASSERTION="PREFER_ASSERTION",h.HTML_ELEMENTS="HTML_ELEMENTS",h.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",h.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",h))(Ju||{}),yf=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(yf||{});var bf=L.object({thoughts:L.string(),category:L.nativeEnum(Ju)}),Ef=L.object({thoughts:L.string(),category:L.nativeEnum(yf)}),xM=L.discriminatedUnion("op",[L.object({op:L.literal("replace"),path:L.string(),value:L.string()}),L.object({op:L.literal("add"),path:L.string(),value:L.string()}),L.object({op:L.literal("remove"),path:L.string()})]),k2=L.object({thoughts:L.string(),patches:xM.array()}),_M=[L.literal("add"),L.literal("replace"),L.literal("remove")],MM=L.object({op:L.union(_M),path:L.string(),value:ot.optional()}),Tf=L.object({patches:MM.array(),thoughts:L.string()}),vf=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(vf||{}),Af=L.object({thoughts:L.string(),scenario:L.nativeEnum(vf),instructions:L.string().nullish()}),wf=L.object({reasoning:L.string(),scenario:L.string(),patch:L.null().optional()}),D2=L.object({thoughts:L.string(),evaluation:L.number().min(0).max(10)}),U2=L.object({observations:L.string(),reasoning:L.string(),command:Rs});var Zu=L.object({summary:L.string(),reasoning:L.string(),evaluation:L.discriminatedUnion("type",[L.object({type:L.literal("DONE")}),L.object({type:L.literal("RIGHT_TRACK")}),L.object({type:L.literal("WRONG_TRACK"),feedback:L.string()}),L.object({type:L.literal("IMPOSSIBLE")})])}),PM=L.object({startId:L.number().int(),endId:L.number().int()}),Qu=(n=>(n.SIMPLE_CONTENT_BASED_LOCATOR="SIMPLE_CONTENT_BASED_LOCATOR",n.SIMPLE_CONTENT_BASED_ASSERTION="SIMPLE_CONTENT_BASED_ASSERTION",n.OTHER="OTHER",n))(Qu||{}),Rf=L.object({categoryThoughts:L.string(),category:L.nativeEnum(Qu),relevantSections:PM.array()});import{z as O}from"zod";import*as oe from"zod";var j2=oe.object({thoughts:oe.string().optional().describe("only provided if a description was provided"),target:on.optional().describe("only provided if a description was provided"),pageState:oe.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:oe.object({label:oe.string(),value:oe.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:oe.object({data:oe.string(),height:oe.number().int(),width:oe.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Cf=oe.union([oe.literal("ELEMENT_CHECK"),oe.literal("NEGATED_CHECK"),oe.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),oe.literal("SELECT_OPTION"),oe.literal("TYPE")]);function ea(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 ta=(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))(ta||{}),zo=oe.object({matched:oe.boolean(),reason:oe.string().optional().describe("Human understandable description"),logs:oe.string().array().optional().describe("Logs for debugging")}),IM=zo.extend({type:oe.literal("USER_SELECTOR")}),OM=zo.extend({type:oe.literal("CSS_SELECTOR"),selectors:oe.string().array()}),LM=zo.extend({type:oe.literal("HYBRID_SELECTOR")}),NM=zo.extend({type:oe.literal("HTML_DISTANCE"),distance:oe.number().optional(),closestElement:oe.string().optional(),savedElement:oe.string().optional()}),kM=zo.extend({type:oe.literal("TEMPLATE_MATCHING"),elementImageUrl:oe.string().url()}),DM=zo.extend({type:oe.literal("AUTO_FRAME"),logs:oe.string().array().optional()}),xf=oe.discriminatedUnion("type",[IM,OM,LM,NM,kM,DM]);import{z as ia}from"zod";import{z as WM}from"zod";import*as W from"zod";import{extendZodWithOpenApi as FM}from"zod-openapi";import{cloneDeep as eK}from"lodash-es";import rK from"truncate-json";import*as qn from"zod";import{extendZodWithOpenApi as UM}from"zod-openapi";import{z as yt}from"zod";import{z as me}from"zod";var ed=me.object({autoFollowNewTabs:me.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:me.union([me.boolean(),me.literal("inputs-only")]).optional(),ignoreHrefForCaching:me.boolean().optional(),disableSecondaryCacheResolution:me.boolean().optional(),hybridSelectorMode:me.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:me.union([me.boolean(),me.literal("always")]).optional(),visualActions:me.boolean().optional(),autoExpandIframes:me.boolean().optional(),disableHtmlSnapshots:me.boolean().optional(),importantAttributes:me.string().array().optional(),importantClasses:me.string().array().optional(),importantStyles:me.string().array().optional()});var _f=1e4,Mf=6e4,$n=ed.extend({pageLoadTimeoutMs:me.number().optional().refine(r=>r===void 0||r<=Mf&&r>=-1,{message:`Page load timeout must be between 0 and ${Mf/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:me.number().optional().refine(r=>r===void 0||r<=_f&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${_f/1e3} seconds`}),localChromeExtensionPaths:me.string().array().optional(),extraHeaders:me.record(me.string(),me.string()).optional().describe("HTTP headers to be sent on every request"),initialLocalStorage:me.record(me.string(),me.record(me.string(),me.string())).optional().describe("Initial local storage key-value pairs to set per domain on browser startup"),userAgent:me.string().optional(),disableGpu:me.boolean().optional(),bustCacheOnBoundingBoxChange:me.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:me.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:me.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 td="BASE_URL";var Wn="ENV_NAME",Ho="TEST_NAME",Y2={[td]:"https://www.google.com"},Pf=yt.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),If=yt.object({name:yt.string(),variables:yt.record(yt.string().describe("variable name"),yt.string().describe("variable value"))}),Of=yt.object({name:yt.string(),variables:yt.record(yt.string().describe("variable name"),yt.unknown().describe("variable value")),browser:$n.optional()});var X2=yt.object({name:yt.string(),variables:yt.record(yt.string().describe("variable name"),yt.unknown().describe("variable value"))});UM(qn);var rd=qn.object({env:qn.record(qn.unknown())}).openapi({ref:"TestContextSnapshot"});var it=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(it||{}),nd=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(nd||{});FM(W);var od=W.object({beforeUrl:W.string().optional(),afterUrl:W.string().optional(),message:W.string().optional(),beforeSnapshot:W.string().optional(),afterSnapshot:W.string().optional(),startedAt:W.coerce.date(),finishedAt:W.coerce.date()}),BM=od.extend({viewport:W.object({height:W.number(),width:W.number()}).nullish(),status:W.nativeEnum(nd),message:W.string().optional(),elementInteracted:W.string().optional()}),Kn=od.extend({status:W.nativeEnum(it),message:W.string().optional(),data:W.unknown().optional(),beforeTestContext:rd.optional(),afterTestContext:rd.optional(),failureReason:W.nativeEnum(Re).optional(),details:W.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"}),Lf=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(Lf||{}),Us=Kn.merge(Xt).extend({results:BM.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:W.lazy(()=>ct.array()).optional(),failureRecoveryStatus:W.object({type:W.nativeEnum(Lf),message:W.string()}).optional()}),zM=Kn.merge(zn).extend({results:W.lazy(()=>Us.array()),previousAttempts:W.lazy(()=>ct.array()).optional()}),HM=Kn.merge(Uo).extend({results:W.lazy(()=>Us.array()),previousAttempts:W.lazy(()=>ct.array()).optional()}),GM=Kn.merge(Wr).extend({moduleName:W.string().optional(),results:W.lazy(()=>ct.array()),previousAttempts:W.lazy(()=>ct.array()).optional()}),jM=Kn.merge(Fo).extend({assertion:Us.optional(),results:W.lazy(()=>ct.array()).describe("results for the block actually executed"),previousAttempts:W.lazy(()=>ct.array()).optional()}),VM=Kn.merge(Zi).extend({results:W.lazy(()=>ct.array()),healingAttempts:W.lazy(()=>ct.array().array()).optional(),previousAttempts:W.lazy(()=>ct.array()).optional()}),ct=W.discriminatedUnion("type",[zM,HM,Us,GM,jM,VM]),yK=Kn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),$M=od.extend({index:W.number().optional(),description:W.string(),pageState:W.string().optional(),elementInteracted:W.string().optional(),startedAt:W.coerce.date().or(W.string()).optional().catch(void 0),finishedAt:W.coerce.date().or(W.string()).optional().catch(void 0)}),Fs=$M.extend({beforeScreenshot:W.string().optional(),afterScreenshot:W.string().optional()});var id=WM.object({results:ct.array().describe("main results"),beforeResults:ct.array().optional(),afterResults:ct.array().optional()}),ra=id.partial();import{z as H}from"zod";import{extendZodWithOpenApi as QM}from"zod-openapi";var Go=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(Go||{});import{isValidCron as qM}from"cron-validator";import{z as ie}from"zod";import{z as ad}from"zod";var dn=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(dn||{});var Bs=ad.object({width:ad.number().min(200).max(1e4),height:ad.number().min(200).max(1e4)}),Nf={"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}},RK=Object.keys(Nf);var pn=Nf["Desktop Large"],kf="en-us",Df="America/Los_Angeles";var Uf={latitude:37.7749,longitude:-122.4194};var Ff=["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 Bf=1e4,KM=$n.extend({browserType:ie.nativeEnum(dn).optional(),slowMoMs:ie.number().optional().refine(r=>r===void 0||r<=Bf&&r>=-1,{message:`Slow motion must be between 0 and ${Bf} milliseconds`}),basicAuthorization:ie.object({username:ie.string().optional(),password:ie.string().optional()}).optional(),geolocation:ie.object({latitude:ie.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:ie.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:ie.boolean().optional(),locale:ie.string().optional(),timezone:ie.enum(Ff).optional(),colorScheme:ie.enum(["light","dark"]).optional()});var sd=ie.object({useMemory:ie.boolean().optional(),failureRecovery:ie.boolean().optional().describe("undefined means inherit org settings")}),YM=sd.extend({disableAICaching:ie.boolean().optional(),failureRecoveryInstructions:ie.string().optional()}),XM=ie.object({viewport:Bs.optional()}),na=XM.merge(YM).merge(KM),jo=ie.object({cron:ie.string().refine(r=>qM(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:ie.boolean().default(!1),env:ie.string().optional(),timeZone:ie.string().default("America/Los_Angeles"),jobKey:ie.string().optional()}),Vo=ie.object({onSuccess:ie.boolean().default(!1),failureMessage:ie.string().optional(),onFailure:ie.boolean().default(!0),successMessage:ie.string().optional()}),JM=ie.object({name:ie.string(),required:ie.boolean().optional(),defaultValue:ie.string().describe("this is not optional because we need a value when the editor is first loaded")}),zs=JM.array(),ZM=ie.object({name:ie.string(),value:ie.string()}),zf=ZM.array(),Hs=ie.object({name:ie.string(),default:ie.boolean().optional(),fixtures:Pf.array().optional()});QM(H);var er={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},Ae=(s=>(s.PENDING="PENDING",s.RUNNING="RUNNING",s.PASSED="PASSED",s.FAILED="FAILED",s.CANCELLED="CANCELLED",s.RETRYING="RETRYING",s.WAITING_FOR_USER="WAITING_FOR_USER",s))(Ae||{}),Gs=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(Gs||{});var Ye=H.string().pipe(H.coerce.date()).or(H.date()),oa=H.object({id:H.string(),runKey:H.string(),organizationId:H.string(),executionType:H.nativeEnum(Go).optional().default("WEB"),createdAt:Ye,createdBy:H.string(),flake:H.boolean().nullish(),scheduledAt:Ye.or(H.null()),startedAt:Ye.or(H.null()),updatedAt:Ye.nullish(),finishedAt:Ye.or(H.null()),resolvedBaseUrl:H.string().nullish(),environmentName:H.string().nullish(),gitBranchName:H.string().nullish(),githubRepository:H.string().nullish(),gitlabProjectPath:H.string().nullish(),labels:H.array(H.string()).optional(),gitOriginUrl:H.string().nullish(),gitCommitSha:H.string().nullish(),gitCommitShaShort:H.string().nullish(),gitCommitAuthorName:H.string().nullish(),cliVersion:H.string().nullish(),section:H.nativeEnum(Gs).nullish(),status:H.nativeEnum(Ae),trigger:H.nativeEnum(er),attempts:H.number(),runAttempts:H.array(H.object({id:H.string(),status:H.nativeEnum(Ae),startedAt:Ye.or(H.null()),finishedAt:Ye.or(H.null())})).optional(),videos:H.array(H.string()).optional(),failureReason:H.nativeEnum(Re).nullish(),failureDetails:Is.nullish(),failureRecoveryDetails:H.record(H.string(),H.unknown()).nullish(),pipelineId:H.string().nullish(),resolvedInputs:H.record(H.string(),H.string()).nullish(),quarantined:H.boolean().nullish().default(!1),quarantinedReason:H.string().nullish(),localTestId:H.string().nullish(),testId:H.string().nullish(),testName:H.string().nullish(),description:H.string().nullish(),test:H.object({name:H.string(),id:H.string()}).nullish().default(null),suiteId:H.string().nullish()}).openapi({ref:"RunMetadata"}),eP={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},js=oa.pick({...eP,test:!0}),Hf=oa.omit({failureReason:!0,failureDetails:!0,test:!0}),ld=oa.extend({stepsSnapshot:H.array(H.record(H.unknown())).nullish(),resolvedInputs:H.record(H.string(),H.string()).nullish(),test:H.object({name:H.string(),id:H.string(),description:H.string().nullish(),baseUrl:H.string().nullish(),advanced:na.nullish()}).nullish()}).merge(id);var tP=ia.object({id:ia.string().uuid(),startedAt:Ye.or(ia.null()),finishedAt:Ye.or(ia.null()),status:ia.nativeEnum(Ae)}).merge(ra),qK=tP.array();import{z as Xe}from"zod";var rP=Xe.object({id:Xe.string(),status:Xe.nativeEnum(Ae),trigger:Xe.nativeEnum(er),createdAt:Ye,startedAt:Ye.nullish(),finishedAt:Ye.nullish(),gitCommitSha:Xe.string().nullish(),gitCommitShaShort:Xe.string().nullish(),gitCommitTimestamp:Ye.nullish(),gitBranchName:Xe.string().nullish(),gitOriginUrl:Xe.string().nullish(),gitCommitMessage:Xe.string().nullish(),gitCommitAuthorName:Xe.string().nullish(),githubRepository:Xe.string().nullish(),gitlabProjectPath:Xe.string().nullish(),pipelineId:Xe.string().nullish(),cliVersion:Xe.string().nullish(),labels:Xe.string().array().optional(),suite:Xe.object({id:Xe.string(),name:Xe.string()}).nullish(),runs:Xe.object({status:Xe.nativeEnum(Ae)}).array()}).openapi({ref:"RunGroup"}),Gf=rP.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:js.array()});import{z as ut}from"zod";var nP=ut.object({type:ut.literal("TARGETING"),name:ut.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:xf.array(),pageState:ut.string().optional(),targetSource:ut.nativeEnum(nn).optional(),targetUpdateTime:ut.string().optional()}),oP=ut.object({type:ut.literal("AI_LOCATION"),matched:ut.boolean(),pageState:ut.string().optional(),ragUsed:ut.boolean().optional(),thoughts:ut.string().optional()}),iP=ut.object({type:ut.literal("ASSERTION"),relevantElementsSerialized:ut.string().array().optional(),pageState:ut.string().optional(),ragUsed:ut.boolean().optional()}),aP=ut.discriminatedUnion("type",[nP,oP,iP]);import{z as Ve}from"zod";var sP=Ve.object({id:Ve.string(),name:Ve.string()}),sY=sP.merge(Ve.object({createdAt:Ye,createdBy:Ve.string(),schedule:jo,notification:Vo,environment:Ve.object({name:Ve.string()}).nullish(),beforeTests:Ve.object({id:Ve.string()}).array().nullish(),afterTests:Ve.object({id:Ve.string()}).array().nullish()})),jf=Ve.object({id:Ve.string().uuid(),orgId:Ve.string(),createdAt:Ye,startedAt:Ye.or(Ve.null()),finishedAt:Ye.or(Ve.null()),status:Ve.nativeEnum(Ae),trigger:Ve.nativeEnum(er),suite:Ve.object({id:Ve.string(),name:Ve.string()}).nullish(),runs:oa.array()}),lY=jf.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),Vf=jf.extend({runs:js.array()});import{z as tr}from"zod";import{cloneDeep as dY}from"lodash-es";import{z as be}from"zod";var SY=be.object({thoughts:be.string(),subGoals:be.object({instruction:be.string()}).array()}),yY=be.object({thoughts:be.string(),newPlanMarkdown:be.string()}),bY=be.object({thoughts:be.string(),correct:be.boolean(),failedActionIndex:be.number().optional()}),lP=be.object({type:be.literal("PLANNING"),beforePlan:be.string(),goalDecision:be.string(),thoughts:be.string()}),cP=be.object({type:be.literal("RUNNING"),stepDisplayName:be.string(),status:be.nativeEnum(it),results:ct.array()}),uP=be.object({type:be.literal("REVISING"),beforePlan:be.string(),afterPlan:be.string(),errString:be.string(),diffs:be.string(),thoughts:be.string()}),dP=be.object({type:be.literal("SYSTEM"),message:be.string()}),pP=be.discriminatedUnion("type",[lP,cP,uP,dP]),$f=pP.array();var wY=tr.object({id:tr.string(),scheduledAt:tr.coerce.date().nullable(),startedAt:tr.coerce.date().nullable(),finishedAt:tr.coerce.date().nullable(),status:tr.nativeEnum(Ae),history:$f.nullable(),testPlan:tr.object({id:tr.string(),name:tr.string()}).nullable(),test:tr.object({id:tr.string(),name:tr.string()}).nullable()});import{z as _t}from"zod";var cd=_t.object({content:_t.string(),ids:_t.string().array(),tokenLength:_t.number()}),mP=_t.object({chunks:cd.array()}),HY=_t.object({ids:_t.string().array(),score:_t.number(),tokenLength:_t.number()}),GY=mP.extend({description:_t.string().describe("Input to pass to RAG engine"),tokenLimit:_t.number()}),Wf=_t.object({ids:_t.number().array()}),qf=_t.object({indices:_t.number().array()});var bt=O.object({disableCache:O.boolean().optional(),useMemory:O.boolean().optional(),loggerTags:O.record(O.string(),O.string()).optional(),langfuseSessionId:O.string().optional(),agentConfigVersion:O.string().optional()}),XY=bt.extend({chunks:cd.array(),description:O.string().describe("Input to pass to AI"),type:O.union([O.literal("locator"),O.literal("assertion"),O.literal("ai-action")]),softTokenLimit:O.number(),hardTokenLimit:O.number(),callId:O.string().optional()}),hP=O.object({screenshotBase64AfterCommand:O.string(),urlAfterCommand:O.string(),serializedCommand:O.string(),elementInteracted:O.string().optional(),thoughts:O.string().optional()}),Kf=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),source:Cf.optional().catch(void 0),memory:O.discriminatedUnion("type",[bs,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional()}),Yf=O.object({target:O.string().or(O.number()),browserState:O.string().optional(),screenshot:O.string().optional(),boundingBox:O.object({x:O.number(),y:O.number(),height:O.number(),width:O.number()}).optional()}),Xf=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string().optional(),returnSchema:O.string().optional()}),gP=O.literal("NEGATED_CHECK"),Jf=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),url:O.string(),contextChoice:_u.optional(),memory:O.discriminatedUnion("type",[Au,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional(),source:gP.optional()}),Zf=O.object({command:No}),Qf=O.object({message:O.string()}),ud=O.object({goal:O.string(),browserState:O.string(),startingScreenshot:O.string().optional(),screenshot:O.string(),url:O.string(),history:hP.array(),actionHint:O.string().optional(),lastError:O.string().optional()}),eS=O.object({results:Fs.array(),errorMessage:O.string(),errorStack:O.string().optional()}),tS=O.object({results:Fs.array(),goal:O.string(),errorMessage:O.string()}),rS=O.object({failedResults:Fs.array(),nextStepsSerialized:O.string().array(),currentUrl:O.string(),currentPageState:O.string(),currentScreenshot:O.string(),customInstructions:O.string().optional(),testDescription:O.string().optional()}),JY=O.object({description:O.string(),type:O.union([O.literal("locator"),O.literal("assertion"),O.literal("ai-action")]),excerpt:O.string()}),nS=O.object({type:O.string(),browserContext:O.string(),currentStep:O.string(),screenshot:O.string()});import{z as aa}from"zod";var e5=aa.object({goal:aa.string()}),oS=aa.object({keywords:aa.array(aa.string())});import{z as dd}from"zod";var Vs=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(Vs||{}),n5=dd.nativeEnum(Vs),fP=dd.enum(["v1","v2"]),o5=fP.or(dd.string().describe("for people with special configurations"));import{z as Ue}from"zod";var iS=Ue.object({attributesRequired:Ue.array(Ue.string()).optional(),textRequired:Ue.boolean().optional(),boundsRequired:Ue.boolean().optional()}),aS=Ue.object({id:Ue.number(),thoughts:Ue.string(),inWebview:Ue.boolean().optional(),requirements:iS.optional(),additionalElements:Ue.object({id:Ue.number(),requirements:iS}).array().optional()}),sS=Ue.object({description:Ue.string(),screenXml:Ue.string(),screenshot:Ue.string()}),lS=Ue.object({assertion:Ue.string(),screenXml:Ue.string(),screenshot:Ue.string()}),cS=Ue.object({thoughts:Ue.string(),result:Ue.boolean(),relevantElements:Ue.array(Ue.number()).optional()});import{z as Yn}from"zod";var uS=Yn.object({id:Yn.string().uuid(),skipped:Yn.boolean().optional(),envKey:Yn.string().optional().describe("key in the environment to save the result of this step to")}),pd=uS.merge(_o).extend({type:Yn.literal("REQUEST")}),md=uS.merge(Ts).extend({type:Yn.literal("JAVASCRIPT")}),hd=Yn.discriminatedUnion("type",[md,pd]);import{z as rr}from"zod";var dS=rr.object({id:rr.string(),name:Bo,description:rr.string().optional().nullish(),baseUrl:Ds.nullish(),schemaVersion:rr.string(),advanced:rr.unknown().optional(),retries:rr.number(),envs:rr.array(Hs).nullish(),parameters:zs.nullish()}),SP=rr.object({createdAt:rr.coerce.date(),updatedAt:rr.coerce.date(),schedule:jo.nullish(),notification:Vo.nullish(),createdBy:rr.string(),organizationId:rr.string()}),yP=dS.merge(SP),_5=yP.extend({steps:hd.array()}),M5=dS.extend({steps:hd.array()});import{z as Lt}from"zod";var pS=Lt.object({startedAt:Lt.coerce.date(),finishedAt:Lt.coerce.date(),status:Lt.nativeEnum(it),message:Lt.string().optional(),data:Lt.unknown().optional()}),bP=pS.merge(md).extend({type:Lt.literal("JAVASCRIPT")}),EP=pS.merge(pd).extend({type:Lt.literal("REQUEST")}),TP=Lt.discriminatedUnion("type",[bP,EP]),mS=Lt.object({startedAt:Lt.coerce.date(),finishedAt:Lt.coerce.date().nullish(),status:Lt.nativeEnum(Ae),results:TP.array(),failureReason:Lt.string().nullish(),failureDetails:Is.nullish()});import{z as Nt}from"zod";var vP=Nt.object({id:Nt.string(),organizationId:Nt.string(),createdAt:Nt.coerce.date(),updatedAt:Nt.coerce.date(),createdBy:Nt.string(),scheduledAt:Nt.coerce.date().nullish(),startedAt:Nt.coerce.date().nullish(),finishedAt:Nt.coerce.date().nullish(),status:Nt.nativeEnum(Ae),trigger:Nt.nativeEnum(er),results:mS.array().nullish(),apiTestName:Nt.string().nullish(),apiTestPath:Nt.string().nullish(),apiTestId:Nt.string().nullish()}),B5=vP.pick({status:!0,startedAt:!0,finishedAt:!0});var sa=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(sa||{}),hS=3;function AP(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function gd(r){if(!AP(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 fd(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return hS;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 $s=class{trackStepExecution(){}async flush(){}};import{parseString as wP,splitCookiesString as RP}from"set-cookie-parser";import{z as Te}from"zod";var Sd=Te.object({name:Te.string(),value:Te.string(),url:Te.string().optional(),domain:Te.string().optional(),path:Te.string().optional(),expires:Te.number().default(Date.now()/1e3+60*60*24*365),httpOnly:Te.boolean().optional(),secure:Te.boolean().default(!0),sameSite:Te.union([Te.literal("Strict"),Te.literal("Lax"),Te.literal("None")]).default("None")});function Ws(r,e){let t=[],n=RP(r);for(let o of n){let i=wP(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 s=Sd.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(s);let c=[s.name,...Object.keys(s)].map(u=>u.toLowerCase()),l=o.match(/\b(\S+)=([^;]*)/g);if(l)for(let u of l){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...s,name:d,value:p})}}return t}var CP=Te.object({origin:Te.string(),localStorage:Te.array(Te.object({name:Te.string(),value:Te.string()}))}),xP=Te.object({entries:Te.record(Te.string(),Te.array(Te.tuple([Te.unknown(),Te.unknown()]))),version:Te.number().optional()}),gS=Te.object({cookies:Sd.array().optional(),origins:CP.array().optional(),idb:Te.record(Te.string(),xP).optional().describe("key is db name")});function qs(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Sd.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 WP from"zod";import{v4 as l4}from"uuid";import{z as j}from"zod";import*as xe from"zod";var fS=xe.object({requiredText:xe.string().optional(),requiredAttributes:xe.record(xe.string(),xe.string()).optional(),requiredBounds:xe.boolean().optional()}),_P=xe.object({xPath:xe.string(),requirements:fS.optional()}),MP=xe.object({type:xe.literal("NATIVE"),bounds:xe.number().array(),resolvedDescription:xe.string(),xPath:xe.string(),elementOnlySerializedXml:xe.string(),requirements:fS.optional(),requiredRelatedElements:_P.array().optional()}),PP=xe.object({type:xe.literal("WEBVIEW"),resolvedDescription:xe.string(),xPath:xe.string(),browserCache:on.optional()}),Ks=xe.discriminatedUnion("type",[MP,PP]);var Xn=(m=>(m.AI_CHECK="AI_CHECK",m.TAP="TAP",m.TYPE="TYPE",m.PRESS="PRESS",m.PRESS_KEYBOARD="PRESS_KEYBOARD",m.OPEN_APP="OPEN_APP",m.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",m.SWIPE="SWIPE",m.JAVASCRIPT="JAVASCRIPT",m.REQUEST="REQUEST",m.WAIT="WAIT",m.ADD_FILE="ADD_FILE",m.ADB="ADB",m.STATE="STATE",m))(Xn||{}),yd=(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))(yd||{}),bd=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(bd||{}),SS=j.object({type:j.literal("description"),description:j.string()}),IP=j.object({type:j.literal("coordinates"),xPercent:j.number(),yPercent:j.number()}),yS=j.discriminatedUnion("type",[SS,IP]),OP=j.object({updatedAt:j.coerce.date().optional()}),kt=j.object({id:j.string().uuid(),disableCache:j.boolean().optional()}),LP=kt.extend({type:j.literal("STATE")}),bS=OP.extend({target:Ks}),NP=kt.extend({type:j.literal("AI_CHECK"),assertion:j.string(),timeoutSecs:j.number().optional()}),Ed=kt.extend({type:j.literal("TAP"),target:yS,cache:bS.optional(),longPress:j.boolean().optional(),longPressDurationMs:j.number().optional(),doubleTap:j.boolean().optional(),doubleTapDelayMs:j.number().optional(),relativePosition:j.object({x:j.number(),y:j.number()}).optional()}),Td=kt.extend({type:j.literal("TYPE"),target:yS.optional(),cache:bS.optional(),keyPressDelayMs:j.number().optional(),text:j.string(),clearContent:j.boolean().optional()}),kP=kt.extend({type:j.literal("PRESS"),key:j.nativeEnum(yd),longPress:j.boolean().optional()}),DP=kt.extend({type:j.literal("PRESS_KEYBOARD"),key:j.nativeEnum(bd)}),UP=kt.extend({type:j.literal("OPEN_APP"),packageName:j.string(),activityName:j.string().optional(),intentExtras:j.string().optional()}),FP=kt.extend({type:j.literal("OPEN_NOTIFICATION_DRAWER")}),BP=j.discriminatedUnion("type",[j.object({type:j.literal("SCREEN")}),j.object({type:j.literal("OPEN_APP")}),j.object({type:j.literal("CUSTOM"),target:SS})]),zP=kt.extend({type:j.literal("SWIPE"),direction:j.enum(["up","down","left","right"]),scrollableElement:BP,viewportPercent:j.number().optional(),durationMs:j.number().optional()}),HP=kt.extend({type:j.literal("JAVASCRIPT"),code:j.string(),timeout:j.number().int().max(60).optional().describe("Max seconds for the code to complete")}),GP=kt.extend({type:j.literal("REQUEST")}).merge(_o),jP=kt.extend({type:j.literal("WAIT"),timeoutSecs:j.number()}),VP=kt.extend({type:j.literal("ADB"),command:j.string(),jsonArgs:j.string().optional()}),$P=kt.extend({type:j.literal("ADD_FILE"),file:j.string(),storageLocation:j.string()}),ES=j.discriminatedUnion("type",[NP,Ed,Td,kP,UP,FP,DP,zP,HP,GP,jP,$P,VP,LP]);var vd=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var TS={type:!0,cache:!0},mn=WP.discriminatedUnion("type",[Ed.pick(TS),Td.pick(TS)]),qP=Object.values(Xn).filter(r=>mn.options.some(e=>e.shape.type.safeParse(r).success));function Ys(r){return qP.includes(r.type)}var vS=Wi(mn),AS=qi(mn),S4=Cs(mn);import{cloneDeep as la}from"lodash-es";import wS from"truncate-json";var KP="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",YP=[Wn,Ho],RS=[Wn,Ho],$o=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[Wn],o=e.env[Ho],i={};for(let[s,c]of Object.entries(e.env))RS.includes(s)||(t??{})[s]===void 0&&(i[s]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=la(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){YP.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[Wn]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return la(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>RS.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,KP]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=wS(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=wS(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=la(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable(Wn,e.envName),e.testName&&this.setMomenticSystemVariable(Ho,e.testName)}getDynamicVariablesCopy(){return la(this.env)}getVariablesFromEnvironmentCopy(){return la(this.varsFromMomenticEnvironment)}};var ca=(t=>(t.USWest1="us-west1",t.EUNorth1="eu-north1",t))(ca||{});import Je from"zod";import{z as gr}from"zod";import{z as Fe}from"zod";var hr=Fe.object({id:Fe.string(),name:Bo,baseUrl:Ds,description:Fe.string().optional().nullish(),schemaVersion:Fe.string(),advanced:na,retries:Fe.number(),envs:Fe.array(Hs).nullish(),parameters:zs.nullish(),disabled:Fe.boolean().optional(),labels:Fe.array(Fe.string()).optional().catch([])}),_4=Fe.enum(["INHERIT","ENABLED","DISABLED"]);var XP=na.extend({failureRecovery:Fe.boolean().or(Fe.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:Fe.boolean().or(Fe.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var M4=hr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:XP}),P4=hr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),JP=Fe.object({labels:Fe.array(Fe.string()).optional(),outputs:zf.nullish()}),Wo=hr.merge(JP),ZP=Fe.object({createdAt:Fe.coerce.date(),updatedAt:Fe.coerce.date(),updatedBy:Fe.string().nullable(),schedule:jo,notification:Vo,createdBy:Fe.string(),organizationId:Fe.string(),folderId:Fe.string().nullable().optional()}),QP=hr.merge(ZP),I4=QP.merge(Hn),Xs=hr.merge(Hn),O4=hr.merge(Gn);var eI="test",tI="module",rI="mobile-test",nI="mobile-module";var _e=(o=>(o.TEST=`momentic/${eI}`,o.MODULE=`momentic/${tI}`,o.MOBILE_TEST=`momentic/${rI}`,o.MOBILE_MODULE=`momentic/${nI}`,o))(_e||{}),B4=hr.merge(Gn),CS=Jt.extend({steps:gr.array(gr.record(gr.string(),gr.unknown())),schemaVersion:gr.string()}),z4=CS.extend({fileType:gr.literal(_e.MODULE)}),H4=gr.object({test:gr.string().describe("YAML for the test, including metadata and steps"),modules:gr.record(gr.string(),gr.string()).describe("Map of module name to YAML for the module")});var Ad=Je.object({parameterNames:Je.string().array(),defaultParameters:Je.record(Je.string(),Je.string()).optional(),parameterEnums:Je.record(Je.string(),Je.string().array()).optional()}),oI=Je.object({moduleId:Je.string().uuid(),name:Je.string(),description:Je.string().nullish(),parameters:Ad.optional(),enabled:Je.boolean().nullish(),schemaVersion:Je.string()}),ua=oI.omit({name:!0}),Js=ua.extend({steps:Je.array(Je.record(Je.string(),Je.unknown()))}),iI=Je.object({fileType:Je.literal(_e.MOBILE_MODULE)}).merge(Js);import Dt from"zod";var fr=(t=>(t.PRESET="MOBILE_PRESET_STEP",t.MODULE="MOBILE_MODULE_STEP",t))(fr||{}),Zs=Dt.object({id:Dt.string().uuid(),envKey:Dt.string().optional(),skipped:Dt.boolean().optional()}),da=Zs.extend({type:Dt.literal("MOBILE_PRESET_STEP"),command:ES,keyPressDelayMs:Dt.number().optional()}),qo=Dt.object({moduleId:Dt.string(),inputs:Dt.record(Dt.string(),Dt.string()).optional(),parameters:Ad.optional()}),pa=Zs.merge(qo.extend({type:Dt.literal("MOBILE_MODULE_STEP")})),Y4=qo.extend({steps:Dt.lazy(()=>Sr.array())}),Sr=Dt.discriminatedUnion("type",[da,pa]);import Ze from"zod";import Qs from"zod";var qr=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(qr||{}),aI=qo.extend({steps:Qs.lazy(()=>ma.array()),name:Qs.string().describe("name of the module")}),sI=Zs.merge(aI).extend({type:Qs.literal("RESOLVED_MOBILE_MODULE")}),ma=Qs.discriminatedUnion("type",[sI,da]);function xS(r){return Object.values(qr).includes(r)||Object.values(fr).includes(r)}var lI=Ze.object({disableMomenticAccessibilityTree:Ze.boolean().optional(),autoGrantPermissions:Ze.boolean().optional()}),wd=lI.extend({region:Ze.nativeEnum(ca).optional()}),ha=Ze.object({retries:Ze.number().optional().describe("number of retries to run"),defaultChannel:Ze.string().optional().describe("default channel to use"),defaultTag:Ze.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:Ze.string().optional(),emulator:wd.optional()}),_r=Ze.object({id:Ze.string().uuid(),description:Ze.string(),schemaVersion:Ze.string(),settings:ha.optional()}),cI=_r.merge(Ze.object({steps:Ze.array(Sr)})),el=Ze.object({fileType:Ze.literal(_e.MOBILE_TEST)}).merge(cI),c3=Ze.object({name:Ze.string(),steps:Ze.array(Sr).optional(),settings:ha.optional()}),uI=_r.extend({steps:ma.array()});import he from"zod";var hn=he.object({startTime:he.number(),endTime:he.number().optional(),durationMs:he.number().optional(),error:he.string().optional(),result:he.unknown().optional(),attributes:he.record(he.string(),he.unknown())});var dI=hn.extend({type:he.literal("SECTION"),name:he.string(),subSpans:he.lazy(()=>Rd.array())}),pI=hn.extend({type:he.literal("AI_LOCATOR_CALL"),result:he.object({id:he.number(),thoughts:he.string()}).optional()}),mI=hn.extend({type:he.literal("AI_ASSERTION_CALL"),result:he.object({thoughts:he.string(),result:he.boolean()}).optional()}),hI=hn.extend({type:he.literal("TARGET_RESOLUTION"),result:he.object({serializedElement:he.string()}).optional()}),gI=hn.extend({type:he.literal("WAIT_FOR_STABILITY"),reason:he.string()}),fI=hn.extend({type:he.literal("EMULATOR_INTERACTION"),name:he.string(),withinWebview:he.boolean().optional()}),SI=hn.extend({type:he.literal("EMULATOR_READ_STATE"),name:he.string()}),yI=hn.extend({type:he.literal("GENERIC"),name:he.string()}),Rd=he.discriminatedUnion("type",[dI,pI,mI,hI,gI,fI,SI,yI]);import yr from"zod";var _S=yr.object({message:yr.string().optional(),startTime:yr.number(),endTime:yr.number(),status:yr.nativeEnum(it),trace:yr.unknown(),beforeSnapshot:yr.string().optional(),afterSnapshot:yr.string().optional(),data:yr.unknown().optional().describe("output data from the step")}),bI=_S.merge(da),EI=_S.merge(pa).extend({steps:yr.lazy(()=>br.array())}),br=yr.discriminatedUnion("type",[bI,EI]);var F3=new Set(Object.values(nt));var TI={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"},B3={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:[]},z3={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."},H3={AI_CHECK:"AI check",RESOLVED_MOBILE_MODULE:"Module",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",SWIPE:"Swipe",OPEN_APP:"Open app",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",JAVASCRIPT:"JavaScript",REQUEST:"API request",WAIT:"Wait",ADD_FILE:"Add file",ADB:"ADB command",STATE:"Debug state"},G3={AI_CHECK:"Ask AI to verify whether something is true on the screen.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests.",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.",SWIPE:"Swipe on the screen.",OPEN_APP:"Open an app on the device.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a specified amount of time.",ADD_FILE:"Add a file to the device's disk.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device."};import vI from"semver";import{z as AI}from"zod";var W3=AI.string().refine(r=>vI.valid(r),{message:"must be a valid semver string"});import{Faker as Y3,en as X3}from"@faker-js/faker";import{z as k}from"zod";var Z3=k.object({body:k.string(),to:k.string(),from:k.string()}),Q3=k.object({from:k.string().optional(),to:k.string(),timeout:k.number().optional(),beforeDate:k.string().pipe(k.coerce.date()).or(k.date()).optional(),afterDate:k.string().pipe(k.coerce.date()).or(k.date()).optional()}),eX=k.object({to:k.string().email(),from:k.string(),subject:k.string(),body:k.string(),html:k.string().optional()}),tX=k.object({inbox:k.string().transform(r=>r.toLowerCase()),afterDate:k.string().pipe(k.coerce.date()).or(k.date()).optional(),timeout:k.number().optional(),trimWhitespace:k.boolean().optional()}),rX=k.object({inbox:k.string(),limit:k.number().optional(),afterDate:k.string().pipe(k.coerce.date()).or(k.date()).optional(),trimWhitespace:k.boolean().optional()});var tl=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(tl||{}),MS=k.object({body:k.string().nullish(),status:k.number().optional(),headers:k.array(k.tuple([k.string(),k.string()])).optional()}),wI=k.object({url:k.string(),options:k.object({method:k.string(),body:k.string().nullish(),headers:k.array(k.tuple([k.string(),k.string()])).optional()}).optional()}).optional(),RI=k.object({body:k.string().nullish(),options:k.object({status:k.number(),statusText:k.string().optional(),headers:k.array(k.tuple([k.string(),k.string()])).optional()}).optional()}).optional(),PS=k.object({result:k.unknown(),variableUpdates:k.record(k.string(),k.unknown()).optional(),persistentVariableUpdates:k.record(k.string(),k.unknown()).optional(),error:k.string().optional(),success:k.boolean()}),nX=k.object({id:k.string().optional(),orgId:k.string(),momenticLambdaAuthHash:k.string(),code:k.string(),fragment:k.boolean(),state:k.object({env:k.record(k.string(),k.unknown()),request:wI,response:RI,additionalBindings:k.record(k.string(),k.unknown()).optional()}),timeoutMs:k.number().optional(),disallowVariableUpdates:k.boolean().optional(),responseSerialization:k.nativeEnum(tl).optional()}),gn=15e3;import*as Et from"zod";import{extendZodWithOpenApi as CI}from"zod-openapi";CI(Et);var xI=Et.object({url:Et.string(),lineNumber:Et.number(),columnNumber:Et.number()}).openapi({ref:"CodeLocation"}),rl=Et.object({timestamp:Et.number(),text:Et.string(),type:Et.string(),tabIndex:Et.number(),args:Et.unknown().array().optional(),url:Et.string().optional(),location:xI.optional()}).openapi({ref:"ConsoleLog"}),IS=rl.array(),_I=IS.array();import*as Cd from"zod";import{extendZodWithOpenApi as KI}from"zod-openapi";import{z as P}from"zod";var MI=P.object({name:P.string(),version:P.string(),comment:P.string().optional()}),PI=P.object({name:P.string(),version:P.string(),comment:P.string().optional()}),II=P.object({onContentLoad:P.number().optional(),onLoad:P.number().optional(),comment:P.string().optional()}),LS=P.object({startedDateTime:P.string(),id:P.string(),title:P.string().optional(),pageTimings:II,comment:P.string().optional()}),OI=P.array(LS),LI=P.object({name:P.string(),value:P.string(),path:P.string().optional(),domain:P.string().optional(),expires:P.string().optional(),httpOnly:P.boolean().optional(),secure:P.boolean().optional(),comment:P.string().optional()}),NS=P.array(LI),NI=P.object({name:P.string(),value:P.string(),comment:P.string().optional()}),kS=P.array(NI),kI=P.object({name:P.string(),value:P.string(),comment:P.string().optional()}),DI=P.array(kI),UI=P.object({name:P.string(),value:P.string().optional(),fileName:P.string().optional(),contentType:P.string().optional(),comment:P.string().optional()}),FI=P.array(UI),BI=P.object({mimeType:P.string(),params:FI,text:P.string(),comment:P.string().optional()}),zI=P.object({method:P.string(),url:P.string(),httpVersion:P.string().optional(),cookies:NS,headers:kS,queryString:DI,postData:BI.optional(),headersSize:P.number().optional(),bodySize:P.number().optional(),comment:P.string().optional()}),HI=P.object({size:P.number().optional(),compression:P.number().optional(),mimeType:P.string().optional(),text:P.string().optional(),encoding:P.string().optional(),comment:P.string().optional()}),GI=P.object({status:P.number(),statusText:P.string(),httpVersion:P.string().optional(),cookies:NS,headers:kS,content:HI,redirectURL:P.string().optional(),headersSize:P.number().optional(),bodySize:P.number().optional(),comment:P.string().optional(),_mocked:P.boolean().optional()}),OS=P.object({expires:P.string().optional(),lastAccess:P.string(),eTag:P.string(),hitCount:P.number(),comment:P.string().optional()}),jI=P.object({beforeRequest:OS.optional(),afterRequest:OS.optional(),comment:P.string().optional()}),VI=P.object({blocked:P.number().optional(),dns:P.number().optional(),connect:P.number().optional(),send:P.number(),wait:P.number(),receive:P.number(),ssl:P.number().optional(),comment:P.string().optional()}),DS=P.object({pageref:P.string().optional(),startedDateTime:P.string(),time:P.number().optional(),request:zI,response:GI.optional(),cache:jI.optional(),timings:VI,serverIPAddress:P.string().optional(),connection:P.string().optional(),comment:P.string().optional(),_resourceType:P.string().optional()}),$I=P.array(DS),WI=P.object({version:P.string().default("1.1"),creator:MI.optional(),browser:PI.optional(),pages:OI.optional(),entries:$I,comment:P.string().optional()}),qI=P.object({log:WI}),US=P.record(P.string(),LS),FS=P.record(P.string(),DS);KI(Cd);var YI=Cd.object({logsPerPage:rl.array().array(),harPages:US.optional(),harEntries:FS.optional()}).openapi({ref:"DebugData"});import{cloneDeep as XI}from"lodash-es";import{z as Mr}from"zod";var zS=(c=>(c.DisableClickhouseCaches="disable_clickhouse_caches",c.ShowZeroOpacityElements="show_zero_opacity_elements",c.VisualActions="visual_actions",c.RagV2="rag_v2",c.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",c.GlobalLocatorRedirect="global_locator_redirect",c.FakerConstantSeed="faker_constant_seed",c.AutoExpandIframes="auto_expand_iframes",c))(zS||{});var BS=Mr.union([Mr.string(),Mr.number(),Mr.boolean(),Mr.null(),Mr.record(Mr.string(),Mr.lazy(()=>BS)),Mr.array(Mr.lazy(()=>BS))]),nl=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=XI(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(zS).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")}},WX=new nl({},{});var xd={".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"},HS=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],KX=Object.keys(xd);import*as GS from"zod";var XX=GS.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as fn}from"zod";var QX=fn.object({id:fn.string(),name:fn.string(),createdAt:fn.coerce.date(),createdBy:fn.string(),updatedAt:fn.coerce.date(),updatedBy:fn.string().nullable(),organizationId:fn.string()});import{z as N}from"zod";import Sn from"zod";var Ko=Sn.object({platformSep:Sn.string(),fullPathSegments:Sn.string().array(),relativePathSegments:Sn.string().array(),relativePath:Sn.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:Sn.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:Sn.coerce.date(),createdAt:Sn.coerce.date()});var JI=N.array(Ko.extend({id:N.string(),name:N.string(),description:N.string().optional(),labels:N.string().array().optional()})),ZI=N.array(Ko.extend({id:N.string(),name:N.string(),description:N.string().optional(),content:Qi})),pJ=N.object({tests:JI,modules:ZI,labels:N.string().array()}),mJ=Xs.merge(Wo),hJ=N.object({schemaVersion:N.string(),stepLists:Hn}),gJ=Wo.partial().merge(hr.pick({id:!0})),QI={name:N.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:N.string().optional(),baseUrl:N.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:N.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:N.nativeEnum(dn).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Bs.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:N.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},fJ=N.object(QI),SJ=Xs.merge(N.object({relativeFilePath:N.string().describe("relative to project root")})),yJ=N.object({name:N.string()}),bJ=N.object({relativeFilePath:N.string()}),EJ=N.object({name:N.string()}),TJ=N.object({relativeFilePath:N.string()}),vJ=N.object({name:N.string(),description:N.string(),enabled:N.boolean(),steps:N.lazy(()=>ot.array()),testFilePath:N.string().describe("relative to the project root"),folderPath:N.string().optional().describe("user selected folder path")}),AJ=N.object({name:N.string(),description:N.string(),enabled:N.boolean()}).partial();var wJ=N.array(Of),RJ=N.object({defaultEnv:N.string().optional().describe("name of the default env, or undefined to unset")}),CJ=N.object({configFilePath:N.string().describe("full path on disk")}),xJ=N.string().array(),_J=N.object({message:N.string(),newRelativeTestPath:N.string().optional()}),_d=N.object({name:N.string(),absolutePath:N.string(),relativePath:N.string(),pathSegments:N.array(N.string()),isDirectory:N.boolean(),size:N.number(),createdAt:N.coerce.date(),modifiedAt:N.coerce.date(),accessedAt:N.coerce.date()}),jS=N.object({pathSegments:N.array(N.string())}),MJ=N.object({absolutePath:N.string(),pathSegments:N.array(N.string()),contents:N.array(_d)}),VS=N.object({pathSegments:N.array(N.string())}),$S=N.object({pathSegments:N.array(N.string()),newPathSegments:N.array(N.string())}),WS=N.object({pathSegments:N.array(N.string()),recursive:N.boolean().optional()}),PJ=N.object({success:N.boolean(),message:N.string(),pathSegments:N.array(N.string()).optional()});var ol=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],il=ol.map(r=>`**/${r}/**`),qS=!0,yn=!1;import Pr from"chalk";import eO from"safe-stable-stringify";import tO from"truncate-json";import rO from"zod";var Yo=eO.configure({deterministic:!1});function KS(r){let e=Yo(r),{jsonString:t}=tO(e,5e4);return t}var nO=["app","version","env","namespace","host"];function ve(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!nO.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var sl=rO.enum(["debug","info","warn","error"]);var ga={debug:20,info:30,warn:40,error:50},ll={20:"debug",30:"info",40:"warn",50:"error"},Md=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=ga[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[s,c]of a){let l=c;c instanceof Error?(l=c.message,console.log(t(` ${s}:`,l)),console.log(t(" stack:",c.stack))):typeof c=="object"?(l=Yo(c,void 0,2),l=l.split(`
|
|
6
10
|
`).map((u,d)=>d>0?` ${u}`:u).join(`
|
|
7
|
-
`),console.log(t(` ${s}:`,l))):console.log(t(` ${s}:`,l))}}else if(o)for(let a of o){let s=a;typeof a=="object"&&(s=
|
|
11
|
+
`),console.log(t(` ${s}:`,l))):console.log(t(` ${s}:`,l))}}else if(o)for(let a of o){let s=a;typeof a=="object"&&(s=Yo(a,void 0,2),s=s.split(`
|
|
8
12
|
`).map((c,l)=>l>0?` ${c}`:c).join(`
|
|
9
|
-
`)),console.log(" ",t(s))}}getLevel(){return Ws[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=ta[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,vr.reset,...e)}info(...e){this.logWithLevel(30,vr.white,...e)}debug(...e){this.logWithLevel(20,vr.dim,...e)}warn(...e){this.logWithLevel(40,vr.yellow,...e)}error(...e){this.logWithLevel(50,vr.red,...e)}success(...e){this.logWithLevel(1/0,vr.green,...e)}dimmed(...e){this.logWithLevel(30,vr.dim,...e)}underline(...e){this.logWithLevel(40,vr.underline,...e)}bold(...e){this.logWithLevel(40,vr.bold,...e)}grey(...e){this.logWithLevel(20,vr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},sd=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},HY=new sd,AP=typeof window>"u"&&typeof process<"u"&&$s.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?$s.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,x=new ad(AP,{}),Hn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Hn,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},Vs={},qs=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let s=Vs[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},Vs[e]=s),s.totalCount++,s.count<t&&(s.count++,r.debug(o,i,...a)),s.timer=setTimeout(()=>{let c=Vs[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete Vs[e]},n)};import{z as fe}from"zod";var wP=fe.array(Fo.extend({id:fe.string(),name:fe.string(),description:fe.string().optional(),labels:fe.string().array().optional()})),RP=fe.array(Fo.extend({id:fe.string(),name:fe.string(),description:fe.string().optional(),content:Fi})),Hf=fe.object({name:fe.string(),description:fe.string().optional(),settings:Qi.optional(),pathSegments:fe.string().array()}),qY=fe.object({id:fe.string(),fileName:fe.string(),fullPath:fe.string(),relativeFilePath:fe.string().describe("relative to project root")});var Gf=fe.object({steps:Zi.array().optional(),settings:Qi.optional()}),KY=fe.object({message:fe.literal("ok")}),jf=fe.object({tag:fe.string(),channel:fe.string(),filePath:fe.string()}),YY=fe.object({tests:wP,modules:RP,labels:fe.string().array()}),Vf=fe.object({name:fe.string(),description:fe.string(),enabled:fe.boolean()}).partial();import{z as ze}from"zod";var $f=ze.object({id:ze.string(),createdAt:ze.coerce.date(),createdBy:ze.string(),organizationId:ze.string(),name:ze.string(),description:ze.string().nullish(),enabled:ze.boolean(),schemaVersion:ze.string().describe("Schema version for steps"),parameters:ze.string().array().nullish().describe("Parameter list"),parameterEnums:ze.record(ze.string(),ze.string().array()).nullish(),defaultParameters:ze.record(ze.string(),ze.string()).nullish(),defaultCacheKey:ze.string().nullish(),defaultCacheTtl:ze.number().nullish(),defaultCacheAllInvocations:ze.boolean().nullish(),autoAuth:ze.boolean().nullish(),advanced:yu.nullish()}),o5=$f.extend({steps:ze.lazy(()=>Tt.array())}),i5=5*60*1e3,CP=$t.merge($f.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as l5}from"date-fns-tz";import{z as Re}from"zod";var ld=Lu.extend({aiAction:Re.boolean().optional(),stepLintSuggestions:Re.boolean().optional(),agentConfig:Re.record(Re.string(),Re.string()).optional(),aiFailureAnalysis:Re.boolean().optional(),aiPageFiltering:Re.boolean().optional().describe("rag v2 feature flag")}),cd=Re.object({fakerConstantSeed:Re.boolean().optional()}),g5=Re.object({ai:ld.optional(),githubAppInstallationId:Re.number().nullish(),githubAppSummaryMessageEnabled:Re.boolean().nullish(),githubReleaseAppInstallationId:Re.number().nullish(),gitlabAppAccessToken:Re.string().nullish(),gitlabAppBaseUrl:Re.string().nullish(),qaseAccessToken:Re.string().nullish(),testSuggestionsEnabled:Re.boolean().nullish(),browser:Ru.optional(),advanced:cd.optional()}),h5=Re.object({globalOverrides:Re.record(Re.string()).optional(),agentConfig:Re.record(Re.string(),Re.string()).optional()}),f5=Re.record(Re.string(),Re.string()).nullish();import*as y from"zod";import{z as Ue}from"zod";var ud=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(ud||{});var xP=Ue.object({type:Ue.literal("DESCRIPTION_UPDATE"),thoughts:Ue.string()}),Ks=Ue.discriminatedUnion("type",[xP]),_P=Ue.object({testId:Ue.string(),name:Ue.string(),orgId:Ue.string(),runId:Ue.string(),steps:Je.array(),purpose:Ue.nativeEnum(ud),details:Ks.or(Ks.array()).optional()});var E5=_P.pick({name:!0,orgId:!0}),MP=Ue.object({id:Ue.string(),name:Ue.string().nullish(),createdAt:Ue.string().pipe(Ue.coerce.date()).or(Ue.date()),organizationId:Ue.string(),schemaVersion:Ue.string(),runId:Ue.string().nullish(),purpose:Ue.nativeEnum(ud),details:Ks.or(Ks.array()).optional(),applied:Ue.boolean().nullish(),appliedAt:Ue.coerce.date().nullish()}),Wf=MP.extend({steps:Je.array()});var Ys="x-momentic-cli-version",qf="x-momentic-cli-type",Kf="x-momentic-logger-tags",PP="x-momentic-main-branch-name",IP="x-momentic-branch-name",OP="x-momentic-commit-timestamp",LP="x-momentic-last-commit-on-main",NP="x-momentic-last-commit-on-main-timestamp",kP="x-momentic-merged-branch-name",Yf="x-momentic-session-id",U5=y.object({error:y.boolean(),reason:y.string(),message:y.string()}),F5=gt.merge(Du),Xf=ms,B5=gt.merge(Du);var z5=gt.merge(Hh).extend({useConsensus:y.boolean().optional(),attemptNumber:y.number().optional()}),dd=Gg,H5=gt.merge(jh),Jf=uh,G5=gt.merge(Gh),Zf=ch,j5=gt.merge(Fh),Qf=sh,V5=gt.merge(Bh),eS=ih,$5=gt.merge(zh);var W5=gt.merge(qh),q5=y.object({testPaths:y.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:y.string().optional(),all:y.boolean().optional(),urlOverride:y.string().optional(),customHeaders:y.record(y.string(),y.string()).optional(),testInputMatrix:y.record(y.string(),y.string()).array().optional()}),tS=y.object({queuedTests:y.unknown().array(),runIds:y.string().uuid().array(),runGroupId:y.string().optional()});var K5=y.string().array(),Y5=y.union([y.object({paths:y.string().array().describe("run specific test paths (e.g. todo-test)"),all:y.boolean().describe("run all tests").optional()}),y.object({path:y.string().describe("deprecated; present for backcompat")})]),rS=y.object({tests:y.record(y.string().describe("Test name"),y.string().describe("Test YAML")),modules:y.record(y.string().describe("Module name"),y.string().describe("Module YAML"))}),DP=y.object({test:y.string().describe("test YAML"),modules:y.record(y.string().describe("moduleId"),y.string().describe("module YAML"))}),X5=DP.array(),J5=y.object({testId:y.string(),schemaVersion:y.string()}).merge(On);function pd(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[PP]=encodeURIComponent(e)),t&&(a[IP]=encodeURIComponent(t)),n&&(a[OP]=n.toISOString()),o&&(a[LP]=encodeURIComponent(o)),i&&(a[NP]=i.toISOString()),r.mergedGitBranchName&&(a[kP]=encodeURIComponent(r.mergedGitBranchName)),a}var Z5=y.object({entries:y.array(Qg),testId:y.string()}),Q5=y.object({entries:y.array(mf),testId:y.string()}),e4=y.object({testId:y.string()});function nS(r){return y.record(y.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 oS=nS(eh),iS=nS(gf),aS=y.object({trigger:y.nativeEnum(Kt),status:y.nativeEnum(be),startedAt:y.coerce.date().optional(),gitCommitSha:y.string().optional(),gitCommitShaShort:y.string().optional(),gitCommitTimestamp:y.coerce.date().optional(),gitBranchName:y.string().optional(),gitOriginUrl:y.string().optional(),gitCommitMessage:y.string().optional(),gitCommitAuthorName:y.string().optional(),githubRepository:y.string().optional(),gitlabProjectPath:y.string().optional(),pipelineId:y.string().optional(),cliVersion:y.string().optional()}),t4=y.object({id:y.string()}),sS=y.object({status:y.nativeEnum(be),updatedAt:y.coerce.date().optional(),finishedAt:y.coerce.date().optional()}),lS=y.object({stepsSnapshot:y.array(y.record(y.unknown())).optional(),runGroupId:y.string().optional(),testId:y.string(),testName:y.string(),resolvedBaseUrl:y.string().optional(),environmentName:y.string().optional(),labels:y.array(y.string()).optional(),cliVersion:y.string().optional(),trigger:y.nativeEnum(Kt),schemaVersion:y.string().optional(),section:y.nativeEnum(vs).optional(),resolvedInputs:y.record(y.string(),y.string()).optional(),quarantined:y.boolean().optional().default(!1),quarantinedReason:y.string().optional()}),r4=y.object({id:y.string()}),UP=Nu.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),cS=UP.array(),uS=Nu.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(),n4=y.object({id:y.string()}),dS=y.object({status:y.nativeEnum(be),finishedAt:y.coerce.date().optional(),schemaVersion:y.string().optional().default("1.0.19"),results:y.record(y.string(),y.unknown()).array().optional(),beforeResults:y.record(y.string(),y.unknown()).array().optional(),afterResults:y.record(y.string(),y.unknown()).array().optional()}),o4=y.object({screenshot:y.string()}),pS=y.object({key:y.string()}),mS=y.object({orgId:y.string(),userId:y.string()}),gS=y.array(Th),i4=y.record(y.string(),y.union([y.string(),y.boolean()])),a4=y.object({paths:y.string().array(),env:y.string().optional(),urlOverride:y.string().optional(),customHeaders:y.record(y.string(),y.string()).optional()}),hS=y.object({suiteRunIds:y.string().array(),runGroupIds:y.string().array()}),s4=y.object({suiteRunIds:y.string().array()}),l4=Nh.array(),c4=y.object({runGroupIds:y.string().array()}),FP=y.object({uploadUrl:y.string()}),u4=gt.merge(Vh),d4=gt.merge(Wh),p4=gt.merge($h),BP=y.object({testId:y.string().optional().default(""),testName:y.string().optional().default(""),suiteId:y.string().optional().default(""),suiteName:y.string().optional().default(""),creditsUsed:y.number().optional()}),zP=y.object({transactionId:y.string(),timestamp:y.string(),event:y.nativeEnum(Wi),properties:BP}),m4=zP.array(),fS=Wf.omit({steps:!0}).extend({steps:y.array(y.record(y.string(),y.unknown())).describe("unparsed ResolvedStep[]")}),g4=y.object({limit:y.number().max(10).optional(),afterTime:y.number().optional()}),SS=Ih.array(),h4=y.object({applied:y.boolean().optional(),appliedAt:y.coerce.date().optional()}),yS=FP.extend({id:y.string()}),f4=y.object({runGroupId:y.string().uuid().optional()}),bS=y.object({runGroupId:y.string().uuid()}),ES=y.object({quarantined:y.object({testId:y.string().uuid(),quarantinedAt:y.coerce.date(),quarantinedBy:y.string().optional(),quarantinedReason:y.string()}).array()}),S4=y.object({testId:y.string().uuid(),testName:y.string().optional(),reason:y.string(),gitLocalUsername:y.string().optional(),gitLocalEmail:y.string().optional(),gitLocalName:y.string().optional()}),y4=y.object({testName:y.string().optional(),reason:y.string().optional(),gitLocalUsername:y.string().optional(),gitLocalEmail:y.string().optional(),gitLocalName:y.string().optional()}),b4=gt.merge(Jh),E4=gt.merge(Zh),T4=y.object({apkToInstall:y.object({channel:y.string(),tag:y.string().optional()}).optional(),hostname:y.string().optional(),region:y.nativeEnum(Ki).optional()}),TS=y.object({name:y.string(),webRtcUrl:y.string(),adbUrl:y.string(),token:y.string(),apkDownloadUrl:y.string().optional(),region:y.string().optional()}),v4=y.object({channel:y.string(),tag:y.string(),md5:y.string()}),vS=y.object({id:y.string(),uploadUrl:y.string().optional(),downloadUrl:y.string(),md5:y.string().optional()}),AS=y.object({assets:y.array(y.object({channel:y.string(),tag:y.string(),md5:y.string(),createdAt:y.number().describe("Unix timestamp in milliseconds")}))});import{z as J}from"zod";var HP=3,R4=J.object({localTestId:J.string(),quarantinedAt:J.date(),quarantinedBy:J.string().optional(),quarantinedReason:J.string(),quarantinedByGitEmail:J.string().optional(),quarantinedByGitName:J.string().optional(),quarantinedByGitUsername:J.string().optional()}).or(J.object({cloudTestId:J.string(),quarantinedAt:J.date(),quarantinedBy:J.string().optional(),quarantinedReason:J.string(),quarantinedByGitEmail:J.string().optional(),quarantinedByGitName:J.string().optional(),quarantinedByGitUsername:J.string().optional()})),wS=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(wS||{});var md=J.object({name:J.string(),description:J.string().nullish(),effect:J.nativeEnum(wS),labels:J.array(J.string()),githubRepository:J.string().nullish(),gitlabProjectPath:J.string().nullish(),gitBranchName:J.string().nullish()}),GP=J.object({type:J.literal("LAST_N_RUNS"),lastN:J.number().min(HP).max(10)}),jP=J.object({type:J.literal("LAST_N_HOURS"),lastN:J.number().min(1).max(24)}),VP=J.object({type:J.literal("LAST_N_DAYS"),lastN:J.number().min(1).max(7)}),gd=J.discriminatedUnion("type",[GP,jP,VP]),$P=J.object({flakeRateThreshold:J.number().min(1).max(100),evaluationWindow:gd}),WP=md.extend({type:J.literal("FLAKE_RATE"),config:$P}),qP=J.object({passRateThreshold:J.number().min(1).max(100),evaluationWindow:gd}),KP=md.extend({type:J.literal("PASS_RATE"),config:qP}),YP=J.object({failureCountThreshold:J.number().min(0),evaluationWindow:gd}),XP=md.extend({type:J.literal("FAILURE_COUNT"),config:YP}),C4=J.discriminatedUnion("type",[WP,KP,XP]);import{z as He}from"zod";var M4=He.object({repositoriesIndexed:He.boolean(),indexingInProgress:He.boolean(),indexesOutdated:He.boolean()}),RS=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(RS||{}),CS=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(CS||{}),P4=He.object({name:He.string(),status:He.nativeEnum(RS),conclusion:He.nativeEnum(CS).nullable()}),ra=He.object({sha:He.string(),message:He.string(),author:He.object({name:He.string().optional(),email:He.string().optional(),date:He.coerce.date().optional()}),committer:He.object({name:He.string().optional(),email:He.string().optional(),date:He.coerce.date().optional()})}),hd=He.object({mergedBranch:He.string().optional()});import{z as Ne}from"zod";var xS=Ne.object({orgId:Ne.string(),cacheKeys:Ne.string().array()}),L4=Ne.object({keyParams:xS,clientMetadata:Ne.string(),lockAcquisitionTimeoutMs:Ne.number().optional()}),_S=Ne.object({acquired:Ne.boolean(),acquiredByMetadata:Ne.string(),keyPrefix:Ne.string()}),N4=Ne.object({keyPrefix:Ne.string(),result:Ne.string(),ttlMs:Ne.number()}),k4=Ne.union([Ne.object({keyPrefix:Ne.string()}),xS]),JP=Ne.object({remainingTtlMs:Ne.number(),value:Ne.string().nullish()}),D4=Ne.object({results:Ne.record(Ne.string(),JP),activeLocks:Ne.string().array()});var U4=5*60*1e3;var H4=90*24*60*60*1e3,G4=7*24*60*60*1e3;import{z as MS}from"zod";var $4=MS.object({quarantineNotifications:MS.string().nullish()});import{z as lt}from"zod";var ZP=lt.object({version:lt.string(),json:lt.record(lt.unknown()),hash:lt.string()}),PS=lt.record(lt.unknown()),Y4=lt.object({newSvgs:lt.array(ZP),metadata:PS.optional()}),QP=lt.object({version:lt.string(),json:lt.record(lt.unknown()).nullish(),hash:lt.string(),description:lt.string().nullish(),metadata:PS.nullish()}),IS=lt.record(lt.string().describe("icon hash"),QP);import{z as De}from"zod";var fd=De.object({assertion:De.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),eI=De.object({instruction:De.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:fd.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.")}),OS=eI.extend({subSteps:De.lazy(()=>OS.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),LS=De.object({name:De.string().describe("Short name describing the test plan"),description:De.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),NS=LS.extend({id:De.string(),createdAt:De.coerce.date(),updatedAt:De.coerce.date(),updatedBy:De.string(),createdBy:De.string(),test:De.object({id:De.string(),name:De.string()}).nullish().transform(r=>r??void 0)}),Q4=NS.extend({testGenRuns:De.tuple([]).or(De.tuple([De.object({id:De.string(),startedAt:De.coerce.date(),status:De.nativeEnum(be)})]))}),kS=De.object({preConditions:fd.array().nullish().transform(r=>r??[]),postConditions:fd.array().nullish().transform(r=>r??[]),steps:OS.array().nullish().transform(r=>r??[])}),e3=NS.extend({plan:kS.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),tI=LS.extend({plan:kS.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),t3=tI.array().nullish().transform(r=>r??[]);import{validator as rI}from"@exodus/schemasafe";function DS(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{rI(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var US=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var Xs=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as y3}from"zod";var Js=class{async resolveEntries(){}async saveEntries(){}};import{z as Sd}from"zod";var FS=Sd.object({parentStepIdChain:Sd.array(Sd.string()),result:dr});import{z as X}from"zod";var nI=X.object({step:Je,status:X.nativeEnum(Ze),startedAt:X.coerce.date(),finishedAt:X.coerce.date().optional(),healMetadata:X.object({healType:X.nativeEnum(zi).or(X.literal("AI")),healedAt:X.coerce.date()}).optional(),beforeSnapshotId:X.string().uuid().optional(),afterSnapshotId:X.string().uuid().optional(),message:X.string().optional()}),oI=nI.extend({finishedAt:X.coerce.date().optional().transform(r=>r??new Date)}),D3=oI.extend({step:X.unknown()}),BS="1.0.0",yd=dS.extend({id:X.string().uuid().optional(),startedAt:X.coerce.date(),runAttemptSchemaVersion:X.string().optional(),schemaVersion:X.string().optional().default("1.0.19"),results:X.record(X.string(),X.unknown()).array().optional(),beforeResults:X.record(X.string(),X.unknown()).array().optional(),afterResults:X.record(X.string(),X.unknown()).array().optional()}),zS=yd.extend({finishedAt:X.coerce.date().optional().transform(r=>r??new Date)}),U3=yd.merge(Hi),F3=zS.merge(Hi),HS=X.object({results:X.array(dr),beforeResults:X.array(dr).optional(),afterResults:X.array(dr).optional()}),B3=yd.merge(HS),z3=zS.merge(HS),iI=uS.merge(lS).extend({executionType:X.nativeEnum(Io).optional().default("WEB"),testId:X.string().uuid(),testDescription:X.string().optional(),runGroupId:X.string().uuid(),status:X.nativeEnum(be),startedAt:X.coerce.date(),attempts:X.number(),failureRecoveryDetails:X.record(X.unknown()).optional()}),H3=iI.extend({finishedAt:X.coerce.date().optional().transform(r=>r??new Date)}),aI=aS.merge(sS).extend({id:X.string().uuid().optional(),startedAt:X.coerce.date(),cliVersion:X.string(),labels:X.string().array().optional().default([])}),na=aI.extend({updatedAt:X.coerce.date().optional().transform(r=>r??new Date),finishedAt:X.coerce.date().optional().transform(r=>r??new Date)});import{fileURLToPath as dI}from"url";var VS,pI=dI(import.meta.url),mI=lI(pI);VS=uI(mI,"..");var oa=VS;x.info(`Setting APPIUM_HOME to ${oa}`);process.env.APPIUM_HOME=oa;var gI="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.",hI="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.",fI="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",$S="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",WS="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function SI(){if(!process.env.JAVA_HOME)x.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)&&x.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)=>cI(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");sI(e)||x.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{GS("java --version",{stdio:"pipe",encoding:"utf-8"})||(x.error(`Could not find a Java installation. ${gI}`),process.exit(1))}catch(r){x.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function yI(){process.env.ANDROID_HOME||(x.error(`The ANDROID_HOME environment variable is not set. ${fI} ${jS()==="darwin"?$S:WS}`),process.exit(1))}function bI(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{GS(`${r} version`,{stdio:"pipe",encoding:"utf-8"})||(x.error(`Could not find the Android Debug Bridge (ADB) tool locally. This tool is included with Android Studio. ${hI} Finally, ensure that the 'adb' command is available in your shell. ${jS()==="darwin"?$S:WS}`),process.exit(1))}catch(e){x.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function qS(){SI(),yI(),bI()}import{create as EI,windowedFiniteBatchScheduler as TI}from"@yornaath/batshit";import vI from"ws";var AI=100,wI=2500,KS=4e3,RI="\u2026";async function Zs({driver:r,onLogs:e}){await r.execute("mobile: startLogsBroadcast");let t=EI({fetcher:async l=>{e(l)},resolver:()=>{},scheduler:TI({windowMs:wI,maxBatchSize:AI})}),{hostname:n="localhost",port:o=4723,protocol:i="http"}=r.options,s=`${i==="https"?"wss":"ws"}://${n}:${o}/ws/session/${r.sessionId}/appium/device/logcat`,c=new vI(s);return c.on("message",l=>{let u=l.toString().trim();u.length!==0&&(u.length>KS&&(u=u.slice(0,KS)+RI),t.fetch(u).catch(()=>{}))}),async()=>{try{c.close()}catch{}try{await r.execute("mobile: stopLogsBroadcast")}catch{}}}import{Server as $U}from"socket.io";import{randomUUID as DI}from"crypto";import{faker as CI}from"@faker-js/faker";import xI from"assert";import _I from"axios";import*as MI from"child_process";import PI from"moment";import*as II from"otpauth";import OI from"pg";var pn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var YS=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 V(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((s,c)=>{let l;if(e.signal){let{signal:p}=e;if(p.aborted)return c(YS(p));l=()=>c(YS(p)),p.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(p){c(p)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let p=o instanceof Error?o:new pn(o??`Promise timed out after ${t}ms`);c(p)}};a=i.setTimeout(u,t);let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(p=>{d(),s(p)}).catch(p=>{d(),c(p)})})}async function XS(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=_s(n,e);t.push(...o)}),t}function LI(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 NI(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 kI=Object.getPrototypeOf(async function(){}).constructor;async function JS(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:s}=e.bindings,c=e.tools,l={},u=(R,A)=>{o[R]=A,l[R]=A},d={},p=(R,A)=>{o[R]=A,d[R]=A},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 kI("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(_I,PI,c.fakerInstance??CI,xI,OI,g,m,II,MI,XS,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,A=>c.sms.send(A),A=>c.sms.fetchLatest(A),c.email,c.sms,c.ai,LI(a,s),...Object.values(i??{}))),f=!0,E,S;try{let R=await V(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});E=await NI(e.options.responseSerialization??"RAW",R)}catch(R){t.error({err:R,env:o,evalCode:n},`[${r}] Error executing code: ${R}`),f=!1,R instanceof pn?S=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:S=R instanceof Error?R.message:`${R}`}return{result:E,variableUpdates:l,persistentVariableUpdates:d,success:f,error:S}}async function ZS({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=sn,disallowVariableUpdates:s,additionalBindings:c,responseSerialization:l,mock:u}){let d=DI(),p=await JS(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:s,responseSerialization:l},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return x.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as UI,randomUUID as FI}from"crypto";import BI from"fetch-retry";var zI=BI(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}}),QS=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,ey=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function ty({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=sn,retries:i=2,signal:a,logger:s,additionalBindings:c,disallowVariableUpdates:l,responseSerialization:u,mock:d}){if(!QS)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,g,m=0;if(!ey)throw new Error("Missing lambda auth secret.");let h=UI("sha256",ey).update(r).digest("hex");for(;m<=i;){m++,a?.throwIfAborted();let E={id:FI(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:l,responseSerialization:u};try{if(p=await V(zI(QS,{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(S){g=S}}if(g)throw s.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=Tf.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 Ar(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await ty(r);else if(r.localTools)e=await ZS({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
13
|
+
`)),console.log(" ",t(s))}}getLevel(){return ll[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=ga[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,Pr.reset,...e)}info(...e){this.logWithLevel(30,Pr.white,...e)}debug(...e){this.logWithLevel(20,Pr.dim,...e)}warn(...e){this.logWithLevel(40,Pr.yellow,...e)}error(...e){this.logWithLevel(50,Pr.red,...e)}success(...e){this.logWithLevel(1/0,Pr.green,...e)}dimmed(...e){this.logWithLevel(30,Pr.dim,...e)}underline(...e){this.logWithLevel(40,Pr.underline,...e)}bold(...e){this.logWithLevel(40,Pr.bold,...e)}grey(...e){this.logWithLevel(20,Pr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},Pd=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},FJ=new Pd,oO=typeof window>"u"&&typeof process<"u"&&sl.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?sl.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,x=new Md(oO,{}),bn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>bn,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},al={},cl=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let s=al[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},al[e]=s),s.totalCount++,s.count<t&&(s.count++,r.debug(o,i,...a)),s.timer=setTimeout(()=>{let c=al[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete al[e]},n)};import{z as Ee}from"zod";var iO=Ee.array(Ko.extend({id:Ee.string(),name:Ee.string(),description:Ee.string().optional(),labels:Ee.string().array().optional()})),aO=Ee.array(Ko.extend({id:Ee.string(),name:Ee.string(),description:Ee.string().optional(),content:Qi})),YS=Ee.object({name:Ee.string(),description:Ee.string().optional(),settings:ha.optional(),pathSegments:Ee.string().array()}),VJ=Ee.object({id:Ee.string(),fileName:Ee.string(),fullPath:Ee.string(),relativeFilePath:Ee.string().describe("relative to project root")});var XS=Ee.object({steps:ma.array().optional(),settings:ha.optional()}),$J=Ee.object({message:Ee.literal("ok")}),JS=Ee.object({tag:Ee.string(),channel:Ee.string(),filePath:Ee.string()}),WJ=Ee.object({tests:iO,modules:aO,labels:Ee.string().array()}),ZS=Ee.object({name:Ee.string(),description:Ee.string(),enabled:Ee.boolean()}).partial();import{z as $e}from"zod";var QS=$e.object({id:$e.string(),createdAt:$e.coerce.date(),createdBy:$e.string(),organizationId:$e.string(),name:$e.string(),description:$e.string().nullish(),enabled:$e.boolean(),schemaVersion:$e.string().describe("Schema version for steps"),parameters:$e.string().array().nullish().describe("Parameter list"),parameterEnums:$e.record($e.string(),$e.string().array()).nullish(),defaultParameters:$e.record($e.string(),$e.string()).nullish(),defaultCacheKey:$e.string().nullish(),defaultCacheTtl:$e.number().nullish(),defaultCacheAllInvocations:$e.boolean().nullish(),autoAuth:$e.boolean().nullish(),advanced:Wu.nullish()}),t6=QS.extend({steps:$e.lazy(()=>xt.array())}),r6=5*60*1e3,sO=Jt.merge(QS.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as i6}from"date-fns-tz";import{z as Me}from"zod";var Id=sd.extend({aiAction:Me.boolean().optional(),stepLintSuggestions:Me.boolean().optional(),agentConfig:Me.record(Me.string(),Me.string()).optional(),aiFailureAnalysis:Me.boolean().optional(),aiPageFiltering:Me.boolean().optional().describe("rag v2 feature flag")}),Od=Me.object({fakerConstantSeed:Me.boolean().optional()}),d6=Me.object({ai:Id.optional(),githubAppInstallationId:Me.number().nullish(),githubAppSummaryMessageEnabled:Me.boolean().nullish(),githubReleaseAppInstallationId:Me.number().nullish(),gitlabAppAccessToken:Me.string().nullish(),gitlabAppBaseUrl:Me.string().nullish(),qaseAccessToken:Me.string().nullish(),testSuggestionsEnabled:Me.boolean().nullish(),browser:ed.optional(),advanced:Od.optional()}),p6=Me.object({globalOverrides:Me.record(Me.string()).optional(),agentConfig:Me.record(Me.string(),Me.string()).optional()}),m6=Me.record(Me.string(),Me.string()).nullish();import*as y from"zod";import{z as Ge}from"zod";var Ld=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(Ld||{});var lO=Ge.object({type:Ge.literal("DESCRIPTION_UPDATE"),thoughts:Ge.string()}),ul=Ge.discriminatedUnion("type",[lO]),cO=Ge.object({testId:Ge.string(),name:Ge.string(),orgId:Ge.string(),runId:Ge.string(),steps:ot.array(),purpose:Ge.nativeEnum(Ld),details:ul.or(ul.array()).optional()});var S6=cO.pick({name:!0,orgId:!0}),uO=Ge.object({id:Ge.string(),name:Ge.string().nullish(),createdAt:Ge.string().pipe(Ge.coerce.date()).or(Ge.date()),organizationId:Ge.string(),schemaVersion:Ge.string(),runId:Ge.string().nullish(),purpose:Ge.nativeEnum(Ld),details:ul.or(ul.array()).optional(),applied:Ge.boolean().nullish(),appliedAt:Ge.coerce.date().nullish()}),ey=uO.extend({steps:ot.array()});var dl="x-momentic-cli-version",ty="x-momentic-cli-type",ry="x-momentic-logger-tags",dO="x-momentic-main-branch-name",pO="x-momentic-branch-name",mO="x-momentic-commit-timestamp",hO="x-momentic-last-commit-on-main",gO="x-momentic-last-commit-on-main-timestamp",fO="x-momentic-merged-branch-name",ny="x-momentic-session-id",N6=y.object({error:y.boolean(),reason:y.string(),message:y.string()}),k6=bt.merge(ud),oy=Rs,D6=bt.merge(ud);var U6=bt.merge(Jf).extend({useConsensus:y.boolean().optional(),attemptNumber:y.number().optional()}),Nd=pg,F6=bt.merge(Qf),iy=Ef,B6=bt.merge(Zf),ay=bf,z6=bt.merge(Kf),sy=Sf,H6=bt.merge(Yf),ly=gf,G6=bt.merge(Xf);var j6=bt.merge(nS),V6=y.object({testPaths:y.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:y.string().optional(),all:y.boolean().optional(),urlOverride:y.string().optional(),customHeaders:y.record(y.string(),y.string()).optional(),testInputMatrix:y.record(y.string(),y.string()).array().optional()}),cy=y.object({queuedTests:y.unknown().array(),runIds:y.string().uuid().array(),runGroupId:y.string().optional()});var $6=y.string().array(),W6=y.union([y.object({paths:y.string().array().describe("run specific test paths (e.g. todo-test)"),all:y.boolean().describe("run all tests").optional()}),y.object({path:y.string().describe("deprecated; present for backcompat")})]),uy=y.object({tests:y.record(y.string().describe("Test name"),y.string().describe("Test YAML")),modules:y.record(y.string().describe("Module name"),y.string().describe("Module YAML"))}),SO=y.object({test:y.string().describe("test YAML"),modules:y.record(y.string().describe("moduleId"),y.string().describe("module YAML"))}),q6=SO.array(),K6=y.object({testId:y.string(),schemaVersion:y.string()}).merge(Gn);function kd(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[dO]=encodeURIComponent(e)),t&&(a[pO]=encodeURIComponent(t)),n&&(a[mO]=n.toISOString()),o&&(a[hO]=encodeURIComponent(o)),i&&(a[gO]=i.toISOString()),r.mergedGitBranchName&&(a[fO]=encodeURIComponent(r.mergedGitBranchName)),a}var Y6=y.object({entries:y.array(_g),testId:y.string()}),X6=y.object({entries:y.array(vS),testId:y.string()}),J6=y.object({testId:y.string()});function dy(r){return y.record(y.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 py=dy(Mg),my=dy(AS),hy=y.object({trigger:y.nativeEnum(er),status:y.nativeEnum(Ae),startedAt:y.coerce.date().optional(),gitCommitSha:y.string().optional(),gitCommitShaShort:y.string().optional(),gitCommitTimestamp:y.coerce.date().optional(),gitBranchName:y.string().optional(),gitOriginUrl:y.string().optional(),gitCommitMessage:y.string().optional(),gitCommitAuthorName:y.string().optional(),githubRepository:y.string().optional(),gitlabProjectPath:y.string().optional(),pipelineId:y.string().optional(),cliVersion:y.string().optional()}),Z6=y.object({id:y.string()}),gy=y.object({status:y.nativeEnum(Ae),updatedAt:y.coerce.date().optional(),finishedAt:y.coerce.date().optional()}),fy=y.object({stepsSnapshot:y.array(y.record(y.unknown())).optional(),runGroupId:y.string().optional(),testId:y.string(),testName:y.string(),resolvedBaseUrl:y.string().optional(),environmentName:y.string().optional(),labels:y.array(y.string()).optional(),cliVersion:y.string().optional(),trigger:y.nativeEnum(er),schemaVersion:y.string().optional(),section:y.nativeEnum(Gs).optional(),resolvedInputs:y.record(y.string(),y.string()).optional(),quarantined:y.boolean().optional().default(!1),quarantinedReason:y.string().optional()}),Q6=y.object({id:y.string()}),yO=ld.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Sy=yO.array(),yy=ld.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(),e8=y.object({id:y.string()}),by=y.object({status:y.nativeEnum(Ae),finishedAt:y.coerce.date().optional(),schemaVersion:y.string().optional().default("1.0.19"),results:y.record(y.string(),y.unknown()).array().optional(),beforeResults:y.record(y.string(),y.unknown()).array().optional(),afterResults:y.record(y.string(),y.unknown()).array().optional()}),t8=y.object({screenshot:y.string()}),Ey=y.object({key:y.string()}),Ty=y.object({orgId:y.string(),userId:y.string()}),vy=y.array(If),r8=y.record(y.string(),y.union([y.string(),y.boolean()])),n8=y.object({paths:y.string().array(),env:y.string().optional(),urlOverride:y.string().optional(),customHeaders:y.record(y.string(),y.string()).optional()}),Ay=y.object({suiteRunIds:y.string().array(),runGroupIds:y.string().array()}),o8=y.object({suiteRunIds:y.string().array()}),i8=Vf.array(),a8=y.object({runGroupIds:y.string().array()}),bO=y.object({uploadUrl:y.string()}),s8=bt.merge(eS),l8=bt.merge(rS),c8=bt.merge(tS),EO=y.object({testId:y.string().optional().default(""),testName:y.string().optional().default(""),suiteId:y.string().optional().default(""),suiteName:y.string().optional().default(""),creditsUsed:y.number().optional()}),TO=y.object({transactionId:y.string(),timestamp:y.string(),event:y.nativeEnum(sa),properties:EO}),u8=TO.array(),wy=ey.omit({steps:!0}).extend({steps:y.array(y.record(y.string(),y.unknown())).describe("unparsed ResolvedStep[]")}),d8=y.object({limit:y.number().max(10).optional(),afterTime:y.number().optional()}),Ry=Hf.array(),p8=y.object({applied:y.boolean().optional(),appliedAt:y.coerce.date().optional()}),Cy=bO.extend({id:y.string()}),m8=y.object({runGroupId:y.string().uuid().optional()}),xy=y.object({runGroupId:y.string().uuid()}),_y=y.object({quarantined:y.object({testId:y.string().uuid(),quarantinedAt:y.coerce.date(),quarantinedBy:y.string().optional(),quarantinedReason:y.string()}).array()}),h8=y.object({testId:y.string().uuid(),testName:y.string().optional(),reason:y.string(),gitLocalUsername:y.string().optional(),gitLocalEmail:y.string().optional(),gitLocalName:y.string().optional()}),g8=y.object({testName:y.string().optional(),reason:y.string().optional(),gitLocalUsername:y.string().optional(),gitLocalEmail:y.string().optional(),gitLocalName:y.string().optional()}),f8=bt.merge(sS),S8=bt.merge(lS),y8=y.object({apkToInstall:y.object({channel:y.string(),tag:y.string().optional()}).optional(),hostname:y.string().optional(),region:y.nativeEnum(ca).optional()}),My=y.object({name:y.string(),webRtcUrl:y.string(),adbUrl:y.string(),token:y.string(),apkDownloadUrl:y.string().optional(),region:y.string().optional()}),b8=y.object({channel:y.string(),tag:y.string(),md5:y.string()}),Py=y.object({id:y.string(),uploadUrl:y.string().optional(),downloadUrl:y.string(),md5:y.string().optional()}),Iy=y.object({assets:y.array(y.object({channel:y.string(),tag:y.string(),md5:y.string(),createdAt:y.number().describe("Unix timestamp in milliseconds")}))});import{z as Q}from"zod";var vO=3,v8=Q.object({localTestId:Q.string(),quarantinedAt:Q.date(),quarantinedBy:Q.string().optional(),quarantinedReason:Q.string(),quarantinedByGitEmail:Q.string().optional(),quarantinedByGitName:Q.string().optional(),quarantinedByGitUsername:Q.string().optional()}).or(Q.object({cloudTestId:Q.string(),quarantinedAt:Q.date(),quarantinedBy:Q.string().optional(),quarantinedReason:Q.string(),quarantinedByGitEmail:Q.string().optional(),quarantinedByGitName:Q.string().optional(),quarantinedByGitUsername:Q.string().optional()})),Oy=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(Oy||{});var Dd=Q.object({name:Q.string(),description:Q.string().nullish(),effect:Q.nativeEnum(Oy),labels:Q.array(Q.string()),githubRepository:Q.string().nullish(),gitlabProjectPath:Q.string().nullish(),gitBranchName:Q.string().nullish()}),AO=Q.object({type:Q.literal("LAST_N_RUNS"),lastN:Q.number().min(vO).max(10)}),wO=Q.object({type:Q.literal("LAST_N_HOURS"),lastN:Q.number().min(1).max(24)}),RO=Q.object({type:Q.literal("LAST_N_DAYS"),lastN:Q.number().min(1).max(7)}),Ud=Q.discriminatedUnion("type",[AO,wO,RO]),CO=Q.object({flakeRateThreshold:Q.number().min(1).max(100),evaluationWindow:Ud}),xO=Dd.extend({type:Q.literal("FLAKE_RATE"),config:CO}),_O=Q.object({passRateThreshold:Q.number().min(1).max(100),evaluationWindow:Ud}),MO=Dd.extend({type:Q.literal("PASS_RATE"),config:_O}),PO=Q.object({failureCountThreshold:Q.number().min(0),evaluationWindow:Ud}),IO=Dd.extend({type:Q.literal("FAILURE_COUNT"),config:PO}),A8=Q.discriminatedUnion("type",[xO,MO,IO]);import{z as We}from"zod";var C8=We.object({repositoriesIndexed:We.boolean(),indexingInProgress:We.boolean(),indexesOutdated:We.boolean()}),Ly=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(Ly||{}),Ny=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(Ny||{}),x8=We.object({name:We.string(),status:We.nativeEnum(Ly),conclusion:We.nativeEnum(Ny).nullable()}),fa=We.object({sha:We.string(),message:We.string(),author:We.object({name:We.string().optional(),email:We.string().optional(),date:We.coerce.date().optional()}),committer:We.object({name:We.string().optional(),email:We.string().optional(),date:We.coerce.date().optional()})}),Fd=We.object({mergedBranch:We.string().optional()});import{z as Be}from"zod";var ky=Be.object({orgId:Be.string(),cacheKeys:Be.string().array()}),P8=Be.object({keyParams:ky,clientMetadata:Be.string(),lockAcquisitionTimeoutMs:Be.number().optional()}),Dy=Be.object({acquired:Be.boolean(),acquiredByMetadata:Be.string(),keyPrefix:Be.string()}),I8=Be.object({keyPrefix:Be.string(),result:Be.string(),ttlMs:Be.number()}),O8=Be.union([Be.object({keyPrefix:Be.string()}),ky]),OO=Be.object({remainingTtlMs:Be.number(),value:Be.string().nullish()}),L8=Be.object({results:Be.record(Be.string(),OO),activeLocks:Be.string().array()});var N8=5*60*1e3;var F8=90*24*60*60*1e3,B8=7*24*60*60*1e3;import{z as Uy}from"zod";var G8=Uy.object({quarantineNotifications:Uy.string().nullish()});import{z as mt}from"zod";var LO=mt.object({version:mt.string(),json:mt.record(mt.unknown()),hash:mt.string()}),Fy=mt.record(mt.unknown()),W8=mt.object({newSvgs:mt.array(LO),metadata:Fy.optional()}),NO=mt.object({version:mt.string(),json:mt.record(mt.unknown()).nullish(),hash:mt.string(),description:mt.string().nullish(),metadata:Fy.nullish()}),By=mt.record(mt.string().describe("icon hash"),NO);import{z as He}from"zod";var Bd=He.object({assertion:He.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),kO=He.object({instruction:He.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:Bd.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.")}),zy=kO.extend({subSteps:He.lazy(()=>zy.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Hy=He.object({name:He.string().describe("Short name describing the test plan"),description:He.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),Gy=Hy.extend({id:He.string(),createdAt:He.coerce.date(),updatedAt:He.coerce.date(),updatedBy:He.string(),createdBy:He.string(),test:He.object({id:He.string(),name:He.string()}).nullish().transform(r=>r??void 0)}),X8=Gy.extend({testGenRuns:He.tuple([]).or(He.tuple([He.object({id:He.string(),startedAt:He.coerce.date(),status:He.nativeEnum(Ae)})]))}),jy=He.object({preConditions:Bd.array().nullish().transform(r=>r??[]),postConditions:Bd.array().nullish().transform(r=>r??[]),steps:zy.array().nullish().transform(r=>r??[])}),J8=Gy.extend({plan:jy.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),DO=Hy.extend({plan:jy.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),Z8=DO.array().nullish().transform(r=>r??[]);import{validator as UO}from"@exodus/schemasafe";function Vy(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{UO(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var $y=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var pl=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as g9}from"zod";var ml=class{async resolveEntries(){}async saveEntries(){}};import{z as zd}from"zod";var Wy=zd.object({parentStepIdChain:zd.array(zd.string()),result:br});import{z as Z}from"zod";var FO=Z.object({step:ot,status:Z.nativeEnum(it),startedAt:Z.coerce.date(),finishedAt:Z.coerce.date().optional(),healMetadata:Z.object({healType:Z.nativeEnum(ta).or(Z.literal("AI")),healedAt:Z.coerce.date()}).optional(),beforeSnapshotId:Z.string().uuid().optional(),afterSnapshotId:Z.string().uuid().optional(),message:Z.string().optional()}),BO=FO.extend({finishedAt:Z.coerce.date().optional().transform(r=>r??new Date)}),L9=BO.extend({step:Z.unknown()}),qy="1.0.0",Hd=by.extend({id:Z.string().uuid().optional(),startedAt:Z.coerce.date(),runAttemptSchemaVersion:Z.string().optional(),schemaVersion:Z.string().optional().default("1.0.19"),results:Z.record(Z.string(),Z.unknown()).array().optional(),beforeResults:Z.record(Z.string(),Z.unknown()).array().optional(),afterResults:Z.record(Z.string(),Z.unknown()).array().optional()}),Ky=Hd.extend({finishedAt:Z.coerce.date().optional().transform(r=>r??new Date)}),N9=Hd.merge(ra),k9=Ky.merge(ra),Yy=Z.object({results:Z.array(br),beforeResults:Z.array(br).optional(),afterResults:Z.array(br).optional()}),D9=Hd.merge(Yy),U9=Ky.merge(Yy),zO=yy.merge(fy).extend({executionType:Z.nativeEnum(Go).optional().default("WEB"),testId:Z.string().uuid(),testDescription:Z.string().optional(),runGroupId:Z.string().uuid(),status:Z.nativeEnum(Ae),startedAt:Z.coerce.date(),attempts:Z.number(),failureRecoveryDetails:Z.record(Z.unknown()).optional()}),F9=zO.extend({finishedAt:Z.coerce.date().optional().transform(r=>r??new Date)}),HO=hy.merge(gy).extend({id:Z.string().uuid().optional(),startedAt:Z.coerce.date(),cliVersion:Z.string(),labels:Z.string().array().optional().default([])}),Sa=HO.extend({updatedAt:Z.coerce.date().optional().transform(r=>r??new Date),finishedAt:Z.coerce.date().optional().transform(r=>r??new Date)});import{fileURLToPath as WO}from"url";var Zy,qO=WO(import.meta.url),KO=jO(qO);Zy=$O(KO,"..");var ya=Zy;x.info(`Setting APPIUM_HOME to ${ya}`);process.env.APPIUM_HOME=ya;var YO="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.",XO="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.",JO="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",Qy="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",eb="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function ZO(){if(!process.env.JAVA_HOME)x.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)&&x.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)=>VO(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");GO(e)||x.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{Xy("java --version",{stdio:"pipe",encoding:"utf-8"})||(x.error(`Could not find a Java installation. ${YO}`),process.exit(1))}catch(r){x.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function QO(){process.env.ANDROID_HOME||(x.error(`The ANDROID_HOME environment variable is not set. ${JO} ${Jy()==="darwin"?Qy:eb}`),process.exit(1))}function eL(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{Xy(`${r} version`,{stdio:"pipe",encoding:"utf-8"})||(x.error(`Could not find the Android Debug Bridge (ADB) tool locally. This tool is included with Android Studio. ${XO} Finally, ensure that the 'adb' command is available in your shell. ${Jy()==="darwin"?Qy:eb}`),process.exit(1))}catch(e){x.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function tb(){ZO(),QO(),eL()}import{create as tL,windowedFiniteBatchScheduler as rL}from"@yornaath/batshit";import nL from"ws";var oL=100,iL=2500,rb=4e3,aL="\u2026";async function hl({driver:r,onLogs:e}){await r.execute("mobile: startLogsBroadcast");let t=tL({fetcher:async l=>{e(l)},resolver:()=>{},scheduler:rL({windowMs:iL,maxBatchSize:oL})}),{hostname:n="localhost",port:o=4723,protocol:i="http"}=r.options,s=`${i==="https"?"wss":"ws"}://${n}:${o}/ws/session/${r.sessionId}/appium/device/logcat`,c=new nL(s);return c.on("message",l=>{let u=l.toString().trim();u.length!==0&&(u.length>rb&&(u=u.slice(0,rb)+aL),t.fetch(u).catch(()=>{}))}),async()=>{try{c.close()}catch{}try{await r.execute("mobile: stopLogsBroadcast")}catch{}}}import{Server as CB}from"socket.io";import{randomUUID as SL}from"crypto";import{faker as sL}from"@faker-js/faker";import lL from"assert";import cL from"axios";import*as uL from"child_process";import dL from"moment";import*as pL from"otpauth";import mL from"pg";var En=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var nb=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 $(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((s,c)=>{let l;if(e.signal){let{signal:p}=e;if(p.aborted)return c(nb(p));l=()=>c(nb(p)),p.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(p){c(p)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let p=o instanceof Error?o:new En(o??`Promise timed out after ${t}ms`);c(p)}};a=i.setTimeout(u,t);let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(p=>{d(),s(p)}).catch(p=>{d(),c(p)})})}async function ob(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Ws(n,e);t.push(...o)}),t}function hL(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 gL(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 fL=Object.getPrototypeOf(async function(){}).constructor;async function ib(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:s}=e.bindings,c=e.tools,l={},u=(w,v)=>{o[w]=v,l[w]=v},d={},p=(w,v)=>{o[w]=v,d[w]=v},h;n.includes("Octokit")&&(h=(await import("@octokit/rest")).Octokit);let m;n.includes("createAppAuth")&&(m=(await import("@octokit/auth-app")).createAppAuth);let g=async()=>await Promise.resolve(new fL("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(cL,dL,c.fakerInstance??sL,lL,mL,h,m,pL,uL,ob,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,v=>c.sms.send(v),v=>c.sms.fetchLatest(v),c.email,c.sms,c.ai,hL(a,s),...Object.values(i??{}))),f=!0,E,S;try{let w=await $(g(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});E=await gL(e.options.responseSerialization??"RAW",w)}catch(w){t.error({err:w,env:o,evalCode:n},`[${r}] Error executing code: ${w}`),f=!1,w instanceof En?S=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:S=w instanceof Error?w.message:`${w}`}return{result:E,variableUpdates:l,persistentVariableUpdates:d,success:f,error:S}}async function ab({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=gn,disallowVariableUpdates:s,additionalBindings:c,responseSerialization:l,mock:u}){let d=SL(),p=await ib(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:s,responseSerialization:l},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return x.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as yL,randomUUID as bL}from"crypto";import EL from"fetch-retry";var TL=EL(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}}),sb=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,lb=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function cb({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=gn,retries:i=2,signal:a,logger:s,additionalBindings:c,disallowVariableUpdates:l,responseSerialization:u,mock:d}){if(!sb)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,h,m=0;if(!lb)throw new Error("Missing lambda auth secret.");let g=yL("sha256",lb).update(r).digest("hex");for(;m<=i;){m++,a?.throwIfAborted();let E={id:bL(),orgId:r,momenticLambdaAuthHash:g,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:l,responseSerialization:u};try{if(p=await $(TL(sb,{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}`);h=void 0;break}catch(S){h=S}}if(h)throw s.error({err:h},"Failed to evaluate code remotely"),h;if(!p)throw new Error(`An unexpected code evaluation error occurred${h?`: ${h}`:""}`);let f;try{f=PS.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 Ir(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await cb(r);else if(r.localTools)e=await ab({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
10
14
|
${e.error}
|
|
11
15
|
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
|
|
13
|
-
${JSON.stringify(t)}`);let n=[];return n.push({key:$I(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function tl({cmd:r,newTarget:e,key:t,logger:n,updatedWithAI:o}){if(r.type==="DRAG")if(t!=="fromTarget"&&t!=="toTarget")n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command");else{let i=r.cache?.updatedAt;r.cache={...r.cache,[t]:e,updatedAt:i&&!o?i:new Date}}else if(t==="target"&&Zg(r)){let i=r.cache?.updatedAt;r.cache={...r.cache,target:e,updatedAt:i&&!o?i:new Date}}else n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function rl(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;return ny(n,e)?(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e},updatedAt:new Date},{changed:!0}):{changed:!1}}function vd(r){return{...r,serializedHtml:void 0,nodeOnlySerializedHtml:void 0,screenshotUrl:void 0,boundingBox:void 0,selector:void 0,hybridSelector:void 0,generatedSelectors:void 0,id:-1}}function oy(r,e){return r?ny(r.target.memory,e.target.memory)?{target:{...r.target,memory:e.target.memory},updatedAt:e.updatedAt}:r:{target:vd(e.target),updatedAt:e.updatedAt}}function At(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var jn={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"},iy={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},ay={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};var I8={CONTENT:"The page"};function sy(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 qI(r){return typeof r=="object"&&r!==null}function Gn(r){if(Array.isArray(r))return r.map(Gn);if(qI(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=Gn(n))}),e}return r}function KI(r){switch(r.type){case"AI_CHECK":return`AI check: ${r.assertion}`;case"TAP":return`Tap on element: ${Yu(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${Yu(r.target)}`:""}`;case"PRESS":return`Press the ${r.key} button`;case"PRESS_KEYBOARD":return`Press the ${r.key} key`;case"SWIPE":return r.scrollableElement.type==="CUSTOM"?`Swipe ${r.direction} in container: ${r.scrollableElement.target.description}`:`Swipe ${r.direction} in the ${r.scrollableElement.type.toLowerCase()}`;case"OPEN_APP":return`Open app: ${r.packageName}`;case"OPEN_NOTIFICATION_DRAWER":return"Open notification drawer";case"JAVASCRIPT":return`Execute JavaScript: ${r.code}`;case"REQUEST":return`Make API request to ${r.url}`;case"WAIT":return`Wait ${r.timeoutSecs} seconds`;case"ADD_FILE":return`Add file: ${r.file} to ${r.storageLocation}`;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 ly(r){switch(r.type){case"MOBILE_PRESET_STEP":return KI(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 cy}from"lodash-es";async function uy(r){let e={},{resolvedSteps:t,newSchemaVersion:n}=await nl({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:s}=await nl({rawSteps:a,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e});o[i]=s}return{resolvedStepLists:o,moduleIds:Array.from(Object.keys(e))}}async function nl({rawSteps:r,onFetchModule:e,logger:t,metadata:n,resolvedModuleCache:o={}}){let i=[];for(let a of r)i.push(await dy({rawStep:cr.parse(a),onFetchModule:e,logger:t,resolvedModuleCache:o}));return{resolvedSteps:i,newSchemaVersion:n.schemaVersion}}async function dy({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{...cy(i),...r,type:"RESOLVED_MOBILE_MODULE"};let a=await e(o);if(!a)throw new Error(`Could not find module with id ${o}`);let s;try{s=cr.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(s.map(u=>dy({rawStep:u,onFetchModule:e,logger:t,resolvedModuleCache:n}))),l={...a,steps:c};return n[o]=cy(l),{...l,...r,type:"RESOLVED_MOBILE_MODULE"}}case"MOBILE_PRESET_STEP":return r}}import{cloneDeep as YI}from"lodash-es";import{v4 as Ad}from"uuid";async function $n(r){let e=new Map,t=new Set,n=YI(r.steps),o=await py({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates}}async function py({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:s,createNewCacheIds:c}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of r)switch(u.id=c?Ad():u.id,u.type){case"MOBILE_PRESET_STEP":{let d=u.command;d.id=c?Ad():d.id,"cache"in d&&d.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(Td({id:d.id,orgId:n.orgId,testId:n.testId,value:on.parse(d),moduleIdParents:o,moduleStepParents:i}))),delete d.cache),l.stepsToSave.push({...u,command:d});break}case"RESOLVED_MOBILE_MODULE":{let d=c?Ad():u.id,p=u.moduleId;a.has(p)?p=a.get(p):s!==void 0&&(p=await s(u),a.set(u.moduleId,p));let{cachesToSave:g,stepsToSave:m,moduleUpdates:h}=await py({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,d],moduleIdParents:[...o,p],skipCacheIntermediateEntries:c});l.moduleUpdates=l.moduleUpdates.concat(h),l.cachesToSave=l.cachesToSave.concat(g),t.has(p)||(t.add(p),l.moduleUpdates.push({...Do.parse(u),steps:cr.array().parse(m),moduleId:p}));let f=Ji.parse({...u,type:"MOBILE_MODULE_STEP",moduleId:p,inputs:u.inputs,id:d});l.stepsToSave.push(f);break}default:{let d=u}}return l}function XI(r){let e={parentChain:[]};return my(r,e),e}function my(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),my({...r,steps:i.steps},e)&&o))return!0;e.parentChain.pop();continue}if(t(i,e)&&o)return!0}return!1}function JI(r,e,t=[]){let n,o=[],i=(a,s)=>{let c=JSON.stringify(s.parentChain.map(u=>u.id)),l=t.length===0?!0:JSON.stringify(t)===c;return a.id===e&&l?(n=a,o=s.parentChain,!0):!1};return XI({steps:r,earlyStop:!0,onPreset:i,onModule:i}),{result:n,parentChain:o}}function gy({currentStep:r,currentParentChain:e,desiredStepId:t,desiredStepParentChain:n}){let o=Array.from(e),i=Array.from(n);for(let s=0;s<o.length;s++){if(o[s]!==i[s])return!1;i.shift()}return!!JI([r],t,i).result}function hy(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 s=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 s=i}}return{firstMetadata:e,lastMetadata:o}}function fy({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 x9}from"lodash-es";import M9 from"truncate-json";import{v4 as F9}from"uuid";import{cloneDeep as S9,unset as y9}from"lodash-es";import{cloneDeep as j9}from"lodash-es";import{cloneDeep as pQ}from"lodash-es";import LZ from"diff-lines";import wd,{gte as kZ}from"semver";var Sy={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 yy={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 ZI=["target","fromTarget","toTarget"];function by(r){for(let e of ZI){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 by(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])by(n);return e}default:return e}})};import{v4 as QI}from"uuid";var Ty={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=QI()),e;default:return e}})};import{v4 as vy}from"uuid";var Ay={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??vy(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??vy()}})),delete e.commands),e;default:return e}})};var wy={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 eO}from"uuid";var Ry={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=eO()),e))};import{v4 as Cy}from"uuid";var xy={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=Cy())}return e.id=Cy(),e})};var _y={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 tO}from"uuid";var My={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=tO()),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 Py={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 Iy={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&&Oy(t),e})};function Oy(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){Oy(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 Ly={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 Ny={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 ky={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 Dy={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 Uy={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 Fy={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 ol=new Set(["CLICK","TYPE","SELECT_OPTION"]),By={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||ol.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let s=a?.elementDescriptor,c=a?.type;(s!==void 0||ol.has(c))&&(a.target={elementDescriptor:s??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let s=a.command,c=s?.elementDescriptor,l=s?.type;(c!==void 0||ol.has(l))&&(s.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,g=d?.type;(p!==void 0||ol.has(g))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var zy={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 Hy={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,s=a?.type;s?.startsWith("PRESET_")&&(a.type=s.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(l=>{let u=l.type;u?.startsWith("PRESET_")&&(l.type=u.slice(7))})}),e}),stopOnFailure:!0};var il=[Fy,zy,Hy,By,Sy,yy,Ey,Ty,Ay,wy,Ry,xy,_y,My,Py,Iy,Ly,Ny,ky,Dy,Uy];if(Ln!==il[il.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");il.forEach((r,e)=>{if(!wd.valid(r.toVersion)||!wd.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!wd.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(il[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});import{diff as PQ}from"deep-object-diff";import{cloneDeep as OQ}from"lodash-es";import{v4 as qQ}from"uuid";import{cloneDeep as JQ}from"lodash-es";import{stringify as c7}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,{once:!0});let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function Rd({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((s,c)=>{function l(){clearInterval(a),e?.removeEventListener("abort",l),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",l,{once:!0}),(async()=>{try{s(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",l)}})()})}async function Wn({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,s=()=>{a.abort()},c=setTimeout(()=>{o?.removeEventListener("abort",s),!i&&a.abort()},e);o?.addEventListener("abort",s,{once:!0});try{return await Rd({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(c)}}function al(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 rO from"picomatch";var sl=(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||rO(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},ll=(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}},zo=r=>{try{return new URL(r),!0}catch{return!1}},jy=r=>!r.toLowerCase().startsWith("http"),Ho=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function qn(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 Vy}from"uuid";function Cd(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var cl=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:Cd({},this.metadata)}]).catch(s=>e.error({err:s},"Failed to report billable event"))]}trackStepExecution(e){if(yf(e.type)){this.creditsUsedV2+=1;return}let t=Gu(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=ju(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:Vy(),properties:Cd({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:Vy(),properties:Cd({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{CookieJar as EU}from"tough-cookie";var $y={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
|
|
16
|
+
${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 vL}from"lodash-es";async function Gd(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:s=gn,allowUndefined:c=!1}=r,l=/{{(.*?)}}/g,u=t.matchAll(l),d=t;for(let p of u){if(p.length<2)continue;let h=p[1].trim(),m;try{m=await Ir({orgId:e,code:h,fragment:!0,context:n,timeoutMs:s,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 _("UserConfigurationError",`Template fragment '${h}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let g=typeof m=="string"?m:`${m}`;g=g.replaceAll(/\$/g,"$$$$"),d=d.replace(p[0],g)}return d}async function gl(r){return ub(r)}async function ub({obj:r,bannedKeys:e,allowList:t,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let s in r){if(e.includes(s))continue;let c=!1;if(t)if(t.includes(s))c=!0;else continue;let l=r[s],u=[...o,s];if(typeof l=="string"&&l.includes("{{")){let d=await Gd({s:l,context:n,...a});if(l===d)continue;i.push({path:u,original:l}),r[s]=d}else typeof l=="object"&&l!==null&&!Array.isArray(l)&&await ub({obj:l,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function fl(r,e){for(let{path:t,original:n}of e)vL(r,t,n)}import AL from"fetch-retry";var x7=process.env.MAILINATOR_API_KEY,_7=AL(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import QF from"fetch-cookie";import eB from"path";import{diff as RL}from"deep-object-diff";import{cloneDeep as Q7}from"lodash-es";function db(r,e){return!r&&!e?!1:!r||!e?!0:Object.keys(RL(r,e)).length>0}function jd({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],s=[],c=[],l=0,u=(p,h)=>{try{let m=mn.parse(h.value);if(m.type!==p.type){o.warn({parsedCacheEntry:m,command:p},"Not using step cache due to type mismatch"),s.push(h.key);return}p.cache=m.cache,a.push(h.key),c.push(h.uniqueKey)}catch(m){s.push(h.key),o.error({err:m,cacheEntry:h},"Not using step cache due to parsing error")}},d=(p,h)=>{let m=xL(p.id,h),g=m.find(f=>!!n[f]);if(g)u(p,n[g]);else{if(p.type==="AI_CHECK")return;s.push(m[0])}};for(let p of r)switch(p.type){case"MOBILE_PRESET_STEP":{if(!Ys(p.command)||p.command.type==="TYPE"&&!p.command.target||"cache"in p.command&&p.command.cache)continue;l++,d(p.command,i);break}case"RESOLVED_MOBILE_MODULE":{l+=p.steps.length;let{cacheKeysHit:h,cacheKeysMissed:m,uniqueKeysHit:g}=jd({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...h),s.push(...m),c.push(...g);break}default:{let h=p}}return e&&l&&s.length>0&&o.warn({totalSteps:l,cacheKeysMissed:s,cacheKeysHit:a,uniqueKeysHit:c,cacheEntries:n.length},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:s,uniqueKeysHit:c}}function CL(r,e){return e?`${e}:${r}`:r}function xL(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 Vd(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
17
|
+
${JSON.stringify(t)}`);let n=[];return n.push({key:CL(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function Sl({cmd:r,newTarget:e,key:t,logger:n,updatedWithAI:o}){if(r.type==="DRAG")if(t!=="fromTarget"&&t!=="toTarget")n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command");else{let i=r.cache?.updatedAt;r.cache={...r.cache,[t]:e,updatedAt:i&&!o?i:new Date}}else if(t==="target"&&xg(r)){let i=r.cache?.updatedAt;r.cache={...r.cache,target:e,updatedAt:i&&!o?i:new Date}}else n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function yl(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;return db(n,e)?(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e},updatedAt:new Date},{changed:!0}):{changed:!1}}function $d(r){return{...r,serializedHtml:void 0,nodeOnlySerializedHtml:void 0,screenshotUrl:void 0,boundingBox:void 0,selector:void 0,hybridSelector:void 0,generatedSelectors:void 0,id:-1}}function pb(r,e){return r?db(r.target.memory,e.target.memory)?{target:{...r.target,memory:e.target.memory},updatedAt:e.updatedAt}:r:{target:$d(e.target),updatedAt:e.updatedAt}}function Mt(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var Zn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},Qn={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},mb={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},hb={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};var _ee={CONTENT:"The page"};function gb(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 _L(r){return typeof r=="object"&&r!==null}function Jn(r){if(Array.isArray(r))return r.map(Jn);if(_L(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=Jn(n))}),e}return r}function ML(r){switch(r.type){case"AI_CHECK":return`AI check: ${r.assertion}`;case"TAP":return`Tap on element: ${vd(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${vd(r.target)}`:""}`;case"PRESS":return`Press the ${r.key} button`;case"PRESS_KEYBOARD":return`Press the ${r.key} key`;case"SWIPE":return r.scrollableElement.type==="CUSTOM"?`Swipe ${r.direction} in container: ${r.scrollableElement.target.description}`:`Swipe ${r.direction} in the ${r.scrollableElement.type.toLowerCase()}`;case"OPEN_APP":return`Open app: ${r.packageName}`;case"OPEN_NOTIFICATION_DRAWER":return"Open notification drawer";case"JAVASCRIPT":return`Execute JavaScript: ${r.code}`;case"REQUEST":return`Make API request to ${r.url}`;case"WAIT":return`Wait ${r.timeoutSecs} seconds`;case"ADD_FILE":return`Add file: ${r.file} to ${r.storageLocation}`;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 fb(r){switch(r.type){case"MOBILE_PRESET_STEP":return ML(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 Sb}from"lodash-es";async function yb(r){let e={},{resolvedSteps:t,newSchemaVersion:n}=await bl({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:s}=await bl({rawSteps:a,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e});o[i]=s}return{resolvedStepLists:o,moduleIds:Array.from(Object.keys(e))}}async function bl({rawSteps:r,onFetchModule:e,logger:t,metadata:n,resolvedModuleCache:o={}}){let i=[];for(let a of r)i.push(await bb({rawStep:Sr.parse(a),onFetchModule:e,logger:t,resolvedModuleCache:o}));return{resolvedSteps:i,newSchemaVersion:n.schemaVersion}}async function bb({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{...Sb(i),...r,type:"RESOLVED_MOBILE_MODULE"};let a=await e(o);if(!a)throw new Error(`Could not find module with id ${o}`);let s;try{s=Sr.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(s.map(u=>bb({rawStep:u,onFetchModule:e,logger:t,resolvedModuleCache:n}))),l={...a,steps:c};return n[o]=Sb(l),{...l,...r,type:"RESOLVED_MOBILE_MODULE"}}case"MOBILE_PRESET_STEP":return r}}import{cloneDeep as PL}from"lodash-es";import{v4 as Wd}from"uuid";async function eo(r){let e=new Map,t=new Set,n=PL(r.steps),o=await Eb({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates}}async function Eb({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:s,createNewCacheIds:c}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of r)switch(u.id=c?Wd():u.id,u.type){case"MOBILE_PRESET_STEP":{let d=u.command;d.id=c?Wd():d.id,"cache"in d&&d.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(Vd({id:d.id,orgId:n.orgId,testId:n.testId,value:mn.parse(d),moduleIdParents:o,moduleStepParents:i}))),delete d.cache),l.stepsToSave.push({...u,command:d});break}case"RESOLVED_MOBILE_MODULE":{let d=c?Wd():u.id,p=u.moduleId;a.has(p)?p=a.get(p):s!==void 0&&(p=await s(u),a.set(u.moduleId,p));let{cachesToSave:h,stepsToSave:m,moduleUpdates:g}=await Eb({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,d],moduleIdParents:[...o,p],skipCacheIntermediateEntries:c});l.moduleUpdates=l.moduleUpdates.concat(g),l.cachesToSave=l.cachesToSave.concat(h),t.has(p)||(t.add(p),l.moduleUpdates.push({...qo.parse(u),steps:Sr.array().parse(m),moduleId:p}));let f=pa.parse({...u,type:"MOBILE_MODULE_STEP",moduleId:p,inputs:u.inputs,id:d});l.stepsToSave.push(f);break}default:{let d=u}}return l}function IL(r){let e={parentChain:[]};return Tb(r,e),e}function Tb(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),Tb({...r,steps:i.steps},e)&&o))return!0;e.parentChain.pop();continue}if(t(i,e)&&o)return!0}return!1}function OL(r,e,t=[]){let n,o=[],i=(a,s)=>{let c=JSON.stringify(s.parentChain.map(u=>u.id)),l=t.length===0?!0:JSON.stringify(t)===c;return a.id===e&&l?(n=a,o=s.parentChain,!0):!1};return IL({steps:r,earlyStop:!0,onPreset:i,onModule:i}),{result:n,parentChain:o}}function vb({currentStep:r,currentParentChain:e,desiredStepId:t,desiredStepParentChain:n}){let o=Array.from(e),i=Array.from(n);for(let s=0;s<o.length;s++){if(o[s]!==i[s])return!1;i.shift()}return!!OL([r],t,i).result}function Ab(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 s=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 s=i}}return{firstMetadata:e,lastMetadata:o}}function wb({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 wte}from"lodash-es";import Cte from"truncate-json";import{v4 as kte}from"uuid";import{cloneDeep as hte,unset as gte}from"lodash-es";import{cloneDeep as zte}from"lodash-es";import{cloneDeep as cne}from"lodash-es";import Pre from"diff-lines";import qd,{gte as Ore}from"semver";var Rb={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 Cb={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 LL=["target","fromTarget","toTarget"];function xb(r){for(let e of LL){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var _b={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 xb(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])xb(n);return e}default:return e}})};import{v4 as NL}from"uuid";var Mb={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=NL()),e;default:return e}})};import{v4 as Pb}from"uuid";var Ib={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??Pb(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??Pb()}})),delete e.commands),e;default:return e}})};var Ob={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 kL}from"uuid";var Lb={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=kL()),e))};import{v4 as Nb}from"uuid";var kb={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=Nb())}return e.id=Nb(),e})};var Db={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 DL}from"uuid";var Ub={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=DL()),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 Fb={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 Bb={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&&zb(t),e})};function zb(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){zb(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 Hb={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 Gb={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 jb={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 Vb={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 $b={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 Wb={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 El=new Set(["CLICK","TYPE","SELECT_OPTION"]),qb={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||El.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let s=a?.elementDescriptor,c=a?.type;(s!==void 0||El.has(c))&&(a.target={elementDescriptor:s??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let s=a.command,c=s?.elementDescriptor,l=s?.type;(c!==void 0||El.has(l))&&(s.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,h=d?.type;(p!==void 0||El.has(h))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var Kb={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 Yb={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,s=a?.type;s?.startsWith("PRESET_")&&(a.type=s.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(l=>{let u=l.type;u?.startsWith("PRESET_")&&(l.type=u.slice(7))})}),e}),stopOnFailure:!0};var Tl=[Wb,Kb,Yb,qb,Rb,Cb,_b,Mb,Ib,Ob,Lb,kb,Db,Ub,Fb,Bb,Hb,Gb,jb,Vb,$b];if(jn!==Tl[Tl.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");Tl.forEach((r,e)=>{if(!qd.valid(r.toVersion)||!qd.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!qd.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(Tl[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});import{diff as xne}from"deep-object-diff";import{cloneDeep as Mne}from"lodash-es";import{v4 as Vne}from"uuid";import{cloneDeep as Kne}from"lodash-es";import{stringify as aoe}from"yaml";async function ee(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function Kd({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((s,c)=>{function l(){clearInterval(a),e?.removeEventListener("abort",l),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",l,{once:!0}),(async()=>{try{s(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",l)}})()})}async function ba({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,s=()=>{a.abort()},c=setTimeout(()=>{o?.removeEventListener("abort",s),!i&&a.abort()},e);o?.addEventListener("abort",s,{once:!0});try{return await Kd({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(c)}}function vl(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 UL from"picomatch";var Al=(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||UL(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},wl=(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}},Xo=r=>{try{return new URL(r),!0}catch{return!1}},Jb=r=>!r.toLowerCase().startsWith("http"),Jo=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function to(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 Zb}from"uuid";function Yd(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var Rl=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:Yd({},this.metadata)}]).catch(s=>e.error({err:s},"Failed to report billable event"))]}trackStepExecution(e){if(xS(e.type)){this.creditsUsedV2+=1;return}let t=gd(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=fd(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:Zb(),properties:Yd({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:Zb(),properties:Yd({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{CookieJar as tB}from"tough-cookie";var Xd={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
|
|
14
18
|
var momenticConstants = {
|
|
15
19
|
bannedClassSubstrings: [
|
|
16
20
|
"relative",
|
|
@@ -138,6 +142,7 @@ var momenticConstants = {
|
|
|
138
142
|
"data-col-index",
|
|
139
143
|
"data-row-index",
|
|
140
144
|
"data-row",
|
|
145
|
+
"data-index",
|
|
141
146
|
"data-col",
|
|
142
147
|
"col-index",
|
|
143
148
|
"row-index",
|
|
@@ -166,7 +171,7 @@ var momenticConstants = {
|
|
|
166
171
|
"aria-label"
|
|
167
172
|
],
|
|
168
173
|
stronglyIdentifyingAttributes: [
|
|
169
|
-
"
|
|
174
|
+
"data-test-id",
|
|
170
175
|
"data-testid",
|
|
171
176
|
"id",
|
|
172
177
|
"name",
|
|
@@ -176,9 +181,13 @@ var momenticConstants = {
|
|
|
176
181
|
"aria-description",
|
|
177
182
|
"data-row",
|
|
178
183
|
"data-col",
|
|
184
|
+
"data-index",
|
|
179
185
|
"data-row-index",
|
|
180
186
|
"data-col-index",
|
|
181
187
|
"for",
|
|
188
|
+
"title",
|
|
189
|
+
"alt",
|
|
190
|
+
"aria-label",
|
|
182
191
|
"aria-modal"
|
|
183
192
|
],
|
|
184
193
|
alwaysInterestingClassNames: ["cm-line", "cm-activeLine", "cm-content"],
|
|
@@ -1873,18 +1882,21 @@ function makeXpathStringLiteral(value) {
|
|
|
1873
1882
|
result += ")";
|
|
1874
1883
|
return result;
|
|
1875
1884
|
}
|
|
1876
|
-
function getTotalPossibleScoreForNode(node, position, totalNodes) {
|
|
1885
|
+
function getTotalPossibleScoreForNode(node, position, totalNodes, importantProperties) {
|
|
1877
1886
|
const customWindow = window;
|
|
1878
1887
|
if (node.tagName === "body") {
|
|
1879
1888
|
return 1;
|
|
1880
1889
|
}
|
|
1881
1890
|
let score = 0;
|
|
1882
|
-
const identifyingAttributes =
|
|
1891
|
+
const identifyingAttributes = [
|
|
1892
|
+
...importantProperties?.attributes ?? [],
|
|
1893
|
+
...customWindow.momenticConstants?.stronglyIdentifyingAttributes ?? []
|
|
1894
|
+
];
|
|
1883
1895
|
for (const attr of identifyingAttributes) {
|
|
1884
|
-
|
|
1896
|
+
const attrVal = node.attributes[attr];
|
|
1897
|
+
if (!attrVal) {
|
|
1885
1898
|
continue;
|
|
1886
1899
|
}
|
|
1887
|
-
const attrVal = node.attributes[attr];
|
|
1888
1900
|
if (checkIsNameAutogenerated(attrVal)) {
|
|
1889
1901
|
score += 2;
|
|
1890
1902
|
} else {
|
|
@@ -1895,14 +1907,19 @@ function getTotalPossibleScoreForNode(node, position, totalNodes) {
|
|
|
1895
1907
|
score += 10 * ((position + 1) / totalNodes);
|
|
1896
1908
|
}
|
|
1897
1909
|
if (node.classNames.length > 0) {
|
|
1898
|
-
score +=
|
|
1910
|
+
score += 1;
|
|
1911
|
+
for (const className of node.classNames) {
|
|
1912
|
+
if (importantProperties?.classes?.includes(className)) {
|
|
1913
|
+
score += 3;
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1899
1916
|
}
|
|
1900
1917
|
for (const attr of Object.keys(node.attributes)) {
|
|
1901
1918
|
if (identifyingAttributes.includes(attr)) {
|
|
1902
1919
|
continue;
|
|
1903
1920
|
}
|
|
1904
1921
|
const attrVal = node.attributes[attr];
|
|
1905
|
-
if (!checkIsNameAutogenerated(attrVal)) {
|
|
1922
|
+
if (attrVal && !checkIsNameAutogenerated(attrVal)) {
|
|
1906
1923
|
score += 1;
|
|
1907
1924
|
}
|
|
1908
1925
|
}
|
|
@@ -1954,7 +1971,7 @@ function addHybridSelectorGenerationScript() {
|
|
|
1954
1971
|
const tagName = currElement.tagName.toLowerCase();
|
|
1955
1972
|
let nthChild = -1;
|
|
1956
1973
|
const parent = currElement.parentElement;
|
|
1957
|
-
let expandShadowRoot =
|
|
1974
|
+
let expandShadowRoot = void 0;
|
|
1958
1975
|
if (parent) {
|
|
1959
1976
|
const children = Array.from(parent.children);
|
|
1960
1977
|
const index = children.indexOf(currElement);
|
|
@@ -2007,7 +2024,8 @@ function addEvaluateHybridSelectorScript() {
|
|
|
2007
2024
|
shadowRoot,
|
|
2008
2025
|
dstNode,
|
|
2009
2026
|
distanceFromSrc,
|
|
2010
|
-
logs
|
|
2027
|
+
logs,
|
|
2028
|
+
importantProperties
|
|
2011
2029
|
} = params;
|
|
2012
2030
|
const rootForQuerySelector = shadowRoot ?? srcEle;
|
|
2013
2031
|
if (dstNode.tagName === "body") {
|
|
@@ -2064,17 +2082,29 @@ function addEvaluateHybridSelectorScript() {
|
|
|
2064
2082
|
matchScore -= 5;
|
|
2065
2083
|
}
|
|
2066
2084
|
} else {
|
|
2067
|
-
logs.push(
|
|
2068
|
-
\`[HOP] Got invalid \${matchingElements.length} text matches: \${xpathTextExpression}\`
|
|
2069
|
-
);
|
|
2070
2085
|
if (matchingElements.length > 0) {
|
|
2086
|
+
logs.push(
|
|
2087
|
+
\`[HOP] Got invalid \${matchingElements.length} text match, multiple elements: \${xpathTextExpression}\`
|
|
2088
|
+
);
|
|
2071
2089
|
mustFullfillTextContent = dstNode.textContent;
|
|
2072
2090
|
} else if (dstNodeIndex === allNodes.length - 1) {
|
|
2073
|
-
|
|
2091
|
+
logs.push(
|
|
2092
|
+
\`[HOP] Got invalid \${matchingElements.length} text match, disqualifying at leaf: \${xpathTextExpression}\`
|
|
2093
|
+
);
|
|
2094
|
+
return false;
|
|
2095
|
+
} else {
|
|
2096
|
+
const penalty = dstNodeIndex < allNodes.length / 2 ? 1 : 5 * ((dstNodeIndex + 1) / allNodes.length);
|
|
2097
|
+
logs.push(
|
|
2098
|
+
\`[HOP] Got invalid \${matchingElements.length} text match, penalizing with \${penalty}: \${xpathTextExpression}\`
|
|
2099
|
+
);
|
|
2100
|
+
matchScore -= penalty;
|
|
2074
2101
|
}
|
|
2075
2102
|
}
|
|
2076
2103
|
}
|
|
2077
|
-
const identifyingAttributes =
|
|
2104
|
+
const identifyingAttributes = [
|
|
2105
|
+
...customWindow.momenticConstants?.stronglyIdentifyingAttributes ?? [],
|
|
2106
|
+
...importantProperties?.attributes ?? []
|
|
2107
|
+
];
|
|
2078
2108
|
for (const attr of identifyingAttributes) {
|
|
2079
2109
|
const attrVal = dstNode.attributes[attr];
|
|
2080
2110
|
if (attrVal === void 0) {
|
|
@@ -2121,34 +2151,38 @@ function addEvaluateHybridSelectorScript() {
|
|
|
2121
2151
|
const classNamesEscaped = dstNode.classNames.map((className) => {
|
|
2122
2152
|
return \`\${CSS.escape(className)}\`;
|
|
2123
2153
|
});
|
|
2154
|
+
const hasImportantClass = importantProperties?.classes?.length && dstNode.classNames.find(
|
|
2155
|
+
(cls) => importantProperties?.classes?.includes(cls)
|
|
2156
|
+
);
|
|
2157
|
+
const classScore = hasImportantClass ? 6 : 3;
|
|
2124
2158
|
const querySelector = \`\${dstNode.tagName}.\${classNamesEscaped.join(".")}\`;
|
|
2125
2159
|
const query = rootForQuerySelector.querySelectorAll(querySelector);
|
|
2126
2160
|
if (query.length === 1) {
|
|
2127
2161
|
logs.push(\`[HOP] Got cls match\`);
|
|
2128
2162
|
const foundElement = query[0];
|
|
2129
2163
|
if (resultingElement === null) {
|
|
2130
|
-
matchScore +=
|
|
2164
|
+
matchScore += classScore;
|
|
2131
2165
|
resultingElement = foundElement;
|
|
2132
2166
|
xPathToken = generateXpathForCssClasses(
|
|
2133
2167
|
dstNode.classNames,
|
|
2134
2168
|
dstNode.tagName
|
|
2135
2169
|
);
|
|
2136
2170
|
} else if (resultingElement === foundElement) {
|
|
2137
|
-
matchScore +=
|
|
2171
|
+
matchScore += classScore;
|
|
2138
2172
|
} else {
|
|
2139
|
-
matchScore
|
|
2173
|
+
matchScore -= classScore;
|
|
2140
2174
|
}
|
|
2141
2175
|
} else {
|
|
2142
2176
|
logs.push(\`[HOP] Got invalid \${query.length} cls matches\`);
|
|
2143
2177
|
if (query.length > 0) {
|
|
2144
2178
|
mustFulfillClassNames = [...dstNode.classNames];
|
|
2179
|
+
} else if (hasImportantClass) {
|
|
2180
|
+
matchScore -= 3;
|
|
2145
2181
|
}
|
|
2146
2182
|
}
|
|
2147
2183
|
}
|
|
2148
2184
|
for (const [attr, attrVal] of Object.entries(dstNode.attributes)) {
|
|
2149
|
-
if (
|
|
2150
|
-
attr
|
|
2151
|
-
)) {
|
|
2185
|
+
if (identifyingAttributes.includes(attr)) {
|
|
2152
2186
|
continue;
|
|
2153
2187
|
}
|
|
2154
2188
|
const query = rootForQuerySelector.querySelectorAll(
|
|
@@ -2164,7 +2198,7 @@ function addEvaluateHybridSelectorScript() {
|
|
|
2164
2198
|
} else if (resultingElement === foundElement) {
|
|
2165
2199
|
matchScore += 1;
|
|
2166
2200
|
} else {
|
|
2167
|
-
matchScore
|
|
2201
|
+
matchScore -= 1;
|
|
2168
2202
|
}
|
|
2169
2203
|
}
|
|
2170
2204
|
}
|
|
@@ -2236,13 +2270,15 @@ function addEvaluateHybridSelectorScript() {
|
|
|
2236
2270
|
}
|
|
2237
2271
|
matchScore += 3;
|
|
2238
2272
|
}
|
|
2273
|
+
matchScore = Math.max(matchScore, 0);
|
|
2239
2274
|
const totalPossibleScore = getTotalPossibleScoreForNode(
|
|
2240
2275
|
dstNode,
|
|
2241
2276
|
dstNodeIndex,
|
|
2242
|
-
allNodes.length
|
|
2277
|
+
allNodes.length,
|
|
2278
|
+
importantProperties
|
|
2243
2279
|
);
|
|
2244
2280
|
const strength = totalPossibleScore === 0 ? requiredAvgScorePerHop : matchScore / totalPossibleScore;
|
|
2245
|
-
if (resultingElement &&
|
|
2281
|
+
if (resultingElement && matchScore > minHopStrength) {
|
|
2246
2282
|
const adjustmentFactor = allNodes.length > 3 ? 0.5 + dstNodeIndex / (allNodes.length - 1) : 1;
|
|
2247
2283
|
const positionAdjustedStrength = strength * adjustmentFactor;
|
|
2248
2284
|
logs.push(\`[HOP] Success: strength \${positionAdjustedStrength}\`);
|
|
@@ -2296,7 +2332,8 @@ function addEvaluateHybridSelectorScript() {
|
|
|
2296
2332
|
dstNode: possibleDestNode,
|
|
2297
2333
|
distanceFromSrc: i + 1,
|
|
2298
2334
|
allNodes: nodes,
|
|
2299
|
-
logs
|
|
2335
|
+
logs,
|
|
2336
|
+
importantProperties: opts.importantProperties
|
|
2300
2337
|
});
|
|
2301
2338
|
if (!hopResult) {
|
|
2302
2339
|
continue;
|
|
@@ -2356,7 +2393,8 @@ function addEvaluateHybridSelectorScript() {
|
|
|
2356
2393
|
dstNode: nextDestNode,
|
|
2357
2394
|
allNodes: nodes,
|
|
2358
2395
|
distanceFromSrc,
|
|
2359
|
-
logs
|
|
2396
|
+
logs,
|
|
2397
|
+
importantProperties: opts.importantProperties
|
|
2360
2398
|
});
|
|
2361
2399
|
const srcHopMap = memoizedHops.get(srcEle) ?? /* @__PURE__ */ new Map();
|
|
2362
2400
|
srcHopMap.set(nextDestNode, hopAttempt);
|
|
@@ -3546,7 +3584,7 @@ function findNearestDocumentRoot(element) {
|
|
|
3546
3584
|
}
|
|
3547
3585
|
throw new Error("element is not in a document fragment");
|
|
3548
3586
|
}
|
|
3549
|
-
function mostCommonTouchedElement(elements, originalElement) {
|
|
3587
|
+
function mostCommonTouchedElement(elements, originalElement, logs) {
|
|
3550
3588
|
const counts = elements.reduce(
|
|
3551
3589
|
(acc, { identifyingAttribute: id }) => {
|
|
3552
3590
|
acc[id] = (acc[id] || 0) + 1;
|
|
@@ -3558,7 +3596,7 @@ function mostCommonTouchedElement(elements, originalElement) {
|
|
|
3558
3596
|
const originalElementExists = elements.some(
|
|
3559
3597
|
({ element }) => element === originalElement
|
|
3560
3598
|
);
|
|
3561
|
-
const
|
|
3599
|
+
const matchingRelevantHits = elements.filter(
|
|
3562
3600
|
({ identifyingAttribute: id, element }) => {
|
|
3563
3601
|
if (originalElementExists) {
|
|
3564
3602
|
return element === originalElement;
|
|
@@ -3566,10 +3604,13 @@ function mostCommonTouchedElement(elements, originalElement) {
|
|
|
3566
3604
|
return id === sortedCounts[0][0];
|
|
3567
3605
|
}
|
|
3568
3606
|
);
|
|
3569
|
-
|
|
3570
|
-
return a.
|
|
3607
|
+
matchingRelevantHits.sort((a, b) => {
|
|
3608
|
+
return a.absolutePoint.x * a.absolutePoint.y - b.absolutePoint.x * b.absolutePoint.y;
|
|
3571
3609
|
});
|
|
3572
|
-
|
|
3610
|
+
logs.push(
|
|
3611
|
+
\`All absolute points considered: \${matchingRelevantHits.map((hit) => \`\${hit.absolutePoint.x},\${hit.absolutePoint.y}\`).join("; ")}\`
|
|
3612
|
+
);
|
|
3613
|
+
return matchingRelevantHits[Math.floor(matchingRelevantHits.length / 2)];
|
|
3573
3614
|
}
|
|
3574
3615
|
function getIdentifyingAttribute(element) {
|
|
3575
3616
|
const customWindow = window;
|
|
@@ -3720,6 +3761,7 @@ function isPointInRoundedRect(point, boundingBox, borderRadii) {
|
|
|
3720
3761
|
function findVisibleMomenticIdAndPoint(documentRoot, originalElement, logs) {
|
|
3721
3762
|
const computedStyle = window.getComputedStyle(originalElement);
|
|
3722
3763
|
const boundingBox = originalElement.getBoundingClientRect();
|
|
3764
|
+
const originalBbSize = boundingBox.width * boundingBox.height;
|
|
3723
3765
|
const borderRadii = parseElementBorderRadii(computedStyle, boundingBox);
|
|
3724
3766
|
if (!boundingBox.width || !boundingBox.height) {
|
|
3725
3767
|
throw new Error("element has no width or height");
|
|
@@ -3738,6 +3780,7 @@ function findVisibleMomenticIdAndPoint(documentRoot, originalElement, logs) {
|
|
|
3738
3780
|
if (nYCoordsToCheck % 2 === 0) {
|
|
3739
3781
|
nYCoordsToCheck += 1;
|
|
3740
3782
|
}
|
|
3783
|
+
logs.push(\`Original BB: \${JSON.stringify(boundingBox)}\`);
|
|
3741
3784
|
logs.push(\`Checking \${nXCoordsToCheck} x \${nYCoordsToCheck}\`);
|
|
3742
3785
|
const xStep = boundingBox.width / (nXCoordsToCheck - 1);
|
|
3743
3786
|
const yStep = boundingBox.height / (nYCoordsToCheck - 1);
|
|
@@ -3745,22 +3788,28 @@ function findVisibleMomenticIdAndPoint(documentRoot, originalElement, logs) {
|
|
|
3745
3788
|
let originalElementFound = false;
|
|
3746
3789
|
for (let i = 0; i < nXCoordsToCheck; i++) {
|
|
3747
3790
|
for (let j = 0; j < nYCoordsToCheck; j++) {
|
|
3748
|
-
let
|
|
3749
|
-
let
|
|
3791
|
+
let relativeX = i * xStep;
|
|
3792
|
+
let relativeY = j * yStep;
|
|
3750
3793
|
if (i < nXCoordsToCheck / 2) {
|
|
3751
|
-
|
|
3794
|
+
relativeX = Math.ceil(relativeX) + 1;
|
|
3752
3795
|
} else {
|
|
3753
|
-
|
|
3796
|
+
relativeX = Math.floor(relativeX) - 1;
|
|
3754
3797
|
}
|
|
3755
3798
|
if (j < nYCoordsToCheck / 2) {
|
|
3756
|
-
|
|
3799
|
+
relativeY = Math.ceil(relativeY) + 1;
|
|
3757
3800
|
} else {
|
|
3758
|
-
|
|
3801
|
+
relativeY = Math.floor(relativeY) - 1;
|
|
3759
3802
|
}
|
|
3760
|
-
|
|
3803
|
+
const absoluteX = boundingBox.x + relativeX;
|
|
3804
|
+
const absoluteY = boundingBox.y + relativeY;
|
|
3805
|
+
const absolutePoint = { x: absoluteX, y: absoluteY };
|
|
3806
|
+
if (!isPointInRoundedRect(absolutePoint, boundingBox, borderRadii)) {
|
|
3761
3807
|
continue;
|
|
3762
3808
|
}
|
|
3763
|
-
const candidateElementsAtPoint = documentRoot.elementsFromPoint(
|
|
3809
|
+
const candidateElementsAtPoint = documentRoot.elementsFromPoint(
|
|
3810
|
+
absoluteX,
|
|
3811
|
+
absoluteY
|
|
3812
|
+
);
|
|
3764
3813
|
let candidateElement = null;
|
|
3765
3814
|
for (const candidate of candidateElementsAtPoint) {
|
|
3766
3815
|
if (!candidate.checkVisibility({
|
|
@@ -3779,15 +3828,20 @@ function findVisibleMomenticIdAndPoint(documentRoot, originalElement, logs) {
|
|
|
3779
3828
|
break;
|
|
3780
3829
|
}
|
|
3781
3830
|
const lcaResult = findLCAWithDistance(originalElement, candidate);
|
|
3831
|
+
const candidateBbSize = candidateBoundingBox.width * candidateBoundingBox.height;
|
|
3832
|
+
if (candidateBbSize > originalBbSize * 8) {
|
|
3833
|
+
continue;
|
|
3834
|
+
}
|
|
3782
3835
|
if (lcaResult.distance > 3) {
|
|
3783
3836
|
continue;
|
|
3784
|
-
} else {
|
|
3785
|
-
candidateElement = candidate;
|
|
3786
|
-
break;
|
|
3787
3837
|
}
|
|
3838
|
+
candidateElement = candidate;
|
|
3839
|
+
break;
|
|
3788
3840
|
}
|
|
3789
3841
|
if (!candidateElement) {
|
|
3790
|
-
logs.push(
|
|
3842
|
+
logs.push(
|
|
3843
|
+
\`No candidate element was found was found at \${absoluteX}, \${absoluteY}\`
|
|
3844
|
+
);
|
|
3791
3845
|
continue;
|
|
3792
3846
|
}
|
|
3793
3847
|
if (candidateElement === originalElement) {
|
|
@@ -3808,10 +3862,7 @@ function findVisibleMomenticIdAndPoint(documentRoot, originalElement, logs) {
|
|
|
3808
3862
|
const payload = {
|
|
3809
3863
|
identifyingAttribute: candidateAttribute,
|
|
3810
3864
|
element: candidateElement,
|
|
3811
|
-
|
|
3812
|
-
x,
|
|
3813
|
-
y
|
|
3814
|
-
}
|
|
3865
|
+
absolutePoint
|
|
3815
3866
|
};
|
|
3816
3867
|
candidateElements.push(payload);
|
|
3817
3868
|
}
|
|
@@ -3834,26 +3885,28 @@ function findVisibleMomenticIdAndPoint(documentRoot, originalElement, logs) {
|
|
|
3834
3885
|
}
|
|
3835
3886
|
const mostCommonCandidate = mostCommonTouchedElement(
|
|
3836
3887
|
candidateElements,
|
|
3837
|
-
originalElement
|
|
3888
|
+
originalElement,
|
|
3889
|
+
logs
|
|
3838
3890
|
);
|
|
3891
|
+
const mostCommonCandidateBb = mostCommonCandidate.element.getBoundingClientRect();
|
|
3892
|
+
const relativePointToCandidateElement = {
|
|
3893
|
+
x: mostCommonCandidate.absolutePoint.x - mostCommonCandidateBb.x,
|
|
3894
|
+
y: mostCommonCandidate.absolutePoint.y - mostCommonCandidateBb.y
|
|
3895
|
+
};
|
|
3839
3896
|
logs.push(
|
|
3840
|
-
\`Suggesting specific click point (\${
|
|
3897
|
+
\`Suggesting specific click point (relative to element: \${JSON.stringify(relativePointToCandidateElement)}; absolute in frame: \${JSON.stringify(mostCommonCandidate.absolutePoint)}) on element: \${mostCommonCandidate.element.outerHTML.slice(0, 300)}\`
|
|
3841
3898
|
);
|
|
3842
3899
|
return {
|
|
3843
3900
|
foundElement: mostCommonCandidate.element,
|
|
3844
|
-
|
|
3901
|
+
foundElementRelativePoint: relativePointToCandidateElement
|
|
3845
3902
|
};
|
|
3846
3903
|
}
|
|
3847
3904
|
function performTargetRedirectionHelper(elm, logs) {
|
|
3848
3905
|
const customWindow = window;
|
|
3849
3906
|
const nearestDocumentRoot = findNearestDocumentRoot(elm);
|
|
3850
|
-
const { foundElement,
|
|
3851
|
-
nearestDocumentRoot,
|
|
3852
|
-
elm,
|
|
3853
|
-
logs
|
|
3854
|
-
);
|
|
3907
|
+
const { foundElement, foundElementRelativePoint, force } = findVisibleMomenticIdAndPoint(nearestDocumentRoot, elm, logs);
|
|
3855
3908
|
if (elm === foundElement) {
|
|
3856
|
-
return {
|
|
3909
|
+
return { foundElementRelativePoint, force, logs };
|
|
3857
3910
|
}
|
|
3858
3911
|
const foundElementDataMomenticId = foundElement.getAttribute("data-momentic-id");
|
|
3859
3912
|
let foundElementMPathSelector;
|
|
@@ -3867,7 +3920,7 @@ function performTargetRedirectionHelper(elm, logs) {
|
|
|
3867
3920
|
foundElement,
|
|
3868
3921
|
{ truncateToLength: 150 }
|
|
3869
3922
|
),
|
|
3870
|
-
|
|
3923
|
+
foundElementRelativePoint,
|
|
3871
3924
|
force,
|
|
3872
3925
|
logs
|
|
3873
3926
|
};
|
|
@@ -3934,67 +3987,67 @@ function registerAllMomenticListeners() {
|
|
|
3934
3987
|
|
|
3935
3988
|
// src/html/index.ts
|
|
3936
3989
|
registerAllMomenticListeners();
|
|
3937
|
-
`};var
|
|
3990
|
+
`};var nr={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-index","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:["data-test-id","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-index","data-row-index","data-col-index","for","title","alt","aria-label","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 Qb="BoundingBoxMovedError",eE="ZeroOpacityError",Cl="visual_actions",Kr="data-momentic-id";function tE(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(`
|
|
3938
3991
|
`,o);a>0&&a<n&&(o=a);let s=i,c=0;for(;c<1e3&&s>n&&r[s]!==`
|
|
3939
3992
|
`;)c++,s--;return s>n&&r[s]===`
|
|
3940
|
-
`&&(i=s),r.slice(o,i)}function pr(r){let e=typeof r=="string"?r:r.toString();return`[${Fr}="${e}"]`}import{execSync as FL}from"child_process";import{randomUUID as up}from"crypto";import{diff as dp}from"deep-object-diff";import{existsSync as Tl,readFileSync as BL,readdirSync as zL,statSync as nE,writeFileSync as HL}from"fs";import{Jimp as oE}from"jimp";import GL from"js-beautify";import{cloneDeep as Wo}from"lodash-es";import jL from"mime";import{platform as VL}from"os";import{basename as $L,extname as WL,join as qL}from"path";import{v4 as KL}from"uuid";import{rmSync as xb}from"fs";import{basename as WO,join as qO}from"path";import{errors as KO}from"playwright-core";import{devices as oO}from"playwright-core";var Yy=2,xd=8e3;var Go=250,Qe=500;var Xy=5e3,Jy=250,Z=3e3,ue=2e3,ee=1e3,_d=3e4,Md=8e3,Zy=10,Pd=.05;var Qy=6e4,eb=new Set(["about:blank","chrome-error://chromewebdata/"]);var Id=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],Od=1e4,ia=500,dl=oO["Desktop Chrome"].userAgent,jo=process.env.TWO_CAPTCHA_KEY;import{mkdirSync as iO,rmSync as tb,statSync as aO}from"fs";import*as Dd from"node:fs";import sO from"nodejs-file-downloader";import{tmpdir as lO}from"os";import mn,{basename as cO,dirname as uO}from"path";var Ud="file://",kd=mn.join(lO(),"momentic","downloads"),Nd=1e4,dO=50*1024*1024;async function rb(r){let{uri:e}=r;if(e.startsWith(Ud))return mO(r);if(e.startsWith("http"))return hO(r);if(Bf)return gO(r);throw new _("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function pO(r,e){let t=mn.join(kd,r,e.slice(Ud.length)),n=mn.join(kd,r),o=t.startsWith(n);if(!Dd.existsSync(t)||!o)throw new _("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function mO({uri:r,orgId:e}){let t=pO(e,r);return{filePath:t,cleanup:()=>{tb(uO(t),{recursive:!0,force:!0})}}}async function gO({uri:r}){let e=mn.resolve(r);if(!Dd.existsSync(e))throw new _("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 hO({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=cO(n.href),i=Bd(o),a=mn.extname(i);if(Lf.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let s=Fd(t),c,l;for(let m=1;m<=3;m++){let h=new sO({url:r,fileName:i,directory:s,maxAttempts:1,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:Nd});try{let{downloadStatus:f,filePath:E}=await V(h.download(),{milliseconds:Nd,message:`Download timed out after ${Nd}ms`});if(f!=="COMPLETE"||!E)throw new Error(`Download ended in non-success status: ${f}`);c=E;break}catch(f){l=f}}if(!c)throw new Error(`Download failed after 3 attempts. Last error: ${l instanceof Error?l.message:l}`);let u=c,p=aO(u).size;if(p>dO)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(()=>tb(s,{recursive:!0,force:!0}),10*60*1e3)}}}function nb(r,e){return`${Ud}${r}/${e}`}function Fd(r){let e=Math.random().toString(36).substring(4),t=mn.join(kd,r,e);return iO(t,{recursive:!0}),t}function Bd(r){let e=mn.extname(r),t=mn.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function Br(r,e){try{return await r.evaluate(n=>window.serializeElementOnlyWithText?.(n,{truncateToLength:500}),void 0,{timeout:ee})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}var pl=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(s=>n-s<=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 ob(r,e){let t=r.evaluate(async()=>{let i=window,a={};try{let s=await indexedDB.databases();for(let c of s){if(!c.name)continue;let l=await i.exportIdbToObject?.(c.name,c.version);l&&(a[c.name]=l)}return[a,void 0]}catch(s){return[void 0,s.message]}}),[n,o]=await V(t,{milliseconds:Z});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function ib(r,e,t){if(e){t.debug("Importing indexedDB data");try{let n=r.evaluate(async o=>{let i=window;for(let[a,s]of Object.entries(o))await i.importObjectToIdb?.(a,s)},e);await V(n,{milliseconds:Z})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function ab(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 V(t,{milliseconds:Z})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function sb(r,e,t,n,o){try{await fO(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function fO(r,e,t,n){let o=n.text();o.length>ia&&(o=o.slice(0,ia)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let s=await a.jsonValue(),c=JSON.stringify(s);c.length>ia?i.push(c.slice(0,ia)+"...(TRUNCATED)"):(typeof s!="object"||Object.keys(s).length>0)&&i.push(s)}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>Od&&(i[t]=i[t].slice(Math.floor(Od/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 Zt({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await Rd({promiseGenerator:r,signal:n,codePath:e,logger:o}),s=Date.now();return t[e]=s-i,a}import SO from"truncate-json";var yO="[redacted due to size]",lb=5e3,bO=5e3;async function ub(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 Hd(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([s,c])=>({name:s,value:c})),i={...await pb(e),url:n.toString(),method:e.method(),queryString:o,postData:await TO(e)};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:mb(t).timings}}async function db(r,e,t){await t.finished();let n={};try{n=await RO(t)}catch{}let o={...await pb(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:s,total:c}=mb(a);r.time=c,r.timings=s}function aa(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function cb(r){try{return new Date(r).toISOString()}catch{return}}function EO(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=wr(i),e.value=wr(a);continue}i==="Domain"&&(e.domain=wr(a)),i==="Expires"&&(e.expires=cb(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=cb(Date.now()+ +a*1e3)),i==="Path"&&(e.path=wr(a)),i==="Secure"&&(e.secure=!0)}return e}async function pb(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(EO)??[];return{headers:Object.entries(e).map(([n,o])=>({name:wr(n),value:wr(o)})),cookies:t}}async function TO(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:wr(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:wr(i),value:a?wr(a):void 0})}return n}var vO=["text"],AO=["json","xml","html","javascript"];function wO(r){let[e,t]=r.split("/");return e?vO.includes(e)?!0:t?!!AO.some(n=>t?.includes(n)):!1:!1}async function RO(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&&wO(t)&&(n.text=wr(await r.text())),n}function wr(r){try{let e=JSON.parse(r),{jsonString:t}=SO(r,bO);return t}catch{return r.length>lb?r.slice(0,lb)+yO:r}}function Kn(r){return r<0?0:r}function mb(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 gb(){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 qe({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await V(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 Gd(){return window.lastCursorPos}import{errors as CO}from"playwright-core";async function Yn({func:r,action:e,logger:t,callbacks:n,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),s;for(;Date.now()-a<o;)try{return await r(i)}catch(c){if(c instanceof CO.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),s=await xO(c,i.locator,n,t);else throw c}throw s instanceof _?s:new _("ActionFailureError",`Failed to interact with targeted element. Error: ${s.message}`,{errOptions:{cause:s}})}async function xO(r,e,t,n){return r.message.includes("attempt #")?_O(r,e,t,n):MO(r)}async function _O(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(`
|
|
3941
|
-
`,"
|
|
3942
|
-
${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 l=await e.boundingBox({timeout:Z});l?l.height===0?c="The element you attempted to interact with has zero height.":l.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 _("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 _("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 MO(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 _("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}import{existsSync as la,mkdirSync as Kd,readdirSync as DO,rmSync as yb}from"fs";import{homedir as Xd}from"os";import{join as zr,resolve as UO}from"path";import{chromium as bb}from"playwright-core";import{addExtra as FO}from"playwright-extra";import BO from"puppeteer-extra-plugin-recaptcha";function hb(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:s}of r)(!s||s.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 IO}from"crypto";function fb(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function Sb(r){let{route:e,mock:t,entry:n,debugData:o,requestId:i,requestRecorders:a,logger:s}=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}},l;if(t.fetchOriginalResponse){let g=await e.fetch();l={body:await g.text(),options:{status:g.status(),statusText:g.statusText(),headers:Object.entries(await g.headers())}}}let u=await PO(t,c,l),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},aa(o,n,i);for(let g of Object.values(a))g.onRequestComplete(i,n)}catch(g){g.message.includes("has been closed")||s.warn({err:g},"Failed to add response to HAR")}}async function PO(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 jd(r){try{await OO(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function OO(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:s}=r,c=IO(),l=await Hd(e,n);try{aa(o,l,c);for(let d of Object.values(a))d.onRequestStart(c,l)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=fb(n,s);u?await Sb({logger:i,route:t,mock:u,entry:l,debugData:o,requestId:c,requestRecorders:a}):await LO({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:l,requestId:c})}async function LO({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let s=await e.response();if(!s||!i)return;await db(i,e,s),aa(t,i,a);for(let c of Object.values(o))c.onRequestComplete(a,i)}catch(s){s.message.includes("has been closed")||n.warn({err:s},"Failed to add response to HAR")}}async function NO(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 kO(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 ml(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 Vd(r){let e=r.request(),t=r.status(),n=r.headers(),o=await kO(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await NO(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var gn=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:sl(t,this.requestMatcher.urlMatcher)}};function sa(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()}import{homedir as $d,platform as Wd}from"os";import{join as qd}from"path";function gl(){let r=[];if(Wd()==="linux"){let e=$d();["chromium","google-chrome","chrome-canary"].forEach(t=>{r.push(qd(e,".config",t,"Crash Reports"))})}else if(Wd()==="darwin"){let e=$d();["Chromium","Google","Chrome for Testing"].forEach(t=>{r.push(qd(e,"Library","Application Support",t,"Crashpad"))})}else if(Wd()==="win32"){let e=$d();["Chromium","Google","Google Chrome Canary"].forEach(t=>{r.push(qd(e,"AppData","Local",t,"User Data","Crashpad","reports"))})}return r}var Yd=zr(Xd(),"momentic","chromium"),zO=zr(Xd(),"video"),Eb=FO(bb);Eb.use(BO({provider:{id:"2captcha",token:jo},visualFeedback:!0}));var HO=["--enable-crashpad","--crash-on-hang-threads=UI:18,IO:18"],GO=["--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"],jO=["--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"];async function Tb({baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,contextArgs:i,recordVideo:a,iconKnowledgeBase:s,callbacks:c}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let l;switch(o.browserType){case"Google Chrome":l="chrome";break;case"Chrome for Testing":l=void 0;break;case"Chromium":l="chromium";break;default:l="chromium";break}let u=[...GO],d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:l},p={...i??{},geolocation:i?.geolocation||xh,locale:i?.locale||Rh,timezoneId:i?.timezoneId||Ch,colorScheme:i?.colorScheme,httpCredentials:o.basicAuthorization?{username:o.basicAuthorization.username??"",password:o.basicAuthorization.password??""}:void 0,javaScriptEnabled:o.disableJavaScript?!1:void 0,ignoreHTTPSErrors:o.ignoreHttpsErrors??!1,userAgent:o.userAgent??dl,viewport:i?.viewport??rn};o.initialLocalStorage&&(p.storageState={cookies:[],origins:Object.entries(o.initialLocalStorage).map(([S,R])=>({origin:S,localStorage:Object.entries(R).map(([A,v])=>({name:A,value:v}))}))}),process.env.MOMENTIC_CHROME_EXTRA_ARGS&&u.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let g=null,m,h,f={systemDevicePixelRatio:i?.deviceScaleFactor,recordVideo:a,isNewHeadless:!1};(l==="chrome"||l==="chromium")&&(f.isNewHeadless=!0,d.headless&&u.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&u.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`);try{let S=gl();S.forEach(R=>{if(!la(R))return;["new","pending","completed"].forEach(v=>{let P=zr(R,v);if(!la(P))return;let C=DO(P);for(let w=0;w<C.length;w++){let F=zr(P,C[w]);yb(F,{force:!0})}})}),S.forEach(R=>{la(R)||Kd(R,{recursive:!0});let A=zr(R,`write-test-${Date.now()}`);Kd(A,{recursive:!0}),yb(A,{recursive:!0,force:!0})}),u.push(...HO)}catch(S){e.warn({err:S},"Could not create Chrome crash report directory, not enabling crashpad")}o.disableGpu&&u.push(...jO);let E=o.localChromeExtensionPaths?.map(S=>S.startsWith("~")?zr(Xd(),S.slice(1)):S);if(E?.length){if(l===void 0)throw new _("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let v of E){let P=zr(v,"manifest.json");if(!la(P))throw new _("UserConfigurationError",`Chrome extension path ${P} does not exist.`)}if(dn)throw new _("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let S=zr(Yd,`momentic-session-${Date.now()}`);if(!la(S))try{Kd(S,{recursive:!0})}catch(v){throw new _("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${Yd} folder: ${v}`)}let R=[...u],A=E.map(v=>UO(v)).join(",");R.push(`--disable-extensions-except=${A}`),p?.deviceScaleFactor&&R.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&R.push(`--window-size=${p.viewport.width},${p.viewport.height}`),m=await bb.launchPersistentContext(zr(Yd,`momentic-session-${Date.now()}`),{...d,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:R,baseURL:r}),e.info({sharedContextOptions:p,sharedBrowserOptions:d,userBrowserSettings:o,chromeArgs:R,properties:f,baseUrl:r},"Browser initialization context args (persistent)"),h=m.pages()[0]}else{g=await Eb.launch({...d,args:u});let S={...p,baseURL:r,recordVideo:a?{dir:zO}:void 0};m=await g.newContext(S),e.info({contextArgs:S,sharedBrowserOptions:d,chromeArgs:u,userBrowserSettings:o,properties:f,baseUrl:r},"Browser initialization context args (standard)"),h=await m.newPage()}return dn&&await m.route("**",sa),{browser:g,context:m,page:h,baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,viewport:p.viewport||rn,properties:f,clientCallbacks:c,iconKnowledgeBase:s}}async function vb(r){try{return await VO(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function VO({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:ee}),o=await Br(r,e),i=await r.boundingBox({timeout:ee});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:ee}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let l=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=l._MOMENTIC_FEATURE_FLAGS?.[ul],h=c.getAttribute(Fr),f=!m&&h?pr(h):l.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:ee});if(a.type==="error")throw new Error(a.error);let s=r.page().locator(a.selector);return await s.waitFor({state:"visible",timeout:ee}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:s,relativePoint:a.relativePoint}}var wb=["date","datetime-local","month","time","week"],Ab={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 Rb(r){try{await V($O(r),{milliseconds:Z})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function $O({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await qe({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:ee,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!Ab[i])return;Ab[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 It}from"zod";var Cb=It.object({doubleClick:It.boolean().optional(),rightClick:It.boolean().optional(),force:It.boolean().optional(),waitForDownload:It.boolean().optional(),delayMs:It.number().optional(),downloadTimeoutMs:It.number().optional(),relativePosition:It.object({x:It.number(),y:It.number()}).optional()}),gre=It.object({repeat:It.number().optional(),convertMeta:It.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:It.number().optional()});async function hl({locator:r,callbacks:e,logger:t,timeoutMs:n=ee}){try{await Jd(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 s=0;for(;!a.momenticIsEligible(i)&&s<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,s++}let c=i.style.getPropertyValue("outline"),l=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,l),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 V(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 Jd(r,e=ee){let t=await r.state.getRoot();await qe({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 Zd(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return Yn({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>_b({...r,targetingResult:t,useVisualClick:e})})}async function YO(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await XO(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 XO(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:ee});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:ee}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),_b({...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 JO(r){let{browserCallbacks:e,logger:t,targetingResult:n,position:o,options:i}=r,a=Cb.safeParse(i),s=await e.state.getRoot(),c=s&&s!==n.locator.page()&&"frameElement"in s?await s.frameElement():null,l;try{l=c?await Wn({promiseGenerator:async()=>c.boundingBox(),timeoutMs:Z,logger:t}):null}catch(m){throw new _("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${m.message}`)}finally{await c?.dispose()}let u=Date.now(),{clickX:d,clickY:p,reason:g}=await eL({frameCoordinates:l,logger:t,targetingResult:n,position:o,options:i});return t.info({frameCoordinates:l,position:o,options:a.success?a.data:void 0,clickLocation:{clickX:d,clickY:p,reason:g},duration:Date.now()-u},"Visual click"),{x:d,y:p}}async function ZO(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 l=await vb({locator:i,logger:o});l&&(i=l.locator,a=l.relativePoint??a)}let s=n?.force||t.hints?.force||!1,c=i.toString();try{o.info({locator:c},"Locator click"),n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:Z,position:a,delay:n?.delayMs??25,force:s}):await i.click({button:n?.rightClick?"right":"left",timeout:Z,position:a,delay:n?.delayMs??25,force:s})}catch(l){let u=l;if(rL(u))o.warn({err:u},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:u},"Error clicking on locator, attempting to recover..."),YO(u,{...r,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function _b(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??_d;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof KO.TimeoutError?new _("ActionFailureError",`Download did not complete in ${u}ms`):new _("ActionFailureError",`Download failed: ${d.message}`)}})());try{await hl({locator:a.locator,callbacks:n,logger:t,timeoutMs:ee})}catch(u){t.warn({err:u},"Error highlighting locator in click, continuing...")}let c,l;if(i?c=await JO(r):l=(await ZO(r)).locatorSource,e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new _("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let u=await V(s,{milliseconds:e.downloadTimeoutMs??_d});if(u instanceof Error)throw u;return{downloadedFile:await tL(u,o.createIsolatedFolder,t),coordinates:c,locatorSource:l}}else throw new Error("No download promise or error but the step requested to wait for a download");return{coordinates:c,locatorSource:l}}async function QO(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:Z});if(!t)throw new _("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 eL({frameCoordinates:r,logger:e,options:t,targetingResult:n,position:o}){let i,a,s;if(t?.relativePosition){let d=await n.locator.boundingBox({timeout:Z}),p=t.relativePosition.x,g=t.relativePosition.y;d?.width&&(p=Math.max(0,Math.min(t.relativePosition.x,d.width))),d?.height&&(g=Math.max(0,Math.min(t.relativePosition.y,d.height))),i=(d?.x??0)+p,a=(d?.y??0)+g,s="relative position from user"}else if(o){let d=await n.locator.boundingBox({timeout:Z});i=(d?.x??0)+o.x,a=(d?.y??0)+o.y,s="predefined position"}else{let[d,p]=await QO(r,n);i=d.x,a=d.y,s=p}let c=n.locator.page(),l=t?.rightClick?"right":"left",u=t?.delayMs??25;return t?.doubleClick?await c.mouse.dblclick(i,a,{button:l,delay:u}):await c.mouse.click(i,a,{button:l,delay:u}),{clickX:i,clickY:a,reason:s}}async function tL(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=Bd(r.suggestedFilename()),i=e();await r.saveAs(qO(i,o)),xb(n,{force:!0}),setTimeout(()=>{xb(i,{recursive:!0,force:!0})},5*60*1e3);let a=nb(WO(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function rL(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as nL}from"os";var oL={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 iL(){let r=nL();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function Mb(r){return JSON.stringify(r.split("+").sort())}function fl(r){let e=iL(),t=Mb(r);for(let n of Object.values(oL))if(Object.values(n).some(o=>Mb(o)===t))return n[e];return process.platform==="darwin"?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function Qd({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:s,logger:c}){if(!t&&!o)return;let l=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await qe({root:r,fn:([d,p,g,m])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*g,window.scrollY+(p??window.innerHeight)*m),arg:[t,o,l,u],waitForPageLoad:s.waitForPageLoad,timeout:ue,codePath:"scrolling page"});else{let d=e.viewportSize()||rn,p=await qe({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:ue,codePath:"computing page height"}),[g,m,h]=await qe({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:s.waitForPageLoad,timeout:ue,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*l,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<ue;){a?.throwIfAborted();let E=await V(e.evaluate(()=>document.body.scrollHeight),{milliseconds:ee}),[S,R,A]=await V(e.evaluate(()=>{let v=document.activeElement;if(!v)return[void 0,void 0,void 0];let P=v.getBoundingClientRect();return[v.scrollTop,P.x,P.y]}),{milliseconds:ee});if(E===p&&S===g&&R===m&&A===h)break;p=E,g=S,m=R,h=A,await Q(Qe)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function ep(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(Qe)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as mL}from"crypto";import{cloneDeep as np}from"lodash-es";function hn(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as aL}from"crypto";var sL="v1";function tp(r,e){if(r.tagName.toLowerCase()==="svg"&&!cL(r))try{let t=Pb(r,e),n=lL(JSON.stringify(t));return{version:sL,json:t,hash:n}}catch{return}}function lL(r){return aL("md5").update(r).digest("hex")}function Pb(r,e){let t=r.tagName.toLowerCase(),n=uL(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 s=Pb(a,e);s&&o.children.push(s)}}return o}function cL(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function uL(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 Xn={r:147,g:196,b:125,a:.55},Ob={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 Lb({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},s={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:s};return i.forEach((l,u)=>{let d=dL({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function dL({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:s}){let c=r[o],l=c.layout,u={};l.nodeIndex.forEach((C,w)=>{u[C]=w});let d=l.styles,p=l.bounds??[],g=c.nodes,m=g.contentDocumentIndex??{index:[],value:[]},h=g.backendNodeId??[],f=g.attributes??[],E=g.parentIndex??[],S=g.nodeName??[],R=g.nodeType??[],A=g.pseudoType??{index:[],value:[]},v=g.inputChecked??{index:[]},P=e[c.frameId];for(let C=0;C<h.length;C++){let w=h[C],F=R[C],D=f[C]??[],k=E[C]!==void 0&&E[C]>=0?E[C]:void 0,Y=k!==void 0?h[k]:void 0,Me=Y!==void 0?a[Y]:void 0,q=A.index.indexOf(C),H=q!==-1?e[A.value[q]]:void 0,ie=u[C],ae;ie?ae=p[ie]??[]:ae=[];let Ie=S[C]!==void 0?e[S[C]]?.toLowerCase():void 0;if(!Ie){s.warn({backendNodeId:w,frameId:P,frameIndex:o,nodeBounds:ae},"DOM node has no tag name");continue}let de={backendNodeId:w,psuedoType:H,nodeType:F,frameIndex:o,parentFrameId:P,ownedFrameId:void 0,bounds:{x:ae[0]??null,y:ae[1]??null,width:ae[2]??null,height:ae[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:Y??null,tagName:Ie,parent:Me??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};Me&&Me.childrenBackendIds.push(w);let at=m.index.indexOf(C);if(at!==-1){let Ee=m.value[at];i[Ee]=de;let Ke=r[Ee]?.frameId;de.ownedFrameId=Ke!==void 0?e[Ke]:void 0}for(let Ee of Object.keys(de.bounds)){let Ke=Ee;de.bounds[Ke]!==null&&(de.bounds[Ke]/=n)}let Bt=ie!==void 0?d[ie]??[]:[];for(let Ee=0;Ee<Bt.length&&!(Ee>=t.length);Ee++){let Ke=Bt[Ee];if(Ke===void 0||isNaN(Ke))continue;let zt=e[Ke];if(zt===void 0)continue;let yo=t[Ee];de.computedStyles[yo]=zt}for(let Ee=0;Ee<D.length;Ee+=2){let Ke=D[Ee],zt=D[Ee+1];if(!Ke||!zt)continue;let yo=e[Ke],_n=e[zt];!yo||!_n||(de.attributes[yo]=_n)}v.index.includes(C)&&(de.attributes.checked="true"),a[de.backendNodeId]=de}return a[h[0]]}function rp(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=`${rp(t,e)}${a}`}return r.mPathSelector=n,n}function Ib(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var pL=["html","#document","#document-fragment"];function Nb({node:r,domGraph:e}){let t=[],n=r,o=Ib(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=Ib(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++,pL.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,l=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(${l})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&l++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function kb(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 Db(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:ue});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:ue}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:ue})).attributes,i=hn(o,Fr);if(!i)throw new Error(`Could not find attribute ${Fr} for object ${e}`);return i}var gL=["focusable","keyshortcuts","controls","live","relevant","orientation"],hL=["selected","readonly","modal","required","invalid"],fL=["id","name","role","content"],Ub=["absolute","fixed","sticky"],SL=["i"],yL=["path"],bL=["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"],zb=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],Hb=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],EL=["menulistpopup","statictext","inlinetextbox"],TL=80,Fb=100,Gb=50,ap=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],vL=["cite"],AL={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"]},wL={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},Bb={indentLevel:0},op=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<Gb?t:""),this.role=this.role||(e.domNode.attributes.role??""),_L(this.properties,e.domNode,e.importantProperties)}PL(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&&yL.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>Hb.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>qb(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>Kb(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),s=i[1]?.trim();if(a===void 0||s===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===s||s==="*")}))return!0}if(this.domNode&&SL.includes(this.domNode.tagName)||bL.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=>Wb(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=Bb){let t=Object.assign({},Bb,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=t,l=np(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",g=this.name;d==="heading"&&g==="heading"&&(g=""),this.nameSources?.find(v=>!v.superseded&&v.type==="contents")&&this.children.length>0&&(g="");let h=this.nameSources?.find(v=>!v.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let v=h.attributeValue?.relatedNodes??[];v.length===1&&v[0].text&&v[0].text===g&&(g="")}let f=ap.includes(this.role)||vL.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${g}
|
|
3943
|
-
`;let E=`${u}<${p}`;!a&&!f&&(E+=` id="${this.id}"`);let S=s??!1;if((l.multiline||l.contenteditable)&&this.children.length>0&&(S=!0),d&&d!=="generic"&&d!==p&&!(AL[d]??[]).includes(p)&&(E+=` role=${JSON.stringify(d)}`),g&&(E+=` name=${JSON.stringify(g)}`),this.content&&!S&&(E+=` content=${JSON.stringify(this.content)}`),this.flagNotActionableNodes&&this.tagName!=="#document"&&this.isNotActionable()&&(E+=` ${Jt.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let v=this.domNode.bounds,P=Math.round(v.x??0),C=Math.round(v.y??0),w=Math.round((v.x??0)+(v.width??0)),F=Math.round((v.y??0)+(v.height??0));E+=` bounds=[${P} ${C} ${w} ${F}]`}let R=Date.now();if(Object.keys(l).length>0&&!i){if(Date.now()-R>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(l).forEach(([v,P])=>{if(!gL.includes(v)){{if(hL.includes(v)&&(!P||P==="false"))return;if(v==="value"&&S&&(l.type==="text"||this.role==="textbox"))return;if(v==="level"&&`${P}`=="1")return;if(v==="url"&&l.src&&p==="img")return;if(v==="url"&&l.href&&p==="a")return;if(v==="editable"&&P==="plaintext")return;if(v==="type"&&P===p)return;if(c&&!wL[v])return}typeof P=="string"?E+=` ${v}="${At(P,Fb,!0)}"`:typeof P=="boolean"?P?E+=` ${v}`:E+=` ${v}={false}`:typeof P<"u"&&(E+=` ${v}={${At(JSON.stringify(P),Fb,!0)}}`)}})}if(p==="::before"||p==="::after"){let v="";for(let P of this.children)v+=P.serialize({...e,indentLevel:n,neighbors:0});return v}let A=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||A)E+=` />
|
|
3944
|
-
`;
|
|
3945
|
-
|
|
3993
|
+
`&&(i=s),r.slice(o,i)}function Er(r){let e=typeof r=="string"?r:r.toString();return`[${Kr}="${e}"]`}import{execSync as E0}from"child_process";import{randomUUID as kp}from"crypto";import{diff as Dp}from"deep-object-diff";import{existsSync as Ul,readFileSync as T0,readdirSync as v0,statSync as uT,writeFileSync as A0}from"fs";import{Jimp as dT}from"jimp";import w0 from"js-beautify";import{cloneDeep as ri}from"lodash-es";import R0 from"mime";import{platform as C0}from"os";import{basename as x0,extname as _0,join as M0}from"path";import{v4 as P0}from"uuid";import{rmSync as NE}from"fs";import{basename as _N,join as MN}from"path";import{errors as PN}from"playwright-core";import{devices as BL}from"playwright-core";var rE=2,Jd=8e3;var Zo=250,at=500;var nE=5e3,oE=250,te=3e3,ge=2e3,re=1e3,Zd=3e4,Qd=8e3,iE=10,ep=.05;var aE=6e4,sE=new Set(["about:blank","chrome-error://chromewebdata/"]);var tp=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],rp=1e4,Ea=500,xl=BL["Desktop Chrome"].userAgent,Qo=process.env.TWO_CAPTCHA_KEY;import{mkdirSync as zL,rmSync as lE,statSync as HL}from"fs";import*as ap from"node:fs";import GL from"nodejs-file-downloader";import{tmpdir as jL}from"os";import Tn,{basename as VL,dirname as $L}from"path";var sp="file://",ip=Tn.join(jL(),"momentic","downloads"),op=1e4,WL=50*1024*1024;async function cE(r){let{uri:e}=r;if(e.startsWith(sp))return KL(r);if(e.startsWith("http"))return XL(r);if(qS)return YL(r);throw new _("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function qL(r,e){let t=Tn.join(ip,r,e.slice(sp.length)),n=Tn.join(ip,r),o=t.startsWith(n);if(!ap.existsSync(t)||!o)throw new _("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function KL({uri:r,orgId:e}){let t=qL(e,r);return{filePath:t,cleanup:()=>{lE($L(t),{recursive:!0,force:!0})}}}async function YL({uri:r}){let e=Tn.resolve(r);if(!ap.existsSync(e))throw new _("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 XL({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=VL(n.href),i=cp(o),a=Tn.extname(i);if(HS.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let s=lp(t),c,l;for(let m=1;m<=3;m++){let g=new GL({url:r,fileName:i,directory:s,maxAttempts:1,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:op});try{let{downloadStatus:f,filePath:E}=await $(g.download(),{milliseconds:op,message:`Download timed out after ${op}ms`});if(f!=="COMPLETE"||!E)throw new Error(`Download ended in non-success status: ${f}`);c=E;break}catch(f){l=f}}if(!c)throw new Error(`Download failed after 3 attempts. Last error: ${l instanceof Error?l.message:l}`);let u=c,p=HL(u).size;if(p>WL)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:p,filePath:u,fileName:i},"Downloaded file to disk");let h;return{filePath:u,cleanup:()=>{clearTimeout(h),h=setTimeout(()=>lE(s,{recursive:!0,force:!0}),10*60*1e3)}}}function uE(r,e){return`${sp}${r}/${e}`}function lp(r){let e=Math.random().toString(36).substring(4),t=Tn.join(ip,r,e);return zL(t,{recursive:!0}),t}function cp(r){let e=Tn.extname(r),t=Tn.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:re})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}var ro=3.1783027;function JL(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 Or(r){return Math.ceil(up(r)/ro)}function up(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
|
|
3994
|
+
`,""),t=t.replaceAll(" ","");let n=JL(t);return t.length-n+ro*n}if(typeof r>"u"||r===null)return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=up(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*ro:e+=85*ro:e+=up(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 _l=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(s=>n-s<=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 dE(r,e){let t=r.evaluate(async()=>{let i=window,a={};try{let s=await indexedDB.databases();for(let c of s){if(!c.name)continue;let l=await i.exportIdbToObject?.(c.name,c.version);l&&(a[c.name]=l)}return[a,void 0]}catch(s){return[void 0,s.message]}}),[n,o]=await $(t,{milliseconds:te});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function pE(r,e,t){if(e){t.debug("Importing indexedDB data");try{let n=r.evaluate(async o=>{let i=window;for(let[a,s]of Object.entries(o))await i.importObjectToIdb?.(a,s)},e);await $(n,{milliseconds:te})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function mE(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 $(t,{milliseconds:te})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function hE(r,e,t,n,o){try{await ZL(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function ZL(r,e,t,n){let o=n.text();o.length>Ea&&(o=o.slice(0,Ea)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let s=await a.jsonValue(),c=JSON.stringify(s);c.length>Ea?i.push(c.slice(0,Ea)+"...(TRUNCATED)"):(typeof s!="object"||Object.keys(s).length>0)&&i.push(s)}catch{}dp(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function dp(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>rp&&(i[t]=i[t].slice(Math.floor(rp/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 or({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await Kd({promiseGenerator:r,signal:n,codePath:e,logger:o}),s=Date.now();return t[e]=s-i,a}import QL from"truncate-json";var eN="[redacted due to size]",gE=5e3,tN=5e3;async function SE(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 pp(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([s,c])=>({name:s,value:c})),i={...await bE(e),url:n.toString(),method:e.method(),queryString:o,postData:await nN(e)};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:EE(t).timings}}async function yE(r,e,t){await t.finished();let n={};try{n=await sN(t)}catch{}let o={...await bE(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:s,total:c}=EE(a);r.time=c,r.timings=s}function Ta(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function fE(r){try{return new Date(r).toISOString()}catch{return}}function rN(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=Lr(i),e.value=Lr(a);continue}i==="Domain"&&(e.domain=Lr(a)),i==="Expires"&&(e.expires=fE(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=fE(Date.now()+ +a*1e3)),i==="Path"&&(e.path=Lr(a)),i==="Secure"&&(e.secure=!0)}return e}async function bE(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(rN)??[];return{headers:Object.entries(e).map(([n,o])=>({name:Lr(n),value:Lr(o)})),cookies:t}}async function nN(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:Lr(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:Lr(i),value:a?Lr(a):void 0})}return n}var oN=["text"],iN=["json","xml","html","javascript"];function aN(r){let[e,t]=r.split("/");return e?oN.includes(e)?!0:t?!!iN.some(n=>t?.includes(n)):!1:!1}async function sN(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&&aN(t)&&(n.text=Lr(await r.text())),n}function Lr(r){try{let e=JSON.parse(r),{jsonString:t}=QL(r,tN);return t}catch{return r.length>gE?r.slice(0,gE)+eN:r}}function no(r){return r<0?0:r}function EE(r){return{timings:{blocked:no(r.domainLookupStart),dns:no(r.domainLookupEnd-r.domainLookupStart),connect:no(r.connectEnd-r.connectStart),send:no(r.responseStart-r.requestStart),wait:0,receive:no(r.responseEnd-r.responseStart),ssl:no(r.connectEnd-r.secureConnectionStart)},total:no(r.responseEnd)}}function TE(){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 Qe({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await $(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 mp(){return window.lastCursorPos}import{errors as lN}from"playwright-core";async function oo({func:r,action:e,logger:t,callbacks:n,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),s;for(;Date.now()-a<o;)try{return await r(i)}catch(c){if(c instanceof lN.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),s=await cN(c,i.locator,n,t);else throw c}throw s instanceof _?s:new _("ActionFailureError",`Failed to interact with targeted element. Error: ${s.message}`,{errOptions:{cause:s}})}async function cN(r,e,t,n){return r.message.includes("attempt #")?uN(r,e,t,n):dN(r)}async function uN(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(`
|
|
3995
|
+
`,";").replace(/\s+/g," ");let a="",s=await Yr(e,n);if(s&&(a=`Target element HTML: ${Mt(s,100,!0)}`),i.includes("element is not enabled"))return new _("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="",l=i.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(l){let u=(await t.state.getRoot()).locator(Er(l)),d=await Yr(u,n);d&&(c=`Covering element HTML: ${Mt(d,100,!0)}`)}return new _("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}
|
|
3996
|
+
${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 l=await e.boundingBox({timeout:te});l?l.height===0?c="The element you attempted to interact with has zero height.":l.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 _("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 _("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 dN(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 _("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}import{existsSync as Aa,mkdirSync as bp,readdirSync as yN,rmSync as RE}from"fs";import{homedir as Tp}from"os";import{join as Xr,resolve as bN}from"path";import{chromium as CE}from"playwright-core";import{addExtra as EN}from"playwright-extra";import TN from"puppeteer-extra-plugin-recaptcha";function vE(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:s}of r)(!s||s.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 mN}from"crypto";function AE(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function wE(r){let{route:e,mock:t,entry:n,debugData:o,requestId:i,requestRecorders:a,logger:s}=r,c={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(h=>[h.name,h.value]),body:n.request.postData?.text}},l;if(t.fetchOriginalResponse){let h=await e.fetch();l={body:await h.text(),options:{status:h.status(),statusText:h.statusText(),headers:Object.entries(await h.headers())}}}let u=await pN(t,c,l),d={};u.headers.forEach((h,m)=>{d[m]=h});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(([h,m])=>({name:h,value:m})),cookies:[],content:{mimeType:p.contentType,text:p.body},_mocked:!0},Ta(o,n,i);for(let h of Object.values(a))h.onRequestComplete(i,n)}catch(h){h.message.includes("has been closed")||s.warn({err:h},"Failed to add response to HAR")}}async function pN(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 hp(r){try{await hN(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function hN(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:s}=r,c=mN(),l=await pp(e,n);try{Ta(o,l,c);for(let d of Object.values(a))d.onRequestStart(c,l)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=AE(n,s);u?await wE({logger:i,route:t,mock:u,entry:l,debugData:o,requestId:c,requestRecorders:a}):await gN({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:l,requestId:c})}async function gN({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let s=await e.response();if(!s||!i)return;await yE(i,e,s),Ta(t,i,a);for(let c of Object.values(o))c.onRequestComplete(a,i)}catch(s){s.message.includes("has been closed")||n.warn({err:s},"Failed to add response to HAR")}}async function fN(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 SN(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 Ml(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 gp(r){let e=r.request(),t=r.status(),n=r.headers(),o=await SN(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await fN(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var vn=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:Al(t,this.requestMatcher.urlMatcher)}};function va(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()}import{homedir as fp,platform as Sp}from"os";import{join as yp}from"path";function Pl(){let r=[];if(Sp()==="linux"){let e=fp();["chromium","google-chrome","chrome-canary"].forEach(t=>{r.push(yp(e,".config",t,"Crash Reports"))})}else if(Sp()==="darwin"){let e=fp();["Chromium","Google","Chrome for Testing"].forEach(t=>{r.push(yp(e,"Library","Application Support",t,"Crashpad"))})}else if(Sp()==="win32"){let e=fp();["Chromium","Google","Google Chrome Canary"].forEach(t=>{r.push(yp(e,"AppData","Local",t,"User Data","Crashpad","reports"))})}return r}var Ep=Xr(Tp(),"momentic","chromium"),vN=Xr(Tp(),"video"),xE=EN(CE);xE.use(TN({provider:{id:"2captcha",token:Qo},visualFeedback:!0}));var AN=["--enable-crashpad","--crash-on-hang-threads=UI:18,IO:18"],wN=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=6","--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"],RN=["--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-webgl2","--disable-audio-input","--disable-audio-output"];async function _E({baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,contextArgs:i,recordVideo:a,iconKnowledgeBase:s,callbacks:c}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let l;switch(o.browserType){case"Google Chrome":l="chrome";break;case"Chrome for Testing":l=void 0;break;case"Chromium":l="chromium";break;default:l="chromium";break}let u=[...wN],d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:l},p={...i??{},geolocation:i?.geolocation||Uf,locale:i?.locale||kf,timezoneId:i?.timezoneId||Df,colorScheme:i?.colorScheme,httpCredentials:o.basicAuthorization?{username:o.basicAuthorization.username??"",password:o.basicAuthorization.password??""}:void 0,javaScriptEnabled:o.disableJavaScript?!1:void 0,ignoreHTTPSErrors:o.ignoreHttpsErrors??!1,userAgent:o.userAgent??xl,viewport:i?.viewport??pn,serviceWorkers:"block"};o.initialLocalStorage&&(p.storageState={cookies:[],origins:Object.entries(o.initialLocalStorage).map(([S,w])=>({origin:S,localStorage:Object.entries(w).map(([v,A])=>({name:v,value:A}))}))}),process.env.MOMENTIC_CHROME_EXTRA_ARGS&&u.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let h=null,m,g,f={systemDevicePixelRatio:i?.deviceScaleFactor,recordVideo:a,isNewHeadless:!1};(l==="chrome"||l==="chromium")&&(f.isNewHeadless=!0,d.headless&&u.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&u.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`);try{let S=Pl();S.forEach(w=>{if(!Aa(w))return;["new","pending","completed"].forEach(A=>{let I=Xr(w,A);if(!Aa(I))return;let C=yN(I);for(let R=0;R<C.length;R++){let B=Xr(I,C[R]);RE(B,{force:!0})}})}),S.forEach(w=>{Aa(w)||bp(w,{recursive:!0});let v=Xr(w,`write-test-${Date.now()}`);bp(v,{recursive:!0}),RE(v,{recursive:!0,force:!0})}),u.push(...AN)}catch(S){e.warn({err:S},"Could not create Chrome crash report directory, not enabling crashpad")}o.disableGpu&&u.push(...RN);let E=o.localChromeExtensionPaths?.map(S=>S.startsWith("~")?Xr(Tp(),S.slice(1)):S);if(E?.length){if(l===void 0)throw new _("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let A of E){let I=Xr(A,"manifest.json");if(!Aa(I))throw new _("UserConfigurationError",`Chrome extension path ${I} does not exist.`)}if(yn)throw new _("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let S=Xr(Ep,`momentic-session-${Date.now()}`);if(!Aa(S))try{bp(S,{recursive:!0})}catch(A){throw new _("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${Ep} folder: ${A}`)}let w=[...u],v=E.map(A=>bN(A)).join(",");w.push(`--disable-extensions-except=${v}`),p?.deviceScaleFactor&&w.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&w.push(`--window-size=${p.viewport.width},${p.viewport.height}`),m=await CE.launchPersistentContext(Xr(Ep,`momentic-session-${Date.now()}`),{...d,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:w,baseURL:r}),e.info({sharedContextOptions:p,sharedBrowserOptions:d,userBrowserSettings:o,chromeArgs:w,properties:f,baseUrl:r},"Browser initialization context args (persistent)"),g=m.pages()[0]}else{h=await xE.launch({...d,args:u});let S={...p,baseURL:r,recordVideo:a?{dir:vN}:void 0};m=await h.newContext(S),e.info({contextArgs:S,sharedBrowserOptions:d,chromeArgs:u,userBrowserSettings:o,properties:f,baseUrl:r},"Browser initialization context args (standard)"),g=await m.newPage()}return yn&&await m.route("**",va),{browser:h,context:m,page:g,baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,viewport:p.viewport||pn,properties:f,clientCallbacks:c,iconKnowledgeBase:s}}async function ME(r){try{return await CN(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function CN({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:re}),o=await Yr(r,e),i=await r.boundingBox({timeout:re});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:re}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let l=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 h={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=l._MOMENTIC_FEATURE_FLAGS?.[Cl],g=c.getAttribute(Kr),f=!m&&g?Er(g):l.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:h,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:re});if(a.type==="error")throw new Error(a.error);let s=r.page().locator(a.selector);return await s.waitFor({state:"visible",timeout:re}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:s,relativePoint:a.relativePoint}}var IE=["date","datetime-local","month","time","week"],PE={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 OE(r){try{await $(xN(r),{milliseconds:te})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function xN({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await Qe({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:re,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!PE[i])return;PE[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 Ut}from"zod";var LE=Ut.object({doubleClick:Ut.boolean().optional(),rightClick:Ut.boolean().optional(),force:Ut.boolean().optional(),waitForDownload:Ut.boolean().optional(),delayMs:Ut.number().optional(),downloadTimeoutMs:Ut.number().optional(),relativePosition:Ut.object({x:Ut.number(),y:Ut.number()}).optional()}),gse=Ut.object({repeat:Ut.number().optional(),convertMeta:Ut.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Ut.number().optional()});async function Il({locator:r,callbacks:e,logger:t,timeoutMs:n=re}){try{await vp(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let h=window.getComputedStyle(d,null).getPropertyValue("display");if(h==="none"||h==="contents")return!1;let m=d.getBoundingClientRect();return!(!m.height||!m.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let s=0;for(;!a.momenticIsEligible(i)&&s<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,s++}let c=i.style.getPropertyValue("outline"),l=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,l),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 $(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 vp(r,e=re){let t=await r.state.getRoot();await Qe({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 Ap(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return oo({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>kE({...r,targetingResult:t,useVisualClick:e})})}async function IN(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await ON(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 ON(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:re});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:re}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),kE({...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 LN(r){let{logger:e,targetingResult:t,position:n,options:o}=r,i=LE.safeParse(o),a=Date.now(),{clickX:s,clickY:c,reason:l}=await DN({targetingResult:t,position:n,options:o});return e.info({position:n,options:i.success?i.data:void 0,clickLocation:{clickX:s,clickY:c,reason:l},duration:Date.now()-a},"Visual click"),{x:s,y:c}}async function NN(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 l=await ME({locator:i,logger:o});l&&(i=l.locator,a=l.relativePoint??a)}let s=n?.force||t.hints?.force||!1;s&&!a&&t.hints?.relativeXYToLocator&&(a=t.hints.relativeXYToLocator);let c=i.toString();try{o.info({locator:c},"Locator click"),n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:te,position:a,delay:n?.delayMs??25,force:s}):await i.click({button:n?.rightClick?"right":"left",timeout:te,position:a,delay:n?.delayMs??25,force:s})}catch(l){let u=l;if(FN(u))o.warn({err:u},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:u},"Error clicking on locator, attempting to recover..."),IN(u,{...r,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function kE(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??Zd;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof PN.TimeoutError?new _("ActionFailureError",`Download did not complete in ${u}ms`):new _("ActionFailureError",`Download failed: ${d.message}`)}})());try{await Il({locator:a.locator,callbacks:n,logger:t,timeoutMs:re})}catch(u){t.warn({err:u},"Error highlighting locator in click, continuing...")}let c,l;if(i?c=await LN(r):l=(await NN(r)).locatorSource,e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new _("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let u=await $(s,{milliseconds:e.downloadTimeoutMs??Zd});if(u instanceof Error)throw u;return{downloadedFile:await UN(u,o.createIsolatedFolder,t),coordinates:c,locatorSource:l}}else throw new Error("No download promise or error but the step requested to wait for a download");return{coordinates:c,locatorSource:l}}async function kN(r){let e=await r.locator.boundingBox({timeout:te});if(!e)throw new _("ActionFailureError","Element does not have a bounding box");if(r.hints?.relativeXYToLocator){let o=e.x+r.hints.relativeXYToLocator.x,i=e.y+r.hints.relativeXYToLocator.y;return[{x:o,y:i},"targeting hint"]}let t=e.x+e.width/2,n=e.y+e.height/2;return[{x:t,y:n},"halfway point"]}async function DN({options:r,targetingResult:e,position:t}){let n,o,i;if(r?.relativePosition){let l=await e.locator.boundingBox({timeout:te}),u=r.relativePosition.x,d=r.relativePosition.y;l?.width&&(u=Math.max(0,Math.min(r.relativePosition.x,l.width))),l?.height&&(d=Math.max(0,Math.min(r.relativePosition.y,l.height))),n=(l?.x??0)+u,o=(l?.y??0)+d,i="relative position from user"}else if(t){let l=await e.locator.boundingBox({timeout:te});n=(l?.x??0)+t.x,o=(l?.y??0)+t.y,i="predefined position"}else{let[l,u]=await kN(e);n=l.x,o=l.y,i=u}let a=e.locator.page(),s=r?.rightClick?"right":"left",c=r?.delayMs??25;return r?.doubleClick?await a.mouse.dblclick(n,o,{button:s,delay:c}):await a.mouse.click(n,o,{button:s,delay:c}),{clickX:n,clickY:o,reason:i}}async function UN(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=cp(r.suggestedFilename()),i=e();await r.saveAs(MN(i,o)),NE(n,{force:!0}),setTimeout(()=>{NE(i,{recursive:!0,force:!0})},5*60*1e3);let a=uE(_N(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function FN(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as BN}from"os";var zN={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 HN(){let r=BN();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function DE(r){return JSON.stringify(r.split("+").sort())}function Ol(r,e){let t=HN(),n=DE(r);for(let o of Object.values(zN))if(Object.values(o).some(i=>DE(i)===n))return o[t];return process.platform==="darwin"&&!e?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function wp({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:s,logger:c}){if(!t&&!o)return;let l=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await Qe({root:r,fn:([d,p,h,m])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*h,window.scrollY+(p??window.innerHeight)*m),arg:[t,o,l,u],waitForPageLoad:s.waitForPageLoad,timeout:ge,codePath:"scrolling page"});else{let d=e.viewportSize()||pn,p=await Qe({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:ge,codePath:"computing page height"}),[h,m,g]=await Qe({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:s.waitForPageLoad,timeout:ge,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*l,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<ge;){a?.throwIfAborted();let E=await $(e.evaluate(()=>document.body.scrollHeight),{milliseconds:re}),[S,w,v]=await $(e.evaluate(()=>{let A=document.activeElement;if(!A)return[void 0,void 0,void 0];let I=A.getBoundingClientRect();return[A.scrollTop,I.x,I.y]}),{milliseconds:re});if(E===p&&S===h&&w===m&&v===g)break;p=E,h=S,m=w,g=v,await ee(at)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function Rp(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 ee(at)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as YN}from"crypto";import{cloneDeep as _p}from"lodash-es";function An(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as GN}from"crypto";var jN="v1";function Cp(r,e){if(r.tagName.toLowerCase()==="svg"&&!$N(r))try{let t=UE(r,e),n=VN(JSON.stringify(t));return{version:jN,json:t,hash:n}}catch{return}}function VN(r){return GN("md5").update(r).digest("hex")}function UE(r,e){let t=r.tagName.toLowerCase(),n=WN(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 s=UE(a,e);s&&o.children.push(s)}}return o}function $N(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function WN(r){let e={},t=r.attributes;for(let n of Object.keys(t))nr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var io={r:147,g:196,b:125,a:.55},BE={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:io,paddingColor:io,borderColor:io,marginColor:io,eventTargetColor:io,shapeColor:io,shapeMarginColor:io,showInfo:!0,showAccessibilityInfo:!0};function zE({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},s={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:s};return i.forEach((l,u)=>{let d=qN({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function qN({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:s}){let c=r[o],l=c.layout,u={};l.nodeIndex.forEach((C,R)=>{u[C]=R});let d=l.styles,p=l.bounds??[],h=c.nodes,m=h.contentDocumentIndex??{index:[],value:[]},g=h.backendNodeId??[],f=h.attributes??[],E=h.parentIndex??[],S=h.nodeName??[],w=h.nodeType??[],v=h.pseudoType??{index:[],value:[]},A=h.inputChecked??{index:[]},I=e[c.frameId];for(let C=0;C<g.length;C++){let R=g[C],B=w[C],U=f[C]??[],D=E[C]!==void 0&&E[C]>=0?E[C]:void 0,J=D!==void 0?g[D]:void 0,Le=J!==void 0?a[J]:void 0,K=v.index.indexOf(C),G=K!==-1?e[v.value[K]]:void 0,se=u[C],ce;se?ce=p[se]??[]:ce=[];let ke=S[C]!==void 0?e[S[C]]?.toLowerCase():void 0;if(!ke){s.warn({backendNodeId:R,frameId:I,frameIndex:o,nodeBounds:ce},"DOM node has no tag name");continue}let fe={backendNodeId:R,psuedoType:G,nodeType:B,frameIndex:o,parentFrameId:I,ownedFrameId:void 0,bounds:{x:ce[0]??null,y:ce[1]??null,width:ce[2]??null,height:ce[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:J??null,tagName:ke,parent:Le??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};Le&&Le.childrenBackendIds.push(R);let pt=m.index.indexOf(C);if(pt!==-1){let we=m.value[pt];i[we]=fe;let tt=r[we]?.frameId;fe.ownedFrameId=tt!==void 0?e[tt]:void 0}for(let we of Object.keys(fe.bounds)){let tt=we;fe.bounds[tt]!==null&&(fe.bounds[tt]/=n)}let $t=se!==void 0?d[se]??[]:[];for(let we=0;we<$t.length&&!(we>=t.length);we++){let tt=$t[we];if(tt===void 0||isNaN(tt))continue;let Wt=e[tt];if(Wt===void 0)continue;let xo=t[we];fe.computedStyles[xo]=Wt}for(let we=0;we<U.length;we+=2){let tt=U[we],Wt=U[we+1];if(!tt||!Wt)continue;let xo=e[tt],Dn=e[Wt];!xo||!Dn||(fe.attributes[xo]=Dn)}A.index.includes(C)&&(fe.attributes.checked="true"),a[fe.backendNodeId]=fe}return a[g[0]]}function xp(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=`${xp(t,e)}${a}`}return r.mPathSelector=n,n}function FE(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var KN=["html","#document","#document-fragment"];function HE({node:r,domGraph:e}){let t=[],n=r,o=FE(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=FE(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++,KN.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,l=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(${l})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&l++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function GE(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 jE(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:ge});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:ge}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:ge})).attributes,i=An(o,Kr);if(!i)throw new Error(`Could not find attribute ${Kr} for object ${e}`);return i}var XN=["focusable","keyshortcuts","controls","live","relevant","orientation"],JN=["selected","readonly","modal","required","invalid"],ZN=["id","name","role","content"],VE=["absolute","fixed","sticky"],QN=["i"],e0=["path"],t0=["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"],qE=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],KE=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],r0=["menulistpopup","statictext","inlinetextbox"],n0=80,$E=100,YE=50,Ip=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],o0=["cite"],i0={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"]},a0={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},WE={indentLevel:0},Mp=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<YE?t:""),this.role=this.role||(e.domNode.attributes.role??""),u0(this.properties,e.domNode,e.importantProperties)}p0(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&&e0.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>KE.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>eT(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>tT(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),s=i[1]?.trim();if(a===void 0||s===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===s||s==="*")}))return!0}if(this.domNode&&QN.includes(this.domNode.tagName)||t0.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||nr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>QE(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=WE){let t=Object.assign({},WE,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=t,l=_p(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",h=this.name;d==="heading"&&h==="heading"&&(h=""),this.nameSources?.find(A=>!A.superseded&&A.type==="contents")&&this.children.length>0&&(h="");let g=this.nameSources?.find(A=>!A.superseded);if(g&&!g.nativeSource&&g.type==="relatedElement"){let A=g.attributeValue?.relatedNodes??[];A.length===1&&A[0].text&&A[0].text===h&&(h="")}let f=Ip.includes(this.role)||o0.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${h}
|
|
3997
|
+
`;let E=`${u}<${p}`;!a&&!f&&(E+=` id="${this.id}"`);let S=s??!1;if((l.multiline||l.contenteditable)&&this.children.length>0&&(S=!0),d&&d!=="generic"&&d!==p&&!(i0[d]??[]).includes(p)&&(E+=` role=${JSON.stringify(d)}`),h&&(E+=` name=${JSON.stringify(h)}`),this.content&&!S&&(E+=` content=${JSON.stringify(this.content)}`),this.flagNotActionableNodes&&this.tagName!=="#document"&&this.isNotActionable()&&(E+=` ${nr.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let A=this.domNode.bounds,I=Math.round(A.x??0),C=Math.round(A.y??0),R=Math.round((A.x??0)+(A.width??0)),B=Math.round((A.y??0)+(A.height??0));E+=` bounds=[${I} ${C} ${R} ${B}]`}let w=Date.now();if(Object.keys(l).length>0&&!i){if(Date.now()-w>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(l).forEach(([A,I])=>{if(!XN.includes(A)){{if(JN.includes(A)&&(!I||I==="false"))return;if(A==="value"&&S&&(l.type==="text"||this.role==="textbox"))return;if(A==="level"&&`${I}`=="1")return;if(A==="url"&&l.src&&p==="img")return;if(A==="url"&&l.href&&p==="a")return;if(A==="editable"&&I==="plaintext")return;if(A==="type"&&I===p)return;if(c&&!a0[A])return}typeof I=="string"?E+=` ${A}="${Mt(I,$E,!0)}"`:typeof I=="boolean"?I?E+=` ${A}`:E+=` ${A}={false}`:typeof I<"u"&&(E+=` ${A}={${Mt(JSON.stringify(I),$E,!0)}}`)}})}if(p==="::before"||p==="::after"){let A="";for(let I of this.children)A+=I.serialize({...e,indentLevel:n,neighbors:0});return A}let v=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||v)E+=` />
|
|
3998
|
+
`;else{let A="";for(let C of this.children)A+=C.serialize({...e,indentLevel:n+2,neighbors:0});let I=A.trim();I.length<=n0&&!I.includes(`
|
|
3999
|
+
`)?E+=`>${I}</${p}>
|
|
3946
4000
|
`:E+=`>
|
|
3947
|
-
${
|
|
3948
|
-
`}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let
|
|
4001
|
+
${A}${u}</${p}>
|
|
4002
|
+
`}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let A=this.parent.children.findIndex(R=>R.id===this.id),I=A>0?this.parent.children[A-1]?.serialize({...e,neighbors:0}):"",C=A<this.parent.children.length-1?this.parent.children[A+1]?.serialize({...e,neighbors:0}):"";return`${I||""}
|
|
3949
4003
|
${E}
|
|
3950
|
-
${C||""}`}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:np(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=np(this.properties),e}},ip=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 l=c.shallowClone();if(e[c.id])return l.properties["data-momentic-summary"]=e[c.id],n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l;let u=[];for(let d of c.children){let p=a(d);p&&(u.push(p),p.parent=l)}return l.children=u,n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l},s=a(t);return new r(s,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 s=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),l=i.children,u=!1,d=[];for(let p of l){let g=n(p,s||u);g&&(d.push(g),g.parent=c,u=!0)}if(c.children=d,s||u)return c;if(ap.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,s)=>{s.children=[];for(let c of a.children){let l=c.shallowClone();if(l.parent=s,s.children.push(l),o()>e){s.children.pop();break}if(i(c,l),o()>e){for(;l.children.length>0&&o()>e;)l.children.pop();if(o()>e){s.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 RL(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 CL(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?(qs({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?(qs({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 jb({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:s,showZeroOpacityElements:c,filterByViewport:l,viewportDetails:u,useMPaths:d,importantProperties:p,allowedA11yIgnoreReasonsOverride:g,cdpClient:m,logger:h,callId:f}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let E=(H,ie={})=>{},S=r.backendDOMNodeId,R=EL.includes(r.role?.value?.toLowerCase()??"");if(!R&&S===void 0)return E("Filtering out node since it doesn't exist in the DOM"),[];let A=S?i.backendIdToNode[S]:void 0;if(!R&&!A)try{let H=await V(m.send({method:"DOM.describeNode",params:{backendNodeId:S}}),{milliseconds:750,fallback:()=>{h.debug("Timeout getting node from CDP while processing a11y tree")}});if(H&&H.node.nodeName.toLowerCase()==="slot"&&H.node.distributedNodes?.length)h.debug({redirectedDomNode:A,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:H},"Redirecting node to assigned slot");else return E("Filtering out node since it doesn't exist in the DOM",{cdpResult:H}),[]}catch(H){return E("Filtering out node since it doesn't exist in the DOM",{err:H}),[]}if(A&&e&&l&&u&&r.backendDOMNodeId&&!CL(A,u,h,f))return A.momenticIgnored=!0,[];if(A&&A.computedStyles.display==="none")return A.momenticIgnored=!0,[];if(A&&A.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&A.tagName.toLowerCase()!=="input")return A.momenticIgnored=!0,[];if(c===!1)return A.momenticIgnored=!0,[]}let v=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",P=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",C=new op({domNode:A,id:parseInt(r.nodeId),role:r.role?.value||"",name:v,nameSources:r.name?.sources,content:P,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(H=>(g??zb).includes(H.name)||Hb.includes(H.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+RL(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:s}),w=n,F=a[t],D=t;if(A?.tagName.toLowerCase()==="iframe"&&A.ownedFrameId){let H=n.childFrames.find(Ie=>Ie.frameId===A.ownedFrameId),ie=o[H?.frameId??""]?.root,ae=a[H?.frameId??""];if(H&&ie&&ae){r.childIds&&r.childIds.length>0&&h.debug("Replacing existing node's children with children from the iframe");let Ie=ie;r.childIds=Ie.childIds,w=H,F=ae,D=H.frameId}}let k=A?.childrenBackendIds?.length??0,Y=(r.childIds??[]).filter(H=>!!F.get(parseInt(H))).length;if(k>Y){let H=r.childIds?.map(ae=>F.get(parseInt(ae))).filter(Boolean).map(ae=>ae?.backendDOMNodeId).filter(ae=>ae!==void 0)??[],ie=0;for(let ae of A?.childrenBackendIds??[]){if(H.includes(ae)){ie=(r.childIds?.findIndex(Ee=>F.get(parseInt(Ee))?.backendDOMNodeId===ae)??0)+1;continue}let Ie=i.backendIdToNode[ae];if(!Ie||Ie?.tagName.toLowerCase()!=="svg")continue;let de=Math.floor(-1*Math.random()*1e7),at={nodeId:de.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:ae,frameId:D,role:{type:"string",value:"graphics-symbol"}};F.set(de,at),r.childIds||(r.childIds=[]),r.childIds.splice(ie,0,de.toString()),ie++}}if(r.childIds?.length===1&&A){let H=F.get(parseInt(r.childIds[0])),ie=H?.role?.value,ae=A.childrenBackendIds;if(H&&ie==="StaticText"&&ae.length===1){let Ie=i.backendIdToNode[ae[0]];if(Ie?.tagName?.toLowerCase()==="span"){let de=Math.floor(-1*Math.random()*1e7).toString(),at={nodeId:de,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Ie.backendNodeId,frameId:D,childIds:[H.nodeId]};H.parentId=de,F.set(parseInt(de),at),r.childIds=[de]}}}for(let H of r.childIds??[]){if(!H)continue;let ie=F.get(parseInt(H));if(!ie)continue;let ae=await jb({node:ie,parent:C,domGraph:i,axGraph:o,frameId:D,frameContext:w,inputNodeMap:a,cdpClient:m,logger:h,callId:f,filterByViewport:l,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:s});ae.length&&(C.children=C.children.concat(ae))}if(C.role==="StaticText"&&(C.children=[]),C.children.length===1&&C.children[0].role==="StaticText"){let H=C.name,ie=C.children[0]?.name;(H===ie||!ie)&&(C.children=[])}let Me=[];for(let H=C.children.length-1;H>=0;H--){let ie=C.children[H];if(ie.role!=="StaticText"){Me.push(ie);continue}if(H===0||C.children[H-1].role!=="StaticText"){Me.push(ie);continue}C.children[H-1].name+=ie.name}if(C.children=Me.reverse(),!C.isInteresting(p)&&r.parentId)return A&&(A.momenticIgnored=!0),C.children;for(let H of C.children)H.parent=C;return ML(C),A&&d&&rp(A,i),[C]}function Vb({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:s,iconKnowledgeBase:c,startId:l=1}){r.id=l,l+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:ap.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(s[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let p=tp(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)l=Vb({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:l,useMPaths:a,domGraph:i,selectorToNodeMap:s,iconKnowledgeBase:c});return l}async function $b({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:s,importantProperties:c,viewportDetails:l,useMPaths:u,frameContext:d,iconKnowledgeBase:p,allowedA11yIgnoreReasonsOverride:g}){let m=t??"root",h=r[m]?.root;if(!h)throw new Error("A11y tree has no root");let f=mL(),E=C=>{let w=C.allNodes.filter(D=>!D.ignoredReasons?.find(Y=>(g??zb).includes(Y.name))),F=new Map;return w.forEach(D=>{F.set(parseInt(D.nodeId),D)}),F},S={};Object.entries(r).forEach(([C,w])=>{S[C]=E(w)});let R=await jb({node:h,domGraph:e,parent:null,inputNodeMap:S,axGraph:r,frameId:m,frameContext:d,cdpClient:o,logger:n,callId:f,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:l,useMPaths:u,flagNotActionableNodes:s,allowedA11yIgnoreReasonsOverride:g});if(R.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(R)}`);if(R.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let A={},v={},P={};return Vb({node:R[0],a11yIdNodeMap:A,dataMomenticIdMap:v,selectorToNodeMap:P,domGraph:e,logger:n,callId:f,useMPaths:u,iconKnowledgeBase:p}),new ip(R[0],A,v,P)}function xL(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<Gb&&!Jt.bannedClassSubstrings.some(s=>a.includes(s))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(Wb(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 _L(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,s])=>{let c=r[a]||a.startsWith("aria")||fL.includes(a);if((Jt.relevantElementAttributes.includes(a)||qb(a,t))&&!c){let u=xL(a,s,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&Ub.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of Ub)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 s=a.split(":"),c=s[0]?.trim(),l=s[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&l!==void 0&&u!==void 0&&(l==="*"||u===l)){let d=e.computedStyles[c],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(r.style=o.join("; "))}function ML(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(l=>l.tagName==="tr");if(c){let l=c.children.filter(u=>u.tagName==="th");l.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(At(u.name,100,!1))}),i?.length!==l.length&&(i=void 0)}}let s=0;for(let c of r.children)if(c.tagName==="tbody")for(let l=0;l<c.children.length;l++){let u=c.children[l];if(u.tagName!=="tr")continue;if(l===0&&!i?.length){let g=u.children.filter(m=>m.tagName==="th");if(g.length){if(i=g.map(m=>At(m.name,100,!1)),i.length===g.length)continue;i=void 0}}s+=1,u.properties["row-index"]||(u.properties["row-index"]=s);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 PL(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function Wb(r,e){if(e&&Kb(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 qb(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 Kb(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 Sl=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(),s,c;for(let u=0;u<2;u++)try{s=await V(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new _("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await Q(Qe),c=d}if(!s)throw c;let l=new r(s,e,t,n,o);try{await V(l.registerHandlers(s),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw l.cdpFullyDead=!0,new _("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return l}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 V(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new _("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 V(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 V(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new _("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 V(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 V(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 Vo="<empty>";function IL(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 Xb(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||IL(r.url)}async function OL(r,e){let t=await r.send({timeout:Z,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:Z,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:Z,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function $o({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:Z,method:"Page.getFrameTree",params:{}}),r.send({timeout:Z,method:"DOM.getDocument",params:{depth:0}})]),l=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(Xb(d.frame))return null;try{return await Jb({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(l);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function Jb({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,s=await OL(r,a),c=s.attributes??[],l=null,u=[];for(let m of["src","name","id","title","srcdoc","sandbox"]){let h=hn(c,m);h&&(u.push(`${m}=${JSON.stringify(h)}`),m==="src"&&(l=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:l,childFrames:[],parent:n,domNode:s},g=(e.childFrames??[]).map(async(m,h)=>{if(Xb(m.frame))return null;try{return await Jb({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 LL(r){try{return await r.owner().count()===1}catch{return!1}}async function NL(r){try{return await r.count()===1}catch{return!1}}async function Rr(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 l of t){let u=!1;for(let d of[...l.locationData.attributeSelectors,Vo]){let p=o.frameLocator(d===Vo?"iframe":`iframe[${d}]`);if(await LL(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new _("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${l.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let l of[...r.locationData.attributeSelectors,Vo]){let u=o.locator(l===Vo?"iframe":`iframe[${l}]`);if(await NL(u)){a=u,i.push(l);break}}if(!a)throw new _("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 s=await a.evaluateHandle(l=>l,{timeout:ee}),c=await s.asElement().contentFrame();if(!c)throw new _("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await s.dispose(),{frame:c,mPathSelectorTokens:i}}function Yb(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 Zb({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let s=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===Vo?s=s.length===1?s[0].childFrames:[]:s=s.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],l=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(l===Vo?c=s:c=s.filter(u=>u.locationData.attributeSelectors.includes(l)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await Rr(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 s=new RegExp(t.frameSrcRegex),c=Yb(o,l=>!!l.src&&s.test(l.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await Rr(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 s=new RegExp(t.frameUrlRegex),c=Yb(o,l=>!!l.url&&s.test(l.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await Rr(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 s=0;s<t.indices.length-1;s++)a=a[t.indices[s]]?.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 Rr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new ln("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function yl(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function sp(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function Qb(r){let e=sp(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let s=a.shift();s.src&&o.push(s.src),s.url&&i.push(s.url),a.push(...s.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function eE(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 tE({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await kL({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 kL({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await Wn({promiseGenerator:async()=>r.evaluate(async i=>{let a=i.scrollTop;i.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(c=>setTimeout(c,250));let s=Date.now();for(;Date.now()-s<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(l=>setTimeout(l,250))}}),timeoutMs:ue,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}async function rE({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:s,properties:c}=r.target;if(s){i.error({error:s,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let l=n.parentFrame()?n.url():void 0,d=n.page().frames().map(m=>m.url());i.debug({frameUrl:l,...r},"Passive click event captured on element");let p,g;if(l)try{let m=await n.frameElement();p=await V(m?.boundingBox(),{milliseconds:Z})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:l});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:l}}(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 Cr}from"crypto";import DL from"js-beautify";var UL=["Dead"],bl=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:(s,c)=>{this.recordedSteps.set(c,{step:s}),t.onStepRecorded(s,c)},onActionReceived:(s,c)=>{this.recordedSteps.set(c,{step:s}),t.onActionReceived?.(s,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:Cr(),type:"PRESET_ACTION",command:kr(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,s=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=s,l;switch(e.frameConfig?e.frameBoundingBox?l={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"):l=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let h=kr(i);a={id:Cr(),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:l}}}};break}case"SELECT":{i="SELECT_OPTION";let h=kr(i);a={id:Cr(),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:l}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=kr(i);a={id:Cr(),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:ye(this.logger),boundingBox:l}}}};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=DL.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=Ky(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,...ye(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=s}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(UL.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=kr("TYPE");i={id:Cr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=kr("PRESS");i={id:Cr(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,s=this.nextStepOffset-1,c=this.recordedSteps.get(s),l=c?.step,u=l?.command;if(n){if(u?.type===i.command.type){let d=u.value,p=i.command.value;i={id:Cr(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},a=s}else if(u?.type==="CLICK"&&i.command.type==="TYPE")l.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=s;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:Cr(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=s}}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,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_DOWN"&&s.deltaY?(i+=s.deltaY,c=a):s?.type==="SCROLL_UP"&&s.deltaY?(i-=s.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_DOWN":"SCROLL_UP",u=kr(l);u.deltaY=Math.abs(i);let d={id:Cr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_RIGHT"&&s.deltaX?(i+=s.deltaX,c=a):s?.type==="SCROLL_LEFT"&&s.deltaX?(i-=s.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=kr(l);u.deltaX=Math.abs(i);let d={id:Cr(),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 lp}from"zod";var poe=lp.object({type:lp.literal("url"),url:lp.string()});var El=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;allowedA11yIgnoreReasonsOverride;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:s,enricher:c,iconKnowledgeBase:l,userBrowserSettings:u,allowedA11yIgnoreReasonsOverride:d}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=s,this.enricher=c,this.iconKnowledgeBase=l,this.userBrowserSettings=u,this.allowedA11yIgnoreReasonsOverride=d,this.userBrowserSettings.importantStyles)for(let p of this.userBrowserSettings.importantStyles){let g=p.split(":");if(g.length!==2){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}let m=g[0]?.trim(),h=g[1]?.trim();if(m===void 0||h===void 0){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(m)||this.computedStylesToFetch.push(m)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userBrowserSettings.autoExpandIframes)return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),n=sp(e),{frame:o,mPathSelectorTokens:i}=await Rr(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 $o({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await Zb({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(yl(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:yl(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await tE({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await $o({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[V(n.evaluate(e,t),{milliseconds:ue})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),l=c.url;l==="about:blank"||l.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(Rr(c,n).then(({frame:u})=>V(u.evaluate(e,t),{milliseconds:ue})).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 $o({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,s,c=null;if(this.frameConfig?.type==="url"){if(a=await Zt({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new _("ActionFailureError","Got null frame details despite active frame config");s=a.handle,c=s.frameId}else this.userBrowserSettings.autoExpandIframes?(s=await Zt({fn:()=>$o({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(s={type:"root",page:i,childFrames:[]},c=null);await Zt({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:s.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let l=await Zt({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await Zt({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:s.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await Zt({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:l,startingFrameId:c,frameContext:s,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=l,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:Hn,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=Nb({node:o,domGraph:this.domGraph});return kb(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:ue});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await Db(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(pr(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,s,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await $o({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(l){if(s=l,l instanceof _&&l.reason==="UserInfrastructureError")throw l;c%3===0&&this.logger.warn({attempt:c,err:l},"Failed to resolve active frame, retrying..."),await Q(Qe,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:yl(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw s}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let s=i.shift(),c=s.domNode;i.push(...s.childFrames);let l=hn(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!l&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[l,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:s,matchType:"regex",...await Rr(s,o)});break}}else if(n.trim()===d.trim()){a.push({handle:s,matchType:"url",...await Rr(s,o)});break}}}if(a.length===1){let s=a[0];return this.userBrowserSettings.autoExpandIframes||(s.handle.childFrames=[]),s}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new _("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:s,showZeroOpacityElements:c,flagNotActionableNodes:l}){let u=await $b({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:l,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userBrowserSettings.importantAttributes,classes:this.userBrowserSettings.importantClasses,styles:this.userBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:s,useMPaths:this.userBrowserSettings.visualActions,allowedA11yIgnoreReasonsOverride:this.allowedA11yIgnoreReasonsOverride});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),s=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let l=async()=>{try{let{frame:u}=await Rr(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...")}};s.push(l())}await Promise.all(s)}async addMomenticIdsHelper(e,t){if(this.userBrowserSettings.visualActions)return t;let n=this.logger;return await qe({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:ue,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(hn(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=hn(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:Z,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:Z,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:Z,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 s=[];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,l;for(let g=0;g<3;g++)try{l=await Zt({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,logger:i});break}catch(m){c=m,i.warn({err:m},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!l)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=l,!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:s});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;s.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 Zt({fn:()=>this.getRawA11yTreeForFrame({frameId:g.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${g.frameId}`,logObject:o,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),s.length>0&&this.logger.warn({warnings:s},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await Zt({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,logger:this.logger})).nodes;else{let a=(await Zt({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:ue}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;o=(await Zt({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,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:Z}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await Q(Qe,t),i++,a=s}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new _("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 Lb({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=Qb(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 cp(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var ca=class r{static USER_AGENT=dl;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,enricher:t,browser:n,context:o,page:i,baseUrl:a,logger:s,userBrowserSettings:c,viewport:l,properties:u,clientCallbacks:d,iconKnowledgeBase:p}){if(US(c),this.storage=e,this.enricher=t,this.browser=n,this.context=o,this.page=i,this.baseUrl=a,this.logger=s,this.userControlledBrowserSettings=c,this.viewport=l,this.properties=u,this.clientCallbacks=d,u.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={[ul]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:$y.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'); });`})],i=a=>this.handleNewPageEvent(a);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)}),await Promise.all(o),t&&await this.page.reload(),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&VL()==="darwin"&&FL("system_profiler SPDisplaysDataType").toString().includes("Retina")?(x.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 Sl.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new El({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,allowedA11yIgnoreReasonsOverride:this.properties.allowedA11yIgnoreReasonsOverride}),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(e){let t=await Tb(e),n=new r(t);return await n.initialize({grantPermissions:!0,runInitScripts:!1}),n}static async fromExistingContext({context:e,storage:t,enricher:n,userBrowserSettings:o,properties:i,logger:a}){let s=e.pages()[0];if(!s)throw new Error("No page found in existing context");let c=s.viewportSize();c||(c=await s.evaluate(()=>({width:window.innerWidth,height:window.innerHeight})));let l=s?.url(),u=new r({browser:e.browser(),context:e,page:s,baseUrl:l,logger:a,storage:t,enricher:n,userBrowserSettings:o,viewport:c,properties:i,clientCallbacks:void 0,iconKnowledgeBase:null});return await u.initialize({grantPermissions:!1,runInitScripts:!0}),u}async handleAvailableTabsChangeHelper(){try{let e=await ep(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=up(),o=`${e}-${n}`,i=Date.now(),a=!1,s=async()=>{try{await V(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]=s().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()||!qn(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=up(),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=>{sb(e,o,this.debugData,a,this.logger)});let i=async()=>{await ub(t,this.debugData,e),await e.route("**/*",async(a,s)=>{await jd({pageId:t,route:a,request:s,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",hb(this.customHeaders,this.logger)),dn&&await e.route("**/*",sa),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){}handleFrameNavigationEvent(e){let t=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${t.slice(0,50)} (${n})`;if(!t||t==="about:blank"||!qn(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}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(s){this.logger.warn({err:s},"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 V(Jd(this.getBrowserCallbacks()),{milliseconds:ee})}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<xd;){a++,n?.throwIfAborted();try{if(await qe({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:ee,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(s){if(i++,i>=3){t.warn({err:s},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await Q(Qe),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),qe({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:Z,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(Go),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 s=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:o??ue}),c=Buffer.from(s.data,"base64"),l=await oE.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(l.bitmap.width!==u||l.bitmap.height!==d)&&(c=await l.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&HL(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:Z});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 oE.fromBuffer(c),S=E.bitmap.width,R=E.bitmap.height;g=Math.max(0,Math.min(g,S-1)),m=Math.max(0,Math.min(m,R-1)),h=Math.max(1,Math.min(h,S-g)),f=Math.max(1,Math.min(f,R-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(){if(this.viewport)return this.viewport;let e=this.page.viewportSize();return e||null}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){jy(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(l){if(a=l,this.abortSignal?.throwIfAborted(),this.logger.warn({err:l},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await Q(Qe),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:ee})}if(!i)throw new _("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 s=this.url();if(eb.has(s))throw new _("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 qe({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:ee,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 Rb({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(Go),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??Yg}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:ue})}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(s=>setTimeout(s,250))}},void 0,{timeout:ue})}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 hl({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:ee}),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 ab(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:ee});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:ee,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(s){this.logger.warn({err:s,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 ib(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 ob(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 _("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return ep(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,startingBoundingBox:o,allowNotActionableNodesOverride:i,logger:a=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let s=await this.fetchHtmlAttributes({locator:n,logger:a,startingBoundingBox:o,allowNotActionableNodesOverride:i});s?(t.generatedSelectors=s.generatedSelectors,t.serializedHtml=s.serializedHtml,t.nodeOnlySerializedHtml=s.nodeOnlySerializedHtml,t.hybridSelector=s.hybridSelector):a.warn("Got undefined HTML attributes when trying to update cache")}catch(s){if(s instanceof Er)throw a.warn({err:s},"Cache attributes disqualify found element"),s;a.warn({err:s},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:a,boundingBox:o})}catch(s){a.debug({err:s},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!Id.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:Z})),!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:s=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-s)<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 l=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(l),{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:Z});if(!o||!o.width||!o.height)throw new _("ActionFailureError","Element does not have a bounding box as required");n.boundingBox=o??void 0}if(t?.text){let o=await e.innerText({timeout:Z});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 s=await e.getAttribute(a,{timeout:Z});s!==null&&(o[i]=s)}catch(s){this.logger.warn({err:s,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 s=await this.fetchHtmlAttributes({locator:a,logger:o});if(!s?.generatedSelectors||s.generatedSelectors.length===0)return;let c={selectors:s.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,s=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let l=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!l)continue;s.push(l)}catch(l){this.logger.warn({err:l,additionalElement:c},"Failed to fetch additional element details, continuing...")}return s}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:s}){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:s}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:s}){if(e<0)throw new _("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new _("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let l=this.stateManager.frameConfig,u,d,p,g;if(this.userBrowserSettings.autoExpandIframes&&!l&&c.parentFrame){let S=c.parentFrame,{cache:R,config:A}=await this.stateManager.getAutoFrameDetailsFromHandle(S);d=R,p=A,u=A.frame,g="auto iframe"}else c.parentFrame&&l?(p=l,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:ye(i),frameCache:d},f,E=!1;o||(p&&(i.info({frameConfigSource:g,frameConfig:eE(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,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:s,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:s}=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 Q(Qe,a)}if(!m)throw g}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let l=Date.now(),u=0,d=0,p;for(;Date.now()-l<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let g=u===2||Date.now()-l>this.smartWaitingTimeout-2e3&&u%2===0;try{p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,logger:g?i:Hn,allowNotActionableNodesOverride:s,signal:a});break}catch(m){if(m instanceof ea)break;if(m instanceof Er){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 Q(Qe,a)}a?.throwIfAborted(),g&&i.info({err:m},`Could not resolve target using primary cache only (x${u})`),await Q(Qe,a)}}return p||(p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:s}),t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=ye(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 s=Wo(t),c=[],l=(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 ln&&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:Wo(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:l,target:t,decisions:c,logger:o,signal:i,allowNotActionableNodesOverride:a});if(d)return d}throw new ln(`Could not find any relevant node given target: ${JSON.stringify(s)}`,c)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o}){if(!t.nodeOnlySerializedHtml)throw new ea("Insufficient data to resolve target using primary methods (missing node HTML)");let i=this.userControlledBrowserSettings.hybridSelectorMode,a={ldistThreshold:Pd,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements},{css:s,hybrid:c}=await qe({fn:E=>window.evaluatePrimaryCaches(E),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:Z,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),l,u,d=[];if(i==="prefer"&&c?.result){l=c.result;let E={type:"HYBRID_SELECTOR",matched:!0,logs:c.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};d.push(E),u="HYBRID_SELECTOR"}else if(s?.result){l=s.result;let E=`${l.workingSelectors.length} CSS selectors matched the following element: ${l.serializedElement}`,S=l.workingSelectors.slice(0,5);d.push({type:"CSS_SELECTOR",matched:!0,logs:s.logs,reason:E,selectors:S}),n.debug({reason:E,workingSelectors:S},"Resolved with CSS selectors"),u="CSS_SELECTOR"}else throw d.push({type:"CSS_SELECTOR",matched:!1,reason:s.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:s.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 ln("Cache evaluation failed",d);let p,g,m;if(this.userBrowserSettings.visualActions){let E=l.mPath;if(!E)throw new Error("Found element did not have an mPath despite using visual actions");let S=E.join(" > ");p=e.locator(S),g=this.stateManager.getNodeUsingMPathSelector(S)}else if(l.dataMomenticId!==void 0)m=parseInt(l.dataMomenticId),g=this.stateManager.dataMomenticIdToNodeMap[m],"workingSelectors"in l?p=e.locator(l.workingSelectors[0]):p=e.locator(pr(m));else throw new _("InternalWebAgentError","Received an element resolution result with no identifying attributes");i&&t.hybridSelector&&(c?.logs.length===1?n.warn({hybridResult:c,cssResult:s,hybridMode:i},"Hybrid selector resolution rejected, continuing..."):c?.result?s?.result&&c?.result&&c.result.serializedElement!==s.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(s.result.mPath)!==JSON.stringify(c.result.mPath)?n.warn({originalCache:t,hybridResult:c,cssResult:s,hybridMode:i,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):s.result.dataMomenticId!==c.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:c,cssResult:s,hybridMode:i,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):n.warn({originalCache:t,hybridResult:c,cssResult:s,hybridMode:i},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let h=Wo(t);await this.updateCacheWithNewNodeDetails({node:g,target:t,locator:p,logger:n,startingBoundingBox:l.boundingBox,allowNotActionableNodesOverride:o});let f=dp(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ye(n),t.cacheResolutionUpdateSource=u,n.debug({diffs:f},"Updated cache")),{a11yNode:g,displayString:l.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,s=await this.getActivePageOrFrame(),c=Date.now(),l=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),l++;let p=s.locator(n),g;try{return await p.waitFor({state:"attached",timeout:ee}),g=await Br(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 _("ActionFailureError",`CSS selector '${n}' failed to resolve after ${l} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await Q(Qe,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 s=await a.locator.boundingBox({timeout:Z});if(!s){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:l,width:u,height:d}=s;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||!l){this.logger.debug({oldX:t,oldY:n,newX:c,newY:l,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-t)>100||Math.abs(l-n)>100){this.logger.debug({newX:c,newY:l,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<Zy){let l="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:l})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let l=await qe({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:ue,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(Pd*t.nodeOnlySerializedHtml.length);if(l&&l.closestDistance&&l.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${l.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:l.closestDistance,closestElement:l.closestNodeSerialized})}else{if(l?.error)throw new Error(l.error);if(l?.dataMomenticId||l?.mPathSelector){let d=l.dataMomenticId?parseInt(l.dataMomenticId):void 0,p,g;if(d)p=this.stateManager.dataMomenticIdToNodeMap[d],g=e.locator(pr(d));else if(l.mPathSelector)p=this.stateManager.getNodeUsingMPathSelector(l.mPathSelector),g=e.locator(l.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let m=l.closestNodeSerialized??await Br(g,o)??"unknown element";o.warn({result:l,originalTarget:t,displayString:m},"Resolved cached target to new node with pure html levenshtein distance");let h=Wo(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:g,logger:o,startingBoundingBox:l.boundingBox,allowNotActionableNodesOverride:a});let f=dp(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ye(o),t.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:l},"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:l.logs,distance:l.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(l)}`)}}catch(l){o.info({err:l},"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: ${l}`})}let s=t.screenshotUrl,c=t.role??"";if(s&&Id.includes(c))try{let l=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:s,signal:i,allowNotActionableNodesOverride:a});return{...l,decisions:[...n,...l.decisions],pageState:void 0}}catch(l){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${l}`,elementImageUrl:s}),o.warn({err:l},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({screenshotUrl:e,oldTarget:t,signal:n,allowNotActionableNodesOverride:o}){let i;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let a=await this.screenshot({retries:0}),c=await(await fetch(e)).arrayBuffer(),l=KL(),u=await this.enricher.runTemplateMatching({id:l,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:a.toString("base64")},{signal:n}),{target:d,locator:p}=await this.getTargetFromPositionPercentages({percentX:u.x,percentY:u.y,allowNotActionableNodesOverride:o}),g=d.boundingBox?.width,m=d.boundingBox?.height;if(!g||!m)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let h=d.id,f=this.stateManager.a11yIdToNodeMap[h],E=Wo(t);await this.updateCacheWithNewNodeDetails({target:t,node:f,locator:p,allowNotActionableNodesOverride:o});let S=dp(E,t);return S&&Object.keys(S).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ye(this.logger),t.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:l,diffs:S,templateMatch:u},"Updated cache after template matching resolution")),{locator:p,a11yNode:f,displayString:d.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:e}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:ee})??"",i=wb.some(a=>a===o.toLowerCase());return await Zd({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 Zd({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,s=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),s=this.url(),sl(s,t,n)){a=!0;break}await Q(Qe,this.abortSignal)}if(!a)throw new _("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${sy(t)} in ${o}ms.
|
|
3951
|
-
Current tab: ${s}`);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:Z});if(!o)throw new _("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,s=n.steps??5;await this.page.mouse.move(i,a,{steps:s}),await Q(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,ue):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(Gd);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(Go),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await Yn({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:Z});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 Yn({func:t=>t.locator.focus({timeout:ue}),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 qe({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:ee,codePath:"blurring the active element"});return}await this.highlight(e.locator),await Yn({func:t=>t.locator.blur({timeout:ue}),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 Yn({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 _("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:Z})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=fl(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=fl(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of cp(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=fl(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of cp(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,s=!i,c=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:a});let l=0,u;for(;l<t;){l++;try{return await V(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:a,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:c,flagNotActionableNodes:s}),{milliseconds:this.pageLoadTimeout*l,signal:a,message:"Getting browser state took too long"})}catch(d){if(a?.throwIfAborted(),u=d instanceof Error?d.message:`${d}`,l>=t)throw d;n.warn({err:d,url:this.url()},"Error getting a11y tree, retrying...")}}throw new _("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${u}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await qe({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:Z,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()},s=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",s);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let l=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",l);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",s),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",l),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),s,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},l=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await Q(Go,this.abortSignal),s)try{let d=await this.screenshot(c);if(!d.equals(s)){s=d,l=!1;continue}l=!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{s=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<Jy)){i=!0;break}}i||t.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:l}},"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,Md):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(Gd);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(Go),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:Z}),n=await V(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:ue});process.platform==="darwin"&&n===1&&(n=Yy);let o=t.documents[0],i=o.layout,a=o.nodes,s=a.nodeName||[],c=a.backendNodeId||[],l=i.nodeIndex,u=i.bounds,d=-1;for(let S=0;S<s.length;S++)if(c[S]===e){d=l.indexOf(S);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 Qd({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 Qd({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 Q(Qe)}}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 _("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)}.
|
|
3952
|
-
Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!qn(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=_s(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 s of Object.values(this.stateManager.a11yIdToNodeMap))if(s.role==="image"&&s.name.toLowerCase().includes("captcha")){if(!s.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,s.backendNodeId);break}if(!e){let s=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!s.captchas||!s.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:Z}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:jo,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let s=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},s),new Error(s)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<Qy;){await Q(2500);let s=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:jo,taskId:o})});if(!s.ok){let l=`Captcha solution API returned error response: ${s.statusText}`;throw this.logger.error({text:await s.text()},l),new Error(l)}let c=await s.json();if(c.errorId){let l=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(l),new Error(l)}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&&rE({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(c=>c.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let c;try{c=(await this.getOpenPages()).map(u=>u.url),o=0}catch(u){this.logger.debug({err:u},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let l=this.url();for(let u=c.length-1;u>=n.length;u--){let d=c[u];qn(d,this.logger)&&d!==l&&this.logger.info({lastActivePages:n,currentUrl:l,newOpenPages:c},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(u)});break}n=c};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(c){this.logger.error({err:c},"Error while checking pages during recording")}finally{i=!1}}},Qe);let s=async()=>{clearInterval(t)};e.addEventListener("abort",s,{once:!0})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(i=>{let a=window;a._MOMENTIC_RECORDING_ACTIVE=!0,a._MOMENTIC_CLICK_RECORD_ACTIVE=i},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page);let o=async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!1,i._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}};e.addEventListener("abort",o,{once:!0})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:ee})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await Wn({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let s=a;if(s.name==="AbortError")throw new _("UserInfrastructureError",`The page with URL ${At(i,50)} did not load within the configured timeout (${o}ms): ${s}`);if(!s.message.includes("detached"))throw s}try{await Wn({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlPageLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){this.logger.warn({err:a,codePath:n,url:i},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return GL.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 qe({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:ue,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new _("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=ue){let i=await this.getActivePageOrFrame();return qe({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=sn}){let i=gb(),a={code:e,fragment:t,context:n},{result:s}=await V(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new _("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return s}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:ue});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:ee})}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 _("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:s}=await this.getViewportOffsetDetails(e),c=Math.round(a),l=Math.round(s),u=Math.ceil(o*t),d=Math.ceil(i*n),p=u+l,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:ee,params:{highlightConfig:Ob,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:ee,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:ee})}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[Fr],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let s=e.locator(pr(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 l=await this.fetchHtmlAttributes({locator:s,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...l};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:s}}async performTargetRedirection(e,t,n){try{return await this.scrollIntoViewIfNeeded(e),await V(this.performTargetRedirectionHelper(e,t,n),{milliseconds:Z})??{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 Br(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:Z})??void 0),!n){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:a,y:s,width:c,height:l}=n,u=this.getViewport();if(a<0||s<0||!u||a+c>u.width||s+l>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:S}=await e.evaluate(A=>{let v=window;if(!v.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return v.performTargetRedirection(A)},void 0,{timeout:ee}),R=Date.now()-o;if(m){t.warn({error:m,serializedElement:h,duration:R,force:E,logs:S},"Got error from target redirection with bounding box");return}else{if(p)return t.info({newDataMomenticId:p,serializedElement:h,duration:R,force:E,logs:S},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(pr(p)),hints:{clickableXY:f,force:E}};if(g)return t.info({newMPathSelector:g,serializedElement:h,duration:R,force:E,logs:S},"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:R,force:E,logs:S},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:E}};if(E)return t.info({serializedElement:h,duration:R,force:E,logs:S},"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,s=await e.evaluate((c,l)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,l):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:ue});if("error"in s&&s.error)throw s.error.startsWith(Wy)?new Bs(s.error):s.error.startsWith(qy)?new zs(s.error):new Error(s.error);return s.warnings.length&&t.warn(s,"Got warnings while generating HTML attributes for target"),s.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:ee})}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),s=Math.ceil(i.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:s,x:n,y:o}}),{deltaX:a,deltaY:s}}canSolveCaptchas(){return!!jo}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(!Tl(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()||$L(e),o=BL(e),i=WL(e),a=od[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!Tl(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:jL.getType(e)||"application/octet-stream"},{timeout:Md})}catch(l){this.logger.error({err:l},"Error handling file chooser"),this.logToUserConsole(this.page,"error",l.message)}});let s=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:l,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=l;let p=atob(l),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:s,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??up();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??Xy}get userBrowserSettings(){return Wo(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??xd}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=gl();for(let t of e)if(!(!Tl(t)||!nE(t).isDirectory()||!["new","pending","completed"].some(o=>{let i=qL(t,o);return Tl(i)&&nE(i).isDirectory()&&zL(i).length>0})))return t}};import kD from"fetch-cookie";import{cloneDeep as PA}from"lodash-es";var vl=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function YL(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 Al(r,e){let t=YL(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var OE="=",xl=";",Ap=",";var LE=8192;var Xo={};uC(Xo,{getKeyPairs:()=>_N,parseKeyPairsIntoRecord:()=>MN,parsePairKeyValue:()=>NE,serializeKeyPairs:()=>xN});ve();var CN=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function xN(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Ap:"")+t;return n.length>LE?e:n},"")}function _N(r){return r.getAllEntries().map(function(e){var t=CN(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=xl+o.metadata.toString()),i})}function NE(r){var e=r.split(xl);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(OE);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=mp(e.join(xl))),{key:o,value:i,metadata:a}}}}}function MN(r){return typeof r!="string"||r.length===0?{}:r.split(Ap).map(function(e){return NE(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}ve();var _l;(function(r){r.AlwaysOff="always_off",r.AlwaysOn="always_on",r.ParentBasedAlwaysOff="parentbased_always_off",r.ParentBasedAlwaysOn="parentbased_always_on",r.ParentBasedTraceIdRatio="parentbased_traceidratio",r.TraceIdRatio="traceidratio"})(_l||(_l={}));var PN=",",IN=["OTEL_SDK_DISABLED"];function ON(r){return IN.indexOf(r)>-1}var LN=["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 NN(r){return LN.indexOf(r)>-1}var kN=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function DN(r){return kN.indexOf(r)>-1}var wp=1/0,Rp=128,UN=128,FN=128,Cp={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:Pe.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:wp,OTEL_ATTRIBUTE_COUNT_LIMIT:Rp,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:wp,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Rp,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:wp,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Rp,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:UN,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:FN,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:_l.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative"};function BN(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function zN(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 HN(r,e,t,n){n===void 0&&(n=PN);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var GN={ALL:Pe.ALL,VERBOSE:Pe.VERBOSE,DEBUG:Pe.DEBUG,INFO:Pe.INFO,WARN:Pe.WARN,ERROR:Pe.ERROR,NONE:Pe.NONE};function jN(r,e,t){var n=t[r];if(typeof n=="string"){var o=GN[n.toUpperCase()];o!=null&&(e[r]=o)}}function kE(r){var e={};for(var t in Cp){var n=t;switch(n){case"OTEL_LOG_LEVEL":jN(n,e,r);break;default:if(ON(n))BN(n,e,r);else if(NN(n))zN(n,e,r);else if(DN(n))HN(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function ct(){var r=kE(process.env);return Object.assign({},Cp,r)}function DE(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Ml(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=DE(r.charCodeAt(n)),i=DE(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var UE="1.25.1";var VN="deployment.environment";var $N="process.runtime.name";var WN="service.name";var qN="service.instance.id";var KN="telemetry.sdk.name",YN="telemetry.sdk.language",XN="telemetry.sdk.version";var FE=VN;var BE=$N;var Pl=WN;var zE=qN;var fa=KN,Sa=YN,ya=XN;var JN="nodejs";var HE=JN;var Jo,Il=(Jo={},Jo[fa]="opentelemetry",Jo[BE]="node",Jo[Sa]=HE,Jo[ya]=UE,Jo);var ZN=9,QN=6,e0=Math.pow(10,QN),t0=Math.pow(10,ZN);function GE(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*e0);return[t,n]}function jE(r){return r[0]*t0+r[1]}function ba(r){return r[0]*1e6+r[1]/1e3}var Zn;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Zn||(Zn={}));var VE=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 r0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},n0=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))},$E=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new VE}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,n0([this._that],r0(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 Qt;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Qt||(Qt={}));var ft;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(ft||(ft={}));var o0=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 ule=function(r){o0(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function WE(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}ve();var er;(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"})(er||(er={}));var qE=function(){function r(){this.kind=er.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();var oe;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(oe||(oe={}));var i0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function a0(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 xp=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=a0(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=WE(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 _p=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=er.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new xp(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new xp(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new xp(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ft.HISTOGRAM,dataPoints:n.map(function(i){var a=i0(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();ve();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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Pp=function(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))},Ip=function(){function r(e,t,n,o){e===void 0&&(e=new s0),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var s0=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,Pp([n,this._counts.length-t],Mp(this._counts.slice(t)),!1)),o.splice.apply(o,Pp([0,t],Mp(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(Pp([],Mp(this._counts),!1))},r}();var KE=52,l0=2146435072,c0=1048575,Op=1023,Ol=-Op+1,Ll=Op,Ea=Math.pow(2,-1022);function Nl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&l0)>>20;return n-Op}function kl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&c0)*Math.pow(2,32);return o+n}function Ta(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function XE(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var u0=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),fn=function(r){u0(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var ZE=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ea)return this._minNormalLowerBoundaryIndex();var t=Nl(e),n=this._rightShift(kl(e)-1,KE);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new fn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new fn("overflow: "+e+" is > maximum lower boundary: "+n);return Ta(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=Ol>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Ll>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var QE=function(){function r(e){this._scale=e,this._scaleFactor=Ta(Math.LOG2E,e),this._inverseFactor=Ta(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ea)return this._minNormalLowerBoundaryIndex()-1;if(kl(e)===0){var t=Nl(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 fn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ea;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new fn("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 Ol<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Ll+1<<this._scale)-1},r}();var eT=-10,tT=20,d0=Array.from({length:31},function(r,e){return e>10?new QE(e-10):new ZE(e-10)});function Lp(r){if(r>tT||r<eT)throw new fn("expected scale >= "+eT+" && <= "+tT+", got: "+r);return d0[r+10]}var p0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Dl=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}(),m0=20,g0=160,Np=2,h0=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=g0),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new Ip),u===void 0&&(u=new Ip),d===void 0&&(d=Lp(m0)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<Np&&(j.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Np),this._maxSize=Np)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=XE(t);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Lp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Dl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Dl.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 Dl(0,-1);var o=t-n;return new Dl(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},r}();var rT=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=er.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new h0(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:ft.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=p0(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();var f0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},kp=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=GE(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var nT=function(){function r(){this.kind=er.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new kp(e)},r.prototype.merge=function(e,t){var n=ba(t.sampleTime)>=ba(e.sampleTime)?t:e;return new kp(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ba(t.sampleTime)>=ba(e.sampleTime)?t:e;return new kp(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ft.GAUGE,dataPoints:n.map(function(i){var a=f0(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var S0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},va=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 Dp=function(){function r(e){this.monotonic=e,this.kind=er.SUM}return r.prototype.createAccumulation=function(e){return new va(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new va(t.startTime,this.monotonic,o,t.reset):new va(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 va(t.startTime,this.monotonic,o,!0):new va(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:ft.SUM,dataPoints:n.map(function(i){var a=S0(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var Qn=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)}}(),_r=function(){function r(){}return r.Drop=function(){return dT},r.Sum=function(){return pT},r.LastValue=function(){return mT},r.Histogram=function(){return gT},r.ExponentialHistogram=function(){return y0},r.Default=function(){return b0},r}();var oT=function(r){Qn(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 qE,e}(_r);var iT=function(r){Qn(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 Dp(!0),e.NON_MONOTONIC_INSTANCE=new Dp(!1),e}(_r);var aT=function(r){Qn(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 nT,e}(_r);var sT=function(r){Qn(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 _p([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(_r);var lT=function(r){Qn(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(s,c){return s-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new _p(this._boundaries,this._recordMinMax)},e}(_r);var cT=function(r){Qn(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 rT(this._maxSize,this._recordMinMax)},e}(_r);var uT=function(r){Qn(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 pT;case oe.GAUGE:case oe.OBSERVABLE_GAUGE:return mT;case oe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new lT(t.advice.explicitBucketBoundaries):gT}return j.warn("Unable to recognize instrument type: "+t.type),dT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(_r);var dT=new oT,pT=new iT,mT=new aT,gT=new sT,y0=new cT,b0=new uT;ve();function Ul(){return"unknown_service:"+process.argv0}var Sn=function(){return Sn=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},Sn.apply(this,arguments)},E0=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},T0=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},v0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Up=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 j.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[Pl]=Ul(),e[Sa]=Il[Sa],e[fa]=Il[fa],e[ya]=Il[ya],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&j.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 E0(this,void 0,void 0,function(){return T0(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=Sn(Sn({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=v0(a,2),l=c[0],u=c[1];return Sn(Sn(Sn(Sn({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var eo;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(eo||(eo={}));ve();var A0=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},w0=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},Fp=function(){return Qt.CUMULATIVE},hT=function(r){switch(r){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.GAUGE:case oe.HISTOGRAM:case oe.OBSERVABLE_GAUGE:return Qt.DELTA;case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return Qt.CUMULATIVE}},fT=function(r){switch(r){case oe.COUNTER:case oe.HISTOGRAM:return Qt.DELTA;case oe.GAUGE:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_GAUGE:return Qt.CUMULATIVE}};function R0(){var r=ct(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Fp:e==="delta"?hT:e==="lowmemory"?fT:(j.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."),Fp)}function C0(r){return r!=null?r===eo.DELTA?hT:r===eo.LOWMEMORY?fT:Fp:R0()}function x0(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return _r.Default()}}var ST=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=x0(t),this._aggregationTemporalitySelector=C0(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return A0(this,void 0,void 0,function(){return w0(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}();ve();ve();var _0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},yT=1e4,bT=5,ET=1e3,TT=5e3,vT=1.5;function Aa(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=_0(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):j.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function Bp(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function zp(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return j.warn("Could not parse export URL: '"+r+"'"),r}}function Hp(r){return typeof r=="number"?r<=0?Gp(r,yT):r:M0()}function M0(){var r,e=Number((r=ct().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:ct().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Gp(e,yT):e}function Gp(r,e){return j.warn("Timeout must be greater than 0",r),e}function AT(r){var e=[429,502,503,504];return e.includes(r)}function wT(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 RT=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 $E(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=Hp(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:Zn.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:Zn.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:Zn.SUCCESS})}).catch(function(n){t({code:Zn.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{j.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 j.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();ve();import*as jp from"url";import*as Bl from"http";import*as zl from"https";import*as CT from"zlib";import{Readable as I0}from"stream";var yn;(function(r){r.NONE="none",r.GZIP="gzip"})(yn||(yn={}));var P0=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)}}(),Zo=function(r){P0(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 Fl=function(){return Fl=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},Fl.apply(this,arguments)};function Vp(r,e,t,n,o){var i=r.timeoutMillis,a=new jp.URL(r.url),s=Number(process.versions.node.split(".")[0]),c,l,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,l.destroyed){var h=new Zo("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:Fl({"Content-Type":t},r.headers),agent:r.agent},g=a.protocol==="http:"?Bl.request:zl.request,m=function(h,f){switch(h===void 0&&(h=bT),f===void 0&&(f=ET),l=g(p,function(S){var R="";S.on("data",function(A){return R+=A}),S.on("aborted",function(){if(u){var A=new Zo("Request Timeout");o(A)}}),S.on("end",function(){if(u===!1)if(S.statusCode&&S.statusCode<299)j.debug("statusCode: "+S.statusCode,R),n(),clearTimeout(d),clearTimeout(c);else if(S.statusCode&&AT(S.statusCode)&&h>0){var A=void 0;f=vT*f,S.headers["retry-after"]?A=wT(S.headers["retry-after"]):A=Math.round(Math.random()*(TT-f)+f),c=setTimeout(function(){m(h-1,f)},A)}else{var v=new Zo(S.statusMessage,S.statusCode,R);o(v),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(S){if(u){var R=new Zo("Request Timeout",S.code);o(R)}else o(S);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var S=new Zo("Request Timeout");o(S)}clearTimeout(d),clearTimeout(c)}),r.compression){case yn.GZIP:{l.setHeader("Content-Encoding","gzip");var E=O0(e);E.on("error",o).pipe(CT.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};m()}function O0(r){var e=new I0;return e.push(r),e.push(null),e}function $p(r){if(r.httpAgentOptions&&r.keepAlive===!1){j.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new jp.URL(r.url),t=e.protocol==="http:"?Bl.Agent:zl.Agent;return new t(Fl({keepAlive:!0},r.httpAgentOptions))}catch(n){j.error("collector exporter failed to create http agent. err: "+n.message);return}}function Wp(r){if(r)return r;var e=ct().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||ct().OTEL_EXPORTER_OTLP_COMPRESSION;return e===yn.GZIP?yn.GZIP:yn.NONE}ve();var L0=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)}}(),Hl=function(r){L0(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&&j.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Aa(t.headers),Xo.parseKeyPairsIntoRecord(ct().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=$p(t),i.compression=Wp(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){j.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;Vp(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,l)}).then(n,o);this._sendingPromises.push(a);var s=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(s,s)},e.prototype.onShutdown=function(){},e}(RT);function _T(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function N0(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function MT(r){var e=_T(r);return N0(e)}function k0(r){var e=_T(r);return e.toString()}var D0=typeof BigInt<"u"?k0:jE;function xT(r){return r}function PT(r){if(r!==void 0)return Ml(r)}var U0={encodeHrTime:MT,encodeSpanContext:Ml,encodeOptionalSpanContext:PT};function IT(r){var e,t;if(r===void 0)return U0;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?MT:D0,encodeSpanContext:o?xT:Ml,encodeOptionalSpanContext:o?xT:PT}}var F0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function OT(r){return{name:r.name,version:r.version}}function Qo(r){return Object.keys(r).map(function(e){return LT(e,r[e])})}function LT(r,e){return{key:r,value:NT(e)}}function NT(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(NT)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=F0(t,2),o=n[0],i=n[1];return LT(o,i)})}}:{}}function kT(r){return{attributes:Qo(r.attributes),droppedAttributesCount:0}}ve();function UT(r,e){var t=IT(e);return{resource:kT(r.resource),schemaUrl:void 0,scopeMetrics:B0(r.scopeMetrics,t)}}function B0(r,e){return Array.from(r.map(function(t){return{scope:OT(t.scope),metrics:t.metrics.map(function(n){return z0(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function z0(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=V0(r.aggregationTemporality);switch(r.dataPointType){case ft.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:DT(r,e)};break;case ft.GAUGE:t.gauge={dataPoints:DT(r,e)};break;case ft.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:G0(r,e)};break;case ft.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:j0(r,e)};break}return t}function H0(r,e,t){var n={attributes:Qo(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Nt.INT:n.asInt=r.value;break;case Nt.DOUBLE:n.asDouble=r.value;break}return n}function DT(r,e){return r.dataPoints.map(function(t){return H0(t,r.descriptor.valueType,e)})}function G0(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Qo(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 j0(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:Qo(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 V0(r){switch(r){case Qt.DELTA:return 1;case Qt.CUMULATIVE:return 2}}function FT(r,e){return{resourceMetrics:r.map(function(t){return UT(t,e)})}}var qp={serializeRequest:function(r){var e=FT(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 BT="0.52.1";var zT=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ei=function(){return ei=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},ei.apply(this,arguments)},HT="v1/metrics",$0="http://localhost:4318/"+HT,W0={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+BT},q0=function(r){zT(e,r);function e(t){var n=r.call(this,t,qp,"application/json")||this;return n.headers=ei(ei(ei(ei({},n.headers),W0),Xo.parseKeyPairsIntoRecord(ct().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Aa(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:ct().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?zp(ct().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):ct().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?Bp(ct().OTEL_EXPORTER_OTLP_ENDPOINT,HT):$0},e}(Hl),GT=function(r){zT(e,r);function e(t){return r.call(this,new q0(t),t)||this}return e}(ST);var ti;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(ti||(ti={}));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={}));ve();var K0=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)}}(),jT=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},VT=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},Y0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},X0=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))},J0=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 $T(r){return r!=null}function Gl(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function WT(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var Kp=function(r){K0(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function bn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new Kp("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function qT(r){return jT(this,void 0,void 0,function(){var e=this;return VT(this,function(t){return[2,Promise.all(r.map(function(n){return jT(e,void 0,void 0,function(){var o,i;return VT(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 KT(r){return r.status==="rejected"}function Yp(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,X0([],Y0(e(n)),!1))}),t}function YT(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=J0(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(s){t={error:s}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function XT(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 JT(r,e){return r.toLowerCase()===e.toLowerCase()}ve();var tr;(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"})(tr||(tr={}));var Xp=function(){function r(){this.kind=tr.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}();ve();var le;(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"})(le||(le={}));function Pr(r,e,t){var n,o,i,a;return Q0(r)||j.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:Nt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function ZT(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 QT(r,e){return JT(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var Z0=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function Q0(r){return r.match(Z0)!=null}var ek=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function tk(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var jl=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=tk(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var t=XT(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 Vl=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=tr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new jl(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new jl(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new jl(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mr.HISTOGRAM,dataPoints:n.map(function(i){var a=ek(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===le.GAUGE||e.type===le.UP_DOWN_COUNTER||e.type===le.OBSERVABLE_GAUGE||e.type===le.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();ve();var Jp=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Zp=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))},Qp=function(){function r(e,t,n,o){e===void 0&&(e=new rk),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var rk=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,Zp([n,this._counts.length-t],Jp(this._counts.slice(t)),!1)),o.splice.apply(o,Zp([0,t],Jp(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(Zp([],Jp(this._counts),!1))},r}();var ev=52,nk=2146435072,ok=1048575,em=1023,$l=-em+1,Wl=em,wa=Math.pow(2,-1022);function ql(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&nk)>>20;return n-em}function Kl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&ok)*Math.pow(2,32);return o+n}function Ra(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function rv(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var ik=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),En=function(r){ik(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var ov=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<wa)return this._minNormalLowerBoundaryIndex();var t=ql(e),n=this._rightShift(Kl(e)-1,ev);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new En("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new En("overflow: "+e+" is > maximum lower boundary: "+n);return Ra(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=$l>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Wl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var iv=function(){function r(e){this._scale=e,this._scaleFactor=Ra(Math.LOG2E,e),this._inverseFactor=Ra(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=wa)return this._minNormalLowerBoundaryIndex()-1;if(Kl(e)===0){var t=ql(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 En("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return wa;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new En("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return $l<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Wl+1<<this._scale)-1},r}();var av=-10,sv=20,ak=Array.from({length:31},function(r,e){return e>10?new iv(e-10):new ov(e-10)});function tm(r){if(r>sv||r<av)throw new En("expected scale >= "+av+" && <= "+sv+", got: "+r);return ak[r+10]}var sk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Yl=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}(),lk=20,ck=160,rm=2,lv=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=ck),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new Qp),u===void 0&&(u=new Qp),d===void 0&&(d=tm(lk)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<rm&&(j.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+rm),this._maxSize=rm)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=rv(t);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=tm(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Yl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Yl.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 Yl(0,-1);var o=t-n;return new Yl(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},r}();var nm=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=tr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new lv(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=sk(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===le.GAUGE||e.type===le.UP_DOWN_COUNTER||e.type===le.OBSERVABLE_GAUGE||e.type===le.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();ve();var uk=gp("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function cv(r){return r.setValue(uk,!0)}ve();function uv(){return function(r){j.error(dk(r))}}function dk(r){return typeof r=="string"?r:JSON.stringify(pk(r))}function pk(r){for(var e={},t=r;t!==null;)Object.getOwnPropertyNames(t).forEach(function(n){if(!e[n]){var o=t[n];o&&(e[n]=String(o))}}),t=Object.getPrototypeOf(t);return e}var mk=uv();function Xl(r){try{mk(r)}catch{}}var dv="1.30.1";var gk="process.runtime.name";var hk="service.name";var fk="telemetry.sdk.name",Sk="telemetry.sdk.language",yk="telemetry.sdk.version";var pv=gk;var mv=hk;var Ca=fk,xa=Sk,_a=yk;var bk="nodejs";var gv=bk;var ri,to=(ri={},ri[Ca]="opentelemetry",ri[pv]="node",ri[xa]=gv,ri[_a]=dv,ri);function Ma(r){r.unref()}var Ck=9,xk=6,_k=Math.pow(10,xk),gde=Math.pow(10,Ck);function ro(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*_k);return[t,n]}function ni(r){return r[0]*1e6+r[1]/1e3}var Pa;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Pa||(Pa={}));ve();function hv(r,e){return new Promise(function(t){Yo.with(cv(Yo.active()),function(){r.export(e,function(n){t(n)})})})}var fv={_export:hv};var Mk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Jl=function(){function r(e,t,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=ro(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var om=function(){function r(){this.kind=tr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Jl(e)},r.prototype.merge=function(e,t){var n=ni(t.sampleTime)>=ni(e.sampleTime)?t:e;return new Jl(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ni(t.sampleTime)>=ni(e.sampleTime)?t:e;return new Jl(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=Mk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var Pk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},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 Zl=function(){function r(e){this.monotonic=e,this.kind=tr.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:Mr.SUM,dataPoints:n.map(function(i){var a=Pk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var no=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)}}(),rr=function(){function r(){}return r.Drop=function(){return Av},r.Sum=function(){return wv},r.LastValue=function(){return Rv},r.Histogram=function(){return Cv},r.ExponentialHistogram=function(){return Ik},r.Default=function(){return Ok},r}();var Sv=function(r){no(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 Xp,e}(rr);var yv=function(r){no(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case le.COUNTER:case le.OBSERVABLE_COUNTER:case le.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Zl(!0),e.NON_MONOTONIC_INSTANCE=new Zl(!1),e}(rr);var bv=function(r){no(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 om,e}(rr);var Ev=function(r){no(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 Vl([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(rr);var Ql=function(r){no(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(s,c){return s-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Vl(this._boundaries,this._recordMinMax)},e}(rr);var Tv=function(r){no(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 nm(this._maxSize,this._recordMinMax)},e}(rr);var vv=function(r){no(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case le.COUNTER:case le.UP_DOWN_COUNTER:case le.OBSERVABLE_COUNTER:case le.OBSERVABLE_UP_DOWN_COUNTER:return wv;case le.GAUGE:case le.OBSERVABLE_GAUGE:return Rv;case le.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Ql(t.advice.explicitBucketBoundaries):Cv}return j.warn("Unable to recognize instrument type: "+t.type),Av},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(rr);var Av=new Sv,wv=new yv,Rv=new bv,Cv=new Ev,Ik=new Tv,Ok=new vv;var xv=function(r){return rr.Default()},_v=function(r){return ti.CUMULATIVE};var im=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},am=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},Mv=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Lk=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))},Pv=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:xv,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:_v,this._metricProducers=(o=e?.metricProducers)!==null&&o!==void 0?o:[],this._cardinalitySelector=e?.cardinalitySelector}return r.prototype.setMetricProducer=function(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r.prototype.selectCardinalityLimit=function(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3},r.prototype.onInitialized=function(){},r.prototype.collect=function(e){return im(this,void 0,void 0,function(){var t,n,o,i,a,s;return am(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(Lk([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],Mv(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=Mv.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Yp(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(Yp(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return im(this,void 0,void 0,function(){return am(this,function(t){switch(t.label){case 0:return this._shutdown?(j.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,bn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return im(this,void 0,void 0,function(){return am(this,function(t){switch(t.label){case 0:return this._shutdown?(j.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,bn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();ve();var Nk=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ec=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},tc=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},kk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Dk=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},sm=function(r){Nk(e,r);function e(t){var n,o,i,a,s=r.call(this,{aggregationSelector:(n=t.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(t.exporter),aggregationTemporalitySelector:(o=t.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(t.exporter),metricProducers:t.metricProducers})||this;if(t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<t.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return s._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,s._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,s._exporter=t.exporter,s}return e.prototype._runOnce=function(){return ec(this,void 0,void 0,function(){var t;return tc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,bn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof Kp?(j.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Xl(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return ec(this,void 0,void 0,function(){var o,i,a,s,c,l;return tc(this,function(u){switch(u.label){case 0:return[4,this.collect({timeoutMillis:this._exportTimeout})];case 1:if(o=u.sent(),i=o.resourceMetrics,a=o.errors,a.length>0&&(l=j).error.apply(l,Dk(["PeriodicExportingMetricReader: metrics collection errors"],kk(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(t=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(t)];case 3:return u.sent(),[3,5];case 4:return s=u.sent(),j.debug("Error while resolving async portion of resource: ",s),Xl(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,fv._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Pa.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),Ma(this._interval)},e.prototype.onForceFlush=function(){return ec(this,void 0,void 0,function(){return tc(this,function(t){switch(t.label){case 0:return[4,this._runOnce()];case 1:return t.sent(),[4,this._exporter.forceFlush()];case 2:return t.sent(),[2]}})})},e.prototype.onShutdown=function(){return ec(this,void 0,void 0,function(){return tc(this,function(t){switch(t.label){case 0:return this._interval&&clearInterval(this._interval),[4,this.onForceFlush()];case 1:return t.sent(),[4,this._exporter.shutdown()];case 2:return t.sent(),[2]}})})},e}(Pv);ve();ve();function rc(){return"unknown_service:"+process.argv0}var Tn=function(){return Tn=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},Tn.apply(this,arguments)},Uk=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Fk=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},Bk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},nc=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return j.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[mv]=rc(),e[xa]=to[xa],e[Ca]=to[Ca],e[_a]=to[_a],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&j.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 Uk(this,void 0,void 0,function(){return Fk(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=Tn(Tn({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=Bk(a,2),l=c[0],u=c[1];return Tn(Tn(Tn(Tn({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var Iv=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}();ve();var oo=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),oc=function(){function r(e,t){this._writableMetricStorage=e,this._descriptor=t}return r.prototype._record=function(e,t,n){if(t===void 0&&(t={}),n===void 0&&(n=Yo.active()),typeof e!="number"){j.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Nt.INT&&!Number.isInteger(e)&&(j.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,ro(Date.now()))},r}();var Ov=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){this._record(t,n,o)},e}(oc);var Lv=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){j.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(oc);var Nv=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){this._record(t,n,o)},e}(oc);var kv=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){j.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(oc);var ic=function(){function r(e,t,n){this._observableRegistry=n,this._descriptor=e,this._metricStorages=t}return r.prototype.addCallback=function(e){this._observableRegistry.addCallback(e,this)},r.prototype.removeCallback=function(e){this._observableRegistry.removeCallback(e,this)},r}();var Dv=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ic);var Uv=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ic);var Fv=function(r){oo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ic);function Ia(r){return r instanceof ic}var Bv=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=Pr(e,le.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new Nv(o,n)},r.prototype.createHistogram=function(e,t){var n=Pr(e,le.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new kv(o,n)},r.prototype.createCounter=function(e,t){var n=Pr(e,le.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new Lv(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Pr(e,le.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new Ov(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Pr(e,le.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Uv(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=Pr(e,le.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Dv(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=Pr(e,le.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Fv(n,o,this._meterSharedState.observableRegistry)},r.prototype.addBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)},r.prototype.removeBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)},r}();var ac=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=Pr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var zk=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)}}(),zv=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},Hk=function(){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 zv(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 zv(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 mr=function(r){zk(e,r);function e(){return r.call(this,Gl)||this}return e}(Hk);var Gk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},sc=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new mr,this._cumulativeMemoStorage=new mr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Gl(this._overflowAttributes)}return r.prototype.record=function(e,t,n,o){var i=this,a=this._activeCollectionStorage.get(t);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var s=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});s?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(t,a)}a?.record(e)},r.prototype.batchCumulate=function(e,t){var n=this;Array.from(e.entries()).forEach(function(o){var i=Gk(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(t);l?.record(s);var u=l;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,l,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new mr,e},r}();var lm=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.")},Hv=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},lc=function(){function r(e,t){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,t.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return r.prototype.buildMetrics=function(e,t,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,s;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),l=c.collectionTime;s=c.aggregationTemporality,s===ti.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,l)}else s=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:s});var u=jk(a);if(u.length!==0)return this._aggregator.toMetricData(t,s,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=lm(o),a=i.next();!a.done;a=i.next()){var s=a.value,c=this._unreportedAccumulations.get(s);c===void 0&&(c=[],this._unreportedAccumulations.set(s,c)),c.push(e)}}catch(l){t={error:l}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}},r.prototype._getMergedUnreportedAccumulations=function(e){var t,n,o=new mr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=lm(i),s=a.next();!s.done;s=a.next()){var c=s.value;o=r.merge(o,c,this._aggregator)}}catch(l){t={error:l}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return o},r.merge=function(e,t,n){for(var o=e,i=t.entries(),a=i.next();a.done!==!0;){var s=Hv(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,l);o.set(c,p,u)}else o.set(c,l,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=lm(e.keys()),s=a.next();!s.done;s=a.next()){var c=Hv(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function jk(r){return Array.from(r.entries())}var Vk=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)}}(),$k=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Gv=function(r){Vk(e,r);function e(t,n,o,i,a){var s=r.call(this,t)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new sc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new lc(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new mr;Array.from(t.entries()).forEach(function(a){var s=$k(a,2),c=s[0],l=s[1];i.set(o._attributesProcessor.process(c),l)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(ac);ve();function cm(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
4004
|
+
${C||""}`}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:_p(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=_p(this.properties),e}},Pp=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 l=c.shallowClone();if(e[c.id])return l.properties["data-momentic-summary"]=e[c.id],n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l;let u=[];for(let d of c.children){let p=a(d);p&&(u.push(p),p.parent=l)}return l.children=u,n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l},s=a(t);return new r(s,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 s=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),l=i.children,u=!1,d=[];for(let p of l){let h=n(p,s||u);h&&(d.push(h),h.parent=c,u=!0)}if(c.children=d,s||u)return c;if(Ip.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=c=>c.role==="StaticText"||c.role==="ListMarker",o=new WeakMap,i=(c,l)=>{if(o.has(c))return o.get(c);let u=c.serialize({indentLevel:l,noChildren:!0});return o.set(c,u),u},a=(c,l,u)=>{let d=c.shallowClone();d.children=[];let p=i(c,l).length;if(u<=p)return{clone:d,used:p};if(n(c)||c.children.length===0)return{clone:d,used:p};let h=p,m=u-h;for(let g of c.children){let f=l+2,E=i(g,f).length;if(m<E)break;let{clone:S,used:w}=a(g,f,m);if(w>m)break;d.children.push(S),S.parent=d,h+=w,m-=w}return{clone:d,used:h}},{clone:s}=a(t,0,Math.max(1e4,e));return new r(s,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function s0(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 l0(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?(cl({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?(cl({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 XE({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:s,showZeroOpacityElements:c,filterByViewport:l,viewportDetails:u,useMPaths:d,importantProperties:p,allowedA11yIgnoreReasonsOverride:h,cdpClient:m,logger:g,callId:f}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let E=(G,se={})=>{},S=r.backendDOMNodeId,w=r0.includes(r.role?.value?.toLowerCase()??"");if(!w&&S===void 0)return E("Filtering out node since it doesn't exist in the DOM"),[];let v=S?i.backendIdToNode[S]:void 0;if(!w&&!v)try{let G=await $(m.send({method:"DOM.describeNode",params:{backendNodeId:S}}),{milliseconds:750,fallback:()=>{g.debug("Timeout getting node from CDP while processing a11y tree")}});if(G&&G.node.nodeName.toLowerCase()==="slot"&&G.node.distributedNodes?.length)g.debug({redirectedDomNode:v,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:G},"Redirecting node to assigned slot");else return E("Filtering out node since it doesn't exist in the DOM",{cdpResult:G}),[]}catch(G){return E("Filtering out node since it doesn't exist in the DOM",{err:G}),[]}if(v&&e&&l&&u&&r.backendDOMNodeId&&!l0(v,u,g,f))return v.momenticIgnored=!0,[];if(v&&v.computedStyles.display==="none")return v.momenticIgnored=!0,[];if(v&&v.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&v.tagName.toLowerCase()!=="input")return v.momenticIgnored=!0,[];if(c===!1)return v.momenticIgnored=!0,[]}let A=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",I=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",C=new Mp({domNode:v,id:parseInt(r.nodeId),role:r.role?.value||"",name:A,nameSources:r.name?.sources,content:I,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(G=>(h??qE).includes(G.name)||KE.includes(G.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+s0(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:s}),R=n,B=a[t],U=t;if(v?.tagName.toLowerCase()==="iframe"&&v.ownedFrameId){let G=n.childFrames.find(ke=>ke.frameId===v.ownedFrameId),se=o[G?.frameId??""]?.root,ce=a[G?.frameId??""];if(G&&se&&ce){r.childIds&&r.childIds.length>0&&g.debug("Replacing existing node's children with children from the iframe");let ke=se;r.childIds=ke.childIds,R=G,B=ce,U=G.frameId}}let D=v?.childrenBackendIds?.length??0,J=(r.childIds??[]).filter(G=>!!B.get(parseInt(G))).length;if(D>J){let G=r.childIds?.map(ce=>B.get(parseInt(ce))).filter(Boolean).map(ce=>ce?.backendDOMNodeId).filter(ce=>ce!==void 0)??[],se=0;for(let ce of v?.childrenBackendIds??[]){if(G.includes(ce)){se=(r.childIds?.findIndex(we=>B.get(parseInt(we))?.backendDOMNodeId===ce)??0)+1;continue}let ke=i.backendIdToNode[ce];if(!ke||ke?.tagName.toLowerCase()!=="svg")continue;let fe=Math.floor(-1*Math.random()*1e7),pt={nodeId:fe.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:ce,frameId:U,role:{type:"string",value:"graphics-symbol"}};B.set(fe,pt),r.childIds||(r.childIds=[]),r.childIds.splice(se,0,fe.toString()),se++}}if(r.childIds?.length===1&&v){let G=B.get(parseInt(r.childIds[0])),se=G?.role?.value,ce=v.childrenBackendIds;if(G&&se==="StaticText"&&ce.length===1){let ke=i.backendIdToNode[ce[0]];if(ke?.tagName?.toLowerCase()==="span"){let fe=Math.floor(-1*Math.random()*1e7).toString(),pt={nodeId:fe,parentId:r.nodeId,ignored:!1,backendDOMNodeId:ke.backendNodeId,frameId:U,childIds:[G.nodeId]};G.parentId=fe,B.set(parseInt(fe),pt),r.childIds=[fe]}}}for(let G of r.childIds??[]){if(!G)continue;let se=B.get(parseInt(G));if(!se)continue;let ce=await XE({node:se,parent:C,domGraph:i,axGraph:o,frameId:U,frameContext:R,inputNodeMap:a,cdpClient:m,logger:g,callId:f,filterByViewport:l,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:s});ce.length&&(C.children=C.children.concat(ce))}if(C.role==="StaticText"&&(C.children=[]),C.children.length===1&&C.children[0].role==="StaticText"){let G=C.name,se=C.children[0]?.name;(G===se||!se)&&(C.children=[])}let Le=[];for(let G=C.children.length-1;G>=0;G--){let se=C.children[G];if(se.role!=="StaticText"){Le.push(se);continue}if(G===0||C.children[G-1].role!=="StaticText"){Le.push(se);continue}C.children[G-1].name+=se.name}if(C.children=Le.reverse(),!C.isInteresting(p)&&r.parentId)return v&&(v.momenticIgnored=!0),C.children;for(let G of C.children)G.parent=C;return d0(C),v&&d&&xp(v,i),[C]}function JE({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:s,iconKnowledgeBase:c,startId:l=1}){r.id=l,l+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:Ip.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(s[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let p=Cp(d,i),h=p?c[p.hash]:void 0,m=h?h.description:void 0;h&&(r.properties["data-momentic-description"]=m)}for(let p of r.children)l=JE({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:l,useMPaths:a,domGraph:i,selectorToNodeMap:s,iconKnowledgeBase:c});return l}async function ZE({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:s,importantProperties:c,viewportDetails:l,useMPaths:u,frameContext:d,iconKnowledgeBase:p,allowedA11yIgnoreReasonsOverride:h}){let m=t??"root",g=r[m]?.root;if(!g)throw new Error("A11y tree has no root");let f=YN(),E=C=>{let R=C.allNodes.filter(U=>!U.ignoredReasons?.find(J=>(h??qE).includes(J.name))),B=new Map;return R.forEach(U=>{B.set(parseInt(U.nodeId),U)}),B},S={};Object.entries(r).forEach(([C,R])=>{S[C]=E(R)});let w=await XE({node:g,domGraph:e,parent:null,inputNodeMap:S,axGraph:r,frameId:m,frameContext:d,cdpClient:o,logger:n,callId:f,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:l,useMPaths:u,flagNotActionableNodes:s,allowedA11yIgnoreReasonsOverride:h});if(w.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(w)}`);if(w.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let v={},A={},I={};return JE({node:w[0],a11yIdNodeMap:v,dataMomenticIdMap:A,selectorToNodeMap:I,domGraph:e,logger:n,callId:f,useMPaths:u,iconKnowledgeBase:p}),new Pp(w[0],v,A,I)}function c0(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<YE&&!nr.bannedClassSubstrings.some(s=>a.includes(s))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(QE(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 u0(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,s])=>{let c=r[a]||a.startsWith("aria")||ZN.includes(a);if((nr.relevantElementAttributes.includes(a)||eT(a,t))&&!c){let u=c0(a,s,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&VE.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of VE)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 s=a.split(":"),c=s[0]?.trim(),l=s[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&l!==void 0&&u!==void 0&&(l==="*"||u===l)){let d=e.computedStyles[c],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(r.style=o.join("; "))}function d0(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(l=>l.tagName==="tr");if(c){let l=c.children.filter(u=>u.tagName==="th");l.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(Mt(u.name,100,!1))}),i?.length!==l.length&&(i=void 0)}}let s=0;for(let c of r.children)if(c.tagName==="tbody")for(let l=0;l<c.children.length;l++){let u=c.children[l];if(u.tagName!=="tr")continue;if(l===0&&!i?.length){let h=u.children.filter(m=>m.tagName==="th");if(h.length){if(i=h.map(m=>Mt(m.name,100,!1)),i.length===h.length)continue;i=void 0}}s+=1,u.properties["row-index"]||(u.properties["row-index"]=s);let d=u.children.filter(h=>h.tagName==="td"||h.tagName==="th"),p=d.length===i?.length;d.forEach((h,m)=>{h.tagName!=="th"&&(h.properties["col-index"]||(h.properties["col-index"]=m+1),p&&(h.properties.col||(h.properties.col=i[m])))})}}}function p0(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function QE(r,e){if(e&&tT(r,e))return!0;if(nr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(nr.alwaysInterestingClassNames.includes(r))return!0;for(let t of nr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function eT(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 tT(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 Ll=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(),s,c;for(let u=0;u<2;u++)try{s=await $(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new _("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await ee(at),c=d}if(!s)throw c;let l=new r(s,e,t,n,o);try{await $(l.registerHandlers(s),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw l.cdpFullyDead=!0,new _("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return l}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 $(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new _("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 $(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 $(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new _("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 $(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 $(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 ei="<empty>";function m0(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 nT(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||m0(r.url)}async function h0(r,e){let t=await r.send({timeout:te,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:te,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:te,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function ti({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:te,method:"Page.getFrameTree",params:{}}),r.send({timeout:te,method:"DOM.getDocument",params:{depth:0}})]),l=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(nT(d.frame))return null;try{return await oT({cdpClient:r,rawFrameTree:d,indices:[p],parent:n,warnings:o,logger:t})}catch(h){return o.push(`Failed to get child frame: ${h}`),null}}),u=await Promise.all(l);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,s=await h0(r,a),c=s.attributes??[],l=null,u=[];for(let m of["src","name","id","title","srcdoc","sandbox"]){let g=An(c,m);g&&(u.push(`${m}=${JSON.stringify(g)}`),m==="src"&&(l=g))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:l,childFrames:[],parent:n,domNode:s},h=(e.childFrames??[]).map(async(m,g)=>{if(nT(m.frame))return null;try{return await oT({cdpClient:r,rawFrameTree:m,indices:[...t,g],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${g} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(h)).filter(m=>m!==null),d}async function g0(r){try{return await r.owner().count()===1}catch{return!1}}async function f0(r){try{return await r.count()===1}catch{return!1}}async function Nr(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 l of t){let u=!1;for(let d of[...l.locationData.attributeSelectors,ei]){let p=o.frameLocator(d===ei?"iframe":`iframe[${d}]`);if(await g0(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new _("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${l.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let l of[...r.locationData.attributeSelectors,ei]){let u=o.locator(l===ei?"iframe":`iframe[${l}]`);if(await f0(u)){a=u,i.push(l);break}}if(!a)throw new _("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 s=await a.evaluateHandle(l=>l,{timeout:re}),c=await s.asElement().contentFrame();if(!c)throw new _("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await s.dispose(),{frame:c,mPathSelectorTokens:i}}function rT(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 iT({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let s=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===ei?s=s.length===1?s[0].childFrames:[]:s=s.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],l=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(l===ei?c=s:c=s.filter(u=>u.locationData.attributeSelectors.includes(l)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await Nr(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 s=new RegExp(t.frameSrcRegex),c=rT(o,l=>!!l.src&&s.test(l.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await Nr(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 s=new RegExp(t.frameUrlRegex),c=rT(o,l=>!!l.url&&s.test(l.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await Nr(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 s=0;s<t.indices.length-1;s++)a=a[t.indices[s]]?.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 Nr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new cn("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function Nl(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function Op(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function aT(r){let e=Op(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let s=a.shift();s.src&&o.push(s.src),s.url&&i.push(s.url),a.push(...s.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function sT(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 lT({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await S0({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 S0({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await ba({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 s=Date.now();for(;Date.now()-s<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(l=>setTimeout(l,250))}}),timeoutMs:ge,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}async function cT({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:s,properties:c}=r.target;if(s){i.error({error:s,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let l=n.parentFrame()?n.url():void 0,d=n.page().frames().map(m=>m.url());i.debug({frameUrl:l,...r},"Passive click event captured on element");let p,h;if(l)try{let m=await n.frameElement();p=await $(m?.boundingBox(),{milliseconds:te})??void 0;let g=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:l});if(g.urlRegex)h={type:"url",url:`/${g.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(g)}`)}catch(m){i.warn({err:m},"Failed to construct iframe details for recorded action, using hardcoded URL only"),h={type:"url",url:l}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:h,frameBoundingBox:p})}catch(m){i.error({err:m},"Failed to transform passive click action")}})()}import{randomUUID as kr}from"crypto";import y0 from"js-beautify";var b0=["Dead"],kl=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:(s,c)=>{this.recordedSteps.set(c,{step:s}),t.onStepRecorded(s,c)},onActionReceived:(s,c)=>{this.recordedSteps.set(c,{step:s}),t.onActionReceived?.(s,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:kr(),type:"PRESET_ACTION",command:$r(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,s=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=s,l;switch(e.frameConfig?e.frameBoundingBox?l={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"):l=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let g=$r(i);a={id:kr(),type:"PRESET_ACTION",command:{...g,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:l}}}};break}case"SELECT":{i="SELECT_OPTION";let g=$r(i);a={id:kr(),type:"PRESET_ACTION",command:{...g,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:l}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let g=$r(i);a={id:kr(),type:"PRESET_ACTION",command:{...g,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:ve(this.logger),boundingBox:l}}}};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=y0.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=tE(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,...ve(this.logger)}})).phrase}catch(g){this.logger.error({err:g},"Error generating reverse mapping description"),p=s}let h=this.recordedSteps.get(u)?.step??a,m=h?.command;m&&"target"in m&&m.target?(m.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...h,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(b0.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=$r("TYPE");i={id:kr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=$r("PRESS");i={id:kr(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,s=this.nextStepOffset-1,c=this.recordedSteps.get(s),l=c?.step,u=l?.command;if(n){if(u?.type===i.command.type){let d=u.value,p=i.command.value;i={id:kr(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},a=s}else if(u?.type==="CLICK"&&i.command.type==="TYPE")l.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=s;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:kr(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=s}}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,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_DOWN"&&s.deltaY?(i+=s.deltaY,c=a):s?.type==="SCROLL_UP"&&s.deltaY?(i-=s.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_DOWN":"SCROLL_UP",u=$r(l);u.deltaY=Math.abs(i);let d={id:kr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_RIGHT"&&s.deltaX?(i+=s.deltaX,c=a):s?.type==="SCROLL_LEFT"&&s.deltaX?(i-=s.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=$r(l);u.deltaX=Math.abs(i);let d={id:kr(),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 Lp}from"zod";var fce=Lp.object({type:Lp.literal("url"),url:Lp.string()});var Dl=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userControlledBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;allowedA11yIgnoreReasonsOverride;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:s,enricher:c,iconKnowledgeBase:l,userBrowserSettings:u,allowedA11yIgnoreReasonsOverride:d}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=s,this.enricher=c,this.iconKnowledgeBase=l,this.userControlledBrowserSettings=u,this.allowedA11yIgnoreReasonsOverride=d,this.userControlledBrowserSettings.importantStyles)for(let p of this.userControlledBrowserSettings.importantStyles){let h=p.split(":");if(h.length!==2){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}let m=h[0]?.trim(),g=h[1]?.trim();if(m===void 0||g===void 0){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(m)||this.computedStylesToFetch.push(m)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userControlledBrowserSettings.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=Op(e),{frame:o,mPathSelectorTokens:i}=await Nr(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 ti({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await iT({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(Nl(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:Nl(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await lT({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await ti({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[$(n.evaluate(e,t),{milliseconds:ge})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),l=c.url;l==="about:blank"||l.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(Nr(c,n).then(({frame:u})=>$(u.evaluate(e,t),{milliseconds:ge})).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 ti({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,s,c=null;if(this.frameConfig?.type==="url"){if(a=await or({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new _("ActionFailureError","Got null frame details despite active frame config");s=a.handle,c=s.frameId}else this.userControlledBrowserSettings.autoExpandIframes?(s=await or({fn:()=>ti({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(s={type:"root",page:i,childFrames:[]},c=null);await or({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:s.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let l=await or({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await or({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:s.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await or({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:l,startingFrameId:c,frameContext:s,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=l,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.userControlledBrowserSettings.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=HE({node:o,domGraph:this.domGraph});return GE(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:ge});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await jE(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(Er(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,s,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await ti({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(l){if(s=l,l instanceof _&&l.reason==="UserInfrastructureError")throw l;c%3===0&&this.logger.warn({attempt:c,err:l},"Failed to resolve active frame, retrying..."),await ee(at,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:Nl(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw s}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let s=i.shift(),c=s.domNode;i.push(...s.childFrames);let l=An(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!l&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[l,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:s,matchType:"regex",...await Nr(s,o)});break}}else if(n.trim()===d.trim()){a.push({handle:s,matchType:"url",...await Nr(s,o)});break}}}if(a.length===1){let s=a[0];return this.userControlledBrowserSettings.autoExpandIframes||(s.handle.childFrames=[]),s}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new _("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:s,showZeroOpacityElements:c,flagNotActionableNodes:l}){let u=await ZE({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:l,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:s,useMPaths:this.userControlledBrowserSettings.visualActions,allowedA11yIgnoreReasonsOverride:this.allowedA11yIgnoreReasonsOverride});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.userControlledBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userControlledBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),s=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let l=async()=>{try{let{frame:u}=await Nr(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...")}};s.push(l())}await Promise.all(s)}async addMomenticIdsHelper(e,t){if(this.userControlledBrowserSettings.visualActions)return t;let n=this.logger;return await Qe({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:ge,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(An(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=An(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:te,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:te,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:te,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 s=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(h){i.warn({err:h},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,l;for(let h=0;h<3;h++)try{l=await or({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,logger:i});break}catch(m){c=m,i.warn({err:m},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!l)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=l,!this.userControlledBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),p=[];for(;d.length>0;){let h=d.shift();try{let{shouldUnroll:g}=await this.decideChildFrameUnrollEligibility({handle:h,warnings:s});if(!g)continue}catch(g){if(g.message.includes("Could not compute box model"))continue;s.push(`Got error when determining whether to filter frame ${h.frameId} with url ${h.url}, allowing it to be fetched: ${g}`)}d.push(...h.childFrames);let m=async()=>{try{let g=await or({fn:()=>this.getRawA11yTreeForFrame({frameId:h.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${h.frameId}`,logObject:o,logger:i});u[h.frameId]=g}catch(g){i.warn({err:g,url:h.url,src:h.src},`Error getting raw a11y tree for child frame ${h.frameId}, continuing...`)}};p.push(m())}return await Promise.all(p),s.length>0&&this.logger.warn({warnings:s},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await or({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,logger:this.logger})).nodes;else{let a=(await or({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:ge}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;o=(await or({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,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:te}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await ee(at,t),i++,a=s}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new _("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 zE({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=aT(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 Np(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var wa=class r{static USER_AGENT=xl;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,enricher:t,browser:n,context:o,page:i,baseUrl:a,logger:s,userBrowserSettings:c,viewport:l,properties:u,clientCallbacks:d,iconKnowledgeBase:p}){if($y(c),this.storage=e,this.enricher=t,this.browser=n,this.context=o,this.page=i,this.baseUrl=a,this.logger=s,this.userControlledBrowserSettings=c,this.viewport=l,this.properties=u,this.clientCallbacks=d,u.recordVideo){let h=this.page.video();h&&this.videos.push(h)}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={[Cl]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:Xd.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'); });`}),this.exposeRecordingBindings()],i=a=>this.handleNewPageEvent(a);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)}),await Promise.all(o),t&&(await this.page.addScriptTag({content:Xd.htmlUtilsLibJs}),await this.page.addScriptTag({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&C0()==="darwin"&&E0("system_profiler SPDisplaysDataType").toString().includes("Retina")?(x.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 Ll.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new Dl({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,allowedA11yIgnoreReasonsOverride:this.properties.allowedA11yIgnoreReasonsOverride}),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(e){let t=await _E(e),n=new r(t);return await n.initialize({grantPermissions:!0,runInitScripts:!1}),n}static async fromExistingContext({context:e,storage:t,enricher:n,userBrowserSettings:o,properties:i,logger:a}){let s=e.pages()[0];if(!s)throw new Error("No page found in existing context");let c=s.viewportSize();c||(c=await s.evaluate(()=>({width:window.innerWidth,height:window.innerHeight})));let l=s?.url(),u=new r({browser:e.browser(),context:e,page:s,baseUrl:l,logger:a,storage:t,enricher:n,userBrowserSettings:o,viewport:c,properties:i,clientCallbacks:void 0,iconKnowledgeBase:null});return await u.initialize({grantPermissions:!1,runInitScripts:!0}),u}async handleAvailableTabsChangeHelper(){try{let e=await Rp(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=kp(),o=`${e}-${n}`,i=Date.now(),a=!1,s=async()=>{try{await $(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]=s().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()||!to(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=kp(),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=>{hE(e,o,this.debugData,a,this.logger)});let i=async()=>{await SE(t,this.debugData,e),await e.route("**/*",async(a,s)=>{await hp({pageId:t,route:a,request:s,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",vE(this.customHeaders,this.logger)),yn&&await e.route("**/*",va),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){}handleFrameNavigationEvent(e){let t=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${t.slice(0,50)} (${n})`;if(!t||t==="about:blank"||!to(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}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(s){this.logger.warn({err:s},"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 $(vp(this.getBrowserCallbacks()),{milliseconds:re})}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<Jd;){a++,n?.throwIfAborted();try{if(await Qe({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:re,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(s){if(i++,i>=3){t.warn({err:s},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await ee(at),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),Qe({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:te,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 ee(Zo),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 s=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:o??ge}),c=Buffer.from(s.data,"base64"),l=await dT.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(l.bitmap.width!==u||l.bitmap.height!==d)&&(c=await l.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&A0(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:te});if(!p)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:h,y:m,width:g,height:f}=p;if(!g||!f)throw new Error("Attempted to screenshot an element with zero width or height");h=Math.floor(h),m=Math.floor(m),g=Math.floor(g),f=Math.floor(f);try{let E=await dT.fromBuffer(c),S=E.bitmap.width,w=E.bitmap.height;h=Math.max(0,Math.min(h,S-1)),m=Math.max(0,Math.min(m,w-1)),g=Math.max(1,Math.min(g,S-h)),f=Math.max(1,Math.min(f,w-m)),c=await E.crop({x:h,y:m,w:g,h:f}).getBuffer("image/jpeg")}catch(E){throw new Error(`Failed taking element screenshot at coordinates (${h}, ${m}) with size (${g}, ${f}): ${E}`)}finally{"dispose"in e&&await e?.dispose()}return c}getViewport(){if(this.viewport)return this.viewport;let e=this.page.viewportSize();return e||null}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){Jb(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(l){if(a=l,this.abortSignal?.throwIfAborted(),this.logger.warn({err:l},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await ee(at),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:re})}if(!i)throw new _("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 s=this.url();if(sE.has(s))throw new _("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);await this.fixViewportForNewHeadless()}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async getActiveElement(e){try{return await Qe({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:re,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 OE({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 ee(Zo),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"?(this.properties.isAndroid?await this.page.keyboard.press("Control+A"):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??Ag}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:ge})}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(s=>setTimeout(s,250))}},void 0,{timeout:ge})}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 Il({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:re}),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 mE(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:re});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:re,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(s){this.logger.warn({err:s,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 pE(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 dE(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 _("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return Rp(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,startingBoundingBox:o,allowNotActionableNodesOverride:i,logger:a=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let s=await this.fetchHtmlAttributes({locator:n,logger:a,startingBoundingBox:o,allowNotActionableNodesOverride:i});s?(t.generatedSelectors=s.generatedSelectors,t.serializedHtml=s.serializedHtml,t.nodeOnlySerializedHtml=s.nodeOnlySerializedHtml,t.hybridSelector=s.hybridSelector):a.warn("Got undefined HTML attributes when trying to update cache")}catch(s){if(s instanceof xr)throw a.warn({err:s},"Cache attributes disqualify found element"),s;a.warn({err:s},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:a,boundingBox:o})}catch(s){a.debug({err:s},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!tp.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:te})),!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:s=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-s)<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 l=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(l),{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:te});if(!o||!o.width||!o.height)throw new _("ActionFailureError","Element does not have a bounding box as required");n.boundingBox=o??void 0}if(t?.text){let o=await e.innerText({timeout:te});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||nr.bannedAiRequiredCacheAttributes.includes(a)))try{let s=await e.getAttribute(a,{timeout:te});s!==null&&(o[i]=s)}catch(s){this.logger.warn({err:s,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 s=await this.fetchHtmlAttributes({locator:a,logger:o});if(!s?.generatedSelectors||s.generatedSelectors.length===0)return;let c={selectors:s.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,s=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let l=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!l)continue;s.push(l)}catch(l){this.logger.warn({err:l,additionalElement:c},"Failed to fetch additional element details, continuing...")}return s}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:s}){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:s}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:s}){if(e<0)throw new _("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new _("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let l=this.stateManager.frameConfig,u,d,p,h;if(this.userBrowserSettings.autoExpandIframes&&!l&&c.parentFrame){let S=c.parentFrame,{cache:w,config:v}=await this.stateManager.getAutoFrameDetailsFromHandle(S);d=w,p=v,u=v.frame,h="auto iframe"}else c.parentFrame&&l?(p=l,u=await this.getActivePageOrFrame(),h="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),h="should not be possible");let m=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:u,node:c}),g={id:e,inputDescription:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:ve(i),frameCache:d},f,E=!1;o||(p&&(i.info({frameConfigSource:h,frameConfig:sT(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:g,locator:m,logger:i,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:s,target:g,root:u,locator:m,logger:i}));try{return{resolution:{locator:m,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:g,frameConfig:p,frameConfigSource:h}}finally{E&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,t,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowNotActionableNodesOverride:s}=n;if(t.frameCache&&this.userBrowserSettings.autoExpandIframes){let h,m=!1,g=Date.now();for(;Date.now()-g<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),m=!0;break}catch(f){h=f,await ee(at,a)}if(!m)throw h}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let l=Date.now(),u=0,d=0,p;for(;Date.now()-l<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let h=u===2||Date.now()-l>this.smartWaitingTimeout-2e3&&u%2===0;try{p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,shouldLogOnFailure:h,logger:i,allowNotActionableNodesOverride:s,signal:a});break}catch(m){if(m instanceof Xi)break;if(m instanceof xr){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 ee(at,a)}a?.throwIfAborted(),h&&i.warn({err:m},`Could not resolve target using primary cache only (x${u})`),await ee(at,a)}}return p||(p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:s}),t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=ve(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,shouldLogOnFailure:s}){let c=ri(t),l=[],u=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),d;if(t.generatedSelectors||t.hybridSelector){let p;try{p=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a,shouldLogOnFailure:s})}catch(h){d=h,h instanceof cn&&l.push(...h.decisions)}if(p)return{...p,pageState:void 0,decisions:[...l,...p.decisions]};n||(l.push({type:"CSS_SELECTOR",matched:!1,reason:d?.message,selectors:ri(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw d;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let p=await this.resolveTargetWithSecondaryMethods({root:e,tree:u,target:t,decisions:l,logger:o,signal:i,allowNotActionableNodesOverride:a});if(p)return p}throw new cn(`Could not find any relevant node given target: ${JSON.stringify(c)}`,l)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o,shouldLogOnFailure:i}){if(!t.nodeOnlySerializedHtml)throw new Xi("Insufficient data to resolve target using primary methods (missing node HTML)");let a=i?n:bn,s=this.userControlledBrowserSettings.hybridSelectorMode,c={ldistThreshold:ep,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles}},{css:l,hybrid:u}=await Qe({fn:w=>window.evaluatePrimaryCaches(w),arg:{cssParams:{selectors:t.generatedSelectors??[],cachedElementSerialized:t.nodeOnlySerializedHtml,opts:c},hybridParams:s&&t.hybridSelector?{nodes:t.hybridSelector,cachedElementSerialized:t.nodeOnlySerializedHtml,opts:c}:void 0},root:e,timeout:te,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),d,p,h=[];if(s==="prefer"&&u?.result){d=u.result;let w={type:"HYBRID_SELECTOR",matched:!0,logs:u.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};h.push(w),p="HYBRID_SELECTOR"}else if(l?.result){d=l.result;let w=`${d.workingSelectors.length} CSS selectors matched the following element: ${d.serializedElement}`,v=d.workingSelectors.slice(0,5);h.push({type:"CSS_SELECTOR",matched:!0,logs:l.logs,reason:w,selectors:v}),n.debug({reason:w,workingSelectors:v},"Resolved with CSS selectors"),p="CSS_SELECTOR"}else throw h.push({type:"CSS_SELECTOR",matched:!1,reason:l.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:l.logs}),u&&h.push({type:"HYBRID_SELECTOR",matched:!1,reason:u.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:u.logs}),new cn("Cache evaluation failed",h);let m,g,f;if(this.userBrowserSettings.visualActions){let w=d.mPath;if(!w)throw new Error("Found element did not have an mPath despite using visual actions");let v=w.join(" > ");m=e.locator(v),g=this.stateManager.getNodeUsingMPathSelector(v)}else if(d.dataMomenticId!==void 0)f=parseInt(d.dataMomenticId),g=this.stateManager.dataMomenticIdToNodeMap[f],"workingSelectors"in d?m=e.locator(d.workingSelectors[0]):m=e.locator(Er(f));else throw new _("InternalWebAgentError","Received an element resolution result with no identifying attributes");s&&t.hybridSelector&&(u?.logs.length===1?a.warn({hybridResult:u,cssResult:l,hybridMode:s},"Hybrid selector resolution rejected, continuing..."):u?.result?l?.result&&u?.result&&u.result.serializedElement!==l.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(l.result.mPath)!==JSON.stringify(u.result.mPath)?n.warn({originalCache:t,hybridResult:u,cssResult:l,hybridMode:s,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):l.result.dataMomenticId!==u.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:u,cssResult:l,hybridMode:s,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):a.warn({originalCache:t,hybridResult:u,cssResult:l,hybridMode:s},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let E=ri(t);await this.updateCacheWithNewNodeDetails({node:g,target:t,locator:m,logger:n,startingBoundingBox:d.boundingBox,allowNotActionableNodesOverride:o});let S=Dp(E,t);return S&&Object.keys(S).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ve(n),t.cacheResolutionUpdateSource=p,n.debug({diffs:S},"Updated cache")),{a11yNode:g,displayString:d.serializedElement,locator:m,decisions:h}}async resolveHardcodedCssSelector(e){let{ctx:t,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,s=await this.getActivePageOrFrame(),c=Date.now(),l=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),l++;let p=s.locator(n),h;try{return await p.waitFor({state:"attached",timeout:re}),h=await Yr(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:h,decisions:d}}catch(m){let g=m.message;u=new _("ActionFailureError",`CSS selector '${n}' failed to resolve after ${l} attempts: ${g.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":g}`),await ee(at,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 s=await a.locator.boundingBox({timeout:te});if(!s){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:l,width:u,height:d}=s;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||!l){this.logger.debug({oldX:t,oldY:n,newX:c,newY:l,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-t)>100||Math.abs(l-n)>100){this.logger.debug({newX:c,newY:l,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<iE){let l="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:l})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let l=await Qe({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:ge,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(ep*t.nodeOnlySerializedHtml.length);if(l&&l.closestDistance&&l.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${l.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:l.closestDistance,closestElement:l.closestNodeSerialized})}else{if(l?.error)throw new Error(l.error);if(l?.dataMomenticId||l?.mPathSelector){let d=l.dataMomenticId?parseInt(l.dataMomenticId):void 0,p,h;if(d)p=this.stateManager.dataMomenticIdToNodeMap[d],h=e.locator(Er(d));else if(l.mPathSelector)p=this.stateManager.getNodeUsingMPathSelector(l.mPathSelector),h=e.locator(l.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let m=l.closestNodeSerialized??await Yr(h,o)??"unknown element";o.warn({result:l,originalTarget:t,displayString:m},"Resolved cached target to new node with pure html levenshtein distance");let g=ri(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:h,logger:o,startingBoundingBox:l.boundingBox,allowNotActionableNodesOverride:a});let f=Dp(g,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ve(o),t.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:l},"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:l.logs,distance:l.closestDistance,closestElement:m,savedElement:t.nodeOnlySerializedHtml}),{locator:h,a11yNode:p,displayString:m,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(l)}`)}}catch(l){o.info({err:l},"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: ${l}`})}let s=t.screenshotUrl,c=t.role??"";if(s&&tp.includes(c))try{let l=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:s,signal:i,allowNotActionableNodesOverride:a});return{...l,decisions:[...n,...l.decisions],pageState:void 0}}catch(l){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${l}`,elementImageUrl:s}),o.warn({err:l},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({screenshotUrl:e,oldTarget:t,signal:n,allowNotActionableNodesOverride:o}){let i;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let a=await this.screenshot({retries:0}),c=await(await fetch(e)).arrayBuffer(),l=P0(),u=await this.enricher.runTemplateMatching({id:l,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:a.toString("base64")},{signal:n}),{target:d,locator:p}=await this.getTargetFromPositionPercentages({percentX:u.x,percentY:u.y,allowNotActionableNodesOverride:o}),h=d.boundingBox?.width,m=d.boundingBox?.height;if(!h||!m)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let g=d.id,f=this.stateManager.a11yIdToNodeMap[g],E=ri(t);await this.updateCacheWithNewNodeDetails({target:t,node:f,locator:p,allowNotActionableNodesOverride:o});let S=Dp(E,t);return S&&Object.keys(S).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ve(this.logger),t.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:l,diffs:S,templateMatch:u},"Updated cache after template matching resolution")),{locator:p,a11yNode:f,displayString:d.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:e}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:re})??"",i=IE.some(a=>a===o.toLowerCase());return await Ap({targetingResult:t,options:{force:n.force,relativePosition:n.relativePosition},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 Ap({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,s=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),s=this.url(),Al(s,t,n)){a=!0;break}await ee(at,this.abortSignal)}if(!a)throw new _("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${gb(t)} in ${o}ms.
|
|
4005
|
+
Current tab: ${s}`);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:te});if(!o)throw new _("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,s=n.steps??5;await this.page.mouse.move(i,a,{steps:s}),await ee(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,ge):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(mp);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 ee(Zo),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await oo({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:te});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 oo({func:t=>t.locator.focus({timeout:ge}),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 Qe({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:re,codePath:"blurring the active element"});return}await this.highlight(e.locator),await oo({func:t=>t.locator.blur({timeout:ge}),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 oo({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 _("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:te})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=Ol(e,this.properties.isAndroid);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=Ol(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Np(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=Ol(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Np(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,shouldLogOnFailure:a}=e,s=e.abortSignal??this.abortSignal,c=!i,l=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements,u=a?n:bn;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:s});let d=0,p;for(;d<t;){d++;try{return await $(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:s,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:l,flagNotActionableNodes:c}),{milliseconds:this.pageLoadTimeout*d,signal:s,message:"Getting browser state took too long"})}catch(h){if(s?.throwIfAborted(),p=h instanceof Error?h.message:`${h}`,d>=t)throw h;u.warn({err:h,url:this.url()},"Error getting a11y tree, retrying...")}}throw new _("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${p}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await Qe({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:te,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()},s=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",s);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let l=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",l);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",s),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",l),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),s,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},l=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await ee(Zo,this.abortSignal),s)try{let d=await this.screenshot(c);if(!d.equals(s)){s=d,l=!1;continue}l=!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{s=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<oE)){i=!0;break}}i||t.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:l}},"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 ee(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,Qd):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(mp);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 ee(Zo),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:te}),n=await $(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:ge});process.platform==="darwin"&&n===1&&(n=rE);let o=t.documents[0],i=o.layout,a=o.nodes,s=a.nodeName||[],c=a.backendNodeId||[],l=i.nodeIndex,u=i.bounds,d=-1;for(let S=0;S<s.length;S++)if(c[S]===e){d=l.indexOf(S);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[p=0,h=0,m=0,g=0]=u[d];p/=n,h/=n,m/=n,g/=n;let f=p+m/2,E=h+g/2;return{centerX:f,centerY:E}}async scrollVertical(e){return wp({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 wp({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 ee(at)}}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 _("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)}.
|
|
4006
|
+
Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!to(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=Ws(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 s of Object.values(this.stateManager.a11yIdToNodeMap))if(s.role==="image"&&s.name.toLowerCase().includes("captcha")){if(!s.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,s.backendNodeId);break}if(!e){let s=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!s.captchas||!s.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:te}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:Qo,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let s=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},s),new Error(s)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<aE;){await ee(2500);let s=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:Qo,taskId:o})});if(!s.ok){let l=`Captcha solution API returned error response: ${s.statusText}`;throw this.logger.error({text:await s.text()},l),new Error(l)}let c=await s.json();if(c.errorId){let l=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(l),new Error(l)}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(){try{await $(this.exposeRecordingBindingsHelper(),{milliseconds:this.pageLoadTimeout})}catch(e){e instanceof Error&&e.message.includes("already registered")||this.logger.error({err:e},"Failed to install Momentic libraries for action recording")}}async exposeRecordingBindingsHelper(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&cT({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(c=>c.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let c;try{c=(await this.getOpenPages()).map(u=>u.url),o=0}catch(u){this.logger.debug({err:u},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let l=this.url();for(let u=c.length-1;u>=n.length;u--){let d=c[u];to(d,this.logger)&&d!==l&&this.logger.info({lastActivePages:n,currentUrl:l,newOpenPages:c},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(u)});break}n=c};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(c){this.logger.error({err:c},"Error while checking pages during recording")}finally{i=!1}}},at);let s=async()=>{clearInterval(t)};e.addEventListener("abort",s,{once:!0})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(i=>{let a=window;a._MOMENTIC_RECORDING_ACTIVE=!0,a._MOMENTIC_CLICK_RECORD_ACTIVE=i},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page);let o=async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!1,i._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}};e.addEventListener("abort",o,{once:!0})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:re})}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 ba({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let s=a;if(s.name==="AbortError")throw new _("UserInfrastructureError",`The page with URL ${Mt(i,50)} did not load within the configured timeout (${o}ms): ${s}`);if(!s.message.includes("detached"))throw s}try{await ba({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 w0.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 Qe({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:ge,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new _("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=ge){let i=await this.getActivePageOrFrame();return Qe({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=gn}){let i=TE(),a={code:e,fragment:t,context:n},{result:s}=await $(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new _("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return s}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:ge});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:re})}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 _("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:s}=await this.getViewportOffsetDetails(e),c=Math.round(a),l=Math.round(s),u=Math.ceil(o*t),d=Math.ceil(i*n),p=u+l,h=d+c;return this.getDomNodeFromPixelPosition(p,h)}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:re,params:{highlightConfig:BE,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:re,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:re})}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[Kr],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let s=e.locator(Er(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 l=await this.fetchHtmlAttributes({locator:s,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...l};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:s}}async performTargetRedirection(e,t,n){try{return await this.scrollIntoViewIfNeeded(e),await $(this.performTargetRedirectionHelper(e,t,n),{milliseconds:te})??{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:te})??void 0),!n){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:a,y:s,width:c,height:l}=n,u=this.getViewport();if(a<0||s<0||!u||a+c>u.width||s+l>u.height){t.info("Skipping locator redirection because the element is outside the viewport");return}let d=await this.getActivePageOrFrame(),{dataMomenticId:p,mPathSelector:h,error:m,serializedElement:g,foundElementRelativePoint:f,force:E,logs:S}=await e.evaluate(v=>{let A=window;if(!A.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return A.performTargetRedirection(v)},void 0,{timeout:re}),w=Date.now()-o;if(m){t.warn({error:m,serializedElement:g,duration:w,force:E,logs:S},"Got error from target redirection with bounding box");return}else{if(p)return t.info({newDataMomenticId:p,serializedElement:g,duration:w,force:E,logs:S},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(Er(p)),hints:{relativeXYToLocator:f,force:E}};if(h)return t.info({newMPathSelector:h,serializedElement:g,duration:w,force:E,logs:S},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(h),hints:{relativeXYToLocator:f,force:E}};if(f)return t.info({foundElementRelativePoint:f,serializedElement:g,duration:w,force:E,logs:S},"Chose specific visible point on original element"),{locator:e,hints:{relativeXYToLocator:f,force:E}};if(E)return t.info({serializedElement:g,duration:w,force:E,logs:S},"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,s=await e.evaluate((c,l)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,l):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:ge});if("error"in s&&s.error)throw s.error.startsWith(Qb)?new Os(s.error):s.error.startsWith(eE)?new Ls(s.error):new Error(s.error);return s.warnings.length&&t.warn(s,"Got warnings while generating HTML attributes for target"),s.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:re})}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),s=Math.ceil(i.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:s,x:n,y:o}}),{deltaX:a,deltaY:s}}canSolveCaptchas(){return!!Qo}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,dp(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()||x0(e),o=T0(e),i=_0(e),a=xd[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:R0.getType(e)||"application/octet-stream"},{timeout:Qd})}catch(l){this.logger.error({err:l},"Error handling file chooser"),this.logToUserConsole(this.page,"error",l.message)}});let s=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:l,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=l;let p=atob(l),h=new Array(p.length);for(let g=0;g<p.length;g++)h[g]=p.charCodeAt(g);let m=new Uint8Array(h);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([m],{type:u})}isSameEntry(g){return g.name===this.name}queryPermission(g){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(g){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let g=new Blob([m]);return new File([g],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:s,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??kp();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??nE}get userBrowserSettings(){return ri(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??Jd}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=Pl();for(let t of e)if(!(!Ul(t)||!uT(t).isDirectory()||!["new","pending","completed"].some(o=>{let i=M0(t,o);return Ul(i)&&uT(i).isDirectory()&&v0(i).length>0})))return t}};import SF from"fetch-cookie";import{cloneDeep as Uw}from"lodash-es";var Fl=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function I0(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 Bl(r,e){let t=I0(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var BT="=",jl=";",Kp=",";var zT=8192;var ai={};yx(ai,{getKeyPairs:()=>uk,parseKeyPairsIntoRecord:()=>dk,parsePairKeyValue:()=>HT,serializeKeyPairs:()=>ck});Ce();var lk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function ck(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Kp:"")+t;return n.length>zT?e:n},"")}function uk(r){return r.getAllEntries().map(function(e){var t=lk(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=jl+o.metadata.toString()),i})}function HT(r){var e=r.split(jl);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(BT);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Fp(e.join(jl))),{key:o,value:i,metadata:a}}}}}function dk(r){return typeof r!="string"||r.length===0?{}:r.split(Kp).map(function(e){return HT(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Ce();var Vl;(function(r){r.AlwaysOff="always_off",r.AlwaysOn="always_on",r.ParentBasedAlwaysOff="parentbased_always_off",r.ParentBasedAlwaysOn="parentbased_always_on",r.ParentBasedTraceIdRatio="parentbased_traceidratio",r.TraceIdRatio="traceidratio"})(Vl||(Vl={}));var pk=",",mk=["OTEL_SDK_DISABLED"];function hk(r){return mk.indexOf(r)>-1}var gk=["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 fk(r){return gk.indexOf(r)>-1}var Sk=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function yk(r){return Sk.indexOf(r)>-1}var Yp=1/0,Xp=128,bk=128,Ek=128,Jp={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:Ne.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Yp,OTEL_ATTRIBUTE_COUNT_LIMIT:Xp,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Yp,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Xp,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Yp,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Xp,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:bk,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:Ek,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Vl.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative"};function Tk(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function vk(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 Ak(r,e,t,n){n===void 0&&(n=pk);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var wk={ALL:Ne.ALL,VERBOSE:Ne.VERBOSE,DEBUG:Ne.DEBUG,INFO:Ne.INFO,WARN:Ne.WARN,ERROR:Ne.ERROR,NONE:Ne.NONE};function Rk(r,e,t){var n=t[r];if(typeof n=="string"){var o=wk[n.toUpperCase()];o!=null&&(e[r]=o)}}function GT(r){var e={};for(var t in Jp){var n=t;switch(n){case"OTEL_LOG_LEVEL":Rk(n,e,r);break;default:if(hk(n))Tk(n,e,r);else if(fk(n))vk(n,e,r);else if(yk(n))Ak(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function ht(){var r=GT(process.env);return Object.assign({},Jp,r)}function jT(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function $l(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=jT(r.charCodeAt(n)),i=jT(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var VT="1.25.1";var Ck="deployment.environment";var xk="process.runtime.name";var _k="service.name";var Mk="service.instance.id";var Pk="telemetry.sdk.name",Ik="telemetry.sdk.language",Ok="telemetry.sdk.version";var $T=Ck;var WT=xk;var Wl=_k;var qT=Mk;var Ia=Pk,Oa=Ik,La=Ok;var Lk="nodejs";var KT=Lk;var si,ql=(si={},si[Ia]="opentelemetry",si[WT]="node",si[Oa]=KT,si[La]=VT,si);var Nk=9,kk=6,Dk=Math.pow(10,kk),Uk=Math.pow(10,Nk);function YT(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*Dk);return[t,n]}function XT(r){return r[0]*Uk+r[1]}function Na(r){return r[0]*1e6+r[1]/1e3}var so;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(so||(so={}));var JT=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 Fk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Bk=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},ZT=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new JT}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,Bk([this._that],Fk(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 ir;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(ir||(ir={}));var Tt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Tt||(Tt={}));var zk=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 hme=function(r){zk(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function QT(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}Ce();var ar;(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"})(ar||(ar={}));var ev=function(){function r(){this.kind=ar.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 ae;(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"})(ae||(ae={}));var Hk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function Gk(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 Zp=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=Gk(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=QT(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 Qp=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=ar.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Zp(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new Zp(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new Zp(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Tt.HISTOGRAM,dataPoints:n.map(function(i){var a=Hk(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ae.GAUGE||e.type===ae.UP_DOWN_COUNTER||e.type===ae.OBSERVABLE_GAUGE||e.type===ae.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();Ce();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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},tm=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},rm=function(){function r(e,t,n,o){e===void 0&&(e=new jk),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var jk=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,tm([n,this._counts.length-t],em(this._counts.slice(t)),!1)),o.splice.apply(o,tm([0,t],em(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(tm([],em(this._counts),!1))},r}();var tv=52,Vk=2146435072,$k=1048575,nm=1023,Kl=-nm+1,Yl=nm,ka=Math.pow(2,-1022);function Xl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&Vk)>>20;return n-nm}function Jl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&$k)*Math.pow(2,32);return o+n}function Da(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function nv(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var Wk=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)}}(),wn=function(r){Wk(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var iv=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<ka)return this._minNormalLowerBoundaryIndex();var t=Xl(e),n=this._rightShift(Jl(e)-1,tv);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new wn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new wn("overflow: "+e+" is > maximum lower boundary: "+n);return Da(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=Kl>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Yl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var av=function(){function r(e){this._scale=e,this._scaleFactor=Da(Math.LOG2E,e),this._inverseFactor=Da(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=ka)return this._minNormalLowerBoundaryIndex()-1;if(Jl(e)===0){var t=Xl(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 wn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return ka;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new wn("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 Kl<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Yl+1<<this._scale)-1},r}();var sv=-10,lv=20,qk=Array.from({length:31},function(r,e){return e>10?new av(e-10):new iv(e-10)});function om(r){if(r>lv||r<sv)throw new wn("expected scale >= "+sv+" && <= "+lv+", got: "+r);return qk[r+10]}var Kk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Zl=function(){function r(e,t){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}(),Yk=20,Xk=160,im=2,Jk=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=Xk),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new rm),u===void 0&&(u=new rm),d===void 0&&(d=om(Yk)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<im&&(V.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+im),this._maxSize=im)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=nv(t);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=om(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Zl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Zl.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 Zl(0,-1);var o=t-n;return new Zl(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},r}();var cv=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=ar.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Jk(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:Tt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=Kk(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ae.GAUGE||e.type===ae.UP_DOWN_COUNTER||e.type===ae.OBSERVABLE_GAUGE||e.type===ae.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();var Zk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},am=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=YT(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var uv=function(){function r(){this.kind=ar.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new am(e)},r.prototype.merge=function(e,t){var n=Na(t.sampleTime)>=Na(e.sampleTime)?t:e;return new am(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Na(t.sampleTime)>=Na(e.sampleTime)?t:e;return new am(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Tt.GAUGE,dataPoints:n.map(function(i){var a=Zk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var Qk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ua=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 sm=function(){function r(e){this.monotonic=e,this.kind=ar.SUM}return r.prototype.createAccumulation=function(e){return new Ua(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ua(t.startTime,this.monotonic,o,t.reset):new Ua(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 Ua(t.startTime,this.monotonic,o,!0):new Ua(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Tt.SUM,dataPoints:n.map(function(i){var a=Qk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var lo=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Ur=function(){function r(){}return r.Drop=function(){return yv},r.Sum=function(){return bv},r.LastValue=function(){return Ev},r.Histogram=function(){return Tv},r.ExponentialHistogram=function(){return eD},r.Default=function(){return tD},r}();var dv=function(r){lo(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 ev,e}(Ur);var pv=function(r){lo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case ae.COUNTER:case ae.OBSERVABLE_COUNTER:case ae.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new sm(!0),e.NON_MONOTONIC_INSTANCE=new sm(!1),e}(Ur);var mv=function(r){lo(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 uv,e}(Ur);var hv=function(r){lo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Qp([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Ur);var gv=function(r){lo(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(s,c){return s-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Qp(this._boundaries,this._recordMinMax)},e}(Ur);var fv=function(r){lo(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 cv(this._maxSize,this._recordMinMax)},e}(Ur);var Sv=function(r){lo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case ae.COUNTER:case ae.UP_DOWN_COUNTER:case ae.OBSERVABLE_COUNTER:case ae.OBSERVABLE_UP_DOWN_COUNTER:return bv;case ae.GAUGE:case ae.OBSERVABLE_GAUGE:return Ev;case ae.HISTOGRAM:return t.advice.explicitBucketBoundaries?new gv(t.advice.explicitBucketBoundaries):Tv}return V.warn("Unable to recognize instrument type: "+t.type),yv},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Ur);var yv=new dv,bv=new pv,Ev=new mv,Tv=new hv,eD=new fv,tD=new Sv;Ce();function Ql(){return"unknown_service:"+process.argv0}var Rn=function(){return Rn=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},Rn.apply(this,arguments)},rD=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},nD=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},oD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},lm=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 V.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[Wl]=Ql(),e[Oa]=ql[Oa],e[Ia]=ql[Ia],e[La]=ql[La],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&V.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 rD(this,void 0,void 0,function(){return nD(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=Rn(Rn({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=oD(a,2),l=c[0],u=c[1];return Rn(Rn(Rn(Rn({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var co;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(co||(co={}));Ce();var iD=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},aD=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},cm=function(){return ir.CUMULATIVE},vv=function(r){switch(r){case ae.COUNTER:case ae.OBSERVABLE_COUNTER:case ae.GAUGE:case ae.HISTOGRAM:case ae.OBSERVABLE_GAUGE:return ir.DELTA;case ae.UP_DOWN_COUNTER:case ae.OBSERVABLE_UP_DOWN_COUNTER:return ir.CUMULATIVE}},Av=function(r){switch(r){case ae.COUNTER:case ae.HISTOGRAM:return ir.DELTA;case ae.GAUGE:case ae.UP_DOWN_COUNTER:case ae.OBSERVABLE_UP_DOWN_COUNTER:case ae.OBSERVABLE_COUNTER:case ae.OBSERVABLE_GAUGE:return ir.CUMULATIVE}};function sD(){var r=ht(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?cm:e==="delta"?vv:e==="lowmemory"?Av:(V.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."),cm)}function lD(r){return r!=null?r===co.DELTA?vv:r===co.LOWMEMORY?Av:cm:sD()}function cD(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Ur.Default()}}var wv=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=cD(t),this._aggregationTemporalitySelector=lD(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return iD(this,void 0,void 0,function(){return aD(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}();Ce();Ce();var uD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Rv=1e4,Cv=5,xv=1e3,_v=5e3,Mv=1.5;function Fa(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=uD(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):V.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function um(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function dm(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return V.warn("Could not parse export URL: '"+r+"'"),r}}function pm(r){return typeof r=="number"?r<=0?mm(r,Rv):r:dD()}function dD(){var r,e=Number((r=ht().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:ht().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?mm(e,Rv):e}function mm(r,e){return V.warn("Timeout must be greater than 0",r),e}function Pv(r){var e=[429,502,503,504];return e.includes(r)}function Iv(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 Ov=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 ZT(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=pm(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:so.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:so.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:so.SUCCESS})}).catch(function(n){t({code:so.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{V.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 V.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();Ce();import*as hm from"url";import*as tc from"http";import*as rc from"https";import*as Lv from"zlib";import{Readable as mD}from"stream";var Cn;(function(r){r.NONE="none",r.GZIP="gzip"})(Cn||(Cn={}));var pD=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),li=function(r){pD(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 ec=function(){return ec=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},ec.apply(this,arguments)};function gm(r,e,t,n,o){var i=r.timeoutMillis,a=new hm.URL(r.url),s=Number(process.versions.node.split(".")[0]),c,l,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,l.destroyed){var g=new li("Request Timeout");o(g)}else s>=14?l.destroy():l.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:ec({"Content-Type":t},r.headers),agent:r.agent},h=a.protocol==="http:"?tc.request:rc.request,m=function(g,f){switch(g===void 0&&(g=Cv),f===void 0&&(f=xv),l=h(p,function(S){var w="";S.on("data",function(v){return w+=v}),S.on("aborted",function(){if(u){var v=new li("Request Timeout");o(v)}}),S.on("end",function(){if(u===!1)if(S.statusCode&&S.statusCode<299)V.debug("statusCode: "+S.statusCode,w),n(),clearTimeout(d),clearTimeout(c);else if(S.statusCode&&Pv(S.statusCode)&&g>0){var v=void 0;f=Mv*f,S.headers["retry-after"]?v=Iv(S.headers["retry-after"]):v=Math.round(Math.random()*(_v-f)+f),c=setTimeout(function(){m(g-1,f)},v)}else{var A=new li(S.statusMessage,S.statusCode,w);o(A),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(S){if(u){var w=new li("Request Timeout",S.code);o(w)}else o(S);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var S=new li("Request Timeout");o(S)}clearTimeout(d),clearTimeout(c)}),r.compression){case Cn.GZIP:{l.setHeader("Content-Encoding","gzip");var E=hD(e);E.on("error",o).pipe(Lv.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};m()}function hD(r){var e=new mD;return e.push(r),e.push(null),e}function fm(r){if(r.httpAgentOptions&&r.keepAlive===!1){V.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new hm.URL(r.url),t=e.protocol==="http:"?tc.Agent:rc.Agent;return new t(ec({keepAlive:!0},r.httpAgentOptions))}catch(n){V.error("collector exporter failed to create http agent. err: "+n.message);return}}function Sm(r){if(r)return r;var e=ht().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||ht().OTEL_EXPORTER_OTLP_COMPRESSION;return e===Cn.GZIP?Cn.GZIP:Cn.NONE}Ce();var gD=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)}}(),nc=function(r){gD(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&&V.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Fa(t.headers),ai.parseKeyPairsIntoRecord(ht().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=fm(t),i.compression=Sm(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){V.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;gm(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,l)}).then(n,o);this._sendingPromises.push(a);var s=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(s,s)},e.prototype.onShutdown=function(){},e}(Ov);function kv(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function fD(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function Dv(r){var e=kv(r);return fD(e)}function SD(r){var e=kv(r);return e.toString()}var yD=typeof BigInt<"u"?SD:XT;function Nv(r){return r}function Uv(r){if(r!==void 0)return $l(r)}var bD={encodeHrTime:Dv,encodeSpanContext:$l,encodeOptionalSpanContext:Uv};function Fv(r){var e,t;if(r===void 0)return bD;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?Dv:yD,encodeSpanContext:o?Nv:$l,encodeOptionalSpanContext:o?Nv:Uv}}var ED=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function Bv(r){return{name:r.name,version:r.version}}function ci(r){return Object.keys(r).map(function(e){return zv(e,r[e])})}function zv(r,e){return{key:r,value:Hv(e)}}function Hv(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(Hv)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=ED(t,2),o=n[0],i=n[1];return zv(o,i)})}}:{}}function Gv(r){return{attributes:ci(r.attributes),droppedAttributesCount:0}}Ce();function Vv(r,e){var t=Fv(e);return{resource:Gv(r.resource),schemaUrl:void 0,scopeMetrics:TD(r.scopeMetrics,t)}}function TD(r,e){return Array.from(r.map(function(t){return{scope:Bv(t.scope),metrics:t.metrics.map(function(n){return vD(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function vD(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=CD(r.aggregationTemporality);switch(r.dataPointType){case Tt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:jv(r,e)};break;case Tt.GAUGE:t.gauge={dataPoints:jv(r,e)};break;case Tt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:wD(r,e)};break;case Tt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:RD(r,e)};break}return t}function AD(r,e,t){var n={attributes:ci(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case zt.INT:n.asInt=r.value;break;case zt.DOUBLE:n.asDouble=r.value;break}return n}function jv(r,e){return r.dataPoints.map(function(t){return AD(t,r.descriptor.valueType,e)})}function wD(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ci(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 RD(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ci(t.attributes),count:n.count,min:n.min,max:n.max,sum:n.sum,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},scale:n.scale,zeroCount:n.zeroCount,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function CD(r){switch(r){case ir.DELTA:return 1;case ir.CUMULATIVE:return 2}}function $v(r,e){return{resourceMetrics:r.map(function(t){return Vv(t,e)})}}var ym={serializeRequest:function(r){var e=$v(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 Wv="0.52.1";var qv=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)}}(),ui=function(){return ui=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},ui.apply(this,arguments)},Kv="v1/metrics",xD="http://localhost:4318/"+Kv,_D={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+Wv},MD=function(r){qv(e,r);function e(t){var n=r.call(this,t,ym,"application/json")||this;return n.headers=ui(ui(ui(ui({},n.headers),_D),ai.parseKeyPairsIntoRecord(ht().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Fa(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:ht().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?dm(ht().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):ht().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?um(ht().OTEL_EXPORTER_OTLP_ENDPOINT,Kv):xD},e}(nc),Yv=function(r){qv(e,r);function e(t){return r.call(this,new MD(t),t)||this}return e}(wv);var di;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(di||(di={}));var Fr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Fr||(Fr={}));Ce();var PD=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Xv=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Jv=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},ID=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},OD=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))},LD=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function Zv(r){return r!=null}function oc(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function Qv(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var bm=function(r){PD(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function xn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new bm("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function eA(r){return Xv(this,void 0,void 0,function(){var e=this;return Jv(this,function(t){return[2,Promise.all(r.map(function(n){return Xv(e,void 0,void 0,function(){var o,i;return Jv(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 tA(r){return r.status==="rejected"}function Em(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,OD([],ID(e(n)),!1))}),t}function rA(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=LD(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(s){t={error:s}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function nA(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 oA(r,e){return r.toLowerCase()===e.toLowerCase()}Ce();var sr;(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"})(sr||(sr={}));var Tm=function(){function r(){this.kind=sr.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}();Ce();var pe;(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"})(pe||(pe={}));function Br(r,e,t){var n,o,i,a;return kD(r)||V.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:zt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function iA(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 aA(r,e){return oA(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var ND=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function kD(r){return r.match(ND)!=null}var DD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function UD(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 ic=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=UD(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=nA(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 ac=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=sr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new ic(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new ic(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new ic(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Fr.HISTOGRAM,dataPoints:n.map(function(i){var a=DD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===pe.GAUGE||e.type===pe.UP_DOWN_COUNTER||e.type===pe.OBSERVABLE_GAUGE||e.type===pe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();Ce();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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Am=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))},wm=function(){function r(e,t,n,o){e===void 0&&(e=new FD),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var FD=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,Am([n,this._counts.length-t],vm(this._counts.slice(t)),!1)),o.splice.apply(o,Am([0,t],vm(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(Am([],vm(this._counts),!1))},r}();var sA=52,BD=2146435072,zD=1048575,Rm=1023,sc=-Rm+1,lc=Rm,Ba=Math.pow(2,-1022);function cc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&BD)>>20;return n-Rm}function uc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&zD)*Math.pow(2,32);return o+n}function za(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function cA(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var HD=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)}}(),_n=function(r){HD(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var dA=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ba)return this._minNormalLowerBoundaryIndex();var t=cc(e),n=this._rightShift(uc(e)-1,sA);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new _n("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new _n("overflow: "+e+" is > maximum lower boundary: "+n);return za(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=sc>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return lc>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var pA=function(){function r(e){this._scale=e,this._scaleFactor=za(Math.LOG2E,e),this._inverseFactor=za(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ba)return this._minNormalLowerBoundaryIndex()-1;if(uc(e)===0){var t=cc(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 _n("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ba;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new _n("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 sc<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(lc+1<<this._scale)-1},r}();var mA=-10,hA=20,GD=Array.from({length:31},function(r,e){return e>10?new pA(e-10):new dA(e-10)});function Cm(r){if(r>hA||r<mA)throw new _n("expected scale >= "+mA+" && <= "+hA+", got: "+r);return GD[r+10]}var jD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},dc=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}(),VD=20,$D=160,xm=2,gA=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=$D),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new wm),u===void 0&&(u=new wm),d===void 0&&(d=Cm(VD)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<xm&&(V.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+xm),this._maxSize=xm)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=cA(t);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Cm(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=dc.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=dc.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 dc(0,-1);var o=t-n;return new dc(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},r}();var _m=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=sr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new gA(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Fr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=jD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===pe.GAUGE||e.type===pe.UP_DOWN_COUNTER||e.type===pe.OBSERVABLE_GAUGE||e.type===pe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();Ce();var WD=Bp("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function fA(r){return r.setValue(WD,!0)}Ce();function SA(){return function(r){V.error(qD(r))}}function qD(r){return typeof r=="string"?r:JSON.stringify(KD(r))}function KD(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 YD=SA();function pc(r){try{YD(r)}catch{}}var yA="1.30.1";var XD="process.runtime.name";var JD="service.name";var ZD="telemetry.sdk.name",QD="telemetry.sdk.language",eU="telemetry.sdk.version";var bA=XD;var EA=JD;var Ha=ZD,Ga=QD,ja=eU;var tU="nodejs";var TA=tU;var pi,uo=(pi={},pi[Ha]="opentelemetry",pi[bA]="node",pi[Ga]=TA,pi[ja]=yA,pi);function Va(r){r.unref()}var lU=9,cU=6,uU=Math.pow(10,cU),yfe=Math.pow(10,lU);function po(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*uU);return[t,n]}function mi(r){return r[0]*1e6+r[1]/1e3}var $a;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})($a||($a={}));Ce();function vA(r,e){return new Promise(function(t){ii.with(fA(ii.active()),function(){r.export(e,function(n){t(n)})})})}var AA={_export:vA};var dU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},mc=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=po(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Mm=function(){function r(){this.kind=sr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new mc(e)},r.prototype.merge=function(e,t){var n=mi(t.sampleTime)>=mi(e.sampleTime)?t:e;return new mc(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=mi(t.sampleTime)>=mi(e.sampleTime)?t:e;return new mc(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Fr.GAUGE,dataPoints:n.map(function(i){var a=dU(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var pU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},hi=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 hc=function(){function r(e){this.monotonic=e,this.kind=sr.SUM}return r.prototype.createAccumulation=function(e){return new hi(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new hi(t.startTime,this.monotonic,o,t.reset):new hi(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 hi(t.startTime,this.monotonic,o,!0):new hi(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Fr.SUM,dataPoints:n.map(function(i){var a=pU(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var mo=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),lr=function(){function r(){}return r.Drop=function(){return PA},r.Sum=function(){return IA},r.LastValue=function(){return OA},r.Histogram=function(){return LA},r.ExponentialHistogram=function(){return mU},r.Default=function(){return hU},r}();var wA=function(r){mo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Tm,e}(lr);var RA=function(r){mo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case pe.COUNTER:case pe.OBSERVABLE_COUNTER:case pe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new hc(!0),e.NON_MONOTONIC_INSTANCE=new hc(!1),e}(lr);var CA=function(r){mo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Mm,e}(lr);var xA=function(r){mo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new ac([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(lr);var gc=function(r){mo(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(s,c){return s-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new ac(this._boundaries,this._recordMinMax)},e}(lr);var _A=function(r){mo(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new _m(this._maxSize,this._recordMinMax)},e}(lr);var MA=function(r){mo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case pe.COUNTER:case pe.UP_DOWN_COUNTER:case pe.OBSERVABLE_COUNTER:case pe.OBSERVABLE_UP_DOWN_COUNTER:return IA;case pe.GAUGE:case pe.OBSERVABLE_GAUGE:return OA;case pe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new gc(t.advice.explicitBucketBoundaries):LA}return V.warn("Unable to recognize instrument type: "+t.type),PA},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(lr);var PA=new wA,IA=new RA,OA=new CA,LA=new xA,mU=new _A,hU=new MA;var NA=function(r){return lr.Default()},kA=function(r){return di.CUMULATIVE};var Pm=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},DA=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},gU=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))},UA=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:NA,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:kA,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 Pm(this,void 0,void 0,function(){var t,n,o,i,a,s;return Im(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(gU([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],DA(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=DA.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Em(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(Em(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return Pm(this,void 0,void 0,function(){return Im(this,function(t){switch(t.label){case 0:return this._shutdown?(V.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,xn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return Pm(this,void 0,void 0,function(){return Im(this,function(t){switch(t.label){case 0:return this._shutdown?(V.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,xn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Ce();var fU=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)}}(),fc=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Sc=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},SU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},yU=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))},Om=function(r){fU(e,r);function e(t){var n,o,i,a,s=r.call(this,{aggregationSelector:(n=t.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(t.exporter),aggregationTemporalitySelector:(o=t.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(t.exporter),metricProducers:t.metricProducers})||this;if(t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<t.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return s._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,s._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,s._exporter=t.exporter,s}return e.prototype._runOnce=function(){return fc(this,void 0,void 0,function(){var t;return Sc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,xn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof bm?(V.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(pc(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return fc(this,void 0,void 0,function(){var o,i,a,s,c,l;return Sc(this,function(u){switch(u.label){case 0:return[4,this.collect({timeoutMillis:this._exportTimeout})];case 1:if(o=u.sent(),i=o.resourceMetrics,a=o.errors,a.length>0&&(l=V).error.apply(l,yU(["PeriodicExportingMetricReader: metrics collection errors"],SU(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(t=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(t)];case 3:return u.sent(),[3,5];case 4:return s=u.sent(),V.debug("Error while resolving async portion of resource: ",s),pc(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,AA._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==$a.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),Va(this._interval)},e.prototype.onForceFlush=function(){return fc(this,void 0,void 0,function(){return Sc(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 fc(this,void 0,void 0,function(){return Sc(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}(UA);Ce();Ce();function yc(){return"unknown_service:"+process.argv0}var Mn=function(){return Mn=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},Mn.apply(this,arguments)},bU=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},EU=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},bc=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 V.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[EA]=yc(),e[Ga]=uo[Ga],e[Ha]=uo[Ha],e[ja]=uo[ja],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&V.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 bU(this,void 0,void 0,function(){return EU(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=Mn(Mn({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=TU(a,2),l=c[0],u=c[1];return Mn(Mn(Mn(Mn({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var FA=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}();Ce();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)}}(),Ec=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=ii.active()),typeof e!="number"){V.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===zt.INT&&!Number.isInteger(e)&&(V.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,po(Date.now()))},r}();var BA=function(r){ho(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}(Ec);var zA=function(r){ho(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){V.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Ec);var HA=function(r){ho(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}(Ec);var GA=function(r){ho(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){V.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Ec);var Tc=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 jA=function(r){ho(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Tc);var VA=function(r){ho(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Tc);var $A=function(r){ho(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Tc);function Wa(r){return r instanceof Tc}var WA=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=Br(e,pe.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new HA(o,n)},r.prototype.createHistogram=function(e,t){var n=Br(e,pe.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new GA(o,n)},r.prototype.createCounter=function(e,t){var n=Br(e,pe.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new zA(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Br(e,pe.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new BA(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Br(e,pe.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new VA(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=Br(e,pe.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new jA(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=Br(e,pe.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new $A(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 vc=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=Br(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var vU=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)}}(),qA=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},AU=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 qA(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 qA(this,function(n){switch(n.label){case 0:e=this._valueMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[this._keyMap.get(t.value[0]),t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},Object.defineProperty(r.prototype,"size",{get:function(){return this._valueMap.size},enumerable:!1,configurable:!0}),r}();var Tr=function(r){vU(e,r);function e(){return r.call(this,oc)||this}return e}(AU);var wU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ac=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Tr,this._cumulativeMemoStorage=new Tr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=oc(this._overflowAttributes)}return r.prototype.record=function(e,t,n,o){var i=this,a=this._activeCollectionStorage.get(t);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var s=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});s?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(t,a)}a?.record(e)},r.prototype.batchCumulate=function(e,t){var n=this;Array.from(e.entries()).forEach(function(o){var i=wU(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(t);l?.record(s);var u=l;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,l,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new Tr,e},r}();var Lm=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.")},KA=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},wc=function(){function r(e,t){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,t.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return r.prototype.buildMetrics=function(e,t,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,s;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),l=c.collectionTime;s=c.aggregationTemporality,s===di.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,l)}else s=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:s});var u=RU(a);if(u.length!==0)return this._aggregator.toMetricData(t,s,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=Lm(o),a=i.next();!a.done;a=i.next()){var s=a.value,c=this._unreportedAccumulations.get(s);c===void 0&&(c=[],this._unreportedAccumulations.set(s,c)),c.push(e)}}catch(l){t={error:l}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}},r.prototype._getMergedUnreportedAccumulations=function(e){var t,n,o=new Tr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Lm(i),s=a.next();!s.done;s=a.next()){var c=s.value;o=r.merge(o,c,this._aggregator)}}catch(l){t={error:l}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return o},r.merge=function(e,t,n){for(var o=e,i=t.entries(),a=i.next();a.done!==!0;){var s=KA(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,l);o.set(c,p,u)}else o.set(c,l,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=Lm(e.keys()),s=a.next();!s.done;s=a.next()){var c=KA(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function RU(r){return Array.from(r.entries())}var CU=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)}}(),xU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},YA=function(r){CU(e,r);function e(t,n,o,i,a){var s=r.call(this,t)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Ac(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new wc(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new Tr;Array.from(t.entries()).forEach(function(a){var s=xU(a,2),c=s[0],l=s[1];i.set(o._attributesProcessor.process(c),l)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(vc);Ce();function Nm(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
3953
4007
|
`),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
|
|
3954
4008
|
`),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
|
|
3955
4009
|
`),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
|
|
3956
|
-
`),t}function
|
|
4010
|
+
`),t}function _U(r,e){return" - use valueType '"+r.valueType+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function MU(r,e){return" - use unit '"+r.unit+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function PU(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 IU(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+`'
|
|
3957
4011
|
- OR - create a new view with the name `+r.name+" and description '"+r.description+"' and InstrumentSelector "+n+`
|
|
3958
|
-
- OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function
|
|
4012
|
+
- OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function km(r,e){return r.valueType!==e.valueType?_U(r,e):r.unit!==e.unit?MU(r,e):r.type!==e.type?PU(r,e):r.description!==e.description?IU(r,e):""}var Dm=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.")},XA=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 s=Dm(this._sharedRegistry.values()),c=s.next();!c.done;c=s.next()){var l=c.value;a=a.concat(l)}}catch(h){t={error:h}}finally{try{c&&!c.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}var u=this._perCollectorRegistry.get(e);if(u!=null)try{for(var d=Dm(u.values()),p=d.next();!p.done;p=d.next()){var l=p.value;a=a.concat(l)}}catch(h){o={error:h}}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=Dm(t),s=a.next();!s.done;s=a.next()){var c=s.value,l=c.getInstrumentDescriptor();aA(l,e)?(l.description!==e.description&&(e.description.length>l.description.length&&c.updateDescription(e.description),V.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.
|
|
3959
4013
|
`,`Details:
|
|
3960
|
-
`,
|
|
3961
|
-
To resolve the conflict:`,
|
|
4014
|
+
`,Nm(l,e),`The longer description will be used.
|
|
4015
|
+
To resolve the conflict:`,km(l,e))),i=c):V.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
|
|
3962
4016
|
`,`Details:
|
|
3963
|
-
`,
|
|
3964
|
-
`,um(l,e))}}catch(u){n={error:u}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var Vv=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}();ve();ve();var $v=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new mr}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){j.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===Nt.INT&&!Number.isInteger(e)&&(j.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 Wv=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!Ia(e)){var o=this._buffer.get(e);if(o==null&&(o=new mr,this._buffer.set(e,o)),typeof t!="number"){j.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===Nt.INT&&!Number.isInteger(t)&&(j.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 pm=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},mm=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},qv=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Kv=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))},Yv=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(Ia));if(n.size===0){j.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(Ia)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return pm(this,void 0,void 0,function(){var n,o,i,a;return mm(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,qT(Kv(Kv([],qv(n),!1),qv(o),!1))];case 1:return i=s.sent(),a=i.filter(KT).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 pm(n,void 0,void 0,function(){var s,c;return mm(this,function(l){switch(l.label){case 0:return s=new $v(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(s)),t!=null&&(c=bn(c,t)),[4,c];case 1:return l.sent(),a._metricStorages.forEach(function(u){u.record(s._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 pm(n,void 0,void 0,function(){var s,c;return mm(this,function(l){switch(l.label){case 0:return s=new Wv,c=Promise.resolve(i(s)),t!=null&&(c=bn(c,t)),[4,c];case 1:return l.sent(),a.forEach(function(u){var d=s._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&&YT(n.instruments,t)})},r}();var Xk=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)}}(),Xv=function(r){Xk(e,r);function e(t,n,o,i,a){var s=r.call(this,t)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new sc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new lc(n,i),s}return e.prototype.record=function(t,n,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}(ac);var Jv=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)}}(),ii=function(){function r(){}return r.Noop=function(){return Zk},r}();var Jk=function(r){Jv(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(ii);var Zv=function(r){Jv(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}(ii);var Zk=new Jk;var Qk=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},eD=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Qv=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new jv,this.observableRegistry=new Yv,this.meter=new Bv(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,Xv);return t.length===1?t[0]:new Vv(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,Gv);return t},r.prototype.collect=function(e,t,n){return Qk(this,void 0,void 0,function(){var o,i,a;return eD(this,function(s){switch(s.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=s.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,t)}).filter($T),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 l=ZT(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(l);if(u!=null)return u;var d=c.aggregation.createAggregator(l),p=new t(l,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),s=a.map(function(c){var l=tD(c,2),u=l[0],d=l[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,ii.Noop(),[u],m);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(s)}return i},r}();var rD=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.")},eA=function(){function r(e){this.resource=e,this.viewRegistry=new Iv,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=WT(e),n=this.meterSharedStates.get(t);return n==null&&(n=new Qv(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=rD(this.metricCollectors),a=i.next();!a.done;a=i.next()){var s=a.value;o.push([s,s.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 cc=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},uc=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},nD=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},oD=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))},tA=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return cc(this,void 0,void 0,function(){var t,n,o,i,a=this;return uc(this,function(s){switch(s.label){case 0:return t=ro(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return cc(a,void 0,void 0,function(){var l;return uc(this,function(u){switch(u.label){case 0:return[4,c.collect(this,t,e)];case 1:return l=u.sent(),l?.scopeMetrics!=null&&n.push(l.scopeMetrics),l?.errors!=null&&o.push.apply(o,oD([],nD(l.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return s.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return cc(this,void 0,void 0,function(){return uc(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 cc(this,void 0,void 0,function(){return uc(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 rA=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},nA=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},oA=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 iD(r,e){var t=e??nc.empty();return r?nc.default().merge(t):t}var gm=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new eA(iD((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=oA(e.views),c=s.next();!c.done;c=s.next()){var l=c.value;this._sharedState.viewRegistry.addView(l)}}catch(g){t={error:g}}finally{try{c&&!c.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=oA(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?(j.warn("A shutdown MeterProvider cannot provide a Meter"),bp()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new tA(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return rA(this,void 0,void 0,function(){return nA(this,function(t){switch(t.label){case 0:return this._shutdown?(j.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 rA(this,void 0,void 0,function(){return nA(this,function(t){switch(t.label){case 0:return this._shutdown?(j.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 aD=/[\^$\\.+?()[\]{}|]/g,dc=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(aD,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var ai=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 iA=function(){function r(e){var t;this._nameFilter=new dc((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new ai(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 aA=function(){function r(e){this._nameFilter=new ai(e?.name),this._versionFilter=new ai(e?.version),this._schemaUrlFilter=new ai(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 sD(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var hm=function(){function r(e){var t;if(sD(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||dc.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 Zv(e.attributeKeys):this.attributesProcessor=ii.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:rr.Default(),this.instrumentSelector=new iA({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new aA({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var Kme=process.env.APP||"unknown";ve();import{v4 as lD}from"uuid";function cD(){return new GT({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:eo.DELTA})}var uD=[new hm({instrumentName:"test_operation_duration_ms",instrumentType:le.HISTOGRAM,aggregation:new Ql([100,500,1e3,5e3,1e4,2e4])})],pc=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 Up({[Pl]:e.serviceName,[FE]:t,[zE]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:lD()}),o=cD(),i=new sm({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new gm({resource:n,readers:[i],views:uD}),Cl.setGlobalMeterProvider(this.provider),this.meter=Cl.getMeter("momentic-serverless")}increment(e,t,n){try{let o=Al(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=Al(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 kt=new vl;function sA(r){r.disabled||(kt=new pc(r))}import{CookieJar as DD}from"tough-cookie";async function Ir({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 dD=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function lA({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(dD.includes(n.type))return;let s=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),l=0;for(;l===0||Date.now()-c<s;){await Q(250),l++;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(qn(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}}}}async function vn(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(e.serializationOpts),tree:t}}var io=3.1783027;function pD(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 jr(r){return Math.ceil(fm(r)/io)}function fm(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
|
|
3965
|
-
|
|
3966
|
-
`),
|
|
3967
|
-
`),tokenLength:d}),
|
|
3968
|
-
|
|
3969
|
-
${r}`;case"ELEMENT_CHECK":return`${fA}
|
|
3970
|
-
${r}`;default:return r}}var CD=15;async function hc({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=CD}){if(!r.assertion.trim())throw new _("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=al(c),u=0,d=Date.now(),p,g,m;try{await Ir({action:()=>s.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:s,logger:t})}catch(f){t.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;u<a&&(!h||h-d<c);){n.abortSignal.throwIfAborted(),u!==0&&await Q(l,n.abortSignal),h=Date.now();try{if(p=await Ir({action:async()=>{let E=await yA(s,t,n.abortSignal);return g&&g.serializedTree===E.serializedTree&&g.screenshotBuff.equals(E.screenshotBuff)?p:(g=E,bA({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:s}),p?.updatedMemory&&rl(r,p.updatedMemory,t),p?.success)break;throw p?.thoughts?new _("AssertionFailureError",p.thoughts):new _("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 Ir({action:async()=>bA({command:r,state:await yA(s,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:s})}catch(f){n.abortSignal.throwIfAborted(),m=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw m&&(f+=` Latest result: ${m.message}`),new _("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:s.url()}}async function yA(r,e,t){let[n,o]=await Promise.all([vn(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function bA({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:p}=t,g={type:"ASSERTION"},{serializedTree:m,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),S=u.url(),R=r.contextChoice??"MULTIMODAL",A=m;R!=="VISION_ONLY"&&(A=await ao({type:"assertion",serializedTree:m,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:l,orgId:t.orgId}}),A!==m&&(g.ragUsed=!0),g.pageState=A);let v={goal:r.assertion,url:S,memory:o?r.cache?.memory:void 0,browserState:A,screenshot:E,contextChoice:R,source:c},C=await(R==="VISION_ONLY"?(w,F)=>d.getVisualAssertionResult(w,F):(w,F)=>d.getAssertionResult(w,F))(v,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:l,loggerTags:ye(l)});return(C.result||i)&&C.relevantElements&&(g.relevantElementsSerialized=C.relevantElements.map(w=>u.getSerializedFormFromA11yId(w)).filter(w=>!!w),await xD(C.relevantElements,u,l)),{success:C.result,thoughts:C.thoughts,afterScreenshotOverride:f,updatedMemory:o?C.updatedMemory:void 0}}async function xD(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 V(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 TA}from"lodash-es";async function vA(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=qg(e.cache)?e.cache:void 0,a=TA(i),s=()=>{if(i){let g=oy(a,i);i.target=g.target,i.updatedAt=g.updatedAt}},c=Date.now(),l=0,u,d=500,p=!1;for(;l<2||Date.now()-c<t;){l++,l>1&&await Q(d,o),o?.throwIfAborted();let{result:g,elementWasFound:m}=await EA({cacheToUse:i,params:r});if(u=g,p=m,g.success)break;s(),d=Math.min(d*2,1e4)}if(!u)throw new _("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!u.success&&i?.target&&ss(i.target)){let g=i?.target?.memory?{target:{id:-1,memory:i.target.memory}}:void 0,{result:m}=await EA({cacheToUse:g,params:r});u=m,u.success||s()}return u.success&&i?.target&&!p&&(i.target=vd(i.target),i.updatedAt=new Date),u}async function EA({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!Jr(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=MD(t.assertion),l,u=!1,d=TA(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=>_D(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:Bi(t),targetName:"target"}});return l={success:g.success,data:g.data,err:g.err,elementInteractedDisplayString:p,thoughts:m},u=!0,g.success||(s.warn({aiThoughts:m,elementString:p,err:g.err},"Element check found an element but failed"),l={...g,thoughts:m}),{result:l,elementWasFound:u}}catch(p){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(p instanceof _)||p.reason!="ActionFailureError")throw p;return l={success:!1,err:p,data:void 0,thoughts:void 0},s.warn({err:p},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function _D(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:At(c,500,!0)},!fc(c,n.value,n.operation,!!n.negated)){let l=n.negated?jn[n.operation]:Vn[n.operation];o=!1,i=new _("AssertionFailureError",`The content ${l} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:At(await r.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(l){i=new _("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${l}`),o=!1;break}if(!fc(c,n.value,n.operation,!!n.negated)){let l=n.negated?jn[n.operation]:Vn[n.operation];o=!1,n.operation==="EXISTS"?i=new _("AssertionFailureError",`The attribute ${n.attr} ${l}`):i=new _("AssertionFailureError",`The attribute ${n.attr} ${l} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(l,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(g=>setTimeout(g,250));let p=l.getBoundingClientRect();if(!(p.width===0||p.height===0)&&window.getComputedStyle(l).visibility!=="hidden"&&window.getComputedStyle(l).display!=="none")return!0}return!1},Qr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:Qr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:Qr*1e3});break}case"FOCUSED":{o=await r.evaluate(l=>l===document.activeElement);break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?iy[n.condition]:ay[n.condition];i=new _("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(l=>l.tagName);if(!fc(c,n.value,n.operation,!!n.negated)){let l=n.negated?jn[n.operation]:Vn[n.operation];o=!1,i=new _("AssertionFailureError",`The element tag name ${l} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((l,u)=>window.getComputedStyle(l).getPropertyValue(u),n.property);if(!fc(c,n.value,n.operation,!!n.negated)){let l=n.negated?jn[n.operation]:Vn[n.operation];o=!1,n.operation==="EXISTS"?i=new _("AssertionFailureError",`The style property ${n.property} ${l}`):i=new _("AssertionFailureError",`The style property ${n.property} ${l} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function fc(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 MD(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function AA(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as PD}from"jimp";async function Oa(r,e){let t=await r.screenshot(e),n=await PD.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as wA}from"jimp";import bm from"jpeg-js";import ID from"pixelmatch";async function RA({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!Jr(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let c={clearHighlights:!0,hideCaret:!0},l;t.target?.elementDescriptor?l=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async k=>Oa(o,{locator:k.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await Oa(o,c);let u=await s.prepareGoldenScreenshotForComparison(a,t,l);if((l.height!==u.height||l.width!==u.width)&&a.warn({currHeight:l.height,currWidth:l.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-u.height)>10||Math.abs(l.width-u.width)>10){let D=`${l.width}x${l.height}`,k=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${D}) does not match saved screenshot dimensions (${k}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await wA.fromBuffer(l.buffer),p={width:l.width,height:l.height},g=await wA.fromBuffer(u.buffer),m={width:u.width,height:u.height},h,f=p.width*p.height,E=m.width*m.height,S=Math.abs(p.height-m.height),R=Math.abs(p.width-m.width);if(f>E){let D=d.cover({w:m.width,h:m.height});l.buffer=await D.getBuffer("image/jpeg"),h="current",l.width=m.width,l.height=m.height}else if(E>f){let D=g.cover({w:p.width,h:p.height});u.buffer=await D.getBuffer("image/jpeg"),h="saved"}let A={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},v=t.threshold??.1,C=ID(bm.decode(u.buffer).data,bm.decode(l.buffer).data,A.data,l.width,l.height,{threshold:v,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,w=C>v*100,F=`Visual diff of ${C.toFixed(2)}% detected, which is ${w?"over":"under"} the threshold of ${v*100}%.`;if(h&&(F+=` The ${h} screenshot was cropped since it was taller by ${S} pixels and wider by ${R} pixels.`),w)throw new _("ActionFailureError",F);return{fail:w,thoughts:F,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:bm.encode(A,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var OD=3e4;async function Sc({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??OD/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([g,m])=>g&&m)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([g,m])=>g&&m).forEach(([g,m])=>{a.append(g,m)});let s=a.toString(),c;if(zo(r.url)&&(c=r.url),t&&Ho(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new _("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:s,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await V((async()=>{let g=s?`${c}?${s}`: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 _("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 _("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 LD=5e3;async function _A({timeout:r=Qr,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,s=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let c=Date.now();i=await CA(e),a=Date.now();let l=a-c;if(l>1e3&&e.logger.warn({pageAssertDuration:l},"Page assertion took longer than expected"),!i.success)await Q(s,e.signal),s=Math.min(Math.floor(s*1.5),LD);else return i}return i=await CA(e),i}async function CA({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let s;if(t){let c=await e.evaluateFunctionInAllFrames(xA,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(l=>l.evaluation):c.some(l=>l.evaluation),s=c.find(l=>l.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(xA,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?jn.CONTAINS:Vn.CONTAINS;a=new _("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new _("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function xA({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 ND=3e4;async function MA({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??ND/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(zo(r.url)&&(s=r.url),t&&Ho(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new _("ActionFailureError",`Invalid URL: ${r.url}`);let l=await V((async()=>{try{return await n(s,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables?JSON.parse(r.variables):void 0}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!l)throw new _("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,p=await l.text();try{d=JSON.parse(p)}catch{throw new _("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new _("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new _("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}let u={};return l.headers.forEach((d,p)=>{u[p]=d}),{status:l.status,headers:u,json:await l.json()}}var yc=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:s,visualDiffScreenshotStorage:c,options:l}){this.orgId=i,this.options=l,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=s,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=a,this.generator=t,this.logger=n}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[c,l]=await Promise.all([vn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${l.toString("base64")}`,d=await ao({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...ye(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let c=this.browser.url(),[l,u]=await Promise.all([vn(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 ao({type:"ai-action",description:e,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),g={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(g,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...ye(a)},langfuseSessionId:s})}catch(m){throw new _("InternalWebAgentError",`Error generating command: ${m instanceof Error?m.message:m}`,{errOptions:{cause:m}})}}async getBrowserState(e){return vn(this.browser,e)}async locateElement(e){return await ym({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return Ir({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:s,options:c,retriesWithAI:l=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],g=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async m=>m,options:{...c,targetName:o[d]}});u.push(g)}try{let d=await s(...u.map(m=>m.result)),p=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",g=u.map((m,h)=>m.thoughts?`${p(o[h])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(m=>m.elementInteractedDisplayString),thoughts:g}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:c,retriesWithAI:l-1});throw new _("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 Ir({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&&ed(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(rd(i)||td(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(nd(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Er&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof _?n:new _("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:s}=o;if(t.type!=="description")throw new _("ActionFailureError","Cannot use selector with non-description target");let c,l=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){l=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:s,logger:a});return{result:await n({locator:d.locator}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;c=d,a.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await Q(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:s,command:c}=e,{disableCache:l,useSelector:u,targetName:d,targetHealingInProgress:p,source:g}=s,m=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,S=PA(e.cache);if((!S||l)&&!au(o))throw new _("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(m.info("Cache explicitly disabled for this step"),E=!0,S=void 0),S&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&S.targetSource==="HEURISTIC_HEALED"&&(E=!0,S=void 0),S?.inputDescription&&!SA(o.elementDescriptor,S.inputDescription)&&(m.warn({old:S.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,S=void 0);let R=v=>!!v&&ss(v),A=!0;if(!R(S)){A=!1,m.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),E&&await Q(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let v;try{v=await ym({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:g,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:m},this.getControllerFixtures(t))}catch(w){if(w instanceof Uo&&w.updatedLocatorMemory){let F={id:-1,...i,memory:w.updatedLocatorMemory};tl({cmd:c,key:d,newTarget:F,logger:m,updatedWithAI:!0})}throw new _("ActionFailureError",w.message)}v.frameConfig&&this.browser.setActiveFrameConfig(v.frameConfig);let P=s.disableGlobalLocatorRedirect?{locator:v.resolution.locator}:await this.attemptLocatorRedirect(v.resolution.locator,m),C=await a(P);return tl({cmd:c,key:d,newTarget:v.target,logger:m,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),v.target.targetSource="AI_HEALED",v.target.targetUpdateTime=new Date().toUTCString(),v.target.targetUpdateLoggerTags=ye(m)),{result:C,elementInteractedDisplayString:v.resolution.displayString,thoughts:v.thoughts}}try{let v=await this.browser.resolveTarget(t,S,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:m,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(v.locator);let P=s.disableGlobalLocatorRedirect?{locator:v.locator}:await this.attemptLocatorRedirect(v.locator,m),C=await a(P);if(kt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`,`orgId:${this.orgId}`]),tl({cmd:c,key:d,newTarget:S,logger:m,updatedWithAI:!1}),A){let w=v.decisions.filter(F=>F.matched);if(w.length!==1)m.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let F=w[0].type;n.recordTargetAutoHeal({healType:F})}}return{result:C,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed(),kt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`,`orgId:${this.orgId}`]);let P=!1;if((v instanceof Er||ed(v)||rd(v)||nd(v)||Pf(v)||td(v))&&(P=!0),v instanceof _&&!P)throw m.error({err:v},"Failed to execute action with cached target (fatal)"),v;if(f>0&&o){m.info({err:v},"Failed to execute action with cached target, retrying with AI");let C;return S.memory&&zg(S.memory)&&(C=S.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:C,retriesWithAI:f,targetHealingInProgress:!0}})}throw new _("ActionFailureError",v.message,{errOptions:{cause:v}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return Oa(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await Q(this.options.slowMoMs);let a=await this.browser.getOpenPages(),s=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(l){throw this.throwIfClosed(),new _("ActionFailureError",`Failed to substitute template strings in command: ${l.message}`,{errOptions:{cause:l}})}try{let l=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&Jg(n)?await this.browser.waitForDOMStability({timeout:ue}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:ee}),this.options?.autoFollowNewTabs&&await lA({beforeUrl:s,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),l}catch(l){throw l.name!=="AbortError"&&this.logger.error({err:l},"Error thrown in action controller"),l}finally{el(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Fd(e)}}async resolveCommandTemplateStrings(e,t){return Qs({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,n,o,i){i=i||"disableCache"in n&&!!n.disableCache;let a=this.logger.child({commandId:n.id});switch(n.type){case"SUCCESS":let s=n.condition;return s?.assertion.trim()?hc({command:s,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!n.assertion.trim())throw new _("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new _("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return hc({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new _("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=DS(n.schema);if(f)throw new _("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:ye(a)});if(f.result==="NOT_FOUND")throw new _("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new _("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 _("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 _("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(!zo(n.url)&&!Ho(n.url,this.browser.baseUrl))throw new _("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&&Sr(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:S,thoughts:R}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:A=>this.browser.hover(A),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});m=S,h=R}let f=this.browser.getViewport()?.height??rn.height,E=this.browser.getViewport()?.width??rn.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 _("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 _("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await Q(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Sr(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:R=>this.browser.click(R,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),S={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:E,data:f.downloadedFile?{downloadedFile:f.downloadedFile}:void 0};return ll(m,S.urlAfterCommand)&&(S.succeedImmediately=!0,S.succeedImmediatelyReason="URL changed"),S}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(Sr(n.fromTarget)&&Sr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Sr(n.fromTarget)||Sr(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 _("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Sr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(m,h,f,n.target.pixels,{force:n.force});break}let E,S,R;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:A,result:v,thoughts:P}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async C=>C.locator,options:{disableCache:i,targetName:"target",...n}});E=v,S=A,R=P}return await this.browser.mouseDrag(m,h,f,E,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:S,thoughts:R}}case"SELECT_OPTION":{if(!Jr(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:S=>this.browser.selectOption(S,h,n.force),options:{...n,targetName:"target",disableCache:i,source:Bi(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 Ar({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 _("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(m)}catch(h){throw new _("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&&Sr(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=PA(n.target);if(E){let{elementInteractedDisplayString:R,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:v=>this.browser.typeIntoTarget(n.value,v,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!0,source:Bi(n)}});h=R,f=A}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let S={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return ll(m,S.urlAfterCommand)&&(S.succeedImmediately=!0,S.succeedImmediatelyReason="URL changed"),S}case"HOVER":{if(Sr(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(!Jr(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&&!Jr(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 ll(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 DD,h=kD(fetch,m),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await Sc({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:Ms(m,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await MA({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return RA({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 rb({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 _("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 Ar({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof m!="object")throw new _("ActionFailureError",`Credentials must evaluate to an object (received ${typeof m} instead)`);let h;try{h=af.optional().parse(m)}catch(f){throw new _("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let m=(n.timeout??Qr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(AA(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 S=await hc({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: ${S.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:S.afterScreenshotOverride}}finally{E.cache?.memory&&rl(n,E.cache?.memory.traces,a)}}let f=await vA({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 Ir({action:async()=>_A({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 gn(n.requestMatcher),h=this.browser.registerRequestListener(m);return this.registeredListeners[n.key]=h.then(async f=>await Vd(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 _("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await V(m,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let m=new gn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,m,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=ml(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=ml(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let m=this.recordedRequests[n.key];if(!m)throw new _("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 gn(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 gn(n.requestMatcher),async(h,f)=>{let E=await Ar({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"}),S=Ef.parse(E);return new Response(S.body,{status:S.status,headers:S.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:ye(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 bl({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:ye(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ye(this.logger)})}};import{mkdirSync as iU}from"fs";import{tmpdir as aU}from"os";import VA from"path";import{cloneDeep as UD}from"lodash-es";import kA from"truncate-json";var IA=1e3,OA=5e6,FD=5*1024*1024;function DA(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=kA(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":LA(n);break;case"MOBILE_MODULE_STEP":LA(n),DA(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 LA(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function NA(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 bc(r,e){let t=UD(r);if(DA(t,e),t.length>IA)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,IA);let n=NA(t,e);if(n.length>OA)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>OA;)t.pop(),n=NA(t,e);let{jsonString:o}=kA(n,FD);try{return dr.array().parse(JSON.parse(o))}catch(i){throw e.error({serialized:n,err:i},"Could not parse serialized results into JSON structure after processing"),i}}import{AsyncLocalStorage as BD}from"async_hooks";var La=new BD;function zD(r){La.enterWith({activeTracers:[r]})}function HD(r,e){let t=La.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function GD(r,e){let t=La.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return La.run({activeTracers:n},e)}var An={globalAls:La,initializeRootTracerContext:zD,withChildTracer:HD,withChildTracerAsync:GD};var so=class r{spans;parentSection;finished=!1;startTime;endTime;constructor(e){this.startTime=e?.startTime??Date.now(),this.spans=e?.subSpans??[],this.parentSection=e}startSection(e,t){let n={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},o=new r(n);try{return An.withChildTracer(o,()=>t(o,n))}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}finally{o.finish(),this.addSpan(n)}}async startAsyncSection(e,t){let n={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},o=new r(n);this.addSpan(n);try{return await An.withChildTracerAsync(o,()=>t(o,n))}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}finally{o.finish()}}finish(){if(!this.finished){this.endTime=Date.now();for(let e of this.spans)e.endTime||(e.endTime=this.endTime,e.durationMs=e.endTime-e.startTime);this.parentSection&&(this.parentSection.endTime=this.endTime,this.parentSection.durationMs=this.parentSection.endTime-this.parentSection.startTime),this.finished=!0}}addSpan(e){this.spans.push(e)}startSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{a=t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}async startAsyncSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{a=await t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:"root step span",startTime:this.startTime,endTime:this.endTime,subSpans:this.spans,attributes:{},durationMs:this.endTime?this.endTime-this.startTime:void 0}}};function ot(){let r=An.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new so}import{diff as nU}from"deep-object-diff";import{cloneDeep as oU}from"lodash-es";import BA from"fontoxpath";import jD from"@prettier/plugin-xml";import VD from"prettier";import{DOMParser as $D,XMLSerializer as WD}from"slimdom";function Em(r){return r.toLowerCase().endsWith("webview")}function qD(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 KD=new Set(["index","package","a11y-important","screen-reader-focusabl"]),YD=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","multiline","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),XD=new Set(["text","hint"]),JD=new Set(["live-region","drawing-order"]),ZD=new Set(["displayed","enabled"]);function QD(r,e){let t={};for(let[n,o]of Object.entries(e))KD.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||YD.has(n)&&o==="false"||XD.has(n)&&o===""||ZD.has(n)&&o==="true"||JD.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function UA(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:s}=r,c=a.value++;t.setAttribute("id",String(c));let l={};for(let p of e.attributes){let g=p.name,m=p.value;m!=null&&(l[g]=String(m))}let u=QD(e.tagName,l);for(let[p,g]of Object.entries(u))t.setAttribute(p,g);if(o.set(c,e),i.set(c,t),Em(e.tagName)){let p=s?.injectedWebviewContent??"";if(!s?.disableMomenticAccessibilityTree&&p.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);p.trim().length>0&&t.appendChild(n.createCDATASection(`
|
|
4017
|
+
`,Nm(l,e),`To resolve the conflict:
|
|
4018
|
+
`,km(l,e))}}catch(u){n={error:u}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var JA=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}();Ce();Ce();var ZA=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Tr}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){V.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===zt.INT&&!Number.isInteger(e)&&(V.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 QA=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!Wa(e)){var o=this._buffer.get(e);if(o==null&&(o=new Tr,this._buffer.set(e,o)),typeof t!="number"){V.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===zt.INT&&!Number.isInteger(t)&&(V.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 Um=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Fm=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},ew=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},tw=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))},rw=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(Wa));if(n.size===0){V.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(Wa)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return Um(this,void 0,void 0,function(){var n,o,i,a;return Fm(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,eA(tw(tw([],ew(n),!1),ew(o),!1))];case 1:return i=s.sent(),a=i.filter(tA).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 Um(n,void 0,void 0,function(){var s,c;return Fm(this,function(l){switch(l.label){case 0:return s=new ZA(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(s)),t!=null&&(c=xn(c,t)),[4,c];case 1:return l.sent(),a._metricStorages.forEach(function(u){u.record(s._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 Um(n,void 0,void 0,function(){var s,c;return Fm(this,function(l){switch(l.label){case 0:return s=new QA,c=Promise.resolve(i(s)),t!=null&&(c=xn(c,t)),[4,c];case 1:return l.sent(),a.forEach(function(u){var d=s._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&&rA(n.instruments,t)})},r}();var OU=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)}}(),nw=function(r){OU(e,r);function e(t,n,o,i,a){var s=r.call(this,t)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Ac(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new wc(n,i),s}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}(vc);var ow=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),gi=function(){function r(){}return r.Noop=function(){return NU},r}();var LU=function(r){ow(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(gi);var iw=function(r){ow(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}(gi);var NU=new LU;var kU=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},DU=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},UU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},aw=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new XA,this.observableRegistry=new rw,this.meter=new WA(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,nw);return t.length===1?t[0]:new JA(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,YA);return t},r.prototype.collect=function(e,t,n){return kU(this,void 0,void 0,function(){var o,i,a;return DU(this,function(s){switch(s.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=s.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,t)}).filter(Zv),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 l=iA(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(l);if(u!=null)return u;var d=c.aggregation.createAggregator(l),p=new t(l,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),s=a.map(function(c){var l=UU(c,2),u=l[0],d=l[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var h=d.createAggregator(e),m=u.selectCardinalityLimit(e.type),g=new t(e,h,gi.Noop(),[u],m);return n.metricStorageRegistry.registerForCollector(u,g),g});i=i.concat(s)}return i},r}();var FU=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.")},sw=function(){function r(e){this.resource=e,this.viewRegistry=new FA,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=Qv(e),n=this.meterSharedStates.get(t);return n==null&&(n=new aw(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=FU(this.metricCollectors),a=i.next();!a.done;a=i.next()){var s=a.value;o.push([s,s.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 Rc=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Cc=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},BU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},zU=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))},lw=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return Rc(this,void 0,void 0,function(){var t,n,o,i,a=this;return Cc(this,function(s){switch(s.label){case 0:return t=po(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return Rc(a,void 0,void 0,function(){var l;return Cc(this,function(u){switch(u.label){case 0:return[4,c.collect(this,t,e)];case 1:return l=u.sent(),l?.scopeMetrics!=null&&n.push(l.scopeMetrics),l?.errors!=null&&o.push.apply(o,zU([],BU(l.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return s.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return Rc(this,void 0,void 0,function(){return Cc(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 Rc(this,void 0,void 0,function(){return Cc(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 cw=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},uw=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},dw=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 HU(r,e){var t=e??bc.empty();return r?bc.default().merge(t):t}var Bm=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new sw(HU((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=dw(e.views),c=s.next();!c.done;c=s.next()){var l=c.value;this._sharedState.viewRegistry.addView(l)}}catch(h){t={error:h}}finally{try{c&&!c.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=dw(e.readers),d=u.next();!d.done;d=u.next()){var p=d.value;this.addMetricReader(p)}}catch(h){o={error:h}}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?(V.warn("A shutdown MeterProvider cannot provide a Meter"),Vp()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new lw(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return cw(this,void 0,void 0,function(){return uw(this,function(t){switch(t.label){case 0:return this._shutdown?(V.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 cw(this,void 0,void 0,function(){return uw(this,function(t){switch(t.label){case 0:return this._shutdown?(V.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 GU=/[\^$\\.+?()[\]{}|]/g,xc=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(GU,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var fi=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 pw=function(){function r(e){var t;this._nameFilter=new xc((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new fi(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 mw=function(){function r(e){this._nameFilter=new fi(e?.name),this._versionFilter=new fi(e?.version),this._schemaUrlFilter=new fi(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 jU(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var zm=function(){function r(e){var t;if(jU(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||xc.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 iw(e.attributeKeys):this.attributesProcessor=gi.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:lr.Default(),this.instrumentSelector=new pw({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new mw({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var Zye=process.env.APP||"unknown";Ce();import{v4 as VU}from"uuid";function $U(){return new Yv({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:co.DELTA})}var WU=[new zm({instrumentName:"test_operation_duration_ms",instrumentType:pe.HISTOGRAM,aggregation:new gc([100,500,1e3,5e3,1e4,2e4])})],_c=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 lm({[Wl]:e.serviceName,[$T]:t,[qT]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:VU()}),o=$U(),i=new Om({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new Bm({resource:n,readers:[i],views:WU}),Gl.setGlobalMeterProvider(this.provider),this.meter=Gl.getMeter("momentic-serverless")}increment(e,t,n){try{let o=Bl(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=Bl(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 Ht=new Fl;function hw(r){r.disabled||(Ht=new _c(r))}import{CookieJar as yF}from"tough-cookie";async function zr({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 qU=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function gw({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(qU.includes(n.type))return;let s=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),l=0;for(;l===0||Date.now()-c<s;){await ee(250),l++;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 h=u[p];if(to(h,o)&&h!==r&&h!==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}}}}async function Pn(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(e.serializationOpts),tree:t}}import{randomUUID as QU}from"crypto";var Sw={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},yw={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:3e4,maxLineLength:500},fw=/<(\S+) id="(\d+)".*?>/g,KU=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,bw=["h1","h2","section","footer","nav","aside","form","label","dialog"],YU=[...bw,"span","div","h3"],XU=["table","select","form","ul","ol","menu","pre","code","dialog"],JU=["table","form","dialog","nav","section","ul","select"];function Mc(r){return ZU(r)}function ZU({logger:r,serializedTree:e,options:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=t,s=[],c=e.split(`
|
|
4019
|
+
`),l=0,u=[],d=0,p=[],h=[],m=!1;for(;l<c.length;){m&&(s.push({ids:p,content:u.join(`
|
|
4020
|
+
`),tokenLength:d}),u=[],d=0,p=h.length?[h[h.length-1].id]:[],m=!1);let g=c[l],f=Or(g);d+=f,g.length>a&&(g=g.slice(0,a));let w=Array.from(g.matchAll(fw)).map(K=>K&&K.length>=3?{tagName:K[1],id:K[2]}:void 0).filter(K=>!!K),A=Array.from(g.matchAll(KU)).map(K=>K&&(K[2]||K[4])).filter(K=>!!K);A.reverse();let I=g.replace(/ id="[0-9]+"/g,"");u.push(I);for(let K of w)p.push(K.id),h.push(K);for(let K of A){let G=h[h.length-1];G&&G.tagName===K&&h.pop()}let C=h.some(K=>XU.includes(K.tagName)),R=c[l+1]??"",B=Or(R),D=Array.from(R.matchAll(fw)).map(K=>K&&K.length>2?K[1]:void 0).filter(K=>!!K),J=D.some(K=>bw.includes(K)),Le=D.some(K=>YU.includes(K));d+B>=i&&(m=!0),d>=n&&(J&&!C||A.some(K=>JU.includes(K)))&&(m=!0),d>=o&&Le&&!C&&(m=!0),l++}return u.length&&s.push({ids:p,content:u.join(`
|
|
4021
|
+
`),tokenLength:d}),s.forEach((g,f)=>{let E=g.ids[0],S=g.ids[g.ids.length-1];r.debug({tokenLength:g.tokenLength,minId:E,maxId:S},`Chunk for page filtering (index ${f+1}/${s.length})`)}),{chunks:s}}var eF=75e4,Pc=3e5,tF=5e3;async function go(r){let{options:e,fixtures:t,screenshot:n}=r,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:s,signal:c}=t,l=r.tree,u=r.serializedTree,d=Or(u);if(d>eF)try{let p=Mc({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});l=await nF({...r,tokenLimit:Pc-1e4,chunks:p.chunks}),u=l.serialize();let h=Or(u);i.info({oldTokens:d,newTokens:h},"Filtered page using keywords"),d=h}catch(p){i.warn({err:p},"Error filtering page using keyword matching, using naive truncation"),l=l.pruneToSerializedCharLimit(Pc*ro),u=l.serialize();let h=Or(u);i.info({oldTokens:d,newTokens:h},"Filtered page using naive truncation"),d=h}if(d>Pc)try{if(o){let p=Mc({serializedTree:u,options:yw,logger:i}),h=QU();l=await $(rF({...r,chunks:p.chunks,callId:h}),{milliseconds:12e3,signal:c}),u=l.serialize();let m=Or(u);i.info({oldTokens:d,newTokens:m,langfuseCallId:h},"Filtered page using AI chunk ranking"),d=m}else{let p=Mc({serializedTree:u,options:Sw,logger:i});l=await $(oF({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=l.serialize();let h=Or(u);i.info({oldTokens:d,newTokens:h},"Filtered page using RAG"),d=h}}catch(p){i.warn({err:p},"Error filtering page using RAG/AI, using naive truncation"),l=l.pruneToSerializedCharLimit(Pc*ro),u=l.serialize(),i.info("Filtered page using naive truncation")}if(o&&d>tF&&r.type==="locator"&&(s==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||s==="org_01HMJTX4GT1KG94KZRCT8MZ6YB"))try{let p=await a.getPageSummary({browserContext:u,currentStep:r.description,screenshot:n,type:r.type},{logger:i,loggerTags:ve(i),abortSignal:c});if(i.info(p,"Got AI summaries"),p.category!=="OTHER"){let h=new Set;for(let g of p.relevantSections){let f=Math.min(g.startId,g.endId),E=Math.max(g.startId,g.endId);for(let S=f;S<=E;S++)h.add(S.toString())}l=l.pruneUsingRelevantIds(h),u=l.serialize();let m=Or(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 rF({type:r,callId:e,chunks:t,description:n,fixtures:o,tree:i}){let{generator:a,signal:s,logger:c}=o,l=await a.rankChunksWithAi({chunks:t,description:n,type:r,softTokenLimit:4e4,hardTokenLimit:8e4,callId:e},{abortSignal:s,logger:c,loggerTags:ve(c)}),u=[];return t.forEach((p,h)=>{l.indices.includes(h)&&(u=u.concat(p.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function nF(r){let{description:e,fixtures:t,tree:n}=r,{generator:o,logger:i,signal:a}=t;if(!e.trim())throw new Error("Empty description passed to page filtering");let s=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:ve(i),abortSignal:a});i.info({keywordsResult:s},"Got keywords for page filtering");for(let c of s.keywords){let l=r.chunks.filter(h=>h.content.toLowerCase().includes(c.toLowerCase()));if(!l.length||l.reduce((h,m)=>h+m.tokenLength,0)>r.tokenLimit&&l.length>1)continue;let d=l.flatMap(h=>h.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function oF(r){let{description:e,fixtures:t,chunkResult:n,tokenLimit:o,tree:i}=r,{generator:a,logger:s,signal:c}=t,l=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:s,loggerTags:ve(s)});if(l.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(l.ids.map(d=>`${d}`)))}async function Gm(r,e){if(!r.description)throw new _("UserConfigurationError","Cannot locate element with empty description");return zr({action:async()=>iF(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function iF(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:s,aiPageFiltering:c,logger:l,allowNotActionableNodesOverride:u}=r,{ctx:d,orgId:p,browser:h,localCodeEvalTools:m,generator:g,abortSignal:f}=e,E=r.description,S=r.useMemory&&!t;n&&(E=await Gd({orgId:p,s:E,context:n,localTools:m,signal:f,logger:l})),a&&(E=sF(E,a));let{serializedTree:w,tree:v}=await Pn(h,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:l}),A,I=Date.now(),C;for(;!A&&Date.now()-I<3e3;){f.throwIfAborted();try{A=await h.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(ce){C=ce}}if(!A)throw new _("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${C?.message}`);let R=w,B=!1,D=`data:image/jpeg;base64,${A.toString("base64")}`;R=await go({type:"locator",description:E,screenshot:D,serializedTree:w,options:{aiPageFiltering:c},tree:v,fixtures:{generator:g,signal:f,logger:l,orgId:p}}),R!==w&&(B=!0);let J=await g.getElementLocation({browserState:R,goal:E,screenshot:D,source:a,memory:S?s:void 0},{disableCache:t,abortSignal:f,loggerTags:ve(l),useMemory:S});l.debug({usedRag:B,result:J},"Got locator result");let Le=J.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:Le,pageState:R,ragUsed:B,thoughts:J.thoughts}),!Le)throw new Do(`Could not find any relevant element: ${J.thoughts}`,J.updatedMemory?{type:"GCS_TRACES",traces:J.updatedMemory}:void 0);let{resolution:K,target:G,frameConfig:se}=await h.createTargetFromA11yId({id:J.id,requirements:J.requirements,additionalElements:J.additionalElements,description:E,targetSource:"AI",logger:l});if(K.a11yNode?.properties?.hidden&&K.a11yNode?.properties?.hidden!=="false")throw new _("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${K.displayString}`);return S&&(J.updatedMemory?G.memory={type:"GCS_TRACES",traces:J.updatedMemory}:s&&(G.memory=s)),{thoughts:J.thoughts,target:G,resolution:K,frameConfig:se,screenshot:D}}var aF=["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:"],Ew="<select> element:",Tw="text input or contenteditable element:",vw="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:",Aw="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:",Hm=[Ew,Tw,vw,Aw,...aF];function ww(r,e){if(r===e)return!0;for(let t of Hm){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Hm.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Hm.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function sF(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${Ew} ${r}`;case"TYPE":return`${Tw} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${vw}
|
|
4022
|
+
${r}`;case"ELEMENT_CHECK":return`${Aw}
|
|
4023
|
+
${r}`;default:return r}}var lF=15;async function Ic({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=lF}){if(!r.assertion.trim())throw new _("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=vl(c),u=0,d=Date.now(),p,h,m;try{await zr({action:()=>s.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:s,logger:t})}catch(f){t.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let g;for(;u<a&&(!g||g-d<c);){n.abortSignal.throwIfAborted(),u!==0&&await ee(l,n.abortSignal),g=Date.now();try{if(p=await zr({action:async()=>{let E=await Rw(s,t,n.abortSignal);return h&&h.serializedTree===E.serializedTree&&h.screenshotBuff.equals(E.screenshotBuff)?p:(h=E,Cw({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:s}),p?.updatedMemory&&yl(r,p.updatedMemory,t),p?.success)break;throw p?.thoughts?new _("AssertionFailureError",p.thoughts):new _("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 zr({action:async()=>Cw({command:r,state:await Rw(s,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:s})}catch(f){n.abortSignal.throwIfAborted(),m=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw m&&(f+=` Latest result: ${m.message}`),new _("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:s.url()}}async function Rw(r,e,t){let[n,o]=await Promise.all([Pn(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function Cw({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:p}=t,h={type:"ASSERTION"},{serializedTree:m,tree:g}=e,f=e.screenshotBuff,E=f.toString("base64"),S=u.url(),w=r.contextChoice??"MULTIMODAL",v=m;w!=="VISION_ONLY"&&(v=await go({type:"assertion",serializedTree:m,tree:g,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:l,orgId:t.orgId}}),v!==m&&(h.ragUsed=!0),h.pageState=v);let A={goal:r.assertion,url:S,memory:o?r.cache?.memory:void 0,browserState:v,screenshot:E,contextChoice:w,source:c},C=await(w==="VISION_ONLY"?(R,B)=>d.getVisualAssertionResult(R,B):(R,B)=>d.getAssertionResult(R,B))(A,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:l,loggerTags:ve(l)});return(C.result||i)&&C.relevantElements&&(h.relevantElementsSerialized=C.relevantElements.map(R=>u.getSerializedFormFromA11yId(R)).filter(R=>!!R),await cF(C.relevantElements,u,l)),{success:C.result,thoughts:C.thoughts,afterScreenshotOverride:f,updatedMemory:o?C.updatedMemory:void 0}}async function cF(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 $(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 _w}from"lodash-es";async function Mw(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=fg(e.cache)?e.cache:void 0,a=_w(i),s=()=>{if(i){let h=pb(a,i);i.target=h.target,i.updatedAt=h.updatedAt}},c=Date.now(),l=0,u,d=500,p=!1;for(;l<2||Date.now()-c<t;){l++,l>1&&await ee(d,o),o?.throwIfAborted();let{result:h,elementWasFound:m}=await xw({cacheToUse:i,params:r});if(u=h,p=m,h.success)break;s(),d=Math.min(d*2,1e4)}if(!u)throw new _("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!u.success&&i?.target&&Es(i.target)){let h=i?.target?.memory?{target:{id:-1,memory:i.target.memory}}:void 0,{result:m}=await xw({cacheToUse:h,params:r});u=m,u.success||s()}return u.success&&i?.target&&!p&&(i.target=$d(i.target),i.updatedAt=new Date),u}async function xw({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!an(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=dF(t.assertion),l,u=!1,d=_w(r);try{let{elementInteractedDisplayString:p,result:h,thoughts:m}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async g=>uF(g.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ea(t),targetName:"target"}});return l={success:h.success,data:h.data,err:h.err,elementInteractedDisplayString:p,thoughts:m},u=!0,h.success||(s.warn({aiThoughts:m,elementString:p,err:h.err},"Element check found an element but failed"),l={...h,thoughts:m}),{result:l,elementWasFound:u}}catch(p){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(p instanceof _)||p.reason!="ActionFailureError")throw p;return l={success:!1,err:p,data:void 0,thoughts:void 0},s.warn({err:p},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function uF(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:Mt(c,500,!0)},!Oc(c,n.value,n.operation,!!n.negated)){let l=n.negated?Zn[n.operation]:Qn[n.operation];o=!1,i=new _("AssertionFailureError",`The content ${l} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:Mt(await r.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(l){i=new _("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${l}`),o=!1;break}if(!Oc(c,n.value,n.operation,!!n.negated)){let l=n.negated?Zn[n.operation]:Qn[n.operation];o=!1,n.operation==="EXISTS"?i=new _("AssertionFailureError",`The attribute ${n.attr} ${l}`):i=new _("AssertionFailureError",`The attribute ${n.attr} ${l} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(l,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(h=>setTimeout(h,250));let p=l.getBoundingClientRect();if(!(p.width===0||p.height===0)&&window.getComputedStyle(l).visibility!=="hidden"&&window.getComputedStyle(l).display!=="none")return!0}return!1},sn*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:sn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:sn*1e3});break}case"FOCUSED":{o=await r.evaluate(l=>l===document.activeElement);break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?mb[n.condition]:hb[n.condition];i=new _("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(l=>l.tagName);if(!Oc(c,n.value,n.operation,!!n.negated)){let l=n.negated?Zn[n.operation]:Qn[n.operation];o=!1,i=new _("AssertionFailureError",`The element tag name ${l} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((l,u)=>window.getComputedStyle(l).getPropertyValue(u),n.property);if(!Oc(c,n.value,n.operation,!!n.negated)){let l=n.negated?Zn[n.operation]:Qn[n.operation];o=!1,n.operation==="EXISTS"?i=new _("AssertionFailureError",`The style property ${n.property} ${l}`):i=new _("AssertionFailureError",`The style property ${n.property} ${l} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function Oc(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 dF(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function Pw(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as pF}from"jimp";async function qa(r,e){let t=await r.screenshot(e),n=await pF.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as Iw}from"jimp";import jm from"jpeg-js";import mF from"pixelmatch";async function Ow({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!an(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let c={clearHighlights:!0,hideCaret:!0},l;t.target?.elementDescriptor?l=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async D=>qa(o,{locator:D.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await qa(o,c);let u=await s.prepareGoldenScreenshotForComparison(a,t,l);if((l.height!==u.height||l.width!==u.width)&&a.warn({currHeight:l.height,currWidth:l.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-u.height)>10||Math.abs(l.width-u.width)>10){let U=`${l.width}x${l.height}`,D=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${U}) does not match saved screenshot dimensions (${D}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await Iw.fromBuffer(l.buffer),p={width:l.width,height:l.height},h=await Iw.fromBuffer(u.buffer),m={width:u.width,height:u.height},g,f=p.width*p.height,E=m.width*m.height,S=Math.abs(p.height-m.height),w=Math.abs(p.width-m.width);if(f>E){let U=d.cover({w:m.width,h:m.height});l.buffer=await U.getBuffer("image/jpeg"),g="current",l.width=m.width,l.height=m.height}else if(E>f){let U=h.cover({w:p.width,h:p.height});u.buffer=await U.getBuffer("image/jpeg"),g="saved"}let v={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},A=t.threshold??.1,C=mF(jm.decode(u.buffer).data,jm.decode(l.buffer).data,v.data,l.width,l.height,{threshold:A,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,R=C>A*100,B=`Visual diff of ${C.toFixed(2)}% detected, which is ${R?"over":"under"} the threshold of ${A*100}%.`;if(g&&(B+=` The ${g} screenshot was cropped since it was taller by ${S} pixels and wider by ${w} pixels.`),R)throw new _("ActionFailureError",B);return{fail:R,thoughts:B,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:jm.encode(v,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var hF=3e4;async function Lc({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??hF/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([h,m])=>h&&m)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([h,m])=>h&&m).forEach(([h,m])=>{a.append(h,m)});let s=a.toString(),c;if(Xo(r.url)&&(c=r.url),t&&Jo(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new _("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:s,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await $((async()=>{let h=s?`${c}?${s}`:c;try{return await n(h,{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 _("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let h;try{h=await u.text()}catch(m){h=`Failed to read response body: ${m}`}throw new _("ActionFailureError",`Fetch request failed with status ${u.status}: ${h}`)}let d={};u.headers.forEach((h,m)=>{d[m]=h});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 gF=5e3;async function kw({timeout:r=sn,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,s=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let c=Date.now();i=await Lw(e),a=Date.now();let l=a-c;if(l>1e3&&e.logger.warn({pageAssertDuration:l},"Page assertion took longer than expected"),!i.success)await ee(s,e.signal),s=Math.min(Math.floor(s*1.5),gF);else return i}return i=await Lw(e),i}async function Lw({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let s;if(t){let c=await e.evaluateFunctionInAllFrames(Nw,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(l=>l.evaluation):c.some(l=>l.evaluation),s=c.find(l=>l.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(Nw,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?Zn.CONTAINS:Qn.CONTAINS;a=new _("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new _("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function Nw({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 fF=3e4;async function Dw({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??fF/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(Xo(r.url)&&(s=r.url),t&&Jo(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new _("ActionFailureError",`Invalid URL: ${r.url}`);let l=await $((async()=>{try{return await n(s,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables?JSON.parse(r.variables):void 0}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!l)throw new _("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,p=await l.text();try{d=JSON.parse(p)}catch{throw new _("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new _("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new _("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}let u={};return l.headers.forEach((d,p)=>{u[p]=d}),{status:l.status,headers:u,json:await l.json()}}var Nc=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:s,visualDiffScreenshotStorage:c,options:l}){this.orgId=i,this.options=l,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=s,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=a,this.generator=t,this.logger=n}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[c,l]=await Promise.all([Pn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${l.toString("base64")}`,d=await go({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...ve(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let c=this.browser.url(),[l,u]=await Promise.all([Pn(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 go({type:"ai-action",description:e,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),h={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(h,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...ve(a)},langfuseSessionId:s})}catch(m){throw new _("InternalWebAgentError",`Error generating command: ${m instanceof Error?m.message:m}`,{errOptions:{cause:m}})}}async getBrowserState(e){return Pn(this.browser,e)}async locateElement(e){return await Gm({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return zr({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:s,options:c,retriesWithAI:l=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],h=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(h)}try{let d=await s(...u.map(m=>m.result)),p=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",h=u.map((m,g)=>m.thoughts?`${p(o[g])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(m=>m.elementInteractedDisplayString),thoughts:h}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:c,retriesWithAI:l-1});throw new _("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 zr({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&&Fu(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(zu(i)||Bu(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Hu(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof xr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof _?n:new _("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:s}=o;if(t.type!=="description")throw new _("ActionFailureError","Cannot use selector with non-description target");let c,l=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){l=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:s,logger:a});return{result:await n({locator:d.locator}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;c=d,a.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await ee(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:s,command:c}=e,{disableCache:l,useSelector:u,targetName:d,targetHealingInProgress:p,source:h}=s,m=this.logger.child({commandId:c.id}),g=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,S=Uw(e.cache);if((!S||l)&&!Tu(o))throw new _("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(m.info("Cache explicitly disabled for this step"),E=!0,S=void 0),S&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&S.targetSource==="HEURISTIC_HEALED"&&(E=!0,S=void 0),S?.inputDescription&&!ww(o.elementDescriptor,S.inputDescription)&&(m.warn({old:S.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,S=void 0);let w=A=>!!A&&Es(A),v=!0;if(!w(S)){v=!1,m.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:s.memory,useMemory:g},"Prompting AI for an updated element location"),E&&await ee(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let A;try{A=await Gm({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:h,useMemory:g,memory:g?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:m},this.getControllerFixtures(t))}catch(R){if(R instanceof Do&&R.updatedLocatorMemory){let B={id:-1,...i,memory:R.updatedLocatorMemory};Sl({cmd:c,key:d,newTarget:B,logger:m,updatedWithAI:!0})}throw new _("ActionFailureError",R.message)}A.frameConfig&&this.browser.setActiveFrameConfig(A.frameConfig);let I=s.disableGlobalLocatorRedirect?{locator:A.resolution.locator}:await this.attemptLocatorRedirect(A.resolution.locator,m),C=await a(I);return Sl({cmd:c,key:d,newTarget:A.target,logger:m,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),A.target.targetSource="AI_HEALED",A.target.targetUpdateTime=new Date().toUTCString(),A.target.targetUpdateLoggerTags=ve(m)),{result:C,elementInteractedDisplayString:A.resolution.displayString,thoughts:A.thoughts}}try{let A=await this.browser.resolveTarget(t,S,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:m,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(A.locator);let I=s.disableGlobalLocatorRedirect?{locator:A.locator}:await this.attemptLocatorRedirect(A.locator,m),C=await a(I);if(Ht.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`,`orgId:${this.orgId}`]),Sl({cmd:c,key:d,newTarget:S,logger:m,updatedWithAI:!1}),v){let R=A.decisions.filter(B=>B.matched);if(R.length!==1)m.warn({decisions:A.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let B=R[0].type;n.recordTargetAutoHeal({healType:B})}}return{result:C,elementInteractedDisplayString:A.displayString}}catch(A){this.throwIfClosed(),Ht.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`,`orgId:${this.orgId}`]);let I=!1;if((A instanceof xr||Fu(A)||zu(A)||Hu(A)||cf(A)||Bu(A))&&(I=!0),A instanceof _&&!I)throw m.error({err:A},"Failed to execute action with cached target (fatal)"),A;if(f>0&&o){m.info({err:A},"Failed to execute action with cached target, retrying with AI");let C;return S.memory&&ug(S.memory)&&(C=S.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:C,retriesWithAI:f,targetHealingInProgress:!0}})}throw new _("ActionFailureError",A.message,{errOptions:{cause:A}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return qa(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await ee(this.options.slowMoMs);let a=await this.browser.getOpenPages(),s=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(l){throw this.throwIfClosed(),new _("ActionFailureError",`Failed to substitute template strings in command: ${l.message}`,{errOptions:{cause:l}})}try{let l=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&Cg(n)?await this.browser.waitForDOMStability({timeout:ge}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:re}),this.options?.autoFollowNewTabs&&await gw({beforeUrl:s,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),l}catch(l){throw l.name!=="AbortError"&&this.logger.error({err:l},"Error thrown in action controller"),l}finally{fl(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>lp(e)}}async resolveCommandTemplateStrings(e,t){return gl({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,n,o,i){i=i||"disableCache"in n&&!!n.disableCache;let a=this.logger.child({commandId:n.id});switch(n.type){case"SUCCESS":let s=n.condition;return s?.assertion.trim()?Ic({command:s,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!n.assertion.trim())throw new _("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new _("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Ic({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new _("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=Vy(n.schema);if(f)throw new _("UserConfigurationError",f)}let m=await this.browser.getCondensedHtml(),g=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,${g.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:ve(a)});if(f.result==="NOT_FOUND")throw new _("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new _("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 _("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 _("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(!Xo(n.url)&&!Jo(n.url,this.browser.baseUrl))throw new _("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,g;if(n.target&&Rr(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:S,thoughts:w}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:v=>this.browser.hover(v),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});m=S,g=w}let f=this.browser.getViewport()?.height??pn.height,E=this.browser.getViewport()?.width??pn.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:g}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new _("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 _("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await ee(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Rr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let m=this.browser.url(),{elementInteractedDisplayString:g,result:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:w=>this.browser.click(w,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),S={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:E,data:f.downloadedFile?{downloadedFile:f.downloadedFile}:void 0};return wl(m,S.urlAfterCommand)&&(S.succeedImmediately=!0,S.succeedImmediatelyReason="URL changed"),S}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(Rr(n.fromTarget)&&Rr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Rr(n.fromTarget)||Rr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:m,thoughts:g}=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:g}}case"MOUSE_DRAG":{let m=parseInt(n.deltaX),g=parseInt(n.deltaY),f=n.steps??5;if(isNaN(m)||isNaN(g))throw new _("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Rr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(m,g,f,n.target.pixels,{force:n.force});break}let E,S,w;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:v,result:A,thoughts:I}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async C=>C.locator,options:{disableCache:i,targetName:"target",...n}});E=A,S=v,w=I}return await this.browser.mouseDrag(m,g,f,E,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:S,thoughts:w}}case"SELECT_OPTION":{if(!an(n.target))throw new Error("Select with x/y is not supported yet");let m=n.target.elementDescriptor,g=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:S=>this.browser.selectOption(S,g,n.force),options:{...n,targetName:"target",disableCache:i,source:ea(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let 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 Ir({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 g=>{if(!this.options?.scratchPadId){a.warn({updates:g},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:g,logger:a})}}})}catch(g){throw this.throwIfClosed(),new _("ActionFailureError",g instanceof Error?g.message:`${g}`,{errOptions:{cause:g}})}try{JSON.stringify(m)}catch(g){throw new _("ActionFailureError",`Return value is not serializable: ${g instanceof Error?g.message:`${g}`}`,{errOptions:{cause:g}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:m}}case"TYPE":{if(n.target&&Rr(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(),g,f,E=Uw(n.target),S=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:v,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:I=>this.browser.typeIntoTarget(n.value,I,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!S,source:ea(n)}});g=v,f=A}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let w={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:f};return wl(m,w.urlAfterCommand)&&(w.succeedImmediately=!0,w.succeedImmediatelyReason="URL changed"),w}case"HOVER":{if(Rr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:m,thoughts:g}=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:g}}case"FOCUS":{if(!an(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:m,thoughts:g}=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:g}}case"BLUR":{if(n.target&&!an(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:g}=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:g}}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 wl(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 yF,g=SF(fetch,m),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await Lc({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:g}),cookies:qs(m,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await Dw({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return Ow({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,g;if(n.fileSource.type==="URL"?(g=n.fileSource.url,m=await cE({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(g=n.fileSource.name,m=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!m)throw new _("UserConfigurationError",`Attempted to use non-existent file for upload step: ${g}`);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 Ir({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof m!="object")throw new _("ActionFailureError",`Credentials must evaluate to an object (received ${typeof m} instead)`);let g;try{g=gS.optional().parse(m)}catch(f){throw new _("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(g);break}case"ELEMENT_CHECK":{let m=(n.timeout??sn)*1e3,g=this.generator.getAgentConfig()?.assertion;if(Pw(n.assertion)&&!n.useSelector&&n.target.type==="description"&&g&&g!=="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 S=await Ic({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: ${S.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:S.afterScreenshotOverride}}finally{E.cache?.memory&&yl(n,E.cache?.memory.traces,a)}}let f=await Mw({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 zr({action:async()=>kw({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 vn(n.requestMatcher),g=this.browser.registerRequestListener(m);return this.registeredListeners[n.key]=g.then(async f=>await gp(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 _("ActionFailureError",`No listener registered with key: ${n.key}`);let g=n.timeout??10;return{data:await $(m,{milliseconds:g*1e3,message:`Request listener timed out after ${g} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let m=new vn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,m,{onRequestStart:(g,f)=>{this.recordedRequests[n.key][g]=Ml(f)},onRequestComplete:(g,f)=>{this.recordedRequests[n.key][g]=Ml(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let m=this.recordedRequests[n.key];if(!m)throw new _("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 vn(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 vn(n.requestMatcher),async(g,f)=>{let E=await Ir({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:g,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),S=MS.parse(E);return new Response(S.body,{status:S.status,headers:S.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:ve(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 kl({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:ve(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ve(this.logger)})}};import{mkdirSync as HF}from"fs";import{tmpdir as GF}from"os";import Jw from"path";import{cloneDeep as bF}from"lodash-es";import Gw from"truncate-json";var Fw=1e3,Bw=5e6,EF=5*1024*1024;function jw(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=Gw(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":zw(n);break;case"MOBILE_MODULE_STEP":zw(n),jw(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 zw(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function Hw(r,e){let t=JSON.stringify(r),n=t.replaceAll("\\u0000","");if(t.length!==n.length){let o=t.indexOf("\\u0000");e.warn({input:t.slice(Math.max(0,o-500),Math.min(t.length,o+500))},"Database content violation: stripped unicode character from input")}return n}function kc(r,e){let t=bF(r);if(jw(t,e),t.length>Fw)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,Fw);let n=Hw(t,e);if(n.length>Bw)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>Bw;)t.pop(),n=Hw(t,e);let{jsonString:o}=Gw(n,EF);try{return br.array().parse(JSON.parse(o))}catch(i){throw e.error({serialized:n,err:i},"Could not parse serialized results into JSON structure after processing"),i}}import{AsyncLocalStorage as TF}from"async_hooks";var Ka=new TF;function vF(r){Ka.enterWith({activeTracers:[r]})}function AF(r,e){let t=Ka.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function wF(r,e){let t=Ka.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return Ka.run({activeTracers:n},e)}var In={globalAls:Ka,initializeRootTracerContext:vF,withChildTracer:AF,withChildTracerAsync:wF};var fo=class r{spans;parentSection;finished=!1;startTime;endTime;constructor(e){this.startTime=e?.startTime??Date.now(),this.spans=e?.subSpans??[],this.parentSection=e}startSection(e,t){let n={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},o=new r(n);try{return In.withChildTracer(o,()=>t(o,n))}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}finally{o.finish(),this.addSpan(n)}}async startAsyncSection(e,t){let n={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},o=new r(n);this.addSpan(n);try{return await In.withChildTracerAsync(o,()=>t(o,n))}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}finally{o.finish()}}finish(){if(!this.finished){this.endTime=Date.now();for(let e of this.spans)e.endTime||(e.endTime=this.endTime,e.durationMs=e.endTime-e.startTime);this.parentSection&&(this.parentSection.endTime=this.endTime,this.parentSection.durationMs=this.parentSection.endTime-this.parentSection.startTime),this.finished=!0}}addSpan(e){this.spans.push(e)}startSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{a=t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}async startAsyncSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{a=await t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:"root step span",startTime:this.startTime,endTime:this.endTime,subSpans:this.spans,attributes:{},durationMs:this.endTime?this.endTime-this.startTime:void 0}}};function et(){let r=In.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new fo}import{diff as BF}from"deep-object-diff";import{cloneDeep as zF}from"lodash-es";import Ww from"fontoxpath";import RF from"@prettier/plugin-xml";import CF from"prettier";import{DOMParser as xF,XMLSerializer as _F}from"slimdom";function Vm(r){return r.toLowerCase().endsWith("webview")}function MF(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 PF=new Set(["index","package","a11y-important","screen-reader-focusabl"]),IF=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","multiline","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),OF=new Set(["text","hint"]),LF=new Set(["live-region","drawing-order"]),NF=new Set(["displayed","enabled"]);function kF(r,e){let t={};for(let[n,o]of Object.entries(e))PF.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||IF.has(n)&&o==="false"||OF.has(n)&&o===""||NF.has(n)&&o==="true"||LF.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function Vw(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:s}=r,c=a.value++;t.setAttribute("id",String(c));let l={};for(let p of e.attributes){let h=p.name,m=p.value;m!=null&&(l[h]=String(m))}let u=kF(e.tagName,l);for(let[p,h]of Object.entries(u))t.setAttribute(p,h);if(o.set(c,e),i.set(c,t),Vm(e.tagName)){let p=s?.injectedWebviewContent??"";if(!s?.disableMomenticAccessibilityTree&&p.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);p.trim().length>0&&t.appendChild(n.createCDATASection(`
|
|
3971
4024
|
${p}
|
|
3972
|
-
`));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(qD(m.tagName));UA(r,m,h),t.appendChild(h)}}}function eU(r,e,t,n){let o=r.parseFromString("<hierarchy/>","text/xml"),i=new Map,a={prunedDocument:o,idToElement:t,prunedIdToElement:i,idCounter:{value:0},opts:n},s=o.documentElement;UA(a,e,s);let c=new WD().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function FA(r,e){let t=new $D,n=t.parseFromString(r,"text/xml"),o=new Map,i=n.documentElement;if(!i)throw new Error("No root element found in XML");if(i.tagName!=="hierarchy")throw new Error("No hierarchy element found in XML");let{prunedDocument:a,prunedIdToElement:s,xml:c}=eU(t,i,o,e);return{xml:await VD.format(c,{parser:"xml",plugins:[jD],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function tU(r){let e=[],t=r;for(;t;){let n=t.tagName,o=t.parentElement,i=1;if(o){let a=Array.from(o.children).filter(s=>s.tagName===n);for(let s=0;s<a.length;s++)if(a[s]===t){i=s+1;break}}e.unshift(`${n}[${i}]`),t=o}return`/${e.join("/")}`}function Ec(r,e){let t=r.idToElement.get(e);if(t)return tU(t)}function Tm(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 Tc(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 vm(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function HA({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=Tc(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=Ec(t.graph,r.id)??"",a=Tm(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=vm(s,r.requirements?.attributesRequired),u={requiredText:r.requirements?.textRequired?s?.getAttribute("text")??void 0:void 0,requiredAttributes:c,requiredBounds:r.requirements?.boundsRequired},d=[];r.additionalElements&&(d=r.additionalElements.map(({id:g,requirements:m})=>{let h=t.graph.idToElement.get(g);if(!h)return;let f=Ec(t.graph,g);return f?{xPath:f,requirements:{requiredText:m.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:vm(h,m.attributesRequired),requiredBounds:m.boundsRequired}}:void 0}).filter(g=>!!g));let p;return Em(n.tagName)&&r.inWebview!==!1?p={type:"WEBVIEW",resolvedDescription:e,xPath:i}:p={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},p}var zA=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i}=e;if(o!==void 0){let a=r.getAttribute("text")??void 0;if(a!==o)throw new Error(`ActionFailureError: Resolved element text mismatch: expected ${o}, got ${a}`)}if(n)for(let[a,s]of Object.entries(n)){let c=r.getAttribute(a)??void 0;if(c!==s)throw new Error(`ActionFailureError: Attribute ${a} mismatch: expected ${s}, got ${c}`)}if(i&&t){let a=Tc(r);if(!a||a.length!==t.length)throw new Error("ActionFailureError: Resolved element has no bounds or unexpected bounds format");if(!a.every((c,l)=>c===t[l]))throw new Error(`ActionFailureError: Bounds changed from [${t.join(",")} ] to [${a.join(",")} ]`)}};async function GA(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=ot();if(e.type==="WEBVIEW")return rU(e,r);let a=BA.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let p=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let g of p){let m=BA.evaluateXPathToFirstNode(g.xPath,o);if(!m)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);zA(m,g.requirements)}})}let s=Tc(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");zA(a,e.requirements,e.bounds);let c;for(let[p,g]of n.idToElement.entries())if(g===a){c=p;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=Tm(n,c)??l,u=Ec(n,c)??u),{resolvedTarget:{...e,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function rU(r,e){let{stateManager:t,logger:n,signal:o}=e,i=ot(),a=await t.getActiveWebview();if(!a||!a.browserController)throw new Error("No browser controller is attached to the requested webview");let s=a.browserController.browser;if(!r.browserCache)throw new Error("No browser target available on cache");let c=r.browserCache,l=await i.startAsyncSection("Resolve target in webview",()=>s.resolveTarget(null,c,{logger:n,signal:o}));return{resolvedTarget:{...r,controller:a.browserController,resolution:l}}}function Am(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;Is(e)&&(e[t]={...e[t],[n]:Ps.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function jA(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var nr=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,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSection("Get emulator state",async c=>{let l=await this.stateManager.getDomState(),u=await c.startAsyncSpan("EMULATOR_READ_STATE",()=>this.stateManager.getCurrentScreenshotPngString(),{name:"Emulator screenshot"});return{emulatorState:l,screenshot:u}}),o;try{o=await t.startAsyncSpan("AI_LOCATOR_CALL",async c=>{let l=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:ye(this.logger),abortSignal:this.aborter.controller?.signal});return c.result=l,l})}catch(c){throw this.throwIfAborted(),this.logger.error({err:c},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${c instanceof Error?c.message:c}`)}if(o.id===-1)throw new Error(`ActionFailureError: No matching element found: ${o.thoughts}`);let i=HA({aiResponse:o,description:e,emulatorState:n.emulatorState});if(i.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:i.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:i,thoughts:o.thoughts};let{browserLocateResult:a,browserController:s}=await t.startAsyncSpan("TARGET_RESOLUTION",async c=>{let l=await this.stateManager.getActiveWebview();if(!l||!l.browserController)throw new Error("No browser controller is attached to the requested webview");let u=await l.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return c.result={serializedElement:u.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:u,browserController:l.browserController}});return{resolvedTarget:{...i,controller:s,resolution:a.resolution,browserCache:a.target},thoughts:a.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c}=e,l=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,u=e.retriesWithAI??1,d=!1,p=oU(l),g;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,p=void 0),s&&(d=!0,p=void 0),p&&p?.resolvedDescription!==n&&(this.logger.info({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,Am({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget,updatedWithAI:!0}),{result:await t(h.resolvedTarget),thoughts:g}}let m;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),m=await c.startAsyncSection("Get emulator XML tree",async()=>await this.stateManager.getDomState());let h=await c.startAsyncSection("Resolve target cache",async(E,S)=>{let{resolvedTarget:R}=await GA({target:p,domState:m,stateManager:this.stateManager,logger:this.logger}),A=jA(R),v=nU(p,A);return this.logger.info({cacheDiffs:v},"Successfully resolved and updated target"),Am({command:o,cacheKey:i,targetName:a,updatedCache:A,updatedWithAI:!1}),S.attributes.serializedElement=R.type==="WEBVIEW"?R.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":R.elementOnlySerializedXml,R}),f=await t(h);return p.type!=="WEBVIEW"&&kt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`]),{result:f,thoughts:"Successfully executed preset action with cache."}}catch(h){if(p.type!=="WEBVIEW"&&kt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`]),this.throwIfAborted(),u>0)return this.logger.warn({err:h},"Failed to resolve target cache, retrying with AI"),this.logger.debug({domState:m?.graph.originalXml},"Emulator state"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};function sU(r){let e={relativePosition:r.relativePosition};if(r.doubleTap&&r.longPress)throw new Error("UserConfigurationError: Cannot specify both doubleTap and longPress");return r.doubleTap?{...e,doubleTap:!0,doubleTapDelayMs:r.doubleTapDelayMs}:r.longPress?{...e,longPress:!0,longPressDurationMs:r.longPressDurationMs}:e}var vc=class extends nr{async tapOnAbsoluteCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(e.doubleTap){await this.driver.tap({x:t,y:n});let o=e.doubleTapDelayMs??100;await new Promise(i=>setTimeout(i,o))}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,s=i-n,c=a-o,l=t?.relativePosition?.x??s/2,u=t?.relativePosition?.y??c/2;l=Math.max(0,Math.min(l,s)),u=Math.max(0,Math.min(u,c));let d=n+l,p=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:p,...t}),{x:d,y:p}}async tapOnWebviewTarget(e,t){let{controller:n}=e;return(await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let i=Math.random().toString(36).substring(4),a=VA.join(aU(),"momentic","downloads"),s=VA.join(a,this.orgId,i);return iU(s,{recursive:!0}),s}},{delayMs:t?.longPressDurationMs,relativePosition:t?.relativePosition,doubleClick:t?.doubleTap})).coordinates}async tapOnTarget({target:e,options:t}){return await ot().startAsyncSpan("EMULATOR_INTERACTION",async o=>"type"in e&&e.type==="NATIVE"?this.tapOnNativeTarget(e,t):(o.withinWebview=!0,this.tapOnWebviewTarget(e,t)),{name:"Tap on target"})}async executeTap({command:e,tracer:t}){let n=sU(e);if(e.target.type==="coordinates"){let a=await this.driver.getWindowSize(),s=e.target.xPercent*a.width,c=e.target.yPercent*a.height;return await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.tapOnAbsoluteCoordinates({...n,x:s,y:c})},{name:`Tap at coordinates ${s}, ${c}`}),{success:!0,message:`Tapped at ${s}, ${c}`}}let o=e.target.description,{thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,action:a=>this.tapOnTarget({target:a,options:n}),description:o});return{success:!0,message:i}}};var wn=class extends nr{async doPress({keycode:e,longPress:t}){await ot().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var Ac=class extends nr{async doType(e){e.clearContent&&await this.clearContent(),await this.doTypeHelper(e)}async doTypeHelper(e){let t=ot(),n=e.keyPressDelayMs;n?await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.updateSettings({keyInjectionDelay:n}),await this.driver.keys(e.text),await this.driver.updateSettings({keyInjectionDelay:0})},{name:"Typing keys with a delay"}):await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.keys(e.text)},{name:"Typing keys"})}async clearContent(){let e=ot();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){throw new Error(`Failed to clear content because the select all button was not found: ${t}`)}}async clearContentHelper(){let e=this.driver.$('//android.widget.LinearLayout[@package="app.lawnchair" and @content-desc="Select all" and @clickable="true"]');await e.waitForExist({timeout:750}),await e.click(),await new wn(this.constructPerformerParams()).doPress({keycode:67})}};import Dt from"zod";var $A=.9,lU=Dt.object({navigationBar:Dt.object({visible:Dt.boolean(),x:Dt.number(),y:Dt.number(),width:Dt.number(),height:Dt.number()}),statusBar:Dt.object({visible:Dt.boolean(),x:Dt.number(),y:Dt.number(),width:Dt.number(),height:Dt.number()})}),wc=class extends nr{async executeSwipe(e){let t=ot();if(e.scrollableElement.type!=="CUSTOM"){await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for screen to stabilize before swiping"});let n=await this.driver.getWindowRect(),o;if(e.scrollableElement.type==="SCREEN")o={left:n.x+25,top:n.y+50,width:n.width-50,height:n.height-100};else try{let i=lU.parse(await this.driver.executeScript("mobile: getSystemBars",[]));o={left:n.x+25,top:n.y+50,width:n.width-50,height:n.height-100},i.navigationBar.visible&&(o.height-=i.navigationBar.height),i.statusBar.visible&&(o.top+=i.statusBar.height,o.height-=i.statusBar.height)}catch(i){this.logger.warn({err:i},"Failed to get system bars, using hardcoded bounds"),o={left:n.x+50,top:n.y+100,width:n.width-100,height:n.height-200}}return await t.startAsyncSpan("EMULATOR_INTERACTION",async i=>{await this.swipeByAbsoluteCoordinates({span:i,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:o})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0}}return await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async n=>ot().startAsyncSpan("EMULATOR_INTERACTION",async i=>"type"in n&&n.type==="NATIVE"?this.scrollInNativeContainer({span:i,cmd:e,target:n}):(i.withinWebview=!0,this.scrollInWebview({cmd:e,target:n})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t}),{success:!0}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=Math.floor(n.bounds[2]*.05),i=Math.floor(n.bounds[3]*.05);await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:{left:n.bounds[0]+o,top:n.bounds[1]+i,width:n.bounds[2]-n.bounds[0]-o*2,height:n.bounds[3]-n.bounds[1]-i*2}})}async scrollInWebview({cmd:e,target:t}){let{controller:n}=t,o=n.browser.getViewport();if(!o)throw new Error("Failed to get viewport size from webview");if(e.direction==="down"||e.direction==="up"){let i=o.height*(e.viewportPercent??$A)*(e.direction==="down"?1:-1);await n.browser.scrollVertical(i)}else{let i=o.width*(e.viewportPercent??.9)*(e.direction==="right"?1:-1);await n.browser.scrollHorizontal(i)}}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=$A,durationMs:o=500,containerBounds:i}){e.attributes.containerBounds=i;let a,s;t==="up"||t==="down"?(a=i.height*n,s=Math.floor(a/(o/1e3))):(a=i.width*n,s=Math.floor(a/(o/1e3))),e.attributes.pixelDelta=a,e.attributes.pixelsPerSecond=s,await this.driver.executeScript("mobile: swipeGesture",[{...i,direction:t,percent:n,speed:s}])}};import{existsSync as cU,readFileSync as uU}from"fs";import dU from"zod";var pU=dU.string().url();async function WA(r){if(pU.safeParse(r).success){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),n;try{n=await fetch(r,{signal:e.signal})}catch(i){throw new Error(`Fetch failed or timed out for URL: ${r}`,{cause:i})}finally{clearTimeout(t)}if(!n.ok)throw new Error(`Failed to fetch file from URL: ${r}, status: ${n.status}`);let o=await n.arrayBuffer();return Buffer.from(o).toString("base64")}if(!cU(r))throw new Error(`File does not exist at path: ${r}`);return uU(r).toString("base64")}import{execSync as KA}from"child_process";import gU from"pixelmatch";import{_android as hU,chromium as fU}from"playwright";import{PNG as YA}from"pngjs";import{z as Fe}from"zod";var qA=Fe.array(Fe.object({proc:Fe.string(),webview:Fe.string(),info:Fe.object({"Android-Package":Fe.string(),Browser:Fe.string(),"Protocol-Version":Fe.string(),"User-Agent":Fe.string(),"V8-Version":Fe.string(),"WebKit-Version":Fe.string(),webSocketDebuggerUrl:Fe.string()}),pages:Fe.array(Fe.object({description:Fe.string(),devtoolsFrontendUrl:Fe.string(),id:Fe.string(),title:Fe.string(),type:Fe.string(),url:Fe.string(),webSocketDebuggerUrl:Fe.string()})),webviewName:Fe.string()}));var Rc=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:s,aborter:c}){this.driver=e,this.device=o,this.currentContext=t,this.logger=n,this.fixtures=i,this.orgId=a,this.options=s,this.aborter=c;for(let l of["SIGINT","SIGTERM"])process.on(l,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,orgId:o,adbPort:i,options:a,aborter:s}){let c=await e.getContext(),l=typeof c=="string"?c:c.id,u=(await hU.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:l,logger:t,device:d,fixtures:n,orgId:o,options:a,aborter:s})}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getRawScreenshotBase64(){return await this.driver.takeScreenshot()}async getCurrentScreenshotPngString(){return`data:image/png;base64,${await this.getRawScreenshotBase64()}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tolerancePercent:o=1}){await ot().startAsyncSpan("WAIT_FOR_STABILITY",async i=>{let a=Date.now(),s,c=!1,l=(u,d)=>{let p=Buffer.from(u,"base64"),g=Buffer.from(d,"base64"),m=YA.sync.read(p),h=YA.sync.read(g);if(m.width!==h.width||m.height!==h.height)return 100;let f=m.width,E=m.height,S=Buffer.alloc(f*E*4);return gU(m.data,h.data,S,f,E,{threshold:.01})/(f*E)*100};for(;Date.now()-a<e;){if(t?.throwIfAborted(),!s){s=await this.getRawScreenshotBase64();continue}let u=await this.getRawScreenshotBase64();if(l(s,u)<=o){c=!0;break}s=u,await Q(250,t)}c||(i.attributes.timedOut=!0,this.logger.warn({purpose:n},"Timed out waiting for screenshot stability"))},{reason:n})}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController,n=await ot().startAsyncSpan("EMULATOR_READ_STATE",()=>t.getBrowserState({abortSignal:this.aborter.controller?.signal,serializationOpts:{noId:!0}}),{name:"Get webview content"});return this.throwIfAborted(),n.serializedTree}async getDomState(e){let t=ot(),n;if(!e?.skipWebviews)try{n=await this.getActiveWebviewContent()}catch(a){this.logger.error({err:a},"Could not get webview info to get the nested DOM state")}let o=await t.startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source"});return this.throwIfAborted(),{graph:await FA(o,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree}),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 s;if(i==="com.android.chrome"?(s=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}`),s=await this.connectPlaywrightToWebview(i,a.socketName),this.logger.info(`Connected Playwright to webview ${o.webview}`)),!s)continue;a.browserController=s,a.active=!0}}for(let[o,i]of this.webviews.entries())!n.has(o)&&i.active&&(this.logger.info(`Disconnecting dead webview ${o}`),this.disconnectPlaywrightFromWebview(i),i.active=!1)}async getActiveWebview(){await ot().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviews()});let e=await this.driver.execute("mobile: getCurrentPackage");e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let t=[];for(let n of this.webviews.values())n.packageName===e&&n.active&&t.push(n);if(t.length!==0){if(t.length>1)throw new Error("Multiple active webviews in a single package is currently not supported");return t[0]}}async executeRawADBCommand(e){let t=this.driver.capabilities,n=t.deviceUDID||t.udid||t["appium:udid"]||t["appium:deviceUDID"],o=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",i=n?`-s ${n}`:"",a=`${o} ${i} ${e}`;this.logger.info(`Executing ADB command: ${a}`);let s=KA(a,{encoding:"utf8"});return this.logger.info(`ADB command result: ${s}`),s}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){let e=await this.driver.execute("mobile: getContexts");return this.aborter.controller?.signal.throwIfAborted(),qA.parse(e)}async createBrowserController({context:e}){let t=await ca.fromExistingContext({context:e,logger:this.logger,userBrowserSettings:{visualActions:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[]},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});await t.getActivePage().waitForLoadState();let n=await t.getBrowserState({skipWait:!0,skipWaitForPageLoad:!0});return new yc({browser:t,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new Xs})}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 fU.connectOverCDP({endpointURL:o,timeout:5e3}),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}`:"",s=`${i} ${a} forward tcp:${t} ${`localabstract:${e}`||"localabstract:chrome_devtools_remote"}`;this.logger.info(`Executing command: ${s}`);let c=KA(s,{encoding:"utf8"});return this.logger.info(`ADB command result: ${c}`),this.logger.info(`Successfully forwarded DevTools socket to port ${t}`),t}async removeDevToolsForwarding(e){await this.executeRawADBCommand(`forward --remove tcp:${e}`),this.logger.info("Successfully removed port forwarding")}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};var si=class r extends nr{options;appsWithGrantedPermissions=new Set;adbPort;constructor(e){super(e),this.options=e.options??{},this.adbPort=e.adbPort}static async init({driver:e,generator:t,logger:n,fixtures:o,orgId:i,options:a,abortController:s,adbPort:c}){let l={controller:s},u=await Rc.init({driver:e,logger:n,fixtures:o,orgId:i,options:a?.emulator??{},aborter:l,adbPort:c}),d=new r({driver:e,generator:t,stateManager:u,logger:n,fixtures:o,options:a,aborter:l,orgId:i,adbPort:c});return await d.initializeSettings(),d}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${bU.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await Qs({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{el(e.command,n)}}async executeCommandHelper({command:e,tracer:t}){switch(e.type){case"TAP":return new vc(this.constructPerformerParams()).executeTap({command:e,tracer:t});case"TYPE":{let n;if(e.target){let i={type:"TAP",id:SU(),target:e.target,cache:e.cache,longPress:e.clearContent};try{n=(await this.executeCommand({command:i,tracer:t})).message}finally{e.cache=i.cache}}return await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await new Ac(this.constructPerformerParams()).doType(e),{success:!0,message:n}}case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=al(o),a=Date.now(),s=0,c,l=!1,u;for(;s<15&&!l;){this.throwIfAborted(),l||c&&c-a>=o&&(l=!0),s!==0&&await Q(i,this.aborter.controller?.signal),c=Date.now();try{let d="",p="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{d=(await this.stateManager.getDomState({})).graph.xml,p=await this.stateManager.getCurrentScreenshotPngString()},{name:"Get emulator state"});let 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:ye(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 ${s} failed, retrying...`),u=d instanceof Error?d:new Error(`${d}`)}finally{s++}}return{success:!1,message:u?.message}}case"SWIPE":return new wc(this.constructPerformerParams()).executeSwipe(e);case"JAVASCRIPT":{let n=await Ar({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"REQUEST":{let n;try{n=new URL(e.url).hostname}catch(l){throw new Error(`UserConfigurationError: Invalid URL: ${l}`)}let o=new EU,i=yU(fetch,o),a=Date.now(),s=await Sc({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),c=Ms(o,n);return{output:{...s,cookies:c},success:!0,message:`Successfully executed request in ${Date.now()-a}ms`}}case"OPEN_NOTIFICATION_DRAWER":return await new wn(this.constructPerformerParams()).doPress({keycode:83}),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let o=await V(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(`
|
|
3973
|
-
`).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,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=new wn(this.constructPerformerParams());switch(e.key){case"HOME":await n.doPress({keycode:3});break;case"BACK":await n.doPress({keycode:4});break;case"APP_SWITCHER":await n.doPress({keycode:187});break;case"POWER":await n.doPress({keycode:26});break;case"SEARCH":await n.doPress({keycode:84});break;case"VOLUME_UP":await n.doPress({keycode:24});break;case"VOLUME_DOWN":await n.doPress({keycode:25});break;case"VOLUME_MUTE":await n.doPress({keycode:164});break}return{success:!0}}case"PRESS_KEYBOARD":{let n=new wn(this.constructPerformerParams()),o=i=>n.doPress({keycode:i});switch(e.key){case"CLOSE_KEYBOARD":await this.driver.isKeyboardShown()&&await this.driver.hideKeyboard();break;case"ENTER":await o(66);break;case"BACKSPACE":await o(67);break;default:{let i=e}}return{success:!0}}case"WAIT":return await Q(e.timeoutSecs*1e3,this.aborter.controller?.signal),{success:!0};case"ADD_FILE":{let n=await WA(e.file);return await this.driver.pushFile(e.storageLocation,n),await this.driver.execute("mobile: shell",{command:"am",args:["broadcast","-a","android.intent.action.MEDIA_SCANNER_SCAN_FILE","-d",`file://${e.storageLocation}`]}),{success:!0}}case"ADB":{let n=await this.driver.execute(e.command,JSON.parse(e.jsonArgs??"{}"));return this.logger.info({output:n},"ADB command executed successfully"),{success:!0,output:n,message:"ADB command executed successfully"}}case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts(),i={xml:n.graph.xml,contexts:o};return this.logger.info({result:i},"State debug command output"),{output:i,success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){}async 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 XA({socket:r,logger:e,androidDriverFactory:t,getOrgId:n,mobileGeneratorFactory:o,browserGeneratorFactory:i,browserEnricherFactory:a,storageFactory:s,localToolsFactory:c,globalStateManager:l,settingsFactory:u}){let d=r.id,p=r.handshake.query?.testMetadata,g=r.handshake.query?.fileName,m=g?.endsWith("test.yaml")?g.slice(0,-"test.yaml".length):g,h=br.parse(JSON.parse(p??"")),f=h.id,E=h.settings?.defaultChannel,S=h.settings?.defaultTag,R=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:R});let v={...(await u(R,e)).emulator,...h.settings?.emulator},P=Date.now(),{driver:C,cleanup:w,limbarToken:F,limbarUrl:D,emulatorName:k,adbTunnelPort:Y}=await t({socket:r,logger:e,creationOpts:{region:v.region,apkToInstall:E?{channel:E,tag:S}:void 0}}),Me=await Zs({driver:C,onLogs:zt=>{r.emit("logcatLogs",zt)}});e.info({adbTunnelPort:Y,apkChannel:E,apkTag:S,duration:Date.now()-P,emulatorName:k},"Android emulator session initiated"),e=e.child({emulator:k});let q=await o(R,e),H=await i(R,e),ie=await a(R,e),ae=await s(R),Ie=c?await c(R):void 0,de={};h.settings?.defaultEnv&&(de=(await ae.fetchEnvironment(h.settings?.defaultEnv,e))?.variables??{});let at=new No({variablesFromEnvironment:de,envName:h.settings?.defaultEnv,testName:m}),Bt=await si.init({driver:C,generator:q,logger:e,options:{emulator:v},fixtures:{storage:ae,browserEnricher:ie,browserGenerator:H,localCodeEvalTools:Ie,testContext:at},orgId:R,adbPort:Y,abortController:new AbortController});if(!r.connected)throw await Me(),await w(),new Error("Socket not connected anymore, not proceeding with Android session setup");let Ee=TU({socket:r,testContext:at}),Ke=async()=>{clearInterval(Ee);try{await Me(),await w()}catch(zt){e.warn({err:zt},"Failed to clean up emulator in socket server")}};return l.registerSession(d,{controller:Bt,cleanup:Ke,emulatorName:k}),r.emit("session",{testId:f,sessionId:d,limbarUrl:D,limbarToken:F}),{sessionId:d,testId:f,orgId:R,emulatorName:k,logger:e}}function TU({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function JA({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var vU=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},ZA={event:"cancel",createHandler:vU};import{diff as zU}from"deep-object-diff";import{cloneDeep as HU}from"lodash-es";import yEe,{multistream as EEe}from"pino";import vEe from"pino-pretty";import AU from"fetch-retry";import wU from"os";import QA,{multistream as RU}from"pino";import CU from"pino-pretty";import xU from"pino-std-serializers";var ci=new Map,_U=!0,ew="Log throttle exceeded",MU=100,PU=5e3,IU=AU(global.fetch,{retries:2,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),Rm=class r{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=!1;lastWindowStart=Date.now();site="https://ingest.us.signoz.cloud:443/logs/json";flushIntervalMs;maxBatchSize;buffer=[];flushTimer;constructor({bindings:e,hostname:t,disableConsoleLogs:n,flushIntervalMs:o,maxBatchSize:i}){this.hostname=t??wU.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=_U?QA(a):QA(a,RU([{stream:CU({colorize:!0})}]))}getLevel(){return Ws[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 IU(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Bo(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===ew)return!0;let t=Date.now();return t-this.lastWindowStart>PU&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,ew),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<MU?(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(ta[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=xU.err(t.err));let i={...this.bindingAttributes,...t&&typeof t=="object"?t:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:zf({message:n||"",...i})};this.buffer.push(s),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let t=this.bindingAttributes.app;this.bindingAttributes.app=e,ci.set("app",this),ci.delete(t)}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=Ws[e]):(this.minLevelValue=ta[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Cc=({app:r,hostname:e,disableConsoleLogs:t})=>(ci.has(r)||ci.set(r,new Rm({bindings:{app:r},hostname:e,disableConsoleLogs:t})),ci.get(r));function tw(){for(let r of ci.values())r.flush()}import{PostHog as FEe}from"posthog-node";import{PostHog as qEe}from"posthog-node";import ka from"os";import OU from"v8";var rw,Or,LU=ka.platform(),NU=ka.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 nw(r){if(dn)return;let e=()=>{try{let t=!1,n=kU(),o=DU();n.freeMemory<1e6&&(t=!0),o&&o?.total>70&&(t=!0);let i=OU.getHeapStatistics(),a=i.used_heap_size,s=i.heap_size_limit;if(a/s>.9&&(t=!0),t)for(let c of[r,x])c.warn({memory:n,cpu:o,heapStats:i},"Critical resource usage metrics detected");else r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,2e4),cpuMetadata:NU,platform:LU}}function kU(){let r=ka.totalmem(),e=ka.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function DU(){let r=ka.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,!Or)return Or=t,null;let n={user:t.user-Or.user,nice:t.nice-Or.nice,sys:t.sys-Or.sys,idle:t.idle-Or.idle,irq:t.irq-Or.irq,total:t.total-Or.total};return rw={measurementTime:e,intervalMs:e-Or.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},Or=t,rw}function ow(r,e,t=1e4,n=5e3){let o=0;async function i(){try{let s=await V(r.driver.execute("mobile: shell",{command:"echo",args:["ping"]}).catch(c=>{throw c}),{milliseconds:n});if(typeof s=="string"&&s.trim()==="ping")o>0&&e.info("Driver heartbeat restored"),o=0;else throw new Error(`Unexpected heartbeat output: ${s}`)}catch(s){o++;let c=s instanceof Error?s.message:`${s}`;e.error({attempt:o,error:c},"Driver heartbeat failed"),o>=3&&e.error("Driver appears unresponsive \u2014 possible ADB tunnel/emulator failure")}}let a=setInterval(()=>{i()},t);return i(),a}async function iw(r){let e=Date.now(),t=r.fixtures.controller;try{return await UU(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 UU({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await FU({step:n,params:e}),s={};Object.entries(a).forEach(([p,g])=>{s[p]=JSON.stringify(g)});let c={...n,type:"MOBILE_MODULE_STEP",inputs:s,startTime:t,steps:[],endTime:Date.now(),status:"SUCCESS"},l=await o.startSubSteps(),{status:u,results:d}=await i({...e,listParams:{steps:n.steps,containerName:`module ('${n.name}')`,tracer:l}});return c.steps=d,c.status=u,c.endTime=Date.now(),fy({result:c,...hy(d)}),c}async function FU({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 Ar({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as aw}from"crypto";async function sw({fixtures:r,step:e,inputs:t,stepTracer:n}){let o=Date.now(),{logger:i,controller:a}=r,s=n.interactionTracer,c;if(!t.interactive)try{c=await a.screenshot()}catch(u){i.warn({err:u},"Failed to take before screenshot")}let l={...e,status:"SUCCESS",startTime:o,endTime:Date.now()};try{let u=await a.executeCommand({command:e.command,tracer:s});l={...e,status:u.success?"SUCCESS":"FAILED",message:u.message,startTime:o,endTime:Date.now(),data:u.output}}catch(u){u instanceof Error&&u.name==="AbortError"||a.isAborted()?l={...e,status:"CANCELLED",message:"Step cancelled.",startTime:o,endTime:Date.now()}:(i.error({err:u},"Failed to execute preset step"),l={...e,status:"FAILED",message:u instanceof Error?u.message:String(u),startTime:o,endTime:Date.now()})}finally{if(l.trace=s.getRootSpan(),!t.interactive){try{let u=aw(),d=await a.screenshot();l.afterSnapshot=u,n.attachAfterScreenshot({logger:i,snapshotId:u,screenshot:Buffer.from(d,"base64")})}catch(u){i.warn({err:u},"Failed to take after screenshot")}if(c){let u=aw();l.beforeSnapshot=u,n.attachBeforeScreenshot({logger:i,snapshotId:u,screenshot:Buffer.from(c,"base64")})}}}return l}async function Cm(r){let{fixtures:e,inputs:t,listParams:n}=r,{containerName:o,steps:i,tracer:a}=n,{logger:s,controller:c,usageTracker:l}=e,u=a.getParentStepIdChain(),d=[],p,g="SUCCESS",{fromStep:m,toStep:h}=t,f=!!m;for(let E=0;E<i.length;E++){let S=i[E];if(s.info({step:S},`Executing step ${E+1}/${i.length} in ${o}: ${ly(S)}`),S.skipped){s.debug("Step skipped");continue}if(f&&m){let v=JSON.stringify(u);if(S.id===m.fromStepId&&v===JSON.stringify(m.parentStepIdChain))f=!1;else if(!gy({currentStep:S,currentParentChain:u,desiredStepId:m.fromStepId,desiredStepParentChain:m.parentStepIdChain}))continue}let R=await a.startStep({logger:s,step:S,attempt:1,parentStepIdChain:u});l.trackStepExecution(S);let A=await BU({step:S,stepTracer:R,params:r});if(A.trace&&s.info({step:{id:S.id},trace:A.trace,status:A.status},`Step ${E+1}/${i.length} done (${S.type==="MOBILE_PRESET_STEP"?S.command.type:S.type})`),d.push(A),await R.finish({parentStepIdChain:u,result:A}),A.status!=="SUCCESS"){g=A.status,p=A;break}if(S.envKey&&c.context.setVariable(S.envKey,A.data),h){let v=JSON.stringify([]);if(S.id===h.toStepId&&v===JSON.stringify(h.parentStepIdChain))break}}return{results:d,status:g,terminalResult:p}}async function BU({step:r,stepTracer:e,params:t}){let{fixtures:n,inputs:o}=t,i;switch(r.type){case"MOBILE_PRESET_STEP":{i=await sw({fixtures:n,inputs:o,step:r,stepTracer:e});break}case"RESOLVED_MOBILE_MODULE":{i=await iw({...t,moduleParams:{step:r,stepTracer:e,executeMobileStepList:Cm}});break}}return i}async function xc(r){let{tracer:e,containerName:t}=r,{steps:n,testMetadata:o}=r.inputs,{cacheStorage:i,logger:a,controller:s}=r.fixtures;await i.resolveEntries({logger:a,testId:o.id,stepLists:{steps:n}});let c=HU(n);a.info({testMetadata:br.parse(o)},"Starting mobile test");let l=await e.startMainStepList(),u=nw(a),d=ow(s,a);a.info({cpu:u?.cpuMetadata,platform:u?.platform},`Starting execution of ${t}`);let{status:p,results:g}=await Cm({...r,listParams:{containerName:t,tracer:l,steps:c}});if(clearInterval(u?.interval),clearInterval(d),p==="SUCCESS"){let m=zU(c,n);if(m&&Object.keys(m).length>0){a.debug({diffs:m},"Saving mobile step cache entries post-success");let{cachesToSave:h}=await $n({steps:c,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 xm=class{parentTracer=null;socket;step;interactionTracer;constructor({step:e,socket:t,parentTracer:n}){this.socket=t,this.parentTracer=n,this.step=e,this.interactionTracer=new so,An.initializeRootTracerContext(this.interactionTracer)}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}async finish(e){this.interactionTracer.finish();let t=this.interactionTracer.getRootSpan(),n={...FS.parse(e),trace:Zu.parse(t)};switch(n.result.status){case"SUCCESS":this.socket.emit("success",n);break;case"FAILED":this.socket.emit("failure",n);break;case"CANCELLED":this.socket.emit("cancelled",n);break}return{trace:t}}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}async startSubSteps(){return new ui({parentStep:this.step,socket:this.socket,parentTracer:this})}},ui=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 xm({step:e.step,parentTracer:this,socket:this.socket})}},_c=class{constructor(e){this.socket=e}appendLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new ui({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new ui({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new ui({parentStep:null,parentTracer:null,socket:this.socket})}};var GU=({metadata:r,logger:e,globalStateManager:t,socket:n,cacheStorageFactory:o})=>async(i,a)=>{let s=t.getSession(n.id);if(!s)throw new Error("No active Android session found");let c=await o(r.orgId),l=s.controller;l.resetAbortController();let u=new _c(n),d=await xc({fixtures:{controller:l,logger:e,cacheStorage:c,usageTracker:new xs},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:dr.array().parse(d.results),status:d.status};a?.(p)},lw={event:"execute",createHandler:GU};import{debounce as jU}from"ts-debounce";var VU=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=jU(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)}},cw={event:"keepalive",createHandler:VU};var uw=[lw,ZA,cw];function dw(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new $U(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 s=>{e.info({event:"connection",transport:s.conn.transport.name},"Android websocket connection initiated"),s.on("disconnect",async()=>{await JA({socket:s,globalStateManager:n,logger:e})});let c;try{c=await XA({...r,socket:s,globalStateManager:n})}catch(l){e.error({err:l},"Failed to setup Android connection"),s.emit("error",{message:l instanceof Error?l.message:JSON.stringify(l)}),s.disconnect(!0);return}uw.forEach(l=>a(l,{...r,socket:s,metadata:c,logger:e}))});let a=(s,c)=>{let l=s.createHandler(c),u=(...d)=>{s.event!=="keepalive"&&c.logger.debug({event:s.event},`Websocket event (${s.event})`);let p=g=>{c.logger.error({event:s.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=l.apply(this,d);g&&typeof g.catch=="function"&&g.catch(p)}catch(g){p(g)}};c.socket.on(s.event,u)};return{server:o,dispose:i}}var Da=!!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 KU,input as YU}from"@inquirer/prompts";import{existsSync as bAe,mkdirSync as EAe,statSync as XU}from"fs";import di,{supportsColor as qU}from"chalk";import{Console as pw}from"console";import{format as Ua}from"util";var _m=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}},Mc=class r extends pw{_buffer=[];_groupDepth=0;Console=pw;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new _m(void 0,r.write).stack;if(!i)return e;let a=i.split(`
|
|
4025
|
+
`));return}}let d=Array.from(e.childNodes??[]);for(let p of d){let h=p.nodeType;if(h===3){let m=p.nodeValue;m&&m.trim().length>0&&t.appendChild(n.createTextNode(m));continue}if(h===1){let m=p,g=n.createElement(MF(m.tagName));Vw(r,m,g),t.appendChild(g)}}}function DF(r,e,t,n){let o=r.parseFromString("<hierarchy/>","text/xml"),i=new Map,a={prunedDocument:o,idToElement:t,prunedIdToElement:i,idCounter:{value:0},opts:n},s=o.documentElement;Vw(a,e,s);let c=new _F().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function $w(r,e){let t=new xF,n=t.parseFromString(r,"text/xml"),o=new Map,i=n.documentElement;if(!i)throw new Error("No root element found in XML");if(i.tagName!=="hierarchy")throw new Error("No hierarchy element found in XML");let{prunedDocument:a,prunedIdToElement:s,xml:c}=DF(t,i,o,e);return{xml:await CF.format(c,{parser:"xml",plugins:[RF],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function UF(r){let e=[],t=r;for(;t;){let n=t.tagName,o=t.parentElement,i=1;if(o){let a=Array.from(o.children).filter(s=>s.tagName===n);for(let s=0;s<a.length;s++)if(a[s]===t){i=s+1;break}}e.unshift(`${n}[${i}]`),t=o}return`/${e.join("/")}`}function Dc(r,e){let t=r.idToElement.get(e);if(t)return UF(t)}function $m(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 Uc(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 Wm(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function Kw({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=Uc(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=Dc(t.graph,r.id)??"",a=$m(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=Wm(s,r.requirements?.attributesRequired),u={requiredText:r.requirements?.textRequired?s?.getAttribute("text")??void 0:void 0,requiredAttributes:c,requiredBounds:r.requirements?.boundsRequired},d=[];r.additionalElements&&(d=r.additionalElements.map(({id:h,requirements:m})=>{let g=t.graph.idToElement.get(h);if(!g)return;let f=Dc(t.graph,h);return f?{xPath:f,requirements:{requiredText:m.textRequired?g.getAttribute("text")??void 0:void 0,requiredAttributes:Wm(g,m.attributesRequired),requiredBounds:m.boundsRequired}}:void 0}).filter(h=>!!h));let p;return Vm(n.tagName)&&r.inWebview!==!1?p={type:"WEBVIEW",resolvedDescription:e,xPath:i}:p={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},p}var qw=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i}=e;if(o!==void 0){let a=r.getAttribute("text")??void 0;if(a!==o)throw new Error(`ActionFailureError: Resolved element text mismatch: expected ${o}, got ${a}`)}if(n)for(let[a,s]of Object.entries(n)){let c=r.getAttribute(a)??void 0;if(c!==s)throw new Error(`ActionFailureError: Attribute ${a} mismatch: expected ${s}, got ${c}`)}if(i&&t){let a=Uc(r);if(!a||a.length!==t.length)throw new Error("ActionFailureError: Resolved element has no bounds or unexpected bounds format");if(!a.every((c,l)=>c===t[l]))throw new Error(`ActionFailureError: Bounds changed from [${t.join(",")} ] to [${a.join(",")} ]`)}};async function Yw(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=et();if(e.type==="WEBVIEW")return FF(e,r);let a=Ww.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let p=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let h of p){let m=Ww.evaluateXPathToFirstNode(h.xPath,o);if(!m)throw new Error(`ActionFailureError: Required related element not found for XPath: ${h.xPath}`);qw(m,h.requirements)}})}let s=Uc(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");qw(a,e.requirements,e.bounds);let c;for(let[p,h]of n.idToElement.entries())if(h===a){c=p;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=$m(n,c)??l,u=Dc(n,c)??u),{resolvedTarget:{...e,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function FF(r,e){let{stateManager:t,logger:n,signal:o}=e,i=et(),a=await t.getActiveWebview();if(!a||!a.browserController)throw new Error("No browser controller is attached to the requested webview");let s=a.browserController.browser;if(!r.browserCache)throw new Error("No browser target available on cache");let c=r.browserCache,l=await i.startAsyncSection("Resolve target in webview",()=>s.resolveTarget(null,c,{logger:n,signal:o}));return{resolvedTarget:{...r,controller:a.browserController,resolution:l}}}function qm(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;Ys(e)&&(e[t]={...e[t],[n]:Ks.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function Xw(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var cr=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,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSection("Get emulator state",async c=>{let l=await this.stateManager.getDomState(),u=await c.startAsyncSpan("EMULATOR_READ_STATE",()=>this.stateManager.getCurrentScreenshotPngString(),{name:"Emulator screenshot"});return{emulatorState:l,screenshot:u}}),o;try{o=await t.startAsyncSpan("AI_LOCATOR_CALL",async c=>{let l=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:ve(this.logger),abortSignal:this.aborter.controller?.signal});return c.result=l,l})}catch(c){throw this.throwIfAborted(),this.logger.error({err:c},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${c instanceof Error?c.message:c}`)}if(o.id===-1)throw new Error(`ActionFailureError: No matching element found: ${o.thoughts}`);let i=Kw({aiResponse:o,description:e,emulatorState:n.emulatorState});if(i.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:i.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:i,thoughts:o.thoughts};let{browserLocateResult:a,browserController:s}=await t.startAsyncSpan("TARGET_RESOLUTION",async c=>{let l=await this.stateManager.getActiveWebview();if(!l||!l.browserController)throw new Error("No browser controller is attached to the requested webview");let u=await l.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return c.result={serializedElement:u.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:u,browserController:l.browserController}});return{resolvedTarget:{...i,controller:s,resolution:a.resolution,browserCache:a.target},thoughts:a.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c}=e,l=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,u=e.retriesWithAI??1,d=!1,p=zF(l),h;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,p=void 0),s&&(d=!0,p=void 0),p&&p?.resolvedDescription!==n&&(this.logger.info({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 g=await this.findElement({description:n,tracer:c});return h=g.thoughts,qm({command:o,cacheKey:i,targetName:a,updatedCache:g.resolvedTarget,updatedWithAI:!0}),{result:await t(g.resolvedTarget),thoughts:h}}let m;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),m=await c.startAsyncSection("Get emulator XML tree",async()=>await this.stateManager.getDomState());let g=await c.startAsyncSection("Resolve target cache",async(E,S)=>{let{resolvedTarget:w}=await Yw({target:p,domState:m,stateManager:this.stateManager,logger:this.logger}),v=Xw(w),A=BF(p,v);return this.logger.info({cacheDiffs:A},"Successfully resolved and updated target"),qm({command:o,cacheKey:i,targetName:a,updatedCache:v,updatedWithAI:!1}),S.attributes.serializedElement=w.type==="WEBVIEW"?w.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":w.elementOnlySerializedXml,w}),f=await t(g);return p.type!=="WEBVIEW"&&Ht.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`]),{result:f,thoughts:"Successfully executed preset action with cache."}}catch(g){if(p.type!=="WEBVIEW"&&Ht.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`]),this.throwIfAborted(),u>0)return this.logger.warn({err:g},"Failed to resolve target cache, retrying with AI"),this.logger.debug({domState:m?.graph.originalXml},"Emulator state"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${g instanceof Error?g.message:g}`,{cause:g})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};function jF(r){let e={relativePosition:r.relativePosition};if(r.doubleTap&&r.longPress)throw new Error("UserConfigurationError: Cannot specify both doubleTap and longPress");return r.doubleTap?{...e,doubleTap:!0,doubleTapDelayMs:r.doubleTapDelayMs}:r.longPress?{...e,longPress:!0,longPressDurationMs:r.longPressDurationMs}:e}var Si=class extends cr{async tapOnAbsoluteCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(e.doubleTap){await this.driver.tap({x:t,y:n});let o=e.doubleTapDelayMs??100;await new Promise(i=>setTimeout(i,o))}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,s=i-n,c=a-o,l=t?.relativePosition?.x??s/2,u=t?.relativePosition?.y??c/2;l=Math.max(0,Math.min(l,s)),u=Math.max(0,Math.min(u,c));let d=n+l,p=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:p,...t}),{x:d,y:p}}async tapOnWebviewTarget(e,t){let{controller:n}=e;return(await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let i=Math.random().toString(36).substring(4),a=Jw.join(GF(),"momentic","downloads"),s=Jw.join(a,this.orgId,i);return HF(s,{recursive:!0}),s}},{delayMs:t?.longPress?t?.longPressDurationMs??2e3:void 0,relativePosition:t?.relativePosition,doubleClick:t?.doubleTap})).coordinates}async tapOnTarget({target:e,options:t}){return await et().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.attributes.options=t,"type"in e&&e.type==="NATIVE"?o.attributes.point=await this.tapOnNativeTarget(e,t):(o.withinWebview=!0,o.attributes.point=await this.tapOnWebviewTarget(e,t))},{name:"Tap on target"})}async executeTap({command:e,tracer:t}){let n=jF(e);if(e.target.type==="coordinates"){let a=await this.driver.getWindowSize(),s=e.target.xPercent*a.width,c=e.target.yPercent*a.height;return await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.tapOnAbsoluteCoordinates({...n,x:s,y:c})},{name:`Tap at coordinates ${s}, ${c}`}),{success:!0,message:`Tapped at ${s}, ${c}`}}let o=e.target.description,{thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,action:a=>this.tapOnTarget({target:a,options:n}),description:o});return{success:!0,message:i}}};var On=class extends cr{async doPress({keycode:e,longPress:t}){await et().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var Fc=class extends cr{async doType(e){if(!e.target){if(e.clearContent)throw new Error("UserConfigurationError: clearing content is only supported when a target is provided to the Type step");return await this.sendKeys(e),{success:!0,message:void 0}}if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Type step");let t=et(),{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{"type"in o&&o.type==="NATIVE"?await this.doNativeType(e,o):await this.doWebviewType(e,o)},description:e.target.description});return{success:!0,message:n}}async doWebviewType(e,t){await et().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0,o.attributes.options={clearContent:e.clearContent};let{controller:i}=t;await i.browser.type(e.text,{clearContent:e.clearContent})},{name:"Typing within web view"})}async doNativeType(e,t){let n=new Si(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=et(),n=e.keyPressDelayMs;n?await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.updateSettings({keyInjectionDelay:n}),await this.driver.keys(e.text),await this.driver.updateSettings({keyInjectionDelay:0})},{name:"Typing keys with a delay"}):await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.keys(e.text)},{name:"Typing keys"})}async clearContent(){let e=et();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to clear content because the select all button was not found, continuing...")}}async clearContentHelper(){let e=this.driver.$('//android.widget.LinearLayout[@content-desc="Select all" and @clickable="true"]');await e.waitForExist({timeout:750}),await e.click(),await new On(this.constructPerformerParams()).doPress({keycode:67})}};import Gt from"zod";var Zw=.9,VF=Gt.object({navigationBar:Gt.object({visible:Gt.boolean(),x:Gt.number(),y:Gt.number(),width:Gt.number(),height:Gt.number()}),statusBar:Gt.object({visible:Gt.boolean(),x:Gt.number(),y:Gt.number(),width:Gt.number(),height:Gt.number()})}),Bc=class extends cr{async executeSwipe(e){let t=et();if(e.scrollableElement.type!=="CUSTOM"){await this.stateManager.waitForScreenshotStability({timeoutMs:2e3,signal:this.aborter.controller?.signal,reason:"Waiting for screen to stabilize before swiping"});let n=await this.driver.getWindowRect(),o;if(e.scrollableElement.type==="SCREEN")o={left:n.x+25,top:n.y+50,width:n.width-50,height:n.height-100};else try{let i=VF.parse(await this.driver.executeScript("mobile: getSystemBars",[]));o={left:n.x+25,top:n.y+50,width:n.width-50,height:n.height-100},i.navigationBar.visible&&(o.height-=i.navigationBar.height),i.statusBar.visible&&(o.top+=i.statusBar.height,o.height-=i.statusBar.height)}catch(i){this.logger.warn({err:i},"Failed to get system bars, using hardcoded bounds"),o={left:n.x+50,top:n.y+100,width:n.width-100,height:n.height-200}}return await t.startAsyncSpan("EMULATOR_INTERACTION",async i=>{await this.swipeByAbsoluteCoordinates({span:i,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:o})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0}}return await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async n=>et().startAsyncSpan("EMULATOR_INTERACTION",async i=>"type"in n&&n.type==="NATIVE"?this.scrollInNativeContainer({span:i,cmd:e,target:n}):(i.withinWebview=!0,this.scrollInWebview({cmd:e,target:n})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t}),{success:!0}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=Math.floor(n.bounds[2]*.05),i=Math.floor(n.bounds[3]*.05);await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:{left:n.bounds[0]+o,top:n.bounds[1]+i,width:n.bounds[2]-n.bounds[0]-o*2,height:n.bounds[3]-n.bounds[1]-i*2}})}async scrollInWebview({cmd:e,target:t}){let{controller:n}=t,o=n.browser.getViewport();if(!o)throw new Error("Failed to get viewport size from webview");if(e.direction==="down"||e.direction==="up"){let i=o.height*(e.viewportPercent??Zw)*(e.direction==="down"?1:-1);await n.browser.scrollVertical(i)}else{let i=o.width*(e.viewportPercent??.9)*(e.direction==="right"?1:-1);await n.browser.scrollHorizontal(i)}}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=Zw,durationMs:o=500,containerBounds:i}){e.attributes.containerBounds=i;let a,s;t==="up"||t==="down"?(a=i.height*n,s=Math.floor(a/(o/1e3))):(a=i.width*n,s=Math.floor(a/(o/1e3))),e.attributes.pixelDelta=a,e.attributes.pixelsPerSecond=s,await this.driver.executeScript("mobile: swipeGesture",[{...i,direction:t,percent:n,speed:s}])}};import{existsSync as $F,readFileSync as WF}from"fs";import qF from"zod";var KF=qF.string().url();async function Qw(r){if(KF.safeParse(r).success){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),n;try{n=await fetch(r,{signal:e.signal})}catch(i){throw new Error(`Fetch failed or timed out for URL: ${r}`,{cause:i})}finally{clearTimeout(t)}if(!n.ok)throw new Error(`Failed to fetch file from URL: ${r}, status: ${n.status}`);let o=await n.arrayBuffer();return Buffer.from(o).toString("base64")}if(!$F(r))throw new Error(`File does not exist at path: ${r}`);return WF(r).toString("base64")}import{execSync as tR}from"child_process";import XF from"pixelmatch";import{_android as JF,chromium as ZF}from"playwright";import{PNG as rR}from"pngjs";import{z as je}from"zod";var eR=je.array(je.object({proc:je.string(),webview:je.string(),info:je.object({"Android-Package":je.string(),Browser:je.string(),"Protocol-Version":je.string(),"User-Agent":je.string(),"V8-Version":je.string(),"WebKit-Version":je.string(),webSocketDebuggerUrl:je.string()}),pages:je.array(je.object({description:je.string(),devtoolsFrontendUrl:je.string(),id:je.string(),title:je.string(),type:je.string(),url:je.string(),webSocketDebuggerUrl:je.string()})),webviewName:je.string()}));var zc=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:s,aborter:c}){this.driver=e,this.device=o,this.currentContext=t,this.logger=n,this.fixtures=i,this.orgId=a,this.options=s,this.aborter=c;for(let l of["SIGINT","SIGTERM"])process.on(l,async()=>{await this.cleanupWebviews(),setImmediate(()=>{setTimeout(()=>{process.exit(1)},2e3).unref()})})}static async init({driver:e,logger:t,fixtures:n,orgId:o,adbPort:i,options:a,aborter:s}){let c=await e.getContext(),l=typeof c=="string"?c:c.id,u=(await JF.devices()).filter(h=>h._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:l,logger:t,device:d,fixtures:n,orgId:o,options:a,aborter:s})}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getRawScreenshotBase64(){return await this.driver.takeScreenshot()}async getCurrentScreenshotPngString(){return`data:image/png;base64,${await this.getRawScreenshotBase64()}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tolerancePercent:o=1}){await et().startAsyncSpan("WAIT_FOR_STABILITY",async i=>{let a=Date.now(),s,c=!1,l=(u,d)=>{let p=Buffer.from(u,"base64"),h=Buffer.from(d,"base64"),m=rR.sync.read(p),g=rR.sync.read(h);if(m.width!==g.width||m.height!==g.height)return 100;let f=m.width,E=m.height,S=Buffer.alloc(f*E*4);return XF(m.data,g.data,S,f,E,{threshold:.01})/(f*E)*100};for(;Date.now()-a<e;){if(t?.throwIfAborted(),!s){s=await this.getRawScreenshotBase64();continue}let u=await this.getRawScreenshotBase64();if(l(s,u)<=o){c=!0;break}s=u,await ee(250,t)}c||(i.attributes.timedOut=!0,this.logger.warn({purpose:n},"Timed out waiting for screenshot stability"))},{reason:n})}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController,n=await et().startAsyncSpan("EMULATOR_READ_STATE",()=>t.getBrowserState({abortSignal:this.aborter.controller?.signal,serializationOpts:{noId:!0}}),{name:"Get webview content"});return this.throwIfAborted(),n.serializedTree}async getDomState(e){let t=et(),n;if(!e?.skipWebviews)try{n=await this.getActiveWebviewContent()}catch(a){this.logger.error({err:a},"Could not get webview info to get the nested DOM state")}let o=await t.startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source"});return this.throwIfAborted(),{graph:await $w(o,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree}),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 s;if(i==="com.android.chrome"?(s=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}`),s=await this.connectPlaywrightToWebview(i,a.socketName),this.logger.info(`Connected Playwright to webview ${o.webview}`)),!s)continue;a.browserController=s,a.active=!0}}for(let[o,i]of this.webviews.entries())!n.has(o)&&i.active&&(this.logger.info(`Disconnecting dead webview ${o}`),this.disconnectPlaywrightFromWebview(i),i.active=!1)}async getActiveWebview(){await et().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviews()});let e=await this.driver.execute("mobile: getCurrentPackage");e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let t=[];for(let n of this.webviews.values())n.packageName===e&&n.active&&t.push(n);if(t.length!==0){if(t.length>1)throw new Error("Multiple active webviews in a single package is currently not supported");return t[0]}}async executeRawADBCommand(e){let t=this.driver.capabilities,n=t.deviceUDID||t.udid||t["appium:udid"]||t["appium:deviceUDID"],o=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",i=n?`-s ${n}`:"",a=`${o} ${i} ${e}`;this.logger.info(`Executing ADB command: ${a}`);let s=tR(a,{encoding:"utf8"});return this.logger.info(`ADB command result: ${s}`),s}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){let e=await this.driver.execute("mobile: getContexts");return this.aborter.controller?.signal.throwIfAborted(),eR.parse(e)}async createBrowserController({context:e}){let t=await wa.fromExistingContext({context:e,logger:this.logger,userBrowserSettings:{visualActions:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[],isAndroid:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});await t.getActivePage().waitForLoadState();let n=await t.getBrowserState({skipWait:!0,skipWaitForPageLoad:!0});return new Nc({browser:t,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new pl})}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 ZF.connectOverCDP({endpointURL:o,timeout:5e3}),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}`:"",s=`${i} ${a} forward tcp:${t} ${`localabstract:${e}`||"localabstract:chrome_devtools_remote"}`;this.logger.info(`Executing command: ${s}`);let c=tR(s,{encoding:"utf8"});return this.logger.info(`ADB command result: ${c}`),this.logger.info(`Successfully forwarded DevTools socket to port ${t}`),t}async removeDevToolsForwarding(e){await this.executeRawADBCommand(`forward --remove tcp:${e}`),this.logger.info("Successfully removed port forwarding")}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};var yi=class r extends cr{options;appsWithGrantedPermissions=new Set;adbPort;constructor(e){super(e),this.options=e.options??{},this.adbPort=e.adbPort}static async init({driver:e,generator:t,logger:n,fixtures:o,orgId:i,options:a,abortController:s,adbPort:c}){let l={controller:s},u=await zc.init({driver:e,logger:n,fixtures:o,orgId:i,options:a?.emulator??{},aborter:l,adbPort:c}),d=new r({driver:e,generator:t,stateManager:u,logger:n,fixtures:o,options:a,aborter:l,orgId:i,adbPort:c});return await d.initializeSettings(),d}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${eB.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await gl({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{fl(e.command,n)}}async executeCommandHelper({command:e,tracer:t}){switch(e.type){case"TAP":return new Si(this.constructPerformerParams()).executeTap({command:e,tracer:t});case"TYPE":return await new Fc(this.constructPerformerParams()).doType(e);case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=vl(o),a=Date.now(),s=0,c,l=!1,u;for(;s<15&&!l;){this.throwIfAborted(),l||c&&c-a>=o&&(l=!0),s!==0&&await ee(i,this.aborter.controller?.signal),c=Date.now();try{let d="",p="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{d=(await this.stateManager.getDomState({})).graph.xml,p=await this.stateManager.getCurrentScreenshotPngString()},{name:"Get emulator state"});let h=await t.startAsyncSpan("AI_ASSERTION_CALL",async m=>{let g=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:p},{logger:this.logger,loggerTags:ve(this.logger)});return m.result={thoughts:g.thoughts,result:g.result},g});if(h.result)return{success:h.result,message:h.thoughts};{let m=`AssertionFailureError: ${h.thoughts}`;u=new Error(m)}}catch(d){this.throwIfAborted(),this.logger.info({err:d},`AI check assert attempt ${s} failed, retrying...`),u=d instanceof Error?d:new Error(`${d}`)}finally{s++}}return{success:!1,message:u?.message}}case"SWIPE":return new Bc(this.constructPerformerParams()).executeSwipe(e);case"JAVASCRIPT":{let n=await Ir({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"REQUEST":{let n;try{n=new URL(e.url).hostname}catch(l){throw new Error(`UserConfigurationError: Invalid URL: ${l}`)}let o=new tB,i=QF(fetch,o),a=Date.now(),s=await Lc({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),c=qs(o,n);return{output:{...s,cookies:c},success:!0,message:`Successfully executed request in ${Date.now()-a}ms`}}case"OPEN_NOTIFICATION_DRAWER":return await new On(this.constructPerformerParams()).doPress({keycode:83}),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let i=["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName],a=await $(this.driver.execute("mobile: shell",{command:"pm",args:i}),{signal:this.aborter.controller?.signal,milliseconds:1e4});if(typeof a!="string")throw new Error(`Could not find main activity name for package ${e.packageName}. Unexpected output: ${a}`);if(a.includes("No activity found"))throw new Error(`No activity found for package ${e.packageName}.`);if(n=a.trim().split(`
|
|
4026
|
+
`).pop()?.replace(/^.*\//,""),!n)throw new Error(`Could not parse main activity name for package ${e.packageName}. Raw output: ${a}`)}if(this.options.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let i={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[i]),this.appsWithGrantedPermissions.add(e.packageName)}let o=["start"];if(e.intentExtras)try{let i=JSON.parse(e.intentExtras);for(let[a,s]of Object.entries(i))o.push("-e",a,typeof s=="string"?s:JSON.stringify(s))}catch(i){throw new Error(`UserConfigurationError: Invalid intent extras does not parse as valid JSON: ${i instanceof Error?i.message:`${i}`}`)}return o.push("-n",`${e.packageName}/${n}`),await this.driver.execute("mobile: shell",{command:"am",args:o}),await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=new On(this.constructPerformerParams());switch(e.key){case"HOME":await n.doPress({keycode:3});break;case"BACK":await n.doPress({keycode:4});break;case"APP_SWITCHER":await n.doPress({keycode:187});break;case"POWER":await n.doPress({keycode:26});break;case"SEARCH":await n.doPress({keycode:84});break;case"VOLUME_UP":await n.doPress({keycode:24});break;case"VOLUME_DOWN":await n.doPress({keycode:25});break;case"VOLUME_MUTE":await n.doPress({keycode:164});break}return{success:!0}}case"PRESS_KEYBOARD":{let n=new On(this.constructPerformerParams()),o=i=>n.doPress({keycode:i});switch(e.key){case"CLOSE_KEYBOARD":await this.driver.isKeyboardShown()&&await this.driver.hideKeyboard();break;case"ENTER":await o(66);break;case"BACKSPACE":await o(67);break;default:{let i=e}}return{success:!0}}case"WAIT":return await ee(e.timeoutSecs*1e3,this.aborter.controller?.signal),{success:!0};case"ADD_FILE":{let n=await Qw(e.file);return await this.driver.pushFile(e.storageLocation,n),await this.driver.execute("mobile: shell",{command:"am",args:["broadcast","-a","android.intent.action.MEDIA_SCANNER_SCAN_FILE","-d",`file://${e.storageLocation}`]}),{success:!0}}case"ADB":{let n=await this.driver.execute(e.command,JSON.parse(e.jsonArgs??"{}"));return this.logger.info({output:n},"ADB command executed successfully"),{success:!0,output:n,message:"ADB command executed successfully"}}case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts(),i={xml:n.graph.xml,contexts:o};return this.logger.info({result:i},"State debug command output"),{output:i,success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){}async 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 nR({socket:r,logger:e,androidDriverFactory:t,getOrgId:n,mobileGeneratorFactory:o,browserGeneratorFactory:i,browserEnricherFactory:a,storageFactory:s,localToolsFactory:c,globalStateManager:l,settingsFactory:u}){let d=r.id,p=r.handshake.query?.testMetadata,h=r.handshake.query?.fileName,m=h?.endsWith("test.yaml")?h.slice(0,-"test.yaml".length):h,g=_r.parse(JSON.parse(p??"")),f=g.id,E=g.settings?.defaultChannel,S=g.settings?.defaultTag,w=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:w});let A={...(await u(w,e)).emulator,...g.settings?.emulator},I=Date.now(),{driver:C,cleanup:R,limbarToken:B,limbarUrl:U,emulatorName:D,adbTunnelPort:J}=await t({socket:r,logger:e,creationOpts:{region:A.region,apkToInstall:E?{channel:E,tag:S}:void 0}}),Le=await hl({driver:C,onLogs:Wt=>{r.emit("logcatLogs",Wt)}});e.info({adbTunnelPort:J,apkChannel:E,apkTag:S,duration:Date.now()-I,emulatorName:D},"Android emulator session initiated"),e=e.child({emulator:D});let K=await o(w,e),G=await i(w,e),se=await a(w,e),ce=await s(w),ke=c?await c(w):void 0,fe={};g.settings?.defaultEnv&&(fe=(await ce.fetchEnvironment(g.settings?.defaultEnv,e))?.variables??{});let pt=new $o({variablesFromEnvironment:fe,envName:g.settings?.defaultEnv,testName:m}),$t=await yi.init({driver:C,generator:K,logger:e,options:{emulator:A},fixtures:{storage:ce,browserEnricher:se,browserGenerator:G,localCodeEvalTools:ke,testContext:pt},orgId:w,adbPort:J,abortController:new AbortController});if(!r.connected)throw await Le(),await R(),new Error("Socket not connected anymore, not proceeding with Android session setup");let we=rB({socket:r,testContext:pt}),tt=async()=>{clearInterval(we);try{await Le(),await R()}catch(Wt){e.warn({err:Wt},"Failed to clean up emulator in socket server")}};return l.registerSession(d,{controller:$t,cleanup:tt,emulatorName:D}),r.emit("session",{testId:f,sessionId:d,limbarUrl:U,limbarToken:B}),{sessionId:d,testId:f,orgId:w,emulatorName:D,logger:e}}function rB({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function oR({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var nB=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},iR={event:"cancel",createHandler:nB};import{diff as TB}from"deep-object-diff";import{cloneDeep as vB}from"lodash-es";import wRe,{multistream as CRe}from"pino";import _Re from"pino-pretty";import oB from"fetch-retry";import iB from"os";import aR,{multistream as aB}from"pino";import sB from"pino-pretty";import lB from"pino-std-serializers";var Ei=new Map,cB=!0,sR="Log throttle exceeded",uB=100,dB=5e3,pB=oB(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}}),Ym=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??iB.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=cB?aR(a):aR(a,aB([{stream:sB({colorize:!0})}]))}getLevel(){return ll[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 pB(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Yo(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===sR)return!0;let t=Date.now();return t-this.lastWindowStart>dB&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,sR),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<uB?(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(ga[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=lB.err(t.err));let i={...this.bindingAttributes,...t&&typeof t=="object"?t:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:KS({message:n||"",...i})};this.buffer.push(s),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let t=this.bindingAttributes.app;this.bindingAttributes.app=e,Ei.set("app",this),Ei.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=ll[e]):(this.minLevelValue=ga[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Hc=({app:r,hostname:e,disableConsoleLogs:t})=>(Ei.has(r)||Ei.set(r,new Ym({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Ei.get(r));function lR(){for(let r of Ei.values())r.flush()}import{PostHog as VRe}from"posthog-node";import{PostHog as QRe}from"posthog-node";import Xa from"os";import mB from"v8";var yo=!!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;var cR,Hr,hB=Xa.platform(),gB=Xa.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),{}),uR=r=>{try{let e=!1,t=fB(),n=SB(),o=`${Math.round(t.freePercentage*100)}%`;t.freePercentage<.05&&(e=!0);let i=`${n?Math.round(n.idle):"unknown"}%`;n&&n?.total>70&&(e=!0);let a=mB.getHeapStatistics(),s=a.used_heap_size,c=a.heap_size_limit;s/c>.9&&(e=!0),e?(r.warn({memory:t,cpu:n,heapStats:a},"Critical resource usage metrics detected"),yo&&x.warn(`Low machine resources detected (memory: ${o} free, cpu: ${i} free)`)):r.debug({memory:t,cpu:n},"Got machine resource usage metrics")}catch{}};function dR(r){if(!yn)return uR(r),{interval:setInterval(()=>uR(r),2e4),cpuMetadata:gB,platform:hB}}function fB(){let r=Xa.totalmem(),e=Xa.freemem(),t=e/r;return{totalMemory:r,freeMemory:e,freePercentage:t}}function SB(){let r=Xa.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,!Hr)return Hr=t,null;let n={user:t.user-Hr.user,nice:t.nice-Hr.nice,sys:t.sys-Hr.sys,idle:t.idle-Hr.idle,irq:t.irq-Hr.irq,total:t.total-Hr.total};return cR={measurementTime:e,intervalMs:e-Hr.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},Hr=t,cR}function pR(r,e,t=1e4,n=5e3){let o=0;async function i(){try{let s=await $(r.driver.execute("mobile: shell",{command:"echo",args:["ping"]}).catch(c=>{throw c}),{milliseconds:n});if(typeof s=="string"&&s.trim()==="ping")o>0&&e.info("Driver heartbeat restored"),o=0;else throw new Error(`Unexpected heartbeat output: ${s}`)}catch(s){o++;let c=s instanceof Error?s.message:`${s}`;e.error({attempt:o,error:c},"Driver heartbeat failed"),o>=3&&e.error("Driver appears unresponsive \u2014 possible ADB tunnel/emulator failure")}}let a=setInterval(()=>{i()},t);return i(),a}async function mR(r){let e=Date.now(),t=r.fixtures.controller;try{return await yB(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 yB({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await bB({step:n,params:e}),s={};Object.entries(a).forEach(([p,h])=>{s[p]=JSON.stringify(h)});let c={...n,type:"MOBILE_MODULE_STEP",inputs:s,startTime:t,steps:[],endTime:Date.now(),status:"SUCCESS"},l=await o.startSubSteps(),{status:u,results:d}=await i({...e,listParams:{steps:n.steps,containerName:`module ('${n.name}')`,tracer:l}});return c.steps=d,c.status=u,c.endTime=Date.now(),wb({result:c,...Ab(d)}),c}async function bB({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 Ir({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as hR}from"crypto";async function gR({fixtures:r,step:e,inputs:t,stepTracer:n}){let o=Date.now(),{logger:i,controller:a}=r,s=n.interactionTracer,c;if(!t.interactive)try{c=await a.screenshot()}catch(u){i.warn({err:u},"Failed to take before screenshot")}let l={...e,status:"SUCCESS",startTime:o,endTime:Date.now()};try{let u=await a.executeCommand({command:e.command,tracer:s});l={...e,status:u.success?"SUCCESS":"FAILED",message:u.message,startTime:o,endTime:Date.now(),data:u.output}}catch(u){u instanceof Error&&u.name==="AbortError"||a.isAborted()?l={...e,status:"CANCELLED",message:"Step cancelled.",startTime:o,endTime:Date.now()}:(i.error({err:u},"Failed to execute preset step"),l={...e,status:"FAILED",message:u instanceof Error?u.message:String(u),startTime:o,endTime:Date.now()})}finally{if(l.trace=s.getRootSpan(),!t.interactive){try{let u=hR(),d=await a.screenshot();l.afterSnapshot=u,n.attachAfterScreenshot({logger:i,snapshotId:u,screenshot:Buffer.from(d,"base64")})}catch(u){i.warn({err:u},"Failed to take after screenshot")}if(c){let u=hR();l.beforeSnapshot=u,n.attachBeforeScreenshot({logger:i,snapshotId:u,screenshot:Buffer.from(c,"base64")})}}}return l}async function Xm(r){let{fixtures:e,inputs:t,listParams:n}=r,{containerName:o,steps:i,tracer:a}=n,{logger:s,controller:c,usageTracker:l}=e,u=a.getParentStepIdChain(),d=[],p,h="SUCCESS",{fromStep:m,toStep:g}=t,f=!!m;for(let E=0;E<i.length;E++){let S=i[E];if(s.info({step:S},`Executing step ${E+1}/${i.length} in ${o}: ${fb(S)}`),S.skipped){s.debug("Step skipped");continue}if(f&&m){let A=JSON.stringify(u);if(S.id===m.fromStepId&&A===JSON.stringify(m.parentStepIdChain))f=!1;else if(!vb({currentStep:S,currentParentChain:u,desiredStepId:m.fromStepId,desiredStepParentChain:m.parentStepIdChain}))continue}let w=await a.startStep({logger:s,step:S,attempt:1,parentStepIdChain:u});l.trackStepExecution(S);let v=await EB({step:S,stepTracer:w,params:r});if(v.trace&&s.info({step:{id:S.id},trace:v.trace,status:v.status},`Step ${E+1}/${i.length} done (${S.type==="MOBILE_PRESET_STEP"?S.command.type:S.type})`),d.push(v),await w.finish({parentStepIdChain:u,result:v}),v.status!=="SUCCESS"){h=v.status,p=v;break}if(S.envKey&&c.context.setVariable(S.envKey,v.data),g){let A=JSON.stringify([]);if(S.id===g.toStepId&&A===JSON.stringify(g.parentStepIdChain))break}}return{results:d,status:h,terminalResult:p}}async function EB({step:r,stepTracer:e,params:t}){let{fixtures:n,inputs:o}=t,i;switch(r.type){case"MOBILE_PRESET_STEP":{i=await gR({fixtures:n,inputs:o,step:r,stepTracer:e});break}case"RESOLVED_MOBILE_MODULE":{i=await mR({...t,moduleParams:{step:r,stepTracer:e,executeMobileStepList:Xm}});break}}return i}async function Gc(r){let{tracer:e,containerName:t}=r,{steps:n,testMetadata:o}=r.inputs,{cacheStorage:i,logger:a,controller:s}=r.fixtures;await i.resolveEntries({logger:a,testId:o.id,stepLists:{steps:n}});let c=vB(n);a.info({testMetadata:_r.parse(o)},"Starting mobile test");let l=await e.startMainStepList(),u=dR(a),d=pR(s,a);a.info({cpu:u?.cpuMetadata,platform:u?.platform},`Starting execution of ${t}`);let{status:p,results:h}=await Xm({...r,listParams:{containerName:t,tracer:l,steps:c}});if(clearInterval(u?.interval),clearInterval(d),p==="SUCCESS"){let m=TB(c,n);if(m&&Object.keys(m).length>0){a.debug({diffs:m},"Saving mobile step cache entries post-success");let{cachesToSave:g}=await eo({steps:c,cacheCreationParams:{orgId:r.inputs.orgId,testId:o.id}});await i.saveEntries({logger:a,testId:o.id,entries:g})}return{status:"PASSED",results:h}}return p==="CANCELLED"?{status:"CANCELLED",results:h}:{status:"FAILED",results:h}}var Jm=class{parentTracer=null;socket;step;interactionTracer;constructor({step:e,socket:t,parentTracer:n}){this.socket=t,this.parentTracer=n,this.step=e,this.interactionTracer=new fo,In.initializeRootTracerContext(this.interactionTracer)}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}async finish(e){this.interactionTracer.finish();let t=this.interactionTracer.getRootSpan(),n={...Wy.parse(e),trace:Rd.parse(t)};switch(n.result.status){case"SUCCESS":this.socket.emit("success",n);break;case"FAILED":this.socket.emit("failure",n);break;case"CANCELLED":this.socket.emit("cancelled",n);break}return{trace:t}}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}async startSubSteps(){return new Ti({parentStep:this.step,socket:this.socket,parentTracer:this})}},Ti=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 Jm({step:e.step,parentTracer:this,socket:this.socket})}},jc=class{constructor(e){this.socket=e}appendLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Ti({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new Ti({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new Ti({parentStep:null,parentTracer:null,socket:this.socket})}};var AB=({metadata:r,logger:e,globalStateManager:t,socket:n,cacheStorageFactory:o})=>async(i,a)=>{let s=t.getSession(n.id);if(!s)throw new Error("No active Android session found");let c=e.child({testId:i.testMetadata.id}),l=await o(r.orgId),u=s.controller;u.resetAbortController();let d=new jc(n),p=await Gc({fixtures:{controller:u,logger:c,cacheStorage:l,usageTracker:new $s},containerName:"entire test",inputs:{steps:i.steps,fromStep:i.fromStep,toStep:i.toStep,orgId:r.orgId,testMetadata:i.testMetadata,interactive:!0},tracer:d});await d.finish();let h={results:br.array().parse(p.results),status:p.status};a?.(h)},fR={event:"execute",createHandler:AB};import{debounce as wB}from"ts-debounce";var RB=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=wB(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)}},SR={event:"keepalive",createHandler:RB};var yR=[fR,iR,SR];function bR(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new CB(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 s=>{let c=s.id,l=e.child({sessionId:c});l.info({event:"connection",transport:s.conn.transport.name},"Android websocket connection initiated"),s.on("disconnect",async()=>{await oR({socket:s,globalStateManager:n,logger:l})});let u;try{u=await nR({...r,socket:s,globalStateManager:n,logger:l})}catch(d){l.error({err:d},"Failed to setup Android connection"),s.emit("error",{message:d instanceof Error?d.message:JSON.stringify(d)}),s.disconnect(!0);return}yR.forEach(d=>a(d,{...r,socket:s,metadata:u,logger:l}))});let a=(s,c)=>{let l=s.createHandler(c),u=(...d)=>{s.event!=="keepalive"&&c.logger.debug({event:s.event},`Websocket event (${s.event})`);let p=h=>{c.logger.error({event:s.event,err:h instanceof Error?h:new Error(`${h}`)},"Unhandled exception in socket handler"),c.socket.emit("error",{message:h instanceof Error?h.message:`${h}`})};try{let h=l.apply(this,d);h&&typeof h.catch=="function"&&h.catch(p)}catch(h){p(h)}};c.socket.on(s.event,u)};return{server:o,dispose:i}}import{confirm as MB,input as PB}from"@inquirer/prompts";import{existsSync as C_e,mkdirSync as x_e,statSync as IB}from"fs";import vi,{supportsColor as _B}from"chalk";import{Console as ER}from"console";import{format as Ja}from"util";var Zm=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}},Vc=class r extends ER{_buffer=[];_groupDepth=0;Console=ER;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new Zm(void 0,r.write).stack;if(!i)return e;let a=i.split(`
|
|
3974
4027
|
`).slice(o).filter(Boolean).join(`
|
|
3975
|
-
`);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",
|
|
4028
|
+
`);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",Ja(e,...t))}error(e,...t){this._log("error",Ja(e,...t))}info(e,...t){this._log("info",Ja(e,...t))}log(e,...t){this._log("log",Ja(e,...t))}warn(e,...t){this._log("warn",Ja(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function TR(r){let e=globalThis.console,t=new Vc;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
|
|
3976
4029
|
`);process.stderr.write(`${o}
|
|
3977
|
-
`),globalThis.console=e}}var Mm=" ".repeat(6);import{hostname as WU}from"os";var Ot=Cc({app:"cli",hostname:WU(),disableConsoleLogs:!0}).child({cliVersion:"0.0.26"});function Pm(r){if(!r)return;r=r.toLowerCase();let e=$s.safeParse(r);if(e.success)return x.setMinLevel(e.data),e.data}function gw({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),s=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),l=r.filter(u=>u.status==="CANCELLED");return mw(()=>{if(c.forEach(u=>{x.log(""),o(u)}),c.length){x.log("");let u=c.length===1?"":"s";x.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{x.dimmed(n(d))})}if(l.length){x.log("");let u=l.length===1?"":"s";x.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{x.dimmed(n(d))})}if(a.length){x.log("");let u=a.length===1?"":"s";x.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{x.dimmed(n(d))})}if(s.length){x.log("");let u=s.length===1?"":"s";x.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{x.dimmed(n(d))})}if(i.length){x.log("");let u=i.length===1?"":"s";x.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{x.dimmed(n(d))})}x.log(""),x.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:s.length,failed:c.length,cancelled:l.length}}var Fa=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=di.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=di.bgGreen.white("PASS"),a=3):r.includes("START")?(i=di.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=di.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=di.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=di.bgMagenta.white("RUNNING"),a=0):(x.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),qU||(i=`${i}`),x.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};var JU=!1,hw=(()=>{try{return XU("/.dockerenv"),!0}catch{return!1}})();async function Pc(r){return Da||JU||hw?!0:(x.flush(),Ot.flush(),await new Promise(t=>setTimeout(t,500)),await KU({message:r}))}async function fw(r,e){return Da||hw?e:(await YU({message:r,default:e})).trim()||e}import ZU from"fs";import{tmpdir as QU}from"os";import eF from"path";import{registry as Ba}from"playwright-core/lib/server";import Sw from"proper-lockfile";var yw=eF.join(QU(),"momenticBrowserInstallation");var Im=["chrome","chromium","chrome-for-testing"],tF={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},bw={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function Ew(r){let e=bw[tF[r]??""]??"",t=Ba.findExecutable(e);return!t||t.installType==="none"?!1:Om(t)}function Om(r){let e=r.executablePath();return ZU.existsSync(e)}function rF(r,e){let t=bw[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Ba.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&Om(n)))return n}async function nF({browser:r,force:e}){let t=rF(r,e);if(!t){x.info(`Browser '${r}' is already installed, skipping...`);return}x.info(`Installing browser '${r}'...`);try{await Ba.installDeps([t],!1),await Ba.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){x.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=Ba.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Om(o);)x.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function Ic({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?Im:Array.from(new Set(r));try{await Sw.lock(yw,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){x.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 nF({browser:i,force:e})}catch(a){o=a,x.error(`Failed to install the ${i} browser: ${a}`)}}finally{await Sw.unlock(yw,{realpath:!1})}if(o)throw o}import{createServer as oF}from"http";async function Oc(r,e){for(let n=0;n<30;n+=1){let o=r+n;if(await iF(o))return o}x.error(`Could not find an available port for ${e} starting from ${r} after 30 attempts`),process.exit(1)}async function iF(r){return new Promise((e,t)=>{let n=oF();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(x.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 Mz}from"crypto";import{diff as Twe}from"deep-object-diff";import Owe from"yaml";import{z as Nwe}from"zod";import{execSync as aF}from"child_process";function co(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,x.debug({postSaveCommand:n},"Executing post-save hook command");try{aF(n,{encoding:"utf-8"})}catch(o){x.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as ZAe}from"deep-object-diff";import{cloneDeep as ewe}from"lodash-es";import{v4 as pwe}from"uuid";import gwe from"yaml";import sF from"@dotenvx/dotenvx";import lF from"fs";import Tw from"path";function cF(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 uF(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 s=cF(i);s&&(n[o]=s);continue}let a;try{a=lF.readFileSync(Tw.resolve(t.rootDir,i.fromFile),"utf-8")}catch(s){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${s}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(s){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${s}`)}else n[o]=a}return Object.keys(n).length>0&&x.debug(n,"Set environment variables with interpolation from project configuration"),n}function dF(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=sF.config({path:Tw.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 Lc(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=uF({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=dF({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 wF,readFileSync as RF,readdirSync as CF,writeFileSync as xF}from"fs";import{glob as _F}from"glob";import uo,{dirname as ww}from"path";import{cwd as Um}from"process";import Rw from"yaml";import{z as Ce}from"zod";import vw from"fs";import{glob as pF}from"glob";import za from"path";import mF from"yaml";import{z as Lm}from"zod";var Aw=!1,Nm=["**/*.test.yaml","**/*.module.yaml"],km=Lm.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),Dm=15,gF=Lm.object({fileType:Lm.nativeEnum(we)});async function gr(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??Nm,o=Array.from(r.config.exclude??[]).concat(js),i=AbortSignal.timeout(3e3),a;try{a=await pF(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:Dm,nodir:!0,signal:i})}catch(s){throw x.error({err:s},"Failed to list all Momentic files in the current directory. This usually indicates the 'include' and 'exclude' globs are misconfigured in your momentic.config.yaml, or that your machine is severely resource constrained."),new Error("Listing Momentic files timed out after 3 seconds.",{cause:s})}for(let s of a){let c=hF(r.rootDir,s,t,e?Hn:x);c&&(t.duplicateEntities[c.id]=c.paths)}return Aw=!0,t}function hF(r,e,t,n){let o=za.join(r,e),i=fF(o,n);if(!i)return;let a=SF(i,o,n);if(!a)return;let s=gF.safeParse(a);if(s.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let c=s.data.fileType,l=yF(o,n);if(!l)return;let u=bF(e,o,l);switch(c){case we.TEST:try{return EF(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case we.MODULE:try{return TF(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case we.MOBILE_TEST:try{return AF(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case we.MOBILE_MODULE:try{return vF(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 fF(r,e){try{return vw.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function SF(r,e,t){try{let n=mF.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 yF(r,e){try{return vw.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function bF(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:za.sep,fullPathSegments:e.split(za.sep),relativePathSegments:r.split(za.sep),fileName:za.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function EF(r,e,t,n,o){let i=ko.parse(r),a;if(e.tests[i.id]){let s=e.tests[i.id].fullFilePath;a={id:i.id,paths:[s,n]}}return e.tests[i.id]={type:we.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function TF(r,e,t,n,o){let i=$t.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:we.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let s=t.fileName.replace(".module.yaml","");return!Aw&&nn(i.name)!==s&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${s}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function vF(r,e,t,n,o){let i=Yi.parse(r),a;if(e.mobileModules[i.moduleId]){let c=e.mobileModules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}let s=t.fileName.replace(".module.yaml","");return e.mobileModules[i.moduleId]={type:we.MOBILE_MODULE,name:s,id:i.moduleId,description:i.description??void 0,...t},a}function AF(r,e,t,n,o){let i=br.parse(r),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let s=t.fileName.replace(".test.yaml","");return e.mobileTests[i.id]={type:we.MOBILE_TEST,name:s,id:i.id,description:i.description??void 0,...t},a}var pi="momentic.config.yaml",Fm="momentic.workspace.yaml",MF=Ce.object({projects:Ce.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),PF=Ce.union([Ce.string(),Ce.object({fromFile:Ce.string(),json:Ce.boolean().optional()})]),IF=Ce.object({name:km,baseUrl:Ce.string().optional().describe("Optional for mobile tests"),envFile:Ce.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Ce.record(Ce.string(),PF).optional(),inheritFromShell:Ce.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Nn.optional().describe("deprecated: use project-level configuration only")}),OF=Ce.object({postSave:Ce.string().optional()}),LF=Ce.object({name:km,include:Ce.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Ce.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:Ce.string().optional(),reporterDir:Ce.string().optional(),outputDir:Ce.string().optional(),retries:Ce.number().optional().describe("number of retries per test"),parallel:Ce.number().optional().describe("degree of parallelism"),environments:Ce.array(IF).optional(),gitMainBranch:Ce.string().optional(),gitProtectedBranches:Ce.string().array().optional(),ai:ld.optional(),browser:Nn.optional(),emulator:Ju.optional(),advanced:cd.optional(),hooks:OF.optional()});function Cw(r,e){let t;try{t=RF(r,"utf-8")}catch(o){x.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=Rw.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){x.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function Bm(r){let e=Cw(r,"project configuration");if(e!==void 0)try{return LF.parse(e)}catch(t){x.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function NF(r){let e=Cw(r,"workspace configuration");if(e!==void 0)try{return MF.parse(e)}catch(t){x.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function kF(){let r=[],e=Um(),t=uo.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=uo.basename(e);if(Gs.includes(i))return x.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of CF(e))if(a.endsWith(pi)){let s=uo.join(e,a),c=Bm(s);c&&r.push({configFilePath:s,config:c,rootDir:ww(s)})}if(r.length)return r;if(e=uo.dirname(e),e===t)break}return r}async function Ha(r={}){let{configFilePath:e,nameFilter:t}=r,n=await UF(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:
|
|
3978
|
-
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return x.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}async function
|
|
3979
|
-
`)){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 GF(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 Mw("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),s=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(s?.[1])return s[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await Mw("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function jF(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return GF(r,e,t);if(o)return}catch{}}function Nc(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 _e(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function VF(){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 $F(r){let[e,t,n]=await Promise.all([_e(r,xe.show(["--no-patch","--format=%ci"])),_e(r,xe.show(["-s","--pretty=%B"])),_e(r,xe.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 WF(r){let[e,t,n]=await Promise.all([_e(r,xe.listRemote(["--get-url","origin"])),_e(r,xe.show(["-s","--pretty=%B"])),_e(r,xe.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 qF(r){let[e,t,n,o]=await Promise.all([_e(r,xe.show(["--no-patch","--format=%ci"])),_e(r,xe.listRemote(["--get-url","origin"])),_e(r,xe.show(["-s","--pretty=%B"])),_e(r,xe.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?Nc(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?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function KF(r){let[e,t,n]=await Promise.all([_e(r,xe.show(["--no-patch","--format=%ci"])),_e(r,xe.show(["-s","--pretty=%B"])),_e(r,xe.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Nc(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?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function YF(r){let[e,t,n]=await Promise.all([_e(r,xe.show(["--no-patch","--format=%ci"])),_e(r,xe.show(["-s","--pretty=%B"])),_e(r,xe.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Nc(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?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function XF(r,e){let[t,n,o,i,a,s,c,l,u]=await Promise.all([_e(r,xe.revparse(["HEAD"])),_e(r,xe.revparse(["--short","HEAD"])),_e(r,xe.revparse(["--abbrev-ref","HEAD"])),_e(r,xe.listRemote(["--get-url","origin"])),_e(r,xe.show(["--no-patch","--format=%ci"])),_e(r,xe.show(["-s","--pretty=%B"])),_e(r,xe.show(["-s","--pretty=%an"])),e?_e(r,xe.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),HF(r)]),d=l?await _e(r,xe.show(["--no-patch","--format=%ci",l])):void 0,p=i?.includes("github.com"),g=i?.includes("gitlab.com"),m=i?Nc(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,S=await jF(r,i,u)??E??void 0;return{gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:c,gitLocalUsername:S,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:l,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?m:void 0,gitlabProjectPath:g?m:void 0,pipelineId:void 0}}async function JF(){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 ZF(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function Hm(r,e){let t=VF();if(!t)return XF(r,e);switch(t){case"GithubActions":return $F(r);case"GitlabCI":return WF(r);case"CircleCI":return qF(r);case"Buildkite":return KF(r);case"AzureDevOps":return YF(r);case"GCPCloudBuild":return JF()}}async function QF(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 eB(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 tB(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await eB(r,e,n,o,t)}else if(t.gitlabProjectPath)return await QF(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function kc(r,e,t){let n=await ZF(t),o=await Hm(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 tB(r,e,i);return{...n,...o,...a}}import{diff as Pw}from"deep-object-diff";import po from"fs";import{cloneDeep as rB}from"lodash-es";import Gm from"path";import{v4 as BRe}from"uuid";import Dc from"yaml";function Iw({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath;if(!i||!po.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let a=po.readFileSync(i,"utf-8"),s=Dc.parse(a),c={...s,...r,schemaVersion:e},l=Gn({fileType:we.MOBILE_MODULE,...Yi.parse(c),steps:cr.array().parse(r.steps)}),u=Pw(l,s);if(u&&Object.keys(u).length===0&&!o)return;let d=Dc.stringify(l);po.writeFileSync(i,d,"utf-8"),co(i,n.config)}function Ow({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=Ga(i,o),s={...a,...e},c=Gn({fileType:we.MOBILE_MODULE,...Ls.parse(s)}),l=Pw(c,a);if(l&&Object.keys(l).length===0)return;let u=Dc.stringify(c);po.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${nn(e.name)}.module.yaml`;if(d=Gm.join(Gm.dirname(i),p),po.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);po.renameSync(i,d)}co(d||i,n.config)}function Ga(r,e){let t=po.readFileSync(r,"utf-8"),n=Dc.parse(t);try{return{...Ls.parse(n),name:Gm.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 jm(r,e,t,n){let o=Ga(r.fullFilePath,t),{resolvedSteps:i}=await nl({rawSteps:o.steps,resolvedModuleCache:n||{},onFetchModule:async s=>{let c=e.mobileModules[s]?.fullFilePath;if(!c)throw new Error(`Could not find mobile module with id ${s}`);return Ga(c,t)},logger:t,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion}}),a={...o,name:r.name,steps:i};return n&&(n[r.id]=rB(a)),a}async function Lw(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await jm(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as nB}from"crypto";import mo from"fs";import Vm from"path";import Uc from"yaml";function Nw({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${nn(r)}.test.yaml`,s=Vm.join(o,a);if(mo.existsSync(s))throw new Error(`A test named '${r}' already exists at path '${s}'. Choose a different name.`);let c={fileType:we.MOBILE_TEST,id:nB(),description:e,schemaVersion:Eu,settings:n,steps:t},l=Uc.stringify(c);return mo.writeFileSync(s,l,"utf-8"),{fullPath:s,testId:c.id}}function oB(r){if(!mo.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=mo.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
|
|
3980
|
-
`),t=
|
|
3981
|
-
`),c=
|
|
3982
|
-
Error message: ${
|
|
3983
|
-
Error message: ${
|
|
3984
|
-
`;break;case"id":s=f.includes("\0")?void 0:f;break;case"retry":/^\d+$/.test(f)?n(parseInt(f,10)):t(new
|
|
3985
|
-
`)?c.slice(0,-1):c}),s=void 0,c="",l=""}function m(
|
|
4030
|
+
`),globalThis.console=e}}var Qm=" ".repeat(6);import{hostname as xB}from"os";var Ft=Hc({app:"cli",hostname:xB(),disableConsoleLogs:!0}).child({cliVersion:"0.0.28"});function eh(r){if(!r)return;r=r.toLowerCase();let e=sl.safeParse(r);if(e.success)return x.setMinLevel(e.data),e.data}function vR({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),s=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),l=r.filter(u=>u.status==="CANCELLED");return TR(()=>{if(c.forEach(u=>{x.log(""),o(u)}),c.length){x.log("");let u=c.length===1?"":"s";x.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{x.dimmed(n(d))})}if(l.length){x.log("");let u=l.length===1?"":"s";x.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{x.dimmed(n(d))})}if(a.length){x.log("");let u=a.length===1?"":"s";x.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{x.dimmed(n(d))})}if(s.length){x.log("");let u=s.length===1?"":"s";x.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{x.dimmed(n(d))})}if(i.length){x.log("");let u=i.length===1?"":"s";x.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{x.dimmed(n(d))})}x.log(""),x.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:s.length,failed:c.length,cancelled:l.length}}var Za=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=vi.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=vi.bgGreen.white("PASS"),a=3):r.includes("START")?(i=vi.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=vi.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=vi.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=vi.bgMagenta.white("RUNNING"),a=0):(x.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),_B||(i=`${i}`),x.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};var OB=!1,AR=(()=>{try{return IB("/.dockerenv"),!0}catch{return!1}})();async function $c(r){return yo||OB||AR?!0:(x.flush(),Ft.flush(),await new Promise(t=>setTimeout(t,500)),await MB({message:r}))}async function wR(r,e){return yo||AR?e:(await PB({message:r,default:e})).trim()||e}import LB from"fs";import{tmpdir as NB}from"os";import kB from"path";import{registry as Qa}from"playwright-core/lib/server";import RR from"proper-lockfile";var CR=kB.join(NB(),"momenticBrowserInstallation");var th=["chrome","chromium","chrome-for-testing"],DB={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},xR={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function _R(r){let e=xR[DB[r]??""]??"",t=Qa.findExecutable(e);return!t||t.installType==="none"?!1:rh(t)}function rh(r){let e=r.executablePath();return LB.existsSync(e)}function UB(r,e){let t=xR[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Qa.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&rh(n)))return n}async function FB({browser:r,force:e}){let t=UB(r,e);if(!t){x.info(`Browser '${r}' is already installed, skipping...`);return}x.info(`Installing browser '${r}'...`);try{await Qa.installDeps([t],!1),await Qa.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){x.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=Qa.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!rh(o);)x.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function Wc({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?th:Array.from(new Set(r));try{await RR.lock(CR,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){x.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 FB({browser:i,force:e})}catch(a){o=a,x.error(`Failed to install the ${i} browser: ${a}`)}}finally{await RR.unlock(CR,{realpath:!1})}if(o)throw o}import{createServer as BB}from"http";async function qc(r,e){for(let n=0;n<30;n+=1){let o=r+n;if(await zB(o))return o}x.error(`Could not find an available port for ${e} starting from ${r} after 30 attempts`),process.exit(1)}async function zB(r){return new Promise((e,t)=>{let n=BB();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(x.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 q_e from"blocked-at";import Y_e from"why-is-node-running";import{randomUUID as iG}from"crypto";import{diff as LMe}from"deep-object-diff";import VMe from"yaml";import{z as WMe}from"zod";import{execSync as HB}from"child_process";function bo(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,x.debug({postSaveCommand:n},"Executing post-save hook command");try{HB(n,{encoding:"utf-8"})}catch(o){x.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as uMe}from"deep-object-diff";import{cloneDeep as pMe}from"lodash-es";import{v4 as wMe}from"uuid";import CMe from"yaml";import GB from"@dotenvx/dotenvx";import jB from"fs";import MR from"path";function VB(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 $B(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 s=VB(i);s&&(n[o]=s);continue}let a;try{a=jB.readFileSync(MR.resolve(t.rootDir,i.fromFile),"utf-8")}catch(s){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${s}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(s){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${s}`)}else n[o]=a}return Object.keys(n).length>0&&x.debug(n,"Set environment variables with interpolation from project configuration"),n}function WB(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=GB.config({path:MR.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 Kc(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=$B({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=WB({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 i1,readFileSync as a1,readdirSync as s1,writeFileSync as l1}from"fs";import{glob as c1}from"glob";import Eo,{dirname as OR}from"path";import{cwd as sh}from"process";import LR from"yaml";import{z as Pe}from"zod";import PR from"fs";import{glob as qB}from"glob";import es from"path";import KB from"yaml";import{z as nh}from"zod";var IR=!1,oh=["**/*.test.yaml","**/*.module.yaml"],ih=nh.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),ah=15,YB=nh.object({fileType:nh.nativeEnum(_e)});async function vr(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??oh,o=Array.from(r.config.exclude??[]).concat(il),i=AbortSignal.timeout(5e3),a;try{a=await qB(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:ah,nodir:!0,signal:i})}catch(s){throw x.error({err:s},"Failed to list all Momentic files in the current directory. This usually indicates the 'include' and 'exclude' globs are misconfigured in your momentic.config.yaml, or that your machine is severely resource constrained."),new Error("Listing Momentic files timed out after 5 seconds.",{cause:s})}for(let s of a){let c=XB(r.rootDir,s,t,e?bn:x);c&&(t.duplicateEntities[c.id]=c.paths)}return IR=!0,t}function XB(r,e,t,n){let o=es.join(r,e),i=JB(o,n);if(!i)return;let a=ZB(i,o,n);if(!a)return;let s=YB.safeParse(a);if(s.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let c=s.data.fileType,l=QB(o,n);if(!l)return;let u=e1(e,o,l);switch(c){case _e.TEST:try{return t1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case _e.MODULE:try{return r1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case _e.MOBILE_TEST:try{return o1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case _e.MOBILE_MODULE:try{return n1(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 JB(r,e){try{return PR.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function ZB(r,e,t){try{let n=KB.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 QB(r,e){try{return PR.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function e1(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:es.sep,fullPathSegments:e.split(es.sep),relativePathSegments:r.split(es.sep),fileName:es.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function t1(r,e,t,n,o){let i=Wo.parse(r),a;if(e.tests[i.id]){let s=e.tests[i.id].fullFilePath;a={id:i.id,paths:[s,n]}}return e.tests[i.id]={type:_e.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function r1(r,e,t,n,o){let i=Jt.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:_e.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let s=t.fileName.replace(".module.yaml","");return!IR&&un(i.name)!==s&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${s}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function n1(r,e,t,n,o){let i=ua.parse(r),a;if(e.mobileModules[i.moduleId]){let c=e.mobileModules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}let s=t.fileName.replace(".module.yaml","");return e.mobileModules[i.moduleId]={type:_e.MOBILE_MODULE,name:s,id:i.moduleId,description:i.description??void 0,...t},a}function o1(r,e,t,n,o){let i=_r.parse(r),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let s=t.fileName.replace(".test.yaml","");return e.mobileTests[i.id]={type:_e.MOBILE_TEST,name:s,id:i.id,description:i.description??void 0,...t},a}var Ai="momentic.config.yaml",lh="momentic.workspace.yaml",u1=Pe.object({projects:Pe.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),d1=Pe.union([Pe.string(),Pe.object({fromFile:Pe.string(),json:Pe.boolean().optional()})]),p1=Pe.object({name:ih,baseUrl:Pe.string().optional().describe("Optional for mobile tests"),envFile:Pe.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Pe.record(Pe.string(),d1).optional(),inheritFromShell:Pe.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:$n.optional().describe("deprecated: use project-level configuration only")}),m1=Pe.object({postSave:Pe.string().optional()}),h1=Pe.object({name:ih,include:Pe.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Pe.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:Pe.string().optional(),reporterDir:Pe.string().optional(),outputDir:Pe.string().optional(),retries:Pe.number().optional().describe("number of retries per test"),parallel:Pe.number().optional().describe("degree of parallelism"),environments:Pe.array(p1).optional(),gitMainBranch:Pe.string().optional(),gitProtectedBranches:Pe.string().array().optional(),ai:Id.optional(),browser:$n.optional(),emulator:wd.optional(),advanced:Od.optional(),hooks:m1.optional()});function NR(r,e){let t;try{t=a1(r,"utf-8")}catch(o){x.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=LR.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){x.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function ch(r){let e=NR(r,"project configuration");if(e!==void 0)try{return h1.parse(e)}catch(t){x.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function g1(r){let e=NR(r,"workspace configuration");if(e!==void 0)try{return u1.parse(e)}catch(t){x.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function f1(){let r=[],e=sh(),t=Eo.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=Eo.basename(e);if(ol.includes(i))return x.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of s1(e))if(a.endsWith(Ai)){let s=Eo.join(e,a),c=ch(s);c&&r.push({configFilePath:s,config:c,rootDir:OR(s)})}if(r.length)return r;if(e=Eo.dirname(e),e===t)break}return r}async function ts(r={}){let{configFilePath:e,nameFilter:t}=r,n=await y1(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:
|
|
4031
|
+
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return x.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}async function S1(r){let e=g1(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${Ai}`)),n=AbortSignal.timeout(2e3),o;try{o=await c1(t,{absolute:!1,cwd:sh(),dotRelative:!1,maxDepth:ah,nodir:!0,signal:n})}catch(a){throw x.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${lh} is misconfigured.`),a}let i=[];for(let a of o){let s=Eo.join(sh(),a),c=ch(s);c&&i.push({configFilePath:s,config:c,rootDir:OR(s)})}return i}async function y1(r){if(r){r=Eo.resolve(r);let t=ch(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:Eo.dirname(r)}]}if(i1(lh)){let t=await S1(lh);if(t)return t}return f1()}function kR(r,e){let t=LR.stringify(r);l1(e,t)}import{z as uh}from"zod";var DR="test-results";var PPe=uh.object({width:uh.number(),height:uh.number()});import{execFile as b1}from"node:child_process";import{promisify as E1}from"node:util";import T1 from"simple-git";var Ie=T1(),UR=E1(b1);async function v1(r){let e=await Oe(r,Ie.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
|
|
4032
|
+
`)){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 A1(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 UR("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),s=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(s?.[1])return s[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await UR("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function w1(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return A1(r,e,t);if(o)return}catch{}}function Yc(r){if(r.startsWith("git@")){let e=r.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let n=t[0],o=t[1];return`${n}/${o}`}}}else if(r.startsWith("http")||r.startsWith("https")){let t=new URL(r).pathname.split("/").filter(Boolean);if(t.length>=2){let n=t[0],o=t[1].replace(".git","");return`${n}/${o}`}}}async function Oe(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function R1(){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 C1(r){let[e,t,n]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]),o=process.env.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 x1(r){let[e,t,n]=await Promise.all([Oe(r,Ie.listRemote(["--get-url","origin"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]);return{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 _1(r){let[e,t,n,o]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.listRemote(["--get-url","origin"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?Yc(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?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function M1(r){let[e,t,n]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Yc(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?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function P1(r){let[e,t,n]=await Promise.all([Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Yc(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?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function I1(r,e){let[t,n,o,i,a,s,c,l,u]=await Promise.all([Oe(r,Ie.revparse(["HEAD"])),Oe(r,Ie.revparse(["--short","HEAD"])),Oe(r,Ie.revparse(["--abbrev-ref","HEAD"])),Oe(r,Ie.listRemote(["--get-url","origin"])),Oe(r,Ie.show(["--no-patch","--format=%ci"])),Oe(r,Ie.show(["-s","--pretty=%B"])),Oe(r,Ie.show(["-s","--pretty=%an"])),e?Oe(r,Ie.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),v1(r)]),d=l?await Oe(r,Ie.show(["--no-patch","--format=%ci",l])):void 0,p=i?.includes("github.com"),h=i?.includes("gitlab.com"),m=i?Yc(i):void 0,g=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,S=await w1(r,i,u)??E??void 0;return{gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:c,gitLocalUsername:S,gitLocalEmail:g,gitLocalName:f,lastCommitOnMainSha:l,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?m:void 0,gitlabProjectPath:h?m:void 0,pipelineId:void 0}}async function O1(){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 L1(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function dh(r,e){let t=R1();if(!t)return I1(r,e);switch(t){case"GithubActions":return C1(r);case"GitlabCI":return x1(r);case"CircleCI":return _1(r);case"Buildkite":return M1(r);case"AzureDevOps":return P1(r);case"GCPCloudBuild":return O1()}}async function N1(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 k1(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 D1(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await k1(r,e,n,o,t)}else if(t.gitlabProjectPath)return await N1(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Xc(r,e,t){let n=await L1(t),o=await dh(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 D1(r,e,i);return{...n,...o,...a}}import{diff as FR}from"deep-object-diff";import To from"fs";import{cloneDeep as U1}from"lodash-es";import ph from"path";import{v4 as JPe}from"uuid";import Jc from"yaml";function BR({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath;if(!i||!To.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let a=To.readFileSync(i,"utf-8"),s=Jc.parse(a),c={...s,...r,schemaVersion:e},l=Jn({fileType:_e.MOBILE_MODULE,...ua.parse(c),steps:Sr.array().parse(r.steps)}),u=FR(l,s);if(u&&Object.keys(u).length===0&&!o)return;let d=Jc.stringify(l);To.writeFileSync(i,d,"utf-8"),bo(i,n.config)}function zR({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=rs(i,o),s={...a,...e},c=Jn({fileType:_e.MOBILE_MODULE,...Js.parse(s)}),l=FR(c,a);if(l&&Object.keys(l).length===0)return;let u=Jc.stringify(c);To.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${un(e.name)}.module.yaml`;if(d=ph.join(ph.dirname(i),p),To.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);To.renameSync(i,d)}bo(d||i,n.config)}function rs(r,e){let t=To.readFileSync(r,"utf-8"),n=Jc.parse(t);try{return{...Js.parse(n),name:ph.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 mh(r,e,t,n){let o=rs(r.fullFilePath,t),{resolvedSteps:i}=await bl({rawSteps:o.steps,resolvedModuleCache:n||{},onFetchModule:async s=>{let c=e.mobileModules[s]?.fullFilePath;if(!c)throw new Error(`Could not find mobile module with id ${s}`);return rs(c,t)},logger:t,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion}}),a={...o,name:r.name,steps:i};return n&&(n[r.id]=U1(a)),a}async function HR(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await mh(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as F1}from"crypto";import vo from"fs";import hh from"path";import Zc from"yaml";function GR({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${un(r)}.test.yaml`,s=hh.join(o,a);if(vo.existsSync(s))throw new Error(`A test named '${r}' already exists at path '${s}'. Choose a different name.`);let c={fileType:_e.MOBILE_TEST,id:F1(),description:e,schemaVersion:Ku,settings:n,steps:t},l=Zc.stringify(c);return vo.writeFileSync(s,l,"utf-8"),{fullPath:s,testId:c.id}}function B1(r){if(!vo.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=vo.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
|
|
4033
|
+
`),t=Zc.parse(e),n=el.parse(t);if(n.fileType!==_e.MOBILE_TEST)throw new Error(`File is not a mobile test (fileType=${n.fileType}): ${r}`);return n}async function Qc(r,e,t){let n=B1(r),o;try{o=_r.parse(n)}catch(s){throw new Error(`Mobile test ${r} is missing metadata or has invalid metadata: ${s}`)}let{resolvedStepLists:i}=await yb({rawStepLists:{steps:n.steps,beforeSteps:void 0,afterSteps:void 0},logger:e,testMetadata:o,onFetchModule:async s=>{let c=t.mobileModules[s]?.fullFilePath;if(!c)throw new Error(`Mobile module ${s} not found`);return rs(c,e)}});return{...o,steps:i.steps}}async function jR({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i}){let a=hh.isAbsolute(r)?r:hh.join(n,r);if(!vo.existsSync(a))throw new Error(`Test file not found: ${a}`);let s=vo.readFileSync(a,"utf-8").replace(/\r\n|\r/g,`
|
|
4034
|
+
`),c=Zc.parse(s),l=el.parse(c);if(l.fileType!==_e.MOBILE_TEST)throw new Error(`File at '${a}' is not a mobile test (fileType=${l.fileType}).`);let u;e&&(u=await eo({steps:e}));let d={...l,...u?.stepsToSave!==void 0?{steps:u.stepsToSave}:{},...t!==void 0?{settings:t}:{}},p=Zc.stringify(el.parse(d));for(let h of u?.moduleUpdates??[])BR({content:h,schemaVersion:Ku,momenticFiles:i,project:o});vo.writeFileSync(a,p,"utf-8"),bo(a,o.config)}import{randomUUID as z1}from"crypto";import Qr from"fs";import Ao from"path";var VR={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 H1(r,e,t){if(VR[t]){let i=VR[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 $R=new Set([".DS_Store","__MACOSX"]);function WR(r,e,t){let n=z1(),o=r.child({runGroupId:n});Qr.rmSync(e,{recursive:!0,force:!0});let i=Qr.readdirSync(t).filter(l=>!$R.has(l)).map(l=>Ao.join(t,l));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Qr.mkdirSync(e,{recursive:!0});let a=Ao.join(i[0],"metadata.json"),s={...Sa.parse(JSON.parse(Qr.readFileSync(a,"utf-8"))),id:n};for(let l of i){let u=Ao.join(l,"runs");if(!Qr.existsSync(u))continue;let d=Qr.readdirSync(u);for(let m of d){if($R.has(m))continue;let g=Ao.join(u,m),f=Ao.join(e,"runs",m);Qr.cpSync(g,f,{recursive:!0})}let p=Ao.join(l,"metadata.json"),h=Sa.parse(JSON.parse(Qr.readFileSync(p,"utf-8")));o.info({oldRunGroupId:h.id},"Merging metadata from run groups");for(let m in h){if(m==="id")continue;let g=m;s[g]=H1(s,h,g)}}let c=Ao.join(e,"metadata.json");Qr.writeFileSync(c,JSON.stringify(s,null,2))}import GC from"adm-zip";import Ih from"fs";import{z as gH}from"zod";var z="v1",gh="mobile-cli",wo="0.0.28";var G1=9e4,j1=3,V1=1500,$1=15e3,Ar=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function W1(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var fh=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return wo&&(e[dl]=wo),gh&&(e[ty]=gh),e}async sendRequest(e,t){let{retries:n=j1,requestTimeoutMs:o=G1,initialRetryDelayMs:i=V1,maxRetryDelayMs:a=$1}=t,s=n,c=n,l,u={path:e,baseUrl:this.baseUrl,method:t.method};for(;s>0;)try{return s--,await this.sendSingleRequestHelper(e,t,o)}catch(d){if(l=d,d instanceof Ar&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError"&&(l=new En),s===0)throw l;let p=c-s,h=Math.min(i*Math.pow(2,p-1),a);await new Promise(m=>setTimeout(m,h))}throw this.logger.warn({...u,err:l},"Got fatal error response from Momentic server"),l}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s,{once:!0});let c={...this.getHeaders(),...t.extraHeaders};try{let l=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:c,signal:i.signal});if(!l.ok){let d=await W1(l);throw new Ar(l.status,d,`Request to ${t.method} ${e} failed with status ${l.status}: ${d}`)}let u;if(l.status===204)u={};else{let d=await l.text();try{u=JSON.parse(d)}catch{u=d}}return this.logger&&t.logResponse===!0&&u&&this.logger.debug({result:u,status:l.status,...o},"Got response from Momentic server"),u}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},Gr=class extends fh{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var qR="vercel.ai.error",q1=Symbol.for(qR),KR,K1=class YR extends Error{constructor({name:e,message:t,cause:n}){super(t),this[KR]=!0,this.name=e,this.cause=n}static isInstance(e){return YR.hasMarker(e,qR)}static hasMarker(e,t){let n=Symbol.for(t);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===!0}};KR=q1;var vt=K1,XR="AI_APICallError",JR=`vercel.ai.error.${XR}`,Y1=Symbol.for(JR),ZR,ur=class extends vt{constructor({message:r,url:e,requestBodyValues:t,statusCode:n,responseHeaders:o,responseBody:i,cause:a,isRetryable:s=n!=null&&(n===408||n===409||n===429||n>=500),data:c}){super({name:XR,message:r,cause:a}),this[ZR]=!0,this.url=e,this.requestBodyValues=t,this.statusCode=n,this.responseHeaders=o,this.responseBody=i,this.isRetryable=s,this.data=c}static isInstance(r){return vt.hasMarker(r,JR)}};ZR=Y1;var QR="AI_EmptyResponseBodyError",eC=`vercel.ai.error.${QR}`,X1=Symbol.for(eC),tC,rC=class extends vt{constructor({message:r="Empty response body"}={}){super({name:QR,message:r}),this[tC]=!0}static isInstance(r){return vt.hasMarker(r,eC)}};tC=X1;function nC(r){return r==null?"unknown error":typeof r=="string"?r:r instanceof Error?r.message:JSON.stringify(r)}var oC="AI_InvalidArgumentError",iC=`vercel.ai.error.${oC}`,J1=Symbol.for(iC),aC,eu=class extends vt{constructor({message:r,cause:e,argument:t}){super({name:oC,message:r,cause:e}),this[aC]=!0,this.argument=t}static isInstance(r){return vt.hasMarker(r,iC)}};aC=J1;var Z1="AI_InvalidPromptError",Q1=`vercel.ai.error.${Z1}`,ez=Symbol.for(Q1),tz;tz=ez;var rz="AI_InvalidResponseDataError",nz=`vercel.ai.error.${rz}`,oz=Symbol.for(nz),iz;iz=oz;var sC="AI_JSONParseError",lC=`vercel.ai.error.${sC}`,az=Symbol.for(lC),cC,ns=class extends vt{constructor({text:r,cause:e}){super({name:sC,message:`JSON parsing failed: Text: ${r}.
|
|
4035
|
+
Error message: ${nC(e)}`,cause:e}),this[cC]=!0,this.text=r}static isInstance(r){return vt.hasMarker(r,lC)}};cC=az;var uC="AI_LoadAPIKeyError",dC=`vercel.ai.error.${uC}`,sz=Symbol.for(dC),pC,os=class extends vt{constructor({message:r}){super({name:uC,message:r}),this[pC]=!0}static isInstance(r){return vt.hasMarker(r,dC)}};pC=sz;var lz="AI_LoadSettingError",cz=`vercel.ai.error.${lz}`,uz=Symbol.for(cz),dz;dz=uz;var pz="AI_NoContentGeneratedError",mz=`vercel.ai.error.${pz}`,hz=Symbol.for(mz),gz;gz=hz;var mC="AI_NoSuchModelError",hC=`vercel.ai.error.${mC}`,fz=Symbol.for(hC),gC,yh=class extends vt{constructor({errorName:r=mC,modelId:e,modelType:t,message:n=`No such ${t}: ${e}`}){super({name:r,message:n}),this[gC]=!0,this.modelId=e,this.modelType=t}static isInstance(r){return vt.hasMarker(r,hC)}};gC=fz;var Sz="AI_TooManyEmbeddingValuesForCallError",yz=`vercel.ai.error.${Sz}`,bz=Symbol.for(yz),Ez;Ez=bz;var fC="AI_TypeValidationError",SC=`vercel.ai.error.${fC}`,Tz=Symbol.for(SC),yC,vz=class Sh extends vt{constructor({value:e,cause:t}){super({name:fC,message:`Type validation failed: Value: ${JSON.stringify(e)}.
|
|
4036
|
+
Error message: ${nC(t)}`,cause:t}),this[yC]=!0,this.value=e}static isInstance(e){return vt.hasMarker(e,SC)}static wrap({value:e,cause:t}){return Sh.isInstance(t)&&t.value===e?t:new Sh({value:e,cause:t})}};yC=Tz;var Ln=vz,bC="AI_UnsupportedFunctionalityError",EC=`vercel.ai.error.${bC}`,Az=Symbol.for(EC),TC,jr=class extends vt{constructor({functionality:r,message:e=`'${r}' functionality not supported.`}){super({name:bC,message:e}),this[TC]=!0,this.functionality=r}static isInstance(r){return vt.hasMarker(r,EC)}};TC=Az;var tu=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function bh(r){}function vC(r){if(typeof r=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=bh,onError:t=bh,onRetry:n=bh,onComment:o}=r,i="",a=!0,s,c="",l="";function u(g){let f=a?g.replace(/^\xEF\xBB\xBF/,""):g,[E,S]=wz(`${i}${f}`);for(let w of E)d(w);i=S,a=!1}function d(g){if(g===""){h();return}if(g.startsWith(":")){o&&o(g.slice(g.startsWith(": ")?2:1));return}let f=g.indexOf(":");if(f!==-1){let E=g.slice(0,f),S=g[f+1]===" "?2:1,w=g.slice(f+S);p(E,w,g);return}p(g,"",g)}function p(g,f,E){switch(g){case"event":l=f;break;case"data":c=`${c}${f}
|
|
4037
|
+
`;break;case"id":s=f.includes("\0")?void 0:f;break;case"retry":/^\d+$/.test(f)?n(parseInt(f,10)):t(new tu(`Invalid \`retry\` value: "${f}"`,{type:"invalid-retry",value:f,line:E}));break;default:t(new tu(`Unknown field "${g.length>20?`${g.slice(0,20)}\u2026`:g}"`,{type:"unknown-field",field:g,value:f,line:E}));break}}function h(){c.length>0&&e({id:s,event:l||void 0,data:c.endsWith(`
|
|
4038
|
+
`)?c.slice(0,-1):c}),s=void 0,c="",l=""}function m(g={}){i&&g.consume&&d(i),a=!0,s=void 0,c="",l="",i=""}return{feed:u,reset:m}}function wz(r){let e=[],t="",n=0;for(;n<r.length;){let o=r.indexOf("\r",n),i=r.indexOf(`
|
|
3986
4039
|
`,n),a=-1;if(o!==-1&&i!==-1?a=Math.min(o,i):o!==-1?a=o:i!==-1&&(a=i),a===-1){t=r.slice(n);break}else{let s=r.slice(n,a);e.push(s),n=a+1,r[n-1]==="\r"&&r[n]===`
|
|
3987
|
-
`&&n++}}return[e,t]}var Hc=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let o;super({start(i){o=gR({onEvent:a=>{i.enqueue(a)},onError(a){e==="terminate"?i.error(a):typeof e=="function"&&e(a)},onRetry:t,onComment:n})},transform(i){o.feed(i)}})}};import*as AR from"zod/v4";var VB=Symbol("Let zodToJsonSchema decide on which parser to use");import{ZodFirstPartyTypeKind as __e}from"zod";import{ZodFirstPartyTypeKind as zCe}from"zod";import{ZodFirstPartyTypeKind as pxe}from"zod";var cxe=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function hR(...r){return r.reduce((e,t)=>({...e,...t??{}}),{})}function Gc(r){return Object.fromEntries([...r.headers])}var YB=({prefix:r,size:e=16,alphabet:t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{let o=()=>{let i=t.length,a=new Array(e);for(let s=0;s<e;s++)a[s]=t[Math.random()*i|0];return a.join("")};if(r==null)return o;if(t.includes(n))throw new Bc({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${t}".`});return()=>`${r}${n}${o()}`},jc=YB();function Xm(r){return(r instanceof Error||r instanceof DOMException)&&(r.name==="AbortError"||r.name==="ResponseAborted"||r.name==="TimeoutError")}var XB=["fetch failed","failed to fetch"];function JB({error:r,url:e,requestBodyValues:t}){if(Xm(r))return r;if(r instanceof TypeError&&XB.includes(r.message.toLowerCase())){let n=r.cause;if(n!=null)return new or({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:t,isRetryable:!0})}return r}function ZB(r){return Object.fromEntries(Object.entries(r).filter(([e,t])=>t!=null))}function fR({apiKey:r,environmentVariableName:e,apiKeyParameterName:t="apiKey",description:n}){if(typeof r=="string")return r;if(r!=null)throw new Va({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Va({message:`${n} API key is missing. Pass it using the '${t}' parameter. Environment variables is not supported in this environment.`});if(r=process.env[e],r==null)throw new Va({message:`${n} API key is missing. Pass it using the '${t}' parameter or the ${e} environment variable.`});if(typeof r!="string")throw new Va({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return r}var QB=/"__proto__"\s*:/,e1=/"constructor"\s*:/;function t1(r){let e=JSON.parse(r);return e===null||typeof e!="object"||QB.test(r)===!1&&e1.test(r)===!1?e:r1(e)}function r1(r){let e=[r];for(;e.length;){let t=e;e=[];for(let n of t){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(let o in n){let i=n[o];i&&typeof i=="object"&&e.push(i)}}}return r}function SR(r){let{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return t1(r)}finally{Error.stackTraceLimit=e}}var Jm=Symbol.for("vercel.ai.validator");function n1(r){return{[Jm]:!0,validate:r}}function o1(r){return typeof r=="object"&&r!==null&&Jm in r&&r[Jm]===!0&&"validate"in r}function i1(r){return o1(r)?r:a1(r)}function a1(r){return n1(async e=>{let t=await r["~standard"].validate(e);return t.issues==null?{success:!0,value:t.value}:{success:!1,error:new Rn({value:e,cause:t.issues})}})}async function s1({value:r,schema:e}){let t=await Zm({value:r,schema:e});if(!t.success)throw Rn.wrap({value:r,cause:t.error});return t.value}async function Zm({value:r,schema:e}){let t=i1(e);try{if(t.validate==null)return{success:!0,value:r,rawValue:r};let n=await t.validate(r);return n.success?{success:!0,value:n.value,rawValue:r}:{success:!1,error:Rn.wrap({value:r,cause:n.error}),rawValue:r}}catch(n){return{success:!1,error:Rn.wrap({value:r,cause:n}),rawValue:r}}}async function l1({text:r,schema:e}){try{let t=SR(r);return e==null?t:s1({value:t,schema:e})}catch(t){throw ja.isInstance(t)||Rn.isInstance(t)?t:new ja({text:r,cause:t})}}async function yR({text:r,schema:e}){try{let t=SR(r);return e==null?{success:!0,value:t,rawValue:t}:await Zm({value:t,schema:e})}catch(t){return{success:!1,error:ja.isInstance(t)?t:new ja({text:r,cause:t}),rawValue:void 0}}}function c1({stream:r,schema:e}){return r.pipeThrough(new TextDecoderStream).pipeThrough(new Hc).pipeThrough(new TransformStream({async transform({data:t},n){t!=="[DONE]"&&n.enqueue(await yR({text:t,schema:e}))}}))}async function mi({provider:r,providerOptions:e,schema:t}){if(e?.[r]==null)return;let n=await Zm({value:e[r],schema:t});if(!n.success)throw new Bc({argument:"providerOptions",message:`invalid ${r} provider options`,cause:n.error});return n.value}var u1=()=>globalThis.fetch,Qm=async({url:r,headers:e,body:t,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:i,fetch:a})=>d1({url:r,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(t),values:t},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:i,fetch:a});var d1=async({url:r,headers:e={},body:t,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:i,fetch:a=u1()})=>{try{let s=await a(r,{method:"POST",headers:ZB(e),body:t.content,signal:i}),c=Gc(s);if(!s.ok){let l;try{l=await o({response:s,url:r,requestBodyValues:t.values})}catch(u){throw Xm(u)||or.isInstance(u)?u:new or({message:"Failed to process error response",cause:u,statusCode:s.status,url:r,responseHeaders:c,requestBodyValues:t.values})}throw l.value}try{return await n({response:s,url:r,requestBodyValues:t.values})}catch(l){throw l instanceof Error&&(Xm(l)||or.isInstance(l))?l:new or({message:"Failed to process successful response",cause:l,statusCode:s.status,url:r,responseHeaders:c,requestBodyValues:t.values})}}catch(s){throw JB({error:s,url:r,requestBodyValues:t.values})}};function Lt({id:r,name:e,inputSchema:t}){return({execute:n,outputSchema:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:c,...l})=>({type:"provider-defined",id:r,name:e,args:l,inputSchema:t,outputSchema:o,execute:n,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:c})}function Vc({id:r,name:e,inputSchema:t,outputSchema:n}){return({execute:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:c,...l})=>({type:"provider-defined",id:r,name:e,args:l,inputSchema:t,outputSchema:n,execute:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:c})}async function bR(r){return typeof r=="function"&&(r=r()),Promise.resolve(r)}var ER=({errorSchema:r,errorToMessage:e,isRetryable:t})=>async({response:n,url:o,requestBodyValues:i})=>{let a=await n.text(),s=Gc(n);if(a.trim()==="")return{responseHeaders:s,value:new or({message:n.statusText,url:o,requestBodyValues:i,statusCode:n.status,responseHeaders:s,responseBody:a,isRetryable:t?.(n)})};try{let c=await l1({text:a,schema:r});return{responseHeaders:s,value:new or({message:e(c),url:o,requestBodyValues:i,statusCode:n.status,responseHeaders:s,responseBody:a,data:c,isRetryable:t?.(n,c)})}}catch{return{responseHeaders:s,value:new or({message:n.statusText,url:o,requestBodyValues:i,statusCode:n.status,responseHeaders:s,responseBody:a,isRetryable:t?.(n)})}}},TR=r=>async({response:e})=>{let t=Gc(e);if(e.body==null)throw new Kw({});return{responseHeaders:t,value:c1({stream:e.body,schema:r})}};var vR=r=>async({response:e,url:t,requestBodyValues:n})=>{let o=await e.text(),i=await yR({text:o,schema:r}),a=Gc(e);if(!i.success)throw new or({message:"Invalid JSON response",cause:i.error,statusCode:e.status,responseHeaders:a,responseBody:o,url:t,requestBodyValues:n});return{responseHeaders:a,value:i.value,rawValue:i.rawValue}};var fPe=Symbol.for("vercel.ai.schema");var{btoa:p1,atob:SPe}=globalThis;function m1(r){let e="";for(let t=0;t<r.length;t++)e+=String.fromCodePoint(r[t]);return p1(e)}function eg(r){return r instanceof Uint8Array?m1(r):r}function wR(r){return r?.replace(/\/$/,"")}import{z as T}from"zod/v4";import{z as Wa}from"zod/v4";import{z as Ut}from"zod/v4";import{z as Ge}from"zod/v4";import{z as fo}from"zod/v4";import tg from"zod/v4";import rg from"zod/v4";import{z as qa}from"zod/v4";import{z as ir}from"zod/v4";import{z as Wr}from"zod/v4";import{z as qr}from"zod/v4";import{z as Kr}from"zod/v4";var g1=Wa.object({type:Wa.literal("error"),error:Wa.object({type:Wa.string(),message:Wa.string()})}),RR=ER({errorSchema:g1,errorToMessage:r=>r.error.message}),CR=Ut.object({citations:Ut.object({enabled:Ut.boolean()}).optional(),title:Ut.string().optional(),context:Ut.string().optional()}),h1=Ut.object({sendReasoning:Ut.boolean().optional(),thinking:Ut.object({type:Ut.union([Ut.literal("enabled"),Ut.literal("disabled")]),budgetTokens:Ut.number().optional()}).optional(),disableParallelToolUse:Ut.boolean().optional()});function Cn(r){var e;let t=r?.anthropic;return(e=t?.cacheControl)!=null?e:t?.cache_control}var f1=Ge.object({maxUses:Ge.number().optional(),allowedDomains:Ge.array(Ge.string()).optional(),blockedDomains:Ge.array(Ge.string()).optional(),userLocation:Ge.object({type:Ge.literal("approximate"),city:Ge.string().optional(),region:Ge.string().optional(),country:Ge.string().optional(),timezone:Ge.string().optional()}).optional()}),MR=Ge.array(Ge.object({url:Ge.string(),title:Ge.string(),pageAge:Ge.string().nullable(),encryptedContent:Ge.string(),type:Ge.string()})),S1=Vc({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:Ge.object({query:Ge.string()}),outputSchema:MR}),y1=(r={})=>S1(r);function b1(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="web_search_20250305"}function E1({tools:r,toolChoice:e,disableParallelToolUse:t}){r=r?.length?r:void 0;let n=[],o=new Set;if(r==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n,betas:o};let i=[];for(let s of r){if(b1(s)){i.push(s);continue}switch(s.type){case"function":let c=Cn(s.providerOptions);i.push({name:s.name,description:s.description,input_schema:s.inputSchema,cache_control:c});break;case"provider-defined":switch(s.id){case"anthropic.computer_20250124":o.add("computer-use-2025-01-24"),i.push({name:"computer",type:"computer_20250124",display_width_px:s.args.displayWidthPx,display_height_px:s.args.displayHeightPx,display_number:s.args.displayNumber});break;case"anthropic.computer_20241022":o.add("computer-use-2024-10-22"),i.push({name:"computer",type:"computer_20241022",display_width_px:s.args.displayWidthPx,display_height_px:s.args.displayHeightPx,display_number:s.args.displayNumber});break;case"anthropic.text_editor_20250124":o.add("computer-use-2025-01-24"),i.push({name:"str_replace_editor",type:"text_editor_20250124"});break;case"anthropic.text_editor_20241022":o.add("computer-use-2024-10-22"),i.push({name:"str_replace_editor",type:"text_editor_20241022"});break;case"anthropic.text_editor_20250429":o.add("computer-use-2025-01-24"),i.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429"});break;case"anthropic.bash_20250124":o.add("computer-use-2025-01-24"),i.push({name:"bash",type:"bash_20250124"});break;case"anthropic.bash_20241022":o.add("computer-use-2024-10-22"),i.push({name:"bash",type:"bash_20241022"});break;case"anthropic.web_search_20250305":{let l=f1.parse(s.args);i.push({type:"web_search_20250305",name:"web_search",max_uses:l.maxUses,allowed_domains:l.allowedDomains,blocked_domains:l.blockedDomains,user_location:l.userLocation});break}case"anthropic.code_execution_20250522":{o.add("code-execution-2025-05-22"),i.push({type:"code_execution_20250522",name:"code_execution"});break}default:n.push({type:"unsupported-tool",tool:s});break}break;default:n.push({type:"unsupported-tool",tool:s});break}}if(e==null)return{tools:i,toolChoice:t?{type:"auto",disable_parallel_tool_use:t}:void 0,toolWarnings:n,betas:o};let a=e.type;switch(a){case"auto":return{tools:i,toolChoice:{type:"auto",disable_parallel_tool_use:t},toolWarnings:n,betas:o};case"required":return{tools:i,toolChoice:{type:"any",disable_parallel_tool_use:t},toolWarnings:n,betas:o};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:n,betas:o};case"tool":return{tools:i,toolChoice:{type:"tool",name:e.toolName,disable_parallel_tool_use:t},toolWarnings:n,betas:o};default:{let s=a;throw new Nr({functionality:`tool choice type: ${s}`})}}}var PR=fo.object({type:fo.literal("code_execution_result"),stdout:fo.string(),stderr:fo.string(),return_code:fo.number()}),T1=Vc({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:fo.object({code:fo.string()}),outputSchema:PR}),v1=(r={})=>T1(r);function A1(r){if(typeof r=="string")return Buffer.from(r,"base64").toString("utf-8");if(r instanceof Uint8Array)return new TextDecoder().decode(r);throw r instanceof URL?new Nr({functionality:"URL-based text documents are not supported for citations"}):new Nr({functionality:`unsupported data type for text documents: ${typeof r}`})}async function w1({prompt:r,sendReasoning:e,warnings:t}){var n,o,i,a,s;let c=new Set,l=R1(r),u,d=[];async function p(m){var h,f;let E=await mi({provider:"anthropic",providerOptions:m,schema:CR});return(f=(h=E?.citations)==null?void 0:h.enabled)!=null?f:!1}async function g(m){let h=await mi({provider:"anthropic",providerOptions:m,schema:CR});return{title:h?.title,context:h?.context}}for(let m=0;m<l.length;m++){let h=l[m],f=m===l.length-1,E=h.type;switch(E){case"system":{if(u!=null)throw new Nr({functionality:"Multiple system messages that are separated by user/assistant messages"});u=h.messages.map(({content:S,providerOptions:R})=>({type:"text",text:S,cache_control:Cn(R)}));break}case"user":{let S=[];for(let R of h.messages){let{role:A,content:v}=R;switch(A){case"user":{for(let P=0;P<v.length;P++){let C=v[P],w=P===v.length-1,F=(n=Cn(C.providerOptions))!=null?n:w?Cn(R.providerOptions):void 0;switch(C.type){case"text":{S.push({type:"text",text:C.text,cache_control:F});break}case"file":{if(C.mediaType.startsWith("image/"))S.push({type:"image",source:C.data instanceof URL?{type:"url",url:C.data.toString()}:{type:"base64",media_type:C.mediaType==="image/*"?"image/jpeg":C.mediaType,data:eg(C.data)},cache_control:F});else if(C.mediaType==="application/pdf"){c.add("pdfs-2024-09-25");let D=await p(C.providerOptions),k=await g(C.providerOptions);S.push({type:"document",source:C.data instanceof URL?{type:"url",url:C.data.toString()}:{type:"base64",media_type:"application/pdf",data:eg(C.data)},title:(o=k.title)!=null?o:C.filename,...k.context&&{context:k.context},...D&&{citations:{enabled:!0}},cache_control:F})}else if(C.mediaType==="text/plain"){let D=await p(C.providerOptions),k=await g(C.providerOptions);S.push({type:"document",source:C.data instanceof URL?{type:"url",url:C.data.toString()}:{type:"text",media_type:"text/plain",data:A1(C.data)},title:(i=k.title)!=null?i:C.filename,...k.context&&{context:k.context},...D&&{citations:{enabled:!0}},cache_control:F})}else throw new Nr({functionality:`media type: ${C.mediaType}`});break}}}break}case"tool":{for(let P=0;P<v.length;P++){let C=v[P],w=P===v.length-1,F=(a=Cn(C.providerOptions))!=null?a:w?Cn(R.providerOptions):void 0,D=C.output,k;switch(D.type){case"content":k=D.value.map(Y=>{switch(Y.type){case"text":return{type:"text",text:Y.text,cache_control:void 0};case"media":{if(Y.mediaType.startsWith("image/"))return{type:"image",source:{type:"base64",media_type:Y.mediaType,data:Y.data},cache_control:void 0};throw new Nr({functionality:`media type: ${Y.mediaType}`})}}});break;case"text":case"error-text":k=D.value;break;case"json":case"error-json":default:k=JSON.stringify(D.value);break}S.push({type:"tool_result",tool_use_id:C.toolCallId,content:k,is_error:D.type==="error-text"||D.type==="error-json"?!0:void 0,cache_control:F})}break}default:{let P=A;throw new Error(`Unsupported role: ${P}`)}}}d.push({role:"user",content:S});break}case"assistant":{let S=[];for(let R=0;R<h.messages.length;R++){let A=h.messages[R],v=R===h.messages.length-1,{content:P}=A;for(let C=0;C<P.length;C++){let w=P[C],F=C===P.length-1,D=(s=Cn(w.providerOptions))!=null?s:F?Cn(A.providerOptions):void 0;switch(w.type){case"text":{S.push({type:"text",text:f&&v&&F?w.text.trim():w.text,cache_control:D});break}case"reasoning":{if(e){let k=await mi({provider:"anthropic",providerOptions:w.providerOptions,schema:P1});k!=null?k.signature!=null?S.push({type:"thinking",thinking:w.text,signature:k.signature,cache_control:D}):k.redactedData!=null?S.push({type:"redacted_thinking",data:k.redactedData,cache_control:D}):t.push({type:"other",message:"unsupported reasoning metadata"}):t.push({type:"other",message:"unsupported reasoning metadata"})}else t.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(w.providerExecuted){if(w.toolName==="web_search"){S.push({type:"server_tool_use",id:w.toolCallId,name:"web_search",input:w.input,cache_control:D});break}if(w.toolName==="code_execution"){S.push({type:"server_tool_use",id:w.toolCallId,name:"code_execution",input:w.input,cache_control:D});break}t.push({type:"other",message:`provider executed tool call for tool ${w.toolName} is not supported`});break}S.push({type:"tool_use",id:w.toolCallId,name:w.toolName,input:w.input,cache_control:D});break}case"tool-result":{if(w.toolName==="web_search"){let k=w.output;if(k.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${k.type} for tool ${w.toolName} is not supported`});break}let Y=MR.parse(k.value);S.push({type:"web_search_tool_result",tool_use_id:w.toolCallId,content:Y.map(Me=>({url:Me.url,title:Me.title,page_age:Me.pageAge,encrypted_content:Me.encryptedContent,type:Me.type})),cache_control:D});break}if(w.toolName==="code_execution"){let k=w.output;if(k.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${k.type} for tool ${w.toolName} is not supported`});break}let Y=PR.parse(k.value);S.push({type:"code_execution_tool_result",tool_use_id:w.toolCallId,content:{type:Y.type,stdout:Y.stdout,stderr:Y.stderr,return_code:Y.return_code},cache_control:D});break}t.push({type:"other",message:`provider executed tool result for tool ${w.toolName} is not supported`});break}}}}d.push({role:"assistant",content:S});break}default:{let S=E;throw new Error(`content type: ${S}`)}}}return{prompt:{system:u,messages:d},betas:c}}function R1(r){let e=[],t;for(let n of r){let{role:o}=n;switch(o){case"system":{t?.type!=="system"&&(t={type:"system",messages:[]},e.push(t)),t.messages.push(n);break}case"assistant":{t?.type!=="assistant"&&(t={type:"assistant",messages:[]},e.push(t)),t.messages.push(n);break}case"user":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}case"tool":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}default:{let i=o;throw new Error(`Unsupported role: ${i}`)}}}return e}function xR({finishReason:r,isJsonResponseFromTool:e}){switch(r){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return e?"stop":"tool-calls";case"max_tokens":return"length";default:return"unknown"}}var Ka={webSearchResult:T.object({type:T.literal("web_search_result_location"),cited_text:T.string(),url:T.string(),title:T.string(),encrypted_index:T.string()}),pageLocation:T.object({type:T.literal("page_location"),cited_text:T.string(),document_index:T.number(),document_title:T.string().nullable(),start_page_number:T.number(),end_page_number:T.number()}),charLocation:T.object({type:T.literal("char_location"),cited_text:T.string(),document_index:T.number(),document_title:T.string().nullable(),start_char_index:T.number(),end_char_index:T.number()})},IR=T.discriminatedUnion("type",[Ka.webSearchResult,Ka.pageLocation,Ka.charLocation]),kPe=T.discriminatedUnion("type",[Ka.pageLocation,Ka.charLocation]);function _R(r,e,t,n){if(r.type==="page_location"||r.type==="char_location"){let o=C1(r,e,t);o&&n(o)}}function C1(r,e,t){var n;let o=e[r.document_index];if(!o)return null;let i=r.type==="page_location"?{citedText:r.cited_text,startPageNumber:r.start_page_number,endPageNumber:r.end_page_number}:{citedText:r.cited_text,startCharIndex:r.start_char_index,endCharIndex:r.end_char_index};return{type:"source",sourceType:"document",id:t(),mediaType:o.mediaType,title:(n=r.document_title)!=null?n:o.title,filename:o.filename,providerMetadata:{anthropic:i}}}var x1=class{constructor(r,e){this.specificationVersion="v2";var t;this.modelId=r,this.config=e,this.generateId=(t=e.generateId)!=null?t:jc}supportsUrl(r){return r.protocol==="https:"}get provider(){return this.config.provider}get supportedUrls(){var r,e,t;return(t=(e=(r=this.config).supportedUrls)==null?void 0:e.call(r))!=null?t:{}}async getArgs({prompt:r,maxOutputTokens:e=4096,temperature:t,topP:n,topK:o,frequencyPenalty:i,presencePenalty:a,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:p}){var g,m,h;let f=[];i!=null&&f.push({type:"unsupported-setting",setting:"frequencyPenalty"}),a!=null&&f.push({type:"unsupported-setting",setting:"presencePenalty"}),l!=null&&f.push({type:"unsupported-setting",setting:"seed"}),c?.type==="json"&&(c.schema==null?f.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."}):u!=null&&f.push({type:"unsupported-setting",setting:"tools",details:"JSON response format does not support tools. The provided tools are ignored."}));let E=c?.type==="json"&&c.schema!=null?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:c.schema}:void 0,S=await mi({provider:"anthropic",providerOptions:p,schema:h1}),{prompt:R,betas:A}=await w1({prompt:r,sendReasoning:(g=S?.sendReasoning)!=null?g:!0,warnings:f}),v=((m=S?.thinking)==null?void 0:m.type)==="enabled",P=(h=S?.thinking)==null?void 0:h.budgetTokens,C={model:this.modelId,max_tokens:e,temperature:t,top_k:o,top_p:n,stop_sequences:s,...v&&{thinking:{type:"enabled",budget_tokens:P}},system:R.system,messages:R.messages};if(v){if(P==null)throw new Nr({functionality:"thinking requires a budget"});C.temperature!=null&&(C.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),o!=null&&(C.top_k=void 0,f.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),n!=null&&(C.top_p=void 0,f.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),C.max_tokens=e+P}let{tools:w,toolChoice:F,toolWarnings:D,betas:k}=E1(E!=null?{tools:[E],toolChoice:{type:"tool",toolName:E.name},disableParallelToolUse:S?.disableParallelToolUse}:{tools:u??[],toolChoice:d,disableParallelToolUse:S?.disableParallelToolUse});return{args:{...C,tools:w,tool_choice:F},warnings:[...f,...D],betas:new Set([...A,...k]),usesJsonResponseTool:E!=null}}async getHeaders({betas:r,headers:e}){return hR(await bR(this.config.headers),r.size>0?{"anthropic-beta":Array.from(r).join(",")}:{},e)}buildRequestUrl(r){var e,t,n;return(n=(t=(e=this.config).buildRequestUrl)==null?void 0:t.call(e,this.config.baseURL,r))!=null?n:`${this.config.baseURL}/messages`}transformRequestBody(r){var e,t,n;return(n=(t=(e=this.config).transformRequestBody)==null?void 0:t.call(e,r))!=null?n:r}extractCitationDocuments(r){let e=t=>{var n,o;if(t.type!=="file"||t.mediaType!=="application/pdf"&&t.mediaType!=="text/plain")return!1;let i=(n=t.providerOptions)==null?void 0:n.anthropic,a=i?.citations;return(o=a?.enabled)!=null?o:!1};return r.filter(t=>t.role==="user").flatMap(t=>t.content).filter(e).map(t=>{var n;let o=t;return{title:(n=o.filename)!=null?n:"Untitled Document",filename:o.filename,mediaType:o.mediaType}})}async doGenerate(r){var e,t,n,o,i;let{args:a,warnings:s,betas:c,usesJsonResponseTool:l}=await this.getArgs(r),u=this.extractCitationDocuments(r.prompt),{responseHeaders:d,value:p,rawValue:g}=await Qm({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:c,headers:r.headers}),body:this.transformRequestBody(a),failedResponseHandler:RR,successfulResponseHandler:vR(_1),abortSignal:r.abortSignal,fetch:this.config.fetch}),m=[];for(let h of p.content)switch(h.type){case"text":{if(!l&&(m.push({type:"text",text:h.text}),h.citations))for(let f of h.citations)_R(f,u,this.generateId,E=>m.push(E));break}case"thinking":{m.push({type:"reasoning",text:h.thinking,providerMetadata:{anthropic:{signature:h.signature}}});break}case"redacted_thinking":{m.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:h.data}}});break}case"tool_use":{m.push(l?{type:"text",text:JSON.stringify(h.input)}:{type:"tool-call",toolCallId:h.id,toolName:h.name,input:JSON.stringify(h.input)});break}case"server_tool_use":{(h.name==="web_search"||h.name==="code_execution")&&m.push({type:"tool-call",toolCallId:h.id,toolName:h.name,input:JSON.stringify(h.input),providerExecuted:!0});break}case"web_search_tool_result":{if(Array.isArray(h.content)){m.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"web_search",result:h.content.map(f=>{var E;return{url:f.url,title:f.title,pageAge:(E=f.page_age)!=null?E:null,encryptedContent:f.encrypted_content,type:f.type}}),providerExecuted:!0});for(let f of h.content)m.push({type:"source",sourceType:"url",id:this.generateId(),url:f.url,title:f.title,providerMetadata:{anthropic:{pageAge:(e=f.page_age)!=null?e:null}}})}else m.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:h.content.error_code},providerExecuted:!0});break}case"code_execution_tool_result":{h.content.type==="code_execution_result"?m.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"code_execution",result:{type:h.content.type,stdout:h.content.stdout,stderr:h.content.stderr,return_code:h.content.return_code},providerExecuted:!0}):h.content.type==="code_execution_tool_result_error"&&m.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:h.content.error_code},providerExecuted:!0});break}}return{content:m,finishReason:xR({finishReason:p.stop_reason,isJsonResponseFromTool:l}),usage:{inputTokens:p.usage.input_tokens,outputTokens:p.usage.output_tokens,totalTokens:p.usage.input_tokens+p.usage.output_tokens,cachedInputTokens:(t=p.usage.cache_read_input_tokens)!=null?t:void 0},request:{body:a},response:{id:(n=p.id)!=null?n:void 0,modelId:(o=p.model)!=null?o:void 0,headers:d,body:g},warnings:s,providerMetadata:{anthropic:{usage:p.usage,cacheCreationInputTokens:(i=p.usage.cache_creation_input_tokens)!=null?i:null}}}}async doStream(r){let{args:e,warnings:t,betas:n,usesJsonResponseTool:o}=await this.getArgs(r),i=this.extractCitationDocuments(r.prompt),a={...e,stream:!0},{responseHeaders:s,value:c}=await Qm({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:n,headers:r.headers}),body:this.transformRequestBody(a),failedResponseHandler:RR,successfulResponseHandler:TR(M1),abortSignal:r.abortSignal,fetch:this.config.fetch}),l="unknown",u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},p,g,m=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(h){h.enqueue({type:"stream-start",warnings:t})},transform(h,f){var E,S,R,A,v,P,C;if(r.includeRawChunks&&f.enqueue({type:"raw",rawValue:h.rawValue}),!h.success){f.enqueue({type:"error",error:h.error});return}let w=h.value;switch(w.type){case"ping":return;case"content_block_start":{let F=w.content_block.type;switch(g=F,F){case"text":{d[w.index]={type:"text"},f.enqueue({type:"text-start",id:String(w.index)});return}case"thinking":{d[w.index]={type:"reasoning"},f.enqueue({type:"reasoning-start",id:String(w.index)});return}case"redacted_thinking":{d[w.index]={type:"reasoning"},f.enqueue({type:"reasoning-start",id:String(w.index),providerMetadata:{anthropic:{redactedData:w.content_block.data}}});return}case"tool_use":{d[w.index]=o?{type:"text"}:{type:"tool-call",toolCallId:w.content_block.id,toolName:w.content_block.name,input:""},f.enqueue(o?{type:"text-start",id:String(w.index)}:{type:"tool-input-start",id:w.content_block.id,toolName:w.content_block.name});return}case"server_tool_use":{(w.content_block.name==="web_search"||w.content_block.name==="code_execution")&&(d[w.index]={type:"tool-call",toolCallId:w.content_block.id,toolName:w.content_block.name,input:"",providerExecuted:!0},f.enqueue({type:"tool-input-start",id:w.content_block.id,toolName:w.content_block.name,providerExecuted:!0}));return}case"web_search_tool_result":{let D=w.content_block;if(Array.isArray(D.content)){f.enqueue({type:"tool-result",toolCallId:D.tool_use_id,toolName:"web_search",result:D.content.map(k=>{var Y;return{url:k.url,title:k.title,pageAge:(Y=k.page_age)!=null?Y:null,encryptedContent:k.encrypted_content,type:k.type}}),providerExecuted:!0});for(let k of D.content)f.enqueue({type:"source",sourceType:"url",id:m(),url:k.url,title:k.title,providerMetadata:{anthropic:{pageAge:(E=k.page_age)!=null?E:null}}})}else f.enqueue({type:"tool-result",toolCallId:D.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:D.content.error_code},providerExecuted:!0});return}case"code_execution_tool_result":{let D=w.content_block;D.content.type==="code_execution_result"?f.enqueue({type:"tool-result",toolCallId:D.tool_use_id,toolName:"code_execution",result:{type:D.content.type,stdout:D.content.stdout,stderr:D.content.stderr,return_code:D.content.return_code},providerExecuted:!0}):D.content.type==="code_execution_tool_result_error"&&f.enqueue({type:"tool-result",toolCallId:D.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:D.content.error_code},providerExecuted:!0});return}default:{let D=F;throw new Error(`Unsupported content block type: ${D}`)}}}case"content_block_stop":{if(d[w.index]!=null){let F=d[w.index];switch(F.type){case"text":{f.enqueue({type:"text-end",id:String(w.index)});break}case"reasoning":{f.enqueue({type:"reasoning-end",id:String(w.index)});break}case"tool-call":o||(f.enqueue({type:"tool-input-end",id:F.toolCallId}),f.enqueue(F));break}delete d[w.index]}g=void 0;return}case"content_block_delta":{let F=w.delta.type;switch(F){case"text_delta":{if(o)return;f.enqueue({type:"text-delta",id:String(w.index),delta:w.delta.text});return}case"thinking_delta":{f.enqueue({type:"reasoning-delta",id:String(w.index),delta:w.delta.thinking});return}case"signature_delta":{g==="thinking"&&f.enqueue({type:"reasoning-delta",id:String(w.index),delta:"",providerMetadata:{anthropic:{signature:w.delta.signature}}});return}case"input_json_delta":{let D=d[w.index],k=w.delta.partial_json;if(o){if(D?.type!=="text")return;f.enqueue({type:"text-delta",id:String(w.index),delta:k})}else{if(D?.type!=="tool-call")return;f.enqueue({type:"tool-input-delta",id:D.toolCallId,delta:k}),D.input+=k}return}case"citations_delta":{let D=w.delta.citation;_R(D,i,m,k=>f.enqueue(k));return}default:{let D=F;throw new Error(`Unsupported delta type: ${D}`)}}}case"message_start":{u.inputTokens=w.message.usage.input_tokens,u.cachedInputTokens=(S=w.message.usage.cache_read_input_tokens)!=null?S:void 0,p={anthropic:{usage:w.message.usage,cacheCreationInputTokens:(R=w.message.usage.cache_creation_input_tokens)!=null?R:null}},f.enqueue({type:"response-metadata",id:(A=w.message.id)!=null?A:void 0,modelId:(v=w.message.model)!=null?v:void 0});return}case"message_delta":{u.outputTokens=w.usage.output_tokens,u.totalTokens=((P=u.inputTokens)!=null?P:0)+((C=w.usage.output_tokens)!=null?C:0),l=xR({finishReason:w.delta.stop_reason,isJsonResponseFromTool:o});return}case"message_stop":{f.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:p});return}case"error":{f.enqueue({type:"error",error:w.error});return}default:{let F=w;throw new Error(`Unsupported chunk type: ${F}`)}}}})),request:{body:a},response:{headers:s}}}},_1=T.object({type:T.literal("message"),id:T.string().nullish(),model:T.string().nullish(),content:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("text"),text:T.string(),citations:T.array(IR).optional()}),T.object({type:T.literal("thinking"),thinking:T.string(),signature:T.string()}),T.object({type:T.literal("redacted_thinking"),data:T.string()}),T.object({type:T.literal("tool_use"),id:T.string(),name:T.string(),input:T.unknown()}),T.object({type:T.literal("server_tool_use"),id:T.string(),name:T.string(),input:T.record(T.string(),T.unknown()).nullish()}),T.object({type:T.literal("web_search_tool_result"),tool_use_id:T.string(),content:T.union([T.array(T.object({type:T.literal("web_search_result"),url:T.string(),title:T.string(),encrypted_content:T.string(),page_age:T.string().nullish()})),T.object({type:T.literal("web_search_tool_result_error"),error_code:T.string()})])}),T.object({type:T.literal("code_execution_tool_result"),tool_use_id:T.string(),content:T.union([T.object({type:T.literal("code_execution_result"),stdout:T.string(),stderr:T.string(),return_code:T.number()}),T.object({type:T.literal("code_execution_tool_result_error"),error_code:T.string()})])})])),stop_reason:T.string().nullish(),usage:T.looseObject({input_tokens:T.number(),output_tokens:T.number(),cache_creation_input_tokens:T.number().nullish(),cache_read_input_tokens:T.number().nullish()})}),M1=T.discriminatedUnion("type",[T.object({type:T.literal("message_start"),message:T.object({id:T.string().nullish(),model:T.string().nullish(),usage:T.looseObject({input_tokens:T.number(),output_tokens:T.number(),cache_creation_input_tokens:T.number().nullish(),cache_read_input_tokens:T.number().nullish()})})}),T.object({type:T.literal("content_block_start"),index:T.number(),content_block:T.discriminatedUnion("type",[T.object({type:T.literal("text"),text:T.string()}),T.object({type:T.literal("thinking"),thinking:T.string()}),T.object({type:T.literal("tool_use"),id:T.string(),name:T.string()}),T.object({type:T.literal("redacted_thinking"),data:T.string()}),T.object({type:T.literal("server_tool_use"),id:T.string(),name:T.string(),input:T.record(T.string(),T.unknown()).nullish()}),T.object({type:T.literal("web_search_tool_result"),tool_use_id:T.string(),content:T.union([T.array(T.object({type:T.literal("web_search_result"),url:T.string(),title:T.string(),encrypted_content:T.string(),page_age:T.string().nullish()})),T.object({type:T.literal("web_search_tool_result_error"),error_code:T.string()})])}),T.object({type:T.literal("code_execution_tool_result"),tool_use_id:T.string(),content:T.union([T.object({type:T.literal("code_execution_result"),stdout:T.string(),stderr:T.string(),return_code:T.number()}),T.object({type:T.literal("code_execution_tool_result_error"),error_code:T.string()})])})])}),T.object({type:T.literal("content_block_delta"),index:T.number(),delta:T.discriminatedUnion("type",[T.object({type:T.literal("input_json_delta"),partial_json:T.string()}),T.object({type:T.literal("text_delta"),text:T.string()}),T.object({type:T.literal("thinking_delta"),thinking:T.string()}),T.object({type:T.literal("signature_delta"),signature:T.string()}),T.object({type:T.literal("citations_delta"),citation:IR})])}),T.object({type:T.literal("content_block_stop"),index:T.number()}),T.object({type:T.literal("error"),error:T.object({type:T.string(),message:T.string()})}),T.object({type:T.literal("message_delta"),delta:T.object({stop_reason:T.string().nullish()}),usage:T.object({output_tokens:T.number()})}),T.object({type:T.literal("message_stop")}),T.object({type:T.literal("ping")})]),P1=T.object({signature:T.string().optional(),redactedData:T.string().optional()}),I1=Lt({id:"anthropic.bash_20241022",name:"bash",inputSchema:tg.object({command:tg.string(),restart:tg.boolean().optional()})}),O1=Lt({id:"anthropic.bash_20250124",name:"bash",inputSchema:rg.object({command:rg.string(),restart:rg.boolean().optional()})}),L1=Lt({id:"anthropic.computer_20241022",name:"computer",inputSchema:qa.object({action:qa.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:qa.array(qa.number().int()).optional(),text:qa.string().optional()})}),N1=Lt({id:"anthropic.computer_20250124",name:"computer",inputSchema:ir.object({action:ir.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:ir.tuple([ir.number().int(),ir.number().int()]).optional(),duration:ir.number().optional(),scroll_amount:ir.number().optional(),scroll_direction:ir.enum(["up","down","left","right"]).optional(),start_coordinate:ir.tuple([ir.number().int(),ir.number().int()]).optional(),text:ir.string().optional()})}),k1=Lt({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:Wr.object({command:Wr.enum(["view","create","str_replace","insert","undo_edit"]),path:Wr.string(),file_text:Wr.string().optional(),insert_line:Wr.number().int().optional(),new_str:Wr.string().optional(),old_str:Wr.string().optional(),view_range:Wr.array(Wr.number().int()).optional()})}),D1=Lt({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:qr.object({command:qr.enum(["view","create","str_replace","insert","undo_edit"]),path:qr.string(),file_text:qr.string().optional(),insert_line:qr.number().int().optional(),new_str:qr.string().optional(),old_str:qr.string().optional(),view_range:qr.array(qr.number().int()).optional()})}),U1=Lt({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:Kr.object({command:Kr.enum(["view","create","str_replace","insert"]),path:Kr.string(),file_text:Kr.string().optional(),insert_line:Kr.number().int().optional(),new_str:Kr.string().optional(),old_str:Kr.string().optional(),view_range:Kr.array(Kr.number().int()).optional()})}),F1={bash_20241022:I1,bash_20250124:O1,textEditor_20241022:k1,textEditor_20250124:D1,textEditor_20250429:U1,computer_20241022:L1,computer_20250124:N1,webSearch_20250305:y1,codeExecution_20250522:v1};function ng(r={}){var e;let t=(e=wR(r.baseURL))!=null?e:"https://api.anthropic.com/v1",n=()=>({"anthropic-version":"2023-06-01","x-api-key":fR({apiKey:r.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...r.headers}),o=a=>{var s;return new x1(a,{provider:"anthropic.messages",baseURL:t,headers:n,fetch:r.fetch,generateId:(s=r.generateId)!=null?s:jc,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},i=function(a){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return o(a)};return i.languageModel=o,i.chat=o,i.messages=o,i.textEmbeddingModel=a=>{throw new Km({modelId:a,modelType:"textEmbeddingModel"})},i.imageModel=a=>{throw new Km({modelId:a,modelType:"imageModel"})},i.tools=F1,i}var XPe=ng();var OR=({baseUrl:r,apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o})=>i=>{let a={Authorization:`Bearer ${e}`,[Ys]:ho??"",...t&&{[Yf]:t},...n||{}};return o&&(a[Kf]=JSON.stringify(o)),ng({baseURL:`${r}/v1/llm/anthropic/${i}`,headers:a,apiKey:e})(i)};var So=class extends Lr{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(`/${B}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return Uh.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${B}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ho,...e},signal:t.abortSignal});return Dh.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${B}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return B1.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(`/${B}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Qf.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(`/${B}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return dd.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${B}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return Zf.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${B}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return Jf.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(`/${B}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return dd.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${B}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Xf.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${B}/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(`/${B}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Au.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${B}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return eS.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${B}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return Tu.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${B}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return hh.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${B}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Mu.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${B}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return Kh.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${B}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return dh.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${B}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return gh.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${B}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return mh.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${B}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Ug.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return OR({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as og}from"zod";var fr=class extends Lr{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(`/${B}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return mS.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${B}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return cS.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${B}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return rS.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${B}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${B}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return oS.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${B}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${B}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return iS.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${B}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return tS.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${B}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return pS.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${B}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return gS.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${B}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return _S.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${B}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${B}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${B}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${B}/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(`/${B}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return hS.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${B}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Oh.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${B}/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(`/${B}/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(`/${B}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return fS.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${B}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${B}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return SS.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${B}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return yS.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${B}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return bS.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${B}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return IS.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${B}/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(`/${B}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ra.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${B}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ra.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${B}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return hd.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(`/${B}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ra.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${B}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ra.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${B}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return hd.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${B}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return og.record(og.string(),og.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${B}/quarantine`,{method:"GET"});return ES.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${B}/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(`/${B}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${B}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return TS.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${B}/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(`/${B}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return vS.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${B}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${B}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return AS.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${B}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function ig(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(x.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),x.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return x.debug("Got auth info from API"),n}var $c=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var gi=class extends Lr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${B}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Fg.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var hi=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 z1,en as H1}from"@faker-js/faker";var fi="v1",Si=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 z1({locale:H1}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${fi}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof hr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${fi}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof hr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${fi}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof hr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${fi}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof hr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${fi}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof hr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${fi}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof hr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function LR(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Wc=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await LR(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 yi=class extends Lr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${B}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Xh.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${B}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Qh.parse(o)}};function qc({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new Js:new ag(r,e,t,n)}var ag=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=pd(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&&Ed({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await $n({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import Kc from"path";function G1(r){let e=new NR,t=Kc.join(r,"metadata.json"),n=na.parse(JSON.parse(sg.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of sg.readdirSync(Kc.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new NR(Kc.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Kc.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Yc(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!sg.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new Wc(e);try{let{runGroupId:i,buffer:a}=G1(n),s=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${s}`;t.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`);return}catch(i){let a;i instanceof Error?a=i.message:typeof i=="string"?a=i:a="Unknown error",t.error(`Failed to upload test results: ${a}.`);return}}import j1 from"adm-zip";import dt from"fs";import Ft from"path";var Ya=class r{constructor(e){this.filePath=e;dt.rmSync(this.filePath,{recursive:!0,force:!0}),dt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Ft.join(this.filePath,e))}mkdir(e){dt.mkdirSync(Ft.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Ft.join(this.filePath,e);if(dt.existsSync(t))return dt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Ft.join(this.filePath,t);try{dt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=Ft.join(this.filePath,e);return dt.createWriteStream(t)}createRunArchive(e){return new lg(Ft.join(this.filePath,"runs"),e)}},lg=class{constructor(e,t){this.filePath=e;this.tempPath=Ft.join(e,`.${t}`),this.finalPath=Ft.join(e,`${t}.zip`),dt.rmSync(this.tempPath,{recursive:!0,force:!0}),dt.rmSync(this.finalPath,{recursive:!0,force:!0}),dt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Ft.join(this.tempPath,e);if(dt.existsSync(t))return dt.readFileSync(t)}mkdir(e){dt.mkdirSync(Ft.join(this.tempPath,e),{recursive:!0})}cd(e){return new Ya(Ft.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=Ft.join(this.tempPath,t);dt.writeFileSync(o,n)}createFileStream(e){let t=Ft.join(this.tempPath,e);return dt.createWriteStream(t)}close(){let e=new j1;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();dt.writeFileSync(this.finalPath,t),dt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import nu from"fs";import qR from"body-parser";import sz from"cors";import lz from"dedent";import{Router as q1}from"express";import wt from"fs";import{globSync as K1}from"glob";import it from"path";import ug from"fs";import V1 from"path";var $1=new pl(30,60*1e3),mg="https://api.momentic.ai",dg,DR=r=>{mg=r},gg=()=>mg,hg=()=>dg;var bi,pg,kR,UR=async r=>{if(dg&&bi&&kR)return bi;let e=new fr({baseUrl:mg,apiKey:r,logger:x});dg=e;try{let t=await e.getAuthInfo();return bi=t.orgId,pg=t.userId,kR=r,bi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Xa=()=>{if(!bi)throw new Error("Your organization ID is invalid.");return bi},Xc=()=>{if(!pg)throw new Error("Your user ID is invalid.");return pg};var fg,cg,FR=(r,e)=>{fg=r,cg?.abort(),cg=new AbortController;let t=cg.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=V1.resolve(r.rootDir,o.envFile);try{if(ug.lstatSync(i).isSymbolicLink())return;ug.existsSync(i)&&n.push(i)}catch(a){x.warn({err:a},`Failed to check if env file ${i} exists`)}});try{W1({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){x.error({err:o},"Failed to start config file watchers")}},et=()=>fg;function W1({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{ug.watch(o,{signal:t,persistent:!1,recursive:!1},async(i,a)=>{a&&($1.increment("setLocalProject")&&x.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.`),fg=await Promise.resolve(e(n.configFilePath)))})})}function tt(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Za=q1();function Ja(r){let e=et(),t=it.dirname(e.configFilePath);return it.join(t,...r)}function Y1(r){let e=et(),t=it.dirname(e.configFilePath),n=it.relative(t,r);return n?n.split(it.sep):[]}function X1(r,e){let t=wt.statSync(r),n=Y1(r);return id.parse({name:e,absolutePath:r,relativePath:n.join(it.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}Za.post("/",tt(async(r,e,t)=>{let n;try{n=kf.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Ja(n);if(!wt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(it.sep)}`});return}if(!wt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(it.sep)}`});return}let a=et(),s=Array.from(a.config.exclude??[]).concat(js),l=K1("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=it.join(o,d);return X1(p,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));Za.put("/",tt(async(r,e,t)=>{let n;try{n=Df.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Ja(n);if(wt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(it.sep)}`,pathSegments:n});return}wt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(it.sep)}`,pathSegments:n};e.status(201).json(i)}));Za.patch("/",tt(async(r,e,t)=>{let n,o;try{let l=Uf.parse(r.body);n=l.pathSegments,o=l.newPathSegments}catch(l){e.status(400).json({error:`Failed to parse folder update body: ${l}`});return}let i=Ja(n),a=Ja(o);if(!wt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(it.sep)}`});return}if(wt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(it.sep)}`});return}let s=it.dirname(a);wt.existsSync(s)||wt.mkdirSync(s,{recursive:!0}),wt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(it.sep)} to ${o.join(it.sep)}`,pathSegments:o};e.status(200).json(c)}));Za.delete("/",tt(async(r,e,t)=>{let n,o=!0;try{let c=Ff.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=Ja(n);if(!wt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(it.sep)}`,pathSegments:n});return}if(!wt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(it.sep)}`});return}if(o)wt.rmSync(i,{recursive:!0,force:!0});else{if(wt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}wt.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var Sg=Za;import cz from"events";import KR,{Router as uz}from"express";import dz from"http";import pz from"path";var Jc=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 BR=new Jc;import{Router as Q1}from"express";import{existsSync as ez}from"fs";import tz from"path";import{hostname as J1}from"os";var Z1="0.0.26",Rt=Cc({app:"mobile-desktop-server",hostname:J1(),disableConsoleLogs:!0}).child({cliVersion:Z1});(async()=>{try{let r=await Hm(Rt);r.gitBranchName&&Rt.addBinding("branch",r.gitBranchName)}catch{}})();var yg=Q1();yg.get("/",tt(async(r,e)=>{let t=hg();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));yg.post("/upload-url",tt(async(r,e)=>{let t;try{t=jf.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=hg();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=tz.resolve(t.filePath);if(!ez(o)){e.status(400).json({error:`File not found: ${o}`});return}await is({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:Rt}),e.sendStatus(204)}));var zR=yg;import{Router as rz}from"express";var HR=rz();HR.get("/",tt(async(r,e)=>{let t=et(),n=await gr(t),o=new Set;n?.tests&&Object.values(n.tests).forEach(c=>{c.labels?.forEach(l=>o.add(l))});let i=Array.from(o).sort(),a=Object.values(n.mobileTests),s={labels:i,modules:[],tests:a};e.status(200).json(s)}));var GR=HR;import{Router as nz}from"express";var jR=nz();jR.get("/",(r,e)=>{e.status(200).json({userId:Xc(),orgId:Xa()})});var VR=jR;import{Router as oz}from"express";var Zc=oz();async function iz(r){return(await Lw(r,Rt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){x.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)}Zc.get("/",tt(async(r,e)=>{let t=et(),n=await gr(t),o=await iz(n);e.status(200).json(o)}));Zc.get("/:moduleId",tt(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await gr(et()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await jm(n,t,x);e.json(o)}catch(o){e.status(400).json({err:o})}}));Zc.patch("/:moduleId/metadata",tt(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=Vf.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=et(),o=await gr(n);Ow({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:x,project:n}),e.status(201).json({message:"ok"})}));var $R=Zc;import{Router as az}from"express";import bg from"path";var Qc=az();Qc.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=Gf.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=et(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await gr(o);await kw({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let s={message:"ok"};e.status(200).json(s)}));Qc.post("/",tt((r,e)=>{let t;try{t=Hf.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{Hu(n)}catch(m){e.status(400).json({error:m.message});return}let s=et(),c=bg.join(s.rootDir,...a),{fullPath:l,testId:u}=Nw({name:n,description:o,steps:[],settings:i,folder:c}),d=bg.basename(l),p=bg.relative(s.rootDir,l),g={id:u,fileName:d,fullPath:l,relativeFilePath:p};e.status(201).json(g)}));Qc.get("/:fileName",tt(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=et(),i=await gr(o),s=await Fc(n,Rt,i);e.status(200).json(s)}));var WR=Qc;var eu=class extends hi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=et();return Lc(t,o,x)}};var YR="10mb";async function XR(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,alwaysSaveCache:s,noCache:c}=r;n&&DR(n),await UR(t);let l=Xa(),u=Xc(),d=r.logger.child({orgId:l,userId:u});FR(i,A=>Ha({configFilePath:A}));let p=KR();p.use(sz()),p.use(qR.json({limit:YR})),p.use(qR.urlencoded({extended:!1,limit:YR}));let g=uz();if(g.use("/folders",Sg),g.use("/entities",GR),g.use("/identify",VR),g.use("/mobile-tests",WR),g.use("/mobile-modules",$R),g.use("/assets",zR),p.use("/api",g),p.use((A,v,P)=>{x.debug({url:A.url,path:A.path,query:A.query,method:A.method,body:A.body,headers:A.rawHeaders,client:A.ip},"Incoming request on mobile-desktop-server"),v.on("close",()=>{v.statusCode>=400&&(x.error({url:A.url,method:A.method,statusCode:v.statusCode},"Request completed in error on mobile-desktop-server"),Rt.error({url:A.url,method:A.method,statusCode:v.statusCode},"Request completed in error on mobile-desktop-server"))}),P()}),p.use((A,v,P,C)=>{if(A instanceof Error&&A.message.includes("BadRequestError: request aborted")){P.status(400).send("Client disconnected");return}x.error({stack:A.stack,msg:A.message,err:A,url:v.url,method:v.method},"Unhandled exception leading to 500 on mobile-desktop-server"),Rt.error({stack:A.stack,msg:A.message,err:A,url:v.url,method:v.method},"Unhandled exception leading to 500 on mobile-desktop-server"),P.status(500).send(`Internal Server Error: ${A.message}`)}),o){let A=KR.static(o,{setHeaders:v=>{v.setHeader("Cache-Control","no-cache")},redirect:!1});p.use(A),p.use("*",(v,P)=>{P.sendFile(pz.join(o,"index.html"))})}let m=dz.createServer(p),h=`http://localhost:${e}`;await new Promise(A=>{try{m.listen(e,()=>{d.info(`Mobile desktop server is running at ${h}`),A()})}catch(v){v.message.includes("EADDRINUSE")?mz(e):x.error(`An unexpected error occurred while starting the server: ${v.message}`),process.exit(1)}});let E={type:"API_KEY",baseUrl:gg(),apiKey:t,logger:d},S=new fr(E),{dispose:R}=dw({baseServer:m,logger:d,authorization:E,globalStateManager:BR,getOrgId:()=>Xa(),androidDriverFactory:async({socket:A,logger:v,creationOpts:P})=>{let C=Math.floor(Math.random()*1e4)+4e4,w=await Oc(C,"appium");return os({logger:v,driverLogLevel:a,apiClient:S,creationOpts:P,socket:A,appiumPort:w,onStatusUpdate:F=>{A.emit("connectionStatusUpdate",{message:F})}})},mobileGeneratorFactory:async A=>new yi({baseUrl:gg(),apiKey:t,logger:d}),browserGeneratorFactory:async A=>new So({},E),browserEnricherFactory:async A=>new gi(E,new So({},E)),storageFactory:async A=>new eu(S,A),cacheStorageFactory:async A=>{let v=et(),P=await kc(d,S,v);return qc({orgId:A,client:S,gitMetadata:P,noCache:c,alwaysSaveCache:s})},localToolsFactory:async()=>new Si({httpClient:S,fakerSeed:void 0}),keepSessionAlive:A=>S.extendAndroidEmulatorTtl(A),settingsFactory:async()=>({emulator:et().config.emulator})});process.once("SIGUSR2",async()=>{return;try{await R(),await kt.flush()}catch(A){x.error({err:A},"Error during session dispose on SIGUSR2")}try{m.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{x.info("SIGTERM in Momentic mobile app received");try{await R(),await kt.flush()}finally{m.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{x.info("SIGINT in Momentic mobile app received");try{await R(),await kt.flush()}finally{m.close(()=>process.exit(0))}})}cz.setMaxListeners(20);process.on("warning",r=>{Rt.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{Rt.error({err:r},"Uncaught exception on mobile-desktop-server"),x.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{Rt.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),x.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function mz(r){x.error(lz`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4040
|
+
`&&n++}}return[e,t]}var ru=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let o;super({start(i){o=vC({onEvent:a=>{i.enqueue(a)},onError(a){e==="terminate"?i.error(a):typeof e=="function"&&e(a)},onRetry:t,onComment:n})},transform(i){o.feed(i)}})}};import*as IC from"zod/v4";function AC(...r){return r.reduce((e,t)=>({...e,...t??{}}),{})}function nu(r){return Object.fromEntries([...r.headers])}var Rz=({prefix:r,size:e=16,alphabet:t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{let o=()=>{let i=t.length,a=new Array(e);for(let s=0;s<e;s++)a[s]=t[Math.random()*i|0];return a.join("")};if(r==null)return o;if(t.includes(n))throw new eu({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${t}".`});return()=>`${r}${n}${o()}`},ou=Rz();function Eh(r){return(r instanceof Error||r instanceof DOMException)&&(r.name==="AbortError"||r.name==="ResponseAborted"||r.name==="TimeoutError")}var Cz=["fetch failed","failed to fetch"];function xz({error:r,url:e,requestBodyValues:t}){if(Eh(r))return r;if(r instanceof TypeError&&Cz.includes(r.message.toLowerCase())){let n=r.cause;if(n!=null)return new ur({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:t,isRetryable:!0})}return r}function _z(r){return Object.fromEntries(Object.entries(r).filter(([e,t])=>t!=null))}function wC({apiKey:r,environmentVariableName:e,apiKeyParameterName:t="apiKey",description:n}){if(typeof r=="string")return r;if(r!=null)throw new os({message:`${n} API key must be a string.`});if(typeof process>"u")throw new os({message:`${n} API key is missing. Pass it using the '${t}' parameter. Environment variables is not supported in this environment.`});if(r=process.env[e],r==null)throw new os({message:`${n} API key is missing. Pass it using the '${t}' parameter or the ${e} environment variable.`});if(typeof r!="string")throw new os({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return r}var Mz=/"__proto__"\s*:/,Pz=/"constructor"\s*:/;function Iz(r){let e=JSON.parse(r);return e===null||typeof e!="object"||Mz.test(r)===!1&&Pz.test(r)===!1?e:Oz(e)}function Oz(r){let e=[r];for(;e.length;){let t=e;e=[];for(let n of t){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(let o in n){let i=n[o];i&&typeof i=="object"&&e.push(i)}}}return r}function RC(r){let{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return Iz(r)}finally{Error.stackTraceLimit=e}}var Th=Symbol.for("vercel.ai.validator");function Lz(r){return{[Th]:!0,validate:r}}function Nz(r){return typeof r=="object"&&r!==null&&Th in r&&r[Th]===!0&&"validate"in r}function kz(r){return Nz(r)?r:Dz(r)}function Dz(r){return Lz(async e=>{let t=await r["~standard"].validate(e);return t.issues==null?{success:!0,value:t.value}:{success:!1,error:new Ln({value:e,cause:t.issues})}})}async function Uz({value:r,schema:e}){let t=await vh({value:r,schema:e});if(!t.success)throw Ln.wrap({value:r,cause:t.error});return t.value}async function vh({value:r,schema:e}){let t=kz(e);try{if(t.validate==null)return{success:!0,value:r,rawValue:r};let n=await t.validate(r);return n.success?{success:!0,value:n.value,rawValue:r}:{success:!1,error:Ln.wrap({value:r,cause:n.error}),rawValue:r}}catch(n){return{success:!1,error:Ln.wrap({value:r,cause:n}),rawValue:r}}}async function Fz({text:r,schema:e}){try{let t=RC(r);return e==null?t:Uz({value:t,schema:e})}catch(t){throw ns.isInstance(t)||Ln.isInstance(t)?t:new ns({text:r,cause:t})}}async function CC({text:r,schema:e}){try{let t=RC(r);return e==null?{success:!0,value:t,rawValue:t}:await vh({value:t,schema:e})}catch(t){return{success:!1,error:ns.isInstance(t)?t:new ns({text:r,cause:t}),rawValue:void 0}}}function Bz({stream:r,schema:e}){return r.pipeThrough(new TextDecoderStream).pipeThrough(new ru).pipeThrough(new TransformStream({async transform({data:t},n){t!=="[DONE]"&&n.enqueue(await CC({text:t,schema:e}))}}))}async function wi({provider:r,providerOptions:e,schema:t}){if(e?.[r]==null)return;let n=await vh({value:e[r],schema:t});if(!n.success)throw new eu({argument:"providerOptions",message:`invalid ${r} provider options`,cause:n.error});return n.value}var zz=()=>globalThis.fetch,Ah=async({url:r,headers:e,body:t,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:i,fetch:a})=>Hz({url:r,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(t),values:t},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:i,fetch:a});var Hz=async({url:r,headers:e={},body:t,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:i,fetch:a=zz()})=>{try{let s=await a(r,{method:"POST",headers:_z(e),body:t.content,signal:i}),c=nu(s);if(!s.ok){let l;try{l=await o({response:s,url:r,requestBodyValues:t.values})}catch(u){throw Eh(u)||ur.isInstance(u)?u:new ur({message:"Failed to process error response",cause:u,statusCode:s.status,url:r,responseHeaders:c,requestBodyValues:t.values})}throw l.value}try{return await n({response:s,url:r,requestBodyValues:t.values})}catch(l){throw l instanceof Error&&(Eh(l)||ur.isInstance(l))?l:new ur({message:"Failed to process successful response",cause:l,statusCode:s.status,url:r,responseHeaders:c,requestBodyValues:t.values})}}catch(s){throw xz({error:s,url:r,requestBodyValues:t.values})}};function Bt({id:r,name:e,inputSchema:t}){return({execute:n,outputSchema:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:c,...l})=>({type:"provider-defined",id:r,name:e,args:l,inputSchema:t,outputSchema:o,execute:n,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:c})}function iu({id:r,name:e,inputSchema:t,outputSchema:n}){return({execute:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:c,...l})=>({type:"provider-defined",id:r,name:e,args:l,inputSchema:t,outputSchema:n,execute:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:c})}async function xC(r){return typeof r=="function"&&(r=r()),Promise.resolve(r)}var _C=({errorSchema:r,errorToMessage:e,isRetryable:t})=>async({response:n,url:o,requestBodyValues:i})=>{let a=await n.text(),s=nu(n);if(a.trim()==="")return{responseHeaders:s,value:new ur({message:n.statusText,url:o,requestBodyValues:i,statusCode:n.status,responseHeaders:s,responseBody:a,isRetryable:t?.(n)})};try{let c=await Fz({text:a,schema:r});return{responseHeaders:s,value:new ur({message:e(c),url:o,requestBodyValues:i,statusCode:n.status,responseHeaders:s,responseBody:a,data:c,isRetryable:t?.(n,c)})}}catch{return{responseHeaders:s,value:new ur({message:n.statusText,url:o,requestBodyValues:i,statusCode:n.status,responseHeaders:s,responseBody:a,isRetryable:t?.(n)})}}},MC=r=>async({response:e})=>{let t=nu(e);if(e.body==null)throw new rC({});return{responseHeaders:t,value:Bz({stream:e.body,schema:r})}};var PC=r=>async({response:e,url:t,requestBodyValues:n})=>{let o=await e.text(),i=await CC({text:o,schema:r}),a=nu(e);if(!i.success)throw new ur({message:"Invalid JSON response",cause:i.error,statusCode:e.status,responseHeaders:a,responseBody:o,url:t,requestBodyValues:n});return{responseHeaders:a,value:i.value,rawValue:i.rawValue}};var tOe=Symbol.for("vercel.ai.schema");var{btoa:Gz,atob:rOe}=globalThis;function jz(r){let e="";for(let t=0;t<r.length;t++)e+=String.fromCodePoint(r[t]);return Gz(e)}function wh(r){return r instanceof Uint8Array?jz(r):r}function OC(r){return r?.replace(/\/$/,"")}import{z as T}from"zod/v4";import{z as is}from"zod/v4";import{z as jt}from"zod/v4";import{z as qe}from"zod/v4";import{z as Ro}from"zod/v4";import Rh from"zod/v4";import Ch from"zod/v4";import{z as as}from"zod/v4";import{z as dr}from"zod/v4";import{z as en}from"zod/v4";import{z as tn}from"zod/v4";import{z as rn}from"zod/v4";var Vz=is.object({type:is.literal("error"),error:is.object({type:is.string(),message:is.string()})}),LC=_C({errorSchema:Vz,errorToMessage:r=>r.error.message}),NC=jt.object({citations:jt.object({enabled:jt.boolean()}).optional(),title:jt.string().optional(),context:jt.string().optional()}),$z=jt.object({sendReasoning:jt.boolean().optional(),thinking:jt.object({type:jt.union([jt.literal("enabled"),jt.literal("disabled")]),budgetTokens:jt.number().optional()}).optional(),disableParallelToolUse:jt.boolean().optional()});function Nn(r){var e;let t=r?.anthropic;return(e=t?.cacheControl)!=null?e:t?.cache_control}var Wz=qe.object({maxUses:qe.number().optional(),allowedDomains:qe.array(qe.string()).optional(),blockedDomains:qe.array(qe.string()).optional(),userLocation:qe.object({type:qe.literal("approximate"),city:qe.string().optional(),region:qe.string().optional(),country:qe.string().optional(),timezone:qe.string().optional()}).optional()}),UC=qe.array(qe.object({url:qe.string(),title:qe.string(),pageAge:qe.string().nullable(),encryptedContent:qe.string(),type:qe.string()})),qz=iu({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:qe.object({query:qe.string()}),outputSchema:UC}),Kz=(r={})=>qz(r);function Yz(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="web_search_20250305"}function Xz({tools:r,toolChoice:e,disableParallelToolUse:t}){r=r?.length?r:void 0;let n=[],o=new Set;if(r==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n,betas:o};let i=[];for(let s of r){if(Yz(s)){i.push(s);continue}switch(s.type){case"function":let c=Nn(s.providerOptions);i.push({name:s.name,description:s.description,input_schema:s.inputSchema,cache_control:c});break;case"provider-defined":switch(s.id){case"anthropic.computer_20250124":o.add("computer-use-2025-01-24"),i.push({name:"computer",type:"computer_20250124",display_width_px:s.args.displayWidthPx,display_height_px:s.args.displayHeightPx,display_number:s.args.displayNumber});break;case"anthropic.computer_20241022":o.add("computer-use-2024-10-22"),i.push({name:"computer",type:"computer_20241022",display_width_px:s.args.displayWidthPx,display_height_px:s.args.displayHeightPx,display_number:s.args.displayNumber});break;case"anthropic.text_editor_20250124":o.add("computer-use-2025-01-24"),i.push({name:"str_replace_editor",type:"text_editor_20250124"});break;case"anthropic.text_editor_20241022":o.add("computer-use-2024-10-22"),i.push({name:"str_replace_editor",type:"text_editor_20241022"});break;case"anthropic.text_editor_20250429":o.add("computer-use-2025-01-24"),i.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429"});break;case"anthropic.bash_20250124":o.add("computer-use-2025-01-24"),i.push({name:"bash",type:"bash_20250124"});break;case"anthropic.bash_20241022":o.add("computer-use-2024-10-22"),i.push({name:"bash",type:"bash_20241022"});break;case"anthropic.web_search_20250305":{let l=Wz.parse(s.args);i.push({type:"web_search_20250305",name:"web_search",max_uses:l.maxUses,allowed_domains:l.allowedDomains,blocked_domains:l.blockedDomains,user_location:l.userLocation});break}case"anthropic.code_execution_20250522":{o.add("code-execution-2025-05-22"),i.push({type:"code_execution_20250522",name:"code_execution"});break}default:n.push({type:"unsupported-tool",tool:s});break}break;default:n.push({type:"unsupported-tool",tool:s});break}}if(e==null)return{tools:i,toolChoice:t?{type:"auto",disable_parallel_tool_use:t}:void 0,toolWarnings:n,betas:o};let a=e.type;switch(a){case"auto":return{tools:i,toolChoice:{type:"auto",disable_parallel_tool_use:t},toolWarnings:n,betas:o};case"required":return{tools:i,toolChoice:{type:"any",disable_parallel_tool_use:t},toolWarnings:n,betas:o};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:n,betas:o};case"tool":return{tools:i,toolChoice:{type:"tool",name:e.toolName,disable_parallel_tool_use:t},toolWarnings:n,betas:o};default:{let s=a;throw new jr({functionality:`tool choice type: ${s}`})}}}var FC=Ro.object({type:Ro.literal("code_execution_result"),stdout:Ro.string(),stderr:Ro.string(),return_code:Ro.number()}),Jz=iu({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:Ro.object({code:Ro.string()}),outputSchema:FC}),Zz=(r={})=>Jz(r);function Qz(r){if(typeof r=="string")return Buffer.from(r,"base64").toString("utf-8");if(r instanceof Uint8Array)return new TextDecoder().decode(r);throw r instanceof URL?new jr({functionality:"URL-based text documents are not supported for citations"}):new jr({functionality:`unsupported data type for text documents: ${typeof r}`})}async function eH({prompt:r,sendReasoning:e,warnings:t}){var n,o,i,a,s;let c=new Set,l=tH(r),u,d=[];async function p(m){var g,f;let E=await wi({provider:"anthropic",providerOptions:m,schema:NC});return(f=(g=E?.citations)==null?void 0:g.enabled)!=null?f:!1}async function h(m){let g=await wi({provider:"anthropic",providerOptions:m,schema:NC});return{title:g?.title,context:g?.context}}for(let m=0;m<l.length;m++){let g=l[m],f=m===l.length-1,E=g.type;switch(E){case"system":{if(u!=null)throw new jr({functionality:"Multiple system messages that are separated by user/assistant messages"});u=g.messages.map(({content:S,providerOptions:w})=>({type:"text",text:S,cache_control:Nn(w)}));break}case"user":{let S=[];for(let w of g.messages){let{role:v,content:A}=w;switch(v){case"user":{for(let I=0;I<A.length;I++){let C=A[I],R=I===A.length-1,B=(n=Nn(C.providerOptions))!=null?n:R?Nn(w.providerOptions):void 0;switch(C.type){case"text":{S.push({type:"text",text:C.text,cache_control:B});break}case"file":{if(C.mediaType.startsWith("image/"))S.push({type:"image",source:C.data instanceof URL?{type:"url",url:C.data.toString()}:{type:"base64",media_type:C.mediaType==="image/*"?"image/jpeg":C.mediaType,data:wh(C.data)},cache_control:B});else if(C.mediaType==="application/pdf"){c.add("pdfs-2024-09-25");let U=await p(C.providerOptions),D=await h(C.providerOptions);S.push({type:"document",source:C.data instanceof URL?{type:"url",url:C.data.toString()}:{type:"base64",media_type:"application/pdf",data:wh(C.data)},title:(o=D.title)!=null?o:C.filename,...D.context&&{context:D.context},...U&&{citations:{enabled:!0}},cache_control:B})}else if(C.mediaType==="text/plain"){let U=await p(C.providerOptions),D=await h(C.providerOptions);S.push({type:"document",source:C.data instanceof URL?{type:"url",url:C.data.toString()}:{type:"text",media_type:"text/plain",data:Qz(C.data)},title:(i=D.title)!=null?i:C.filename,...D.context&&{context:D.context},...U&&{citations:{enabled:!0}},cache_control:B})}else throw new jr({functionality:`media type: ${C.mediaType}`});break}}}break}case"tool":{for(let I=0;I<A.length;I++){let C=A[I],R=I===A.length-1,B=(a=Nn(C.providerOptions))!=null?a:R?Nn(w.providerOptions):void 0,U=C.output,D;switch(U.type){case"content":D=U.value.map(J=>{switch(J.type){case"text":return{type:"text",text:J.text,cache_control:void 0};case"media":{if(J.mediaType.startsWith("image/"))return{type:"image",source:{type:"base64",media_type:J.mediaType,data:J.data},cache_control:void 0};throw new jr({functionality:`media type: ${J.mediaType}`})}}});break;case"text":case"error-text":D=U.value;break;case"json":case"error-json":default:D=JSON.stringify(U.value);break}S.push({type:"tool_result",tool_use_id:C.toolCallId,content:D,is_error:U.type==="error-text"||U.type==="error-json"?!0:void 0,cache_control:B})}break}default:{let I=v;throw new Error(`Unsupported role: ${I}`)}}}d.push({role:"user",content:S});break}case"assistant":{let S=[];for(let w=0;w<g.messages.length;w++){let v=g.messages[w],A=w===g.messages.length-1,{content:I}=v;for(let C=0;C<I.length;C++){let R=I[C],B=C===I.length-1,U=(s=Nn(R.providerOptions))!=null?s:B?Nn(v.providerOptions):void 0;switch(R.type){case"text":{S.push({type:"text",text:f&&A&&B?R.text.trim():R.text,cache_control:U});break}case"reasoning":{if(e){let D=await wi({provider:"anthropic",providerOptions:R.providerOptions,schema:aH});D!=null?D.signature!=null?S.push({type:"thinking",thinking:R.text,signature:D.signature,cache_control:U}):D.redactedData!=null?S.push({type:"redacted_thinking",data:D.redactedData,cache_control:U}):t.push({type:"other",message:"unsupported reasoning metadata"}):t.push({type:"other",message:"unsupported reasoning metadata"})}else t.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(R.providerExecuted){if(R.toolName==="web_search"){S.push({type:"server_tool_use",id:R.toolCallId,name:"web_search",input:R.input,cache_control:U});break}if(R.toolName==="code_execution"){S.push({type:"server_tool_use",id:R.toolCallId,name:"code_execution",input:R.input,cache_control:U});break}t.push({type:"other",message:`provider executed tool call for tool ${R.toolName} is not supported`});break}S.push({type:"tool_use",id:R.toolCallId,name:R.toolName,input:R.input,cache_control:U});break}case"tool-result":{if(R.toolName==="web_search"){let D=R.output;if(D.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${D.type} for tool ${R.toolName} is not supported`});break}let J=UC.parse(D.value);S.push({type:"web_search_tool_result",tool_use_id:R.toolCallId,content:J.map(Le=>({url:Le.url,title:Le.title,page_age:Le.pageAge,encrypted_content:Le.encryptedContent,type:Le.type})),cache_control:U});break}if(R.toolName==="code_execution"){let D=R.output;if(D.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${D.type} for tool ${R.toolName} is not supported`});break}let J=FC.parse(D.value);S.push({type:"code_execution_tool_result",tool_use_id:R.toolCallId,content:{type:J.type,stdout:J.stdout,stderr:J.stderr,return_code:J.return_code},cache_control:U});break}t.push({type:"other",message:`provider executed tool result for tool ${R.toolName} is not supported`});break}}}}d.push({role:"assistant",content:S});break}default:{let S=E;throw new Error(`content type: ${S}`)}}}return{prompt:{system:u,messages:d},betas:c}}function tH(r){let e=[],t;for(let n of r){let{role:o}=n;switch(o){case"system":{t?.type!=="system"&&(t={type:"system",messages:[]},e.push(t)),t.messages.push(n);break}case"assistant":{t?.type!=="assistant"&&(t={type:"assistant",messages:[]},e.push(t)),t.messages.push(n);break}case"user":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}case"tool":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}default:{let i=o;throw new Error(`Unsupported role: ${i}`)}}}return e}function kC({finishReason:r,isJsonResponseFromTool:e}){switch(r){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return e?"stop":"tool-calls";case"max_tokens":return"length";default:return"unknown"}}var ss={webSearchResult:T.object({type:T.literal("web_search_result_location"),cited_text:T.string(),url:T.string(),title:T.string(),encrypted_index:T.string()}),pageLocation:T.object({type:T.literal("page_location"),cited_text:T.string(),document_index:T.number(),document_title:T.string().nullable(),start_page_number:T.number(),end_page_number:T.number()}),charLocation:T.object({type:T.literal("char_location"),cited_text:T.string(),document_index:T.number(),document_title:T.string().nullable(),start_char_index:T.number(),end_char_index:T.number()})},BC=T.discriminatedUnion("type",[ss.webSearchResult,ss.pageLocation,ss.charLocation]),EOe=T.discriminatedUnion("type",[ss.pageLocation,ss.charLocation]);function DC(r,e,t,n){if(r.type==="page_location"||r.type==="char_location"){let o=rH(r,e,t);o&&n(o)}}function rH(r,e,t){var n;let o=e[r.document_index];if(!o)return null;let i=r.type==="page_location"?{citedText:r.cited_text,startPageNumber:r.start_page_number,endPageNumber:r.end_page_number}:{citedText:r.cited_text,startCharIndex:r.start_char_index,endCharIndex:r.end_char_index};return{type:"source",sourceType:"document",id:t(),mediaType:o.mediaType,title:(n=r.document_title)!=null?n:o.title,filename:o.filename,providerMetadata:{anthropic:i}}}var nH=class{constructor(r,e){this.specificationVersion="v2";var t;this.modelId=r,this.config=e,this.generateId=(t=e.generateId)!=null?t:ou}supportsUrl(r){return r.protocol==="https:"}get provider(){return this.config.provider}get supportedUrls(){var r,e,t;return(t=(e=(r=this.config).supportedUrls)==null?void 0:e.call(r))!=null?t:{}}async getArgs({prompt:r,maxOutputTokens:e=4096,temperature:t,topP:n,topK:o,frequencyPenalty:i,presencePenalty:a,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:p}){var h,m,g;let f=[];i!=null&&f.push({type:"unsupported-setting",setting:"frequencyPenalty"}),a!=null&&f.push({type:"unsupported-setting",setting:"presencePenalty"}),l!=null&&f.push({type:"unsupported-setting",setting:"seed"}),c?.type==="json"&&(c.schema==null?f.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."}):u!=null&&f.push({type:"unsupported-setting",setting:"tools",details:"JSON response format does not support tools. The provided tools are ignored."}));let E=c?.type==="json"&&c.schema!=null?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:c.schema}:void 0,S=await wi({provider:"anthropic",providerOptions:p,schema:$z}),{prompt:w,betas:v}=await eH({prompt:r,sendReasoning:(h=S?.sendReasoning)!=null?h:!0,warnings:f}),A=((m=S?.thinking)==null?void 0:m.type)==="enabled",I=(g=S?.thinking)==null?void 0:g.budgetTokens,C={model:this.modelId,max_tokens:e,temperature:t,top_k:o,top_p:n,stop_sequences:s,...A&&{thinking:{type:"enabled",budget_tokens:I}},system:w.system,messages:w.messages};if(A){if(I==null)throw new jr({functionality:"thinking requires a budget"});C.temperature!=null&&(C.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),o!=null&&(C.top_k=void 0,f.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),n!=null&&(C.top_p=void 0,f.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),C.max_tokens=e+I}let{tools:R,toolChoice:B,toolWarnings:U,betas:D}=Xz(E!=null?{tools:[E],toolChoice:{type:"tool",toolName:E.name},disableParallelToolUse:S?.disableParallelToolUse}:{tools:u??[],toolChoice:d,disableParallelToolUse:S?.disableParallelToolUse});return{args:{...C,tools:R,tool_choice:B},warnings:[...f,...U],betas:new Set([...v,...D]),usesJsonResponseTool:E!=null}}async getHeaders({betas:r,headers:e}){return AC(await xC(this.config.headers),r.size>0?{"anthropic-beta":Array.from(r).join(",")}:{},e)}buildRequestUrl(r){var e,t,n;return(n=(t=(e=this.config).buildRequestUrl)==null?void 0:t.call(e,this.config.baseURL,r))!=null?n:`${this.config.baseURL}/messages`}transformRequestBody(r){var e,t,n;return(n=(t=(e=this.config).transformRequestBody)==null?void 0:t.call(e,r))!=null?n:r}extractCitationDocuments(r){let e=t=>{var n,o;if(t.type!=="file"||t.mediaType!=="application/pdf"&&t.mediaType!=="text/plain")return!1;let i=(n=t.providerOptions)==null?void 0:n.anthropic,a=i?.citations;return(o=a?.enabled)!=null?o:!1};return r.filter(t=>t.role==="user").flatMap(t=>t.content).filter(e).map(t=>{var n;let o=t;return{title:(n=o.filename)!=null?n:"Untitled Document",filename:o.filename,mediaType:o.mediaType}})}async doGenerate(r){var e,t,n,o,i;let{args:a,warnings:s,betas:c,usesJsonResponseTool:l}=await this.getArgs(r),u=this.extractCitationDocuments(r.prompt),{responseHeaders:d,value:p,rawValue:h}=await Ah({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:c,headers:r.headers}),body:this.transformRequestBody(a),failedResponseHandler:LC,successfulResponseHandler:PC(oH),abortSignal:r.abortSignal,fetch:this.config.fetch}),m=[];for(let g of p.content)switch(g.type){case"text":{if(!l&&(m.push({type:"text",text:g.text}),g.citations))for(let f of g.citations)DC(f,u,this.generateId,E=>m.push(E));break}case"thinking":{m.push({type:"reasoning",text:g.thinking,providerMetadata:{anthropic:{signature:g.signature}}});break}case"redacted_thinking":{m.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:g.data}}});break}case"tool_use":{m.push(l?{type:"text",text:JSON.stringify(g.input)}:{type:"tool-call",toolCallId:g.id,toolName:g.name,input:JSON.stringify(g.input)});break}case"server_tool_use":{(g.name==="web_search"||g.name==="code_execution")&&m.push({type:"tool-call",toolCallId:g.id,toolName:g.name,input:JSON.stringify(g.input),providerExecuted:!0});break}case"web_search_tool_result":{if(Array.isArray(g.content)){m.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"web_search",result:g.content.map(f=>{var E;return{url:f.url,title:f.title,pageAge:(E=f.page_age)!=null?E:null,encryptedContent:f.encrypted_content,type:f.type}}),providerExecuted:!0});for(let f of g.content)m.push({type:"source",sourceType:"url",id:this.generateId(),url:f.url,title:f.title,providerMetadata:{anthropic:{pageAge:(e=f.page_age)!=null?e:null}}})}else m.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:g.content.error_code},providerExecuted:!0});break}case"code_execution_tool_result":{g.content.type==="code_execution_result"?m.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"code_execution",result:{type:g.content.type,stdout:g.content.stdout,stderr:g.content.stderr,return_code:g.content.return_code},providerExecuted:!0}):g.content.type==="code_execution_tool_result_error"&&m.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:g.content.error_code},providerExecuted:!0});break}}return{content:m,finishReason:kC({finishReason:p.stop_reason,isJsonResponseFromTool:l}),usage:{inputTokens:p.usage.input_tokens,outputTokens:p.usage.output_tokens,totalTokens:p.usage.input_tokens+p.usage.output_tokens,cachedInputTokens:(t=p.usage.cache_read_input_tokens)!=null?t:void 0},request:{body:a},response:{id:(n=p.id)!=null?n:void 0,modelId:(o=p.model)!=null?o:void 0,headers:d,body:h},warnings:s,providerMetadata:{anthropic:{usage:p.usage,cacheCreationInputTokens:(i=p.usage.cache_creation_input_tokens)!=null?i:null}}}}async doStream(r){let{args:e,warnings:t,betas:n,usesJsonResponseTool:o}=await this.getArgs(r),i=this.extractCitationDocuments(r.prompt),a={...e,stream:!0},{responseHeaders:s,value:c}=await Ah({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:n,headers:r.headers}),body:this.transformRequestBody(a),failedResponseHandler:LC,successfulResponseHandler:MC(iH),abortSignal:r.abortSignal,fetch:this.config.fetch}),l="unknown",u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},p,h,m=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(g){g.enqueue({type:"stream-start",warnings:t})},transform(g,f){var E,S,w,v,A,I,C;if(r.includeRawChunks&&f.enqueue({type:"raw",rawValue:g.rawValue}),!g.success){f.enqueue({type:"error",error:g.error});return}let R=g.value;switch(R.type){case"ping":return;case"content_block_start":{let B=R.content_block.type;switch(h=B,B){case"text":{d[R.index]={type:"text"},f.enqueue({type:"text-start",id:String(R.index)});return}case"thinking":{d[R.index]={type:"reasoning"},f.enqueue({type:"reasoning-start",id:String(R.index)});return}case"redacted_thinking":{d[R.index]={type:"reasoning"},f.enqueue({type:"reasoning-start",id:String(R.index),providerMetadata:{anthropic:{redactedData:R.content_block.data}}});return}case"tool_use":{d[R.index]=o?{type:"text"}:{type:"tool-call",toolCallId:R.content_block.id,toolName:R.content_block.name,input:""},f.enqueue(o?{type:"text-start",id:String(R.index)}:{type:"tool-input-start",id:R.content_block.id,toolName:R.content_block.name});return}case"server_tool_use":{(R.content_block.name==="web_search"||R.content_block.name==="code_execution")&&(d[R.index]={type:"tool-call",toolCallId:R.content_block.id,toolName:R.content_block.name,input:"",providerExecuted:!0},f.enqueue({type:"tool-input-start",id:R.content_block.id,toolName:R.content_block.name,providerExecuted:!0}));return}case"web_search_tool_result":{let U=R.content_block;if(Array.isArray(U.content)){f.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:"web_search",result:U.content.map(D=>{var J;return{url:D.url,title:D.title,pageAge:(J=D.page_age)!=null?J:null,encryptedContent:D.encrypted_content,type:D.type}}),providerExecuted:!0});for(let D of U.content)f.enqueue({type:"source",sourceType:"url",id:m(),url:D.url,title:D.title,providerMetadata:{anthropic:{pageAge:(E=D.page_age)!=null?E:null}}})}else f.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:U.content.error_code},providerExecuted:!0});return}case"code_execution_tool_result":{let U=R.content_block;U.content.type==="code_execution_result"?f.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:"code_execution",result:{type:U.content.type,stdout:U.content.stdout,stderr:U.content.stderr,return_code:U.content.return_code},providerExecuted:!0}):U.content.type==="code_execution_tool_result_error"&&f.enqueue({type:"tool-result",toolCallId:U.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:U.content.error_code},providerExecuted:!0});return}default:{let U=B;throw new Error(`Unsupported content block type: ${U}`)}}}case"content_block_stop":{if(d[R.index]!=null){let B=d[R.index];switch(B.type){case"text":{f.enqueue({type:"text-end",id:String(R.index)});break}case"reasoning":{f.enqueue({type:"reasoning-end",id:String(R.index)});break}case"tool-call":o||(f.enqueue({type:"tool-input-end",id:B.toolCallId}),f.enqueue(B));break}delete d[R.index]}h=void 0;return}case"content_block_delta":{let B=R.delta.type;switch(B){case"text_delta":{if(o)return;f.enqueue({type:"text-delta",id:String(R.index),delta:R.delta.text});return}case"thinking_delta":{f.enqueue({type:"reasoning-delta",id:String(R.index),delta:R.delta.thinking});return}case"signature_delta":{h==="thinking"&&f.enqueue({type:"reasoning-delta",id:String(R.index),delta:"",providerMetadata:{anthropic:{signature:R.delta.signature}}});return}case"input_json_delta":{let U=d[R.index],D=R.delta.partial_json;if(o){if(U?.type!=="text")return;f.enqueue({type:"text-delta",id:String(R.index),delta:D})}else{if(U?.type!=="tool-call")return;f.enqueue({type:"tool-input-delta",id:U.toolCallId,delta:D}),U.input+=D}return}case"citations_delta":{let U=R.delta.citation;DC(U,i,m,D=>f.enqueue(D));return}default:{let U=B;throw new Error(`Unsupported delta type: ${U}`)}}}case"message_start":{u.inputTokens=R.message.usage.input_tokens,u.cachedInputTokens=(S=R.message.usage.cache_read_input_tokens)!=null?S:void 0,p={anthropic:{usage:R.message.usage,cacheCreationInputTokens:(w=R.message.usage.cache_creation_input_tokens)!=null?w:null}},f.enqueue({type:"response-metadata",id:(v=R.message.id)!=null?v:void 0,modelId:(A=R.message.model)!=null?A:void 0});return}case"message_delta":{u.outputTokens=R.usage.output_tokens,u.totalTokens=((I=u.inputTokens)!=null?I:0)+((C=R.usage.output_tokens)!=null?C:0),l=kC({finishReason:R.delta.stop_reason,isJsonResponseFromTool:o});return}case"message_stop":{f.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:p});return}case"error":{f.enqueue({type:"error",error:R.error});return}default:{let B=R;throw new Error(`Unsupported chunk type: ${B}`)}}}})),request:{body:a},response:{headers:s}}}},oH=T.object({type:T.literal("message"),id:T.string().nullish(),model:T.string().nullish(),content:T.array(T.discriminatedUnion("type",[T.object({type:T.literal("text"),text:T.string(),citations:T.array(BC).optional()}),T.object({type:T.literal("thinking"),thinking:T.string(),signature:T.string()}),T.object({type:T.literal("redacted_thinking"),data:T.string()}),T.object({type:T.literal("tool_use"),id:T.string(),name:T.string(),input:T.unknown()}),T.object({type:T.literal("server_tool_use"),id:T.string(),name:T.string(),input:T.record(T.string(),T.unknown()).nullish()}),T.object({type:T.literal("web_search_tool_result"),tool_use_id:T.string(),content:T.union([T.array(T.object({type:T.literal("web_search_result"),url:T.string(),title:T.string(),encrypted_content:T.string(),page_age:T.string().nullish()})),T.object({type:T.literal("web_search_tool_result_error"),error_code:T.string()})])}),T.object({type:T.literal("code_execution_tool_result"),tool_use_id:T.string(),content:T.union([T.object({type:T.literal("code_execution_result"),stdout:T.string(),stderr:T.string(),return_code:T.number()}),T.object({type:T.literal("code_execution_tool_result_error"),error_code:T.string()})])})])),stop_reason:T.string().nullish(),usage:T.looseObject({input_tokens:T.number(),output_tokens:T.number(),cache_creation_input_tokens:T.number().nullish(),cache_read_input_tokens:T.number().nullish()})}),iH=T.discriminatedUnion("type",[T.object({type:T.literal("message_start"),message:T.object({id:T.string().nullish(),model:T.string().nullish(),usage:T.looseObject({input_tokens:T.number(),output_tokens:T.number(),cache_creation_input_tokens:T.number().nullish(),cache_read_input_tokens:T.number().nullish()})})}),T.object({type:T.literal("content_block_start"),index:T.number(),content_block:T.discriminatedUnion("type",[T.object({type:T.literal("text"),text:T.string()}),T.object({type:T.literal("thinking"),thinking:T.string()}),T.object({type:T.literal("tool_use"),id:T.string(),name:T.string()}),T.object({type:T.literal("redacted_thinking"),data:T.string()}),T.object({type:T.literal("server_tool_use"),id:T.string(),name:T.string(),input:T.record(T.string(),T.unknown()).nullish()}),T.object({type:T.literal("web_search_tool_result"),tool_use_id:T.string(),content:T.union([T.array(T.object({type:T.literal("web_search_result"),url:T.string(),title:T.string(),encrypted_content:T.string(),page_age:T.string().nullish()})),T.object({type:T.literal("web_search_tool_result_error"),error_code:T.string()})])}),T.object({type:T.literal("code_execution_tool_result"),tool_use_id:T.string(),content:T.union([T.object({type:T.literal("code_execution_result"),stdout:T.string(),stderr:T.string(),return_code:T.number()}),T.object({type:T.literal("code_execution_tool_result_error"),error_code:T.string()})])})])}),T.object({type:T.literal("content_block_delta"),index:T.number(),delta:T.discriminatedUnion("type",[T.object({type:T.literal("input_json_delta"),partial_json:T.string()}),T.object({type:T.literal("text_delta"),text:T.string()}),T.object({type:T.literal("thinking_delta"),thinking:T.string()}),T.object({type:T.literal("signature_delta"),signature:T.string()}),T.object({type:T.literal("citations_delta"),citation:BC})])}),T.object({type:T.literal("content_block_stop"),index:T.number()}),T.object({type:T.literal("error"),error:T.object({type:T.string(),message:T.string()})}),T.object({type:T.literal("message_delta"),delta:T.object({stop_reason:T.string().nullish()}),usage:T.object({output_tokens:T.number()})}),T.object({type:T.literal("message_stop")}),T.object({type:T.literal("ping")})]),aH=T.object({signature:T.string().optional(),redactedData:T.string().optional()}),sH=Bt({id:"anthropic.bash_20241022",name:"bash",inputSchema:Rh.object({command:Rh.string(),restart:Rh.boolean().optional()})}),lH=Bt({id:"anthropic.bash_20250124",name:"bash",inputSchema:Ch.object({command:Ch.string(),restart:Ch.boolean().optional()})}),cH=Bt({id:"anthropic.computer_20241022",name:"computer",inputSchema:as.object({action:as.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:as.array(as.number().int()).optional(),text:as.string().optional()})}),uH=Bt({id:"anthropic.computer_20250124",name:"computer",inputSchema:dr.object({action:dr.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:dr.tuple([dr.number().int(),dr.number().int()]).optional(),duration:dr.number().optional(),scroll_amount:dr.number().optional(),scroll_direction:dr.enum(["up","down","left","right"]).optional(),start_coordinate:dr.tuple([dr.number().int(),dr.number().int()]).optional(),text:dr.string().optional()})}),dH=Bt({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:en.object({command:en.enum(["view","create","str_replace","insert","undo_edit"]),path:en.string(),file_text:en.string().optional(),insert_line:en.number().int().optional(),new_str:en.string().optional(),old_str:en.string().optional(),view_range:en.array(en.number().int()).optional()})}),pH=Bt({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:tn.object({command:tn.enum(["view","create","str_replace","insert","undo_edit"]),path:tn.string(),file_text:tn.string().optional(),insert_line:tn.number().int().optional(),new_str:tn.string().optional(),old_str:tn.string().optional(),view_range:tn.array(tn.number().int()).optional()})}),mH=Bt({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:rn.object({command:rn.enum(["view","create","str_replace","insert"]),path:rn.string(),file_text:rn.string().optional(),insert_line:rn.number().int().optional(),new_str:rn.string().optional(),old_str:rn.string().optional(),view_range:rn.array(rn.number().int()).optional()})}),hH={bash_20241022:sH,bash_20250124:lH,textEditor_20241022:dH,textEditor_20250124:pH,textEditor_20250429:mH,computer_20241022:cH,computer_20250124:uH,webSearch_20250305:Kz,codeExecution_20250522:Zz};function xh(r={}){var e;let t=(e=OC(r.baseURL))!=null?e:"https://api.anthropic.com/v1",n=()=>({"anthropic-version":"2023-06-01","x-api-key":wC({apiKey:r.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...r.headers}),o=a=>{var s;return new nH(a,{provider:"anthropic.messages",baseURL:t,headers:n,fetch:r.fetch,generateId:(s=r.generateId)!=null?s:ou,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},i=function(a){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return o(a)};return i.languageModel=o,i.chat=o,i.messages=o,i.textEmbeddingModel=a=>{throw new yh({modelId:a,modelType:"textEmbeddingModel"})},i.imageModel=a=>{throw new yh({modelId:a,modelType:"imageModel"})},i.tools=hH,i}var kOe=xh();var zC=({baseUrl:r,apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o})=>i=>{let a={Authorization:`Bearer ${e}`,[dl]:wo??"",...t&&{[ny]:t},...n||{}};return o&&(a[ry]=JSON.stringify(o)),xh({baseURL:`${r}/v1/llm/anthropic/${i}`,headers:a,apiKey:e})(i)};var Co=class extends Gr{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(`/${z}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return qf.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${z}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:wo,...e},signal:t.abortSignal});return Wf.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${z}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return gH.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(`/${z}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return sy.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(`/${z}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Nd.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${z}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return ay.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${z}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return iy.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(`/${z}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return Nd.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${z}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return oy.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${z}/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(`/${z}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Zu.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${z}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return ly.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${z}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return Xu.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${z}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return Rf.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${z}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Uu.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${z}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return oS.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${z}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Tf.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${z}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return wf.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${z}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Af.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${z}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return sg.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return zC({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as _h}from"zod";var wr=class extends Gr{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(`/${z}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return Ty.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${z}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Sy.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${z}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return uy.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${z}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${z}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return py.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${z}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${z}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return my.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${z}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return cy.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${z}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Ey.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${z}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return vy.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${z}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return Dy.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${z}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${z}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${z}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${z}/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(`/${z}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Ay.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${z}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Gf.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${z}/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(`/${z}/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(`/${z}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return wy.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${z}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${z}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Ry.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${z}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Cy.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${z}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return xy.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${z}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return By.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${z}/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(`/${z}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return fa.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${z}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return fa.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${z}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Fd.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(`/${z}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return fa.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${z}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return fa.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${z}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Fd.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${z}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return _h.record(_h.string(),_h.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${z}/quarantine`,{method:"GET"});return _y.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${z}/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(`/${z}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${z}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return My.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${z}/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(`/${z}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return Py.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${z}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${z}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Iy.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${z}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function Mh(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(x.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),x.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return x.debug("Got auth info from API"),n}var au=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Ri=class extends Gr{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${z}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return lg.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var Ci=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 fH,en as SH}from"@faker-js/faker";var xi="v1",_i=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new fH({locale:SH}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${xi}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Ar?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${xi}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Ar?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${xi}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ar?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${xi}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Ar?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${xi}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ar?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${xi}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ar?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function HC(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var su=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await HC(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 Mi=class extends Gr{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${z}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return aS.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${z}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return cS.parse(o)}};function lu({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new ml:new Ph(r,e,t,n)}var Ph=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=kd(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateMobileStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save mobile step cache entries")}}async resolveEntries(e){let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&jd({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await eo({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import cu from"path";function yH(r){let e=new GC,t=cu.join(r,"metadata.json"),n=Sa.parse(JSON.parse(Ih.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of Ih.readdirSync(cu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new GC(cu.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(cu.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function uu(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!Ih.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new su(e);try{let{runGroupId:i,buffer:a}=yH(n),s=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${s}`;t.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`);return}catch(i){let a;i instanceof Error?a=i.message:typeof i=="string"?a=i:a="Unknown error",t.error(`Failed to upload test results: ${a}.`);return}}import bH from"adm-zip";import gt from"fs";import Vt from"path";var ls=class r{constructor(e){this.filePath=e;gt.rmSync(this.filePath,{recursive:!0,force:!0}),gt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Vt.join(this.filePath,e))}mkdir(e){gt.mkdirSync(Vt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Vt.join(this.filePath,e);if(gt.existsSync(t))return gt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Vt.join(this.filePath,t);try{gt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=Vt.join(this.filePath,e);return gt.createWriteStream(t)}createRunArchive(e){return new Oh(Vt.join(this.filePath,"runs"),e)}},Oh=class{constructor(e,t){this.filePath=e;this.tempPath=Vt.join(e,`.${t}`),this.finalPath=Vt.join(e,`${t}.zip`),gt.rmSync(this.tempPath,{recursive:!0,force:!0}),gt.rmSync(this.finalPath,{recursive:!0,force:!0}),gt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Vt.join(this.tempPath,e);if(gt.existsSync(t))return gt.readFileSync(t)}mkdir(e){gt.mkdirSync(Vt.join(this.tempPath,e),{recursive:!0})}cd(e){return new ls(Vt.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=Vt.join(this.tempPath,t);gt.writeFileSync(o,n)}createFileStream(e){let t=Vt.join(this.tempPath,e);return gt.createWriteStream(t)}close(){let e=new bH;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();gt.writeFileSync(this.finalPath,t),gt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import yu from"fs";import tx from"body-parser";import UH from"cors";import FH from"dedent";import{Router as AH}from"express";import Pt from"fs";import{globSync as wH}from"glob";import dt from"path";import Nh from"fs";import EH from"path";var TH=new _l(30,60*1e3),Uh="https://api.momentic.ai",kh,VC=r=>{Uh=r},Fh=()=>Uh,Bh=()=>kh;var Pi,Dh,jC,$C=async r=>{if(kh&&Pi&&jC)return Pi;let e=new wr({baseUrl:Uh,apiKey:r,logger:x});kh=e;try{let t=await e.getAuthInfo();return Pi=t.orgId,Dh=t.userId,jC=r,Pi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},cs=()=>{if(!Pi)throw new Error("Your organization ID is invalid.");return Pi},du=()=>{if(!Dh)throw new Error("Your user ID is invalid.");return Dh};var zh,Lh,WC=(r,e)=>{zh=r,Lh?.abort(),Lh=new AbortController;let t=Lh.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=EH.resolve(r.rootDir,o.envFile);try{if(Nh.lstatSync(i).isSymbolicLink())return;Nh.existsSync(i)&&n.push(i)}catch(a){x.warn({err:a},`Failed to check if env file ${i} exists`)}});try{vH({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){x.error({err:o},"Failed to start config file watchers")}},st=()=>zh;function vH({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{Nh.watch(o,{signal:t,persistent:!1,recursive:!1},async(i,a)=>{a&&(TH.increment("setLocalProject")&&x.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.`),zh=await Promise.resolve(e(n.configFilePath)))})})}function lt(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var ds=AH();function us(r){let e=st(),t=dt.dirname(e.configFilePath);return dt.join(t,...r)}function RH(r){let e=st(),t=dt.dirname(e.configFilePath),n=dt.relative(t,r);return n?n.split(dt.sep):[]}function CH(r,e){let t=Pt.statSync(r),n=RH(r);return _d.parse({name:e,absolutePath:r,relativePath:n.join(dt.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}ds.post("/",lt(async(r,e,t)=>{let n;try{n=jS.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=us(n);if(!Pt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(dt.sep)}`});return}if(!Pt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(dt.sep)}`});return}let a=st(),s=Array.from(a.config.exclude??[]).concat(il),l=wH("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=dt.join(o,d);return CH(p,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));ds.put("/",lt(async(r,e,t)=>{let n;try{n=VS.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=us(n);if(Pt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(dt.sep)}`,pathSegments:n});return}Pt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(dt.sep)}`,pathSegments:n};e.status(201).json(i)}));ds.patch("/",lt(async(r,e,t)=>{let n,o;try{let l=$S.parse(r.body);n=l.pathSegments,o=l.newPathSegments}catch(l){e.status(400).json({error:`Failed to parse folder update body: ${l}`});return}let i=us(n),a=us(o);if(!Pt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(dt.sep)}`});return}if(Pt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(dt.sep)}`});return}let s=dt.dirname(a);Pt.existsSync(s)||Pt.mkdirSync(s,{recursive:!0}),Pt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(dt.sep)} to ${o.join(dt.sep)}`,pathSegments:o};e.status(200).json(c)}));ds.delete("/",lt(async(r,e,t)=>{let n,o=!0;try{let c=WS.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=us(n);if(!Pt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(dt.sep)}`,pathSegments:n});return}if(!Pt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(dt.sep)}`});return}if(o)Pt.rmSync(i,{recursive:!0,force:!0});else{if(Pt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Pt.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var Hh=ds;import BH from"events";import rx,{Router as zH}from"express";import HH from"http";import GH from"path";var pu=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 qC=new pu;import{Router as MH}from"express";import{existsSync as PH}from"fs";import IH from"path";import{hostname as xH}from"os";var _H="0.0.28",It=Hc({app:"mobile-desktop-server",hostname:xH(),disableConsoleLogs:!0}).child({cliVersion:_H});(async()=>{try{let r=await dh(It);r.gitBranchName&&It.addBinding("branch",r.gitBranchName)}catch{}})();var Gh=MH();Gh.get("/",lt(async(r,e)=>{let t=Bh();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));Gh.post("/upload-url",lt(async(r,e)=>{let t;try{t=JS.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Bh();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=IH.resolve(t.filePath);if(!PH(o)){e.status(400).json({error:`File not found: ${o}`});return}await ys({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:It}),e.sendStatus(204)}));var KC=Gh;import{Router as OH}from"express";var YC=OH();YC.get("/",lt(async(r,e)=>{let t=st(),n=await vr(t),o=new Set;n?.tests&&Object.values(n.tests).forEach(c=>{c.labels?.forEach(l=>o.add(l))});let i=Array.from(o).sort(),a=Object.values(n.mobileTests),s={labels:i,modules:[],tests:a};e.status(200).json(s)}));var XC=YC;import{Router as LH}from"express";var JC=LH();JC.get("/",(r,e)=>{e.status(200).json({userId:du(),orgId:cs()})});var ZC=JC;import{Router as NH}from"express";var mu=NH();async function kH(r){return(await HR(r,It)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){x.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)}mu.get("/",lt(async(r,e)=>{let t=st(),n=await vr(t),o=await kH(n);e.status(200).json(o)}));mu.get("/:moduleId",lt(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await vr(st()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await mh(n,t,x);e.json(o)}catch(o){e.status(400).json({err:o})}}));mu.patch("/:moduleId/metadata",lt(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=ZS.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=st(),o=await vr(n);zR({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:x,project:n}),e.status(201).json({message:"ok"})}));var QC=mu;import{Router as DH}from"express";import jh from"path";var hu=DH();hu.patch("/:testPath",lt(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=XS.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=st(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await vr(o);await jR({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let s={message:"ok"};e.status(200).json(s)}));hu.post("/",lt((r,e)=>{let t;try{t=YS.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{Yu(n)}catch(m){e.status(400).json({error:m.message});return}let s=st(),c=jh.join(s.rootDir,...a),{fullPath:l,testId:u}=GR({name:n,description:o,steps:[],settings:i,folder:c}),d=jh.basename(l),p=jh.relative(s.rootDir,l),h={id:u,fileName:d,fullPath:l,relativeFilePath:p};e.status(201).json(h)}));hu.get("/:fileName",lt(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=st(),i=await vr(o),s=await Qc(n,It,i);e.status(200).json(s)}));var ex=hu;var gu=class extends Ci{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=st();return Kc(t,o,x)}};var nx="10mb";async function ox(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,alwaysSaveCache:s,noCache:c}=r;n&&VC(n),await $C(t);let l=cs(),u=du(),d=r.logger.child({orgId:l,userId:u});WC(i,v=>ts({configFilePath:v}));let p=rx();p.use(UH()),p.use(tx.json({limit:nx})),p.use(tx.urlencoded({extended:!1,limit:nx}));let h=zH();if(h.use("/folders",Hh),h.use("/entities",XC),h.use("/identify",ZC),h.use("/mobile-tests",ex),h.use("/mobile-modules",QC),h.use("/assets",KC),p.use("/api",h),p.use((v,A,I)=>{x.debug({url:v.url,path:v.path,query:v.query,method:v.method,body:v.body,headers:v.rawHeaders,client:v.ip},"Incoming request on mobile-desktop-server"),A.on("close",()=>{A.statusCode>=400&&(x.error({url:v.url,method:v.method,statusCode:A.statusCode},"Request completed in error on mobile-desktop-server"),It.error({url:v.url,method:v.method,statusCode:A.statusCode},"Request completed in error on mobile-desktop-server"))}),I()}),p.use((v,A,I,C)=>{if(v instanceof Error&&v.message.includes("BadRequestError: request aborted")){I.status(400).send("Client disconnected");return}x.error({stack:v.stack,msg:v.message,err:v,url:A.url,method:A.method},"Unhandled exception leading to 500 on mobile-desktop-server"),It.error({stack:v.stack,msg:v.message,err:v,url:A.url,method:A.method},"Unhandled exception leading to 500 on mobile-desktop-server"),I.status(500).send(`Internal Server Error: ${v.message}`)}),o){let v=rx.static(o,{setHeaders:A=>{A.setHeader("Cache-Control","no-cache")},redirect:!1});p.use(v),p.use("*",(A,I)=>{I.sendFile(GH.join(o,"index.html"))})}let m=HH.createServer(p),g=`http://localhost:${e}`;await new Promise(v=>{try{m.listen(e,()=>{d.info(`Mobile desktop server is running at ${g}`),v()})}catch(A){A.message.includes("EADDRINUSE")?jH(e):x.error(`An unexpected error occurred while starting the server: ${A.message}`),process.exit(1)}});let E={type:"API_KEY",baseUrl:Fh(),apiKey:t,logger:d},S=new wr(E),{dispose:w}=bR({baseServer:m,logger:d,authorization:E,globalStateManager:qC,getOrgId:()=>cs(),androidDriverFactory:async({socket:v,logger:A,creationOpts:I})=>{let C=Math.floor(Math.random()*1e4)+4e4,R=await qc(C,"appium");return Ss({logger:A,driverLogLevel:a,apiClient:S,creationOpts:I,socket:v,appiumPort:R,onStatusUpdate:B=>{v.emit("connectionStatusUpdate",{message:B})}})},mobileGeneratorFactory:async v=>new Mi({baseUrl:Fh(),apiKey:t,logger:d}),browserGeneratorFactory:async v=>new Co({},E),browserEnricherFactory:async v=>new Ri(E,new Co({},E)),storageFactory:async v=>new gu(S,v),cacheStorageFactory:async v=>{let A=st(),I=await Xc(d,S,A);return lu({orgId:v,client:S,gitMetadata:I,noCache:c,alwaysSaveCache:s})},localToolsFactory:async()=>new _i({httpClient:S,fakerSeed:void 0}),keepSessionAlive:v=>S.extendAndroidEmulatorTtl(v),settingsFactory:async()=>({emulator:st().config.emulator})});process.once("SIGUSR2",async()=>{return;try{await w(),await Ht.flush()}catch(v){x.error({err:v},"Error during session dispose on SIGUSR2")}try{m.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{x.info("SIGTERM in Momentic mobile app received");try{await w(),await Ht.flush()}finally{m.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{x.info("SIGINT in Momentic mobile app received");try{await w(),await Ht.flush()}finally{m.close(()=>process.exit(0))}})}BH.setMaxListeners(25);process.on("warning",r=>{It.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{It.error({err:r},"Uncaught exception on mobile-desktop-server"),x.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{It.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),x.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function jH(r){x.error(FH`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
3988
4041
|
Using Bash on MacOS or Linux:
|
|
3989
4042
|
lsof -t -i :58888 | xargs kill -9
|
|
3990
4043
|
|
|
3991
4044
|
Using Command Prompt on Windows:
|
|
3992
4045
|
for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
|
|
3993
|
-
`)}import
|
|
4046
|
+
`)}import aG from"open";import bu from"path";import{fileURLToPath as sG}from"url";import{InvalidArgumentError as Vh,Option as Ot}from"@commander-js/extra-typings";import{z as VH}from"zod";var ix=58890;function $H(r){let e=parseInt(r,10);if(isNaN(e))throw new Vh("Not a number.");return e}var ps=new Ot("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new Vh("API key is required.");return r}).makeOptionMandatory(),$h=new Ot("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),ms=new Ot("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return VH.string().url().parse(r),r}catch{throw new Vh("Not a valid URL.")}}),Wh=new Ot("-y, --yes","Skip all confirmation prompts.").env("CI"),qh=new Ot("--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"),Kh=new Ot("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes."),Yh=new Ot("--tag <tag>","Tag identifier for the asset."),ax=new Ot("--channel <channel>","Channel name for the asset."),sx=new Ot("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),lx=new Ot("--env <env>","Environment to run all tests in (overrides test-level configuration)."),cx=new Ot("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser($H),Xh=new Ot("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),ux=new Ot("--upload-results","Upload test results to Momentic Cloud.").default(!1),Jh=new Ot("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),dx=new Ot("--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 eG}from"crypto";import{existsSync as tG}from"fs";import Zh from"fs";import hs from"path";import{cwd as qH}from"process";async function px({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,logger:a,quarantinedTestReasons:s}){let c=new Set;if(r&&r.length>0){let u=r.some(p=>Zh.existsSync(p)),d=qH();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:
|
|
3994
4047
|
- ${r.join(`
|
|
3995
4048
|
- `)}
|
|
3996
|
-
`),r.forEach(p=>{if(!
|
|
4049
|
+
`),r.forEach(p=>{if(!Zh.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let h,m;try{h=Zh.statSync(p),m=h.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let g=hs.resolve(p);Object.values(e.mobileTests).filter(f=>m?f.fullFilePath.startsWith(g):f.fullFilePath===g).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(h=>p.relativePath.includes(h))&&c.add(p.fullFilePath)}))}else{!n&&!await $c("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=hs.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=hs.relative(t.rootDir,u),p=await Qc(u,a,e),h=hs.basename(u,hs.extname(u));return{id:p.id,name:h,description:p.description,schemaVersion:p.schemaVersion,settings:p.settings,steps:p.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!s[p.id],quarantinedReason:s[p.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{cloneDeep as KH}from"lodash-es";async function mx(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:s}=n,{testDefinition:c,runSigIntHandlers:l}=e,u=new Date,d=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:s,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:KH(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),p=a.child(d.loggerBindings||{}),h=1+(c.settings?.retries??1);try{for(let m=0;m<h;m++){let g=new Date,f=await YH({runTracer:d,testDefinition:c,metadata:n,constants:{attemptNumber:m,totalAttempts:h},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:g,finishedAt:E,attempts:m+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(m!==h-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:g,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{l?.pop()}}async function YH(r){let{runTracer:e,testDefinition:t,metadata:n,constants:o,fixtures:i,inputs:a,options:s}=r,{attemptNumber:c,totalAttempts:l}=o,{orgId:u,gitMetadata:d}=n,{apiClient:p,logger:h,usageTracker:m}=i,{logUpdate:g,channel:f,tag:E,project:S,envOverride:w}=a,{alwaysSaveCache:v,noCache:A,logLevel:I}=s;c!==0&&g("RETRY",`attempt ${c}/${l}`);let C={...a.project.config.emulator,...t.settings?.emulator},R=lu({orgId:u,client:p,gitMetadata:d,alwaysSaveCache:v,noCache:A}),B=new Ci(p,u),U=new Mi(p),D={type:"API_KEY",baseUrl:p.baseUrl,apiKey:p.apiKey,logger:h},J=new Co({},D),Le=new Ri(D,J),K=new _i({httpClient:p,fakerSeed:void 0}),G=Math.floor(Math.random()*1e4)+4e4,se=await qc(G,"appium"),ke=await Ss({apiClient:p,logger:h,driverLogLevel:I,creationOpts:{apkToInstall:f?{channel:f,tag:E}:void 0,region:C.region},onStatusUpdate:fs=>{h.debug({status:fs},"Limbar emulator status update")},appiumPort:se}),fe=await e.startAttempt({emulatorName:ke.emulatorName}),pt=h.child(fe.loggerBindings||{}),$t=await hl({driver:ke.driver,onLogs:fs=>{fe.appendLogs(fs)}}),we=w||t.settings?.defaultEnv,tt;we&&(tt=Kc(we,S,pt).variables);let Wt=new $o({variablesFromEnvironment:tt??{},envName:we,testName:t.name}),xo=await yi.init({driver:ke.driver,generator:U,logger:pt,orgId:u,adbPort:ke.adbTunnelPort,options:{emulator:C},fixtures:{storage:B,browserEnricher:Le,browserGenerator:J,localCodeEvalTools:K,testContext:Wt}}),Dn;try{Dn=await Gc({containerName:"mobile-test",fixtures:{controller:xo,logger:pt,cacheStorage:R,usageTracker:m},inputs:{steps:t.steps,orgId:u,testMetadata:t},tracer:fe})}finally{await $t(),await ke.cleanup()}return await fe.finish({logger:pt,results:Dn.results,status:Dn.status}),Dn}import{randomUUID as XH}from"crypto";import{debounce as JH}from"ts-debounce";var gs="0.0.28";var fu="assets";function ZH(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 QH(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var Qh=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new fo,In.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${fu}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${fu}/${t}.jpeg`,contents:n})}async finishInternal(e){this.finished||(this.finished=!0,this.interactionTracer.finish(),await Promise.all(this.children.map(t=>t.finish({status:QH(e.status),finishedAt:e.finishedAt}))))}async finish(e){return await this.finishInternal({status:e.result.status,finishedAt:new Date(e.result.endTime)}),{trace:this.interactionTracer.getRootSpan()}}async startSubSteps(){let e=new Ii(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Ii=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(`${fu}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new Qh(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:ZH(e.status),finishedAt:e.finishedAt}))))}},eg=class{constructor(e,t,n,o,i,a){this.keepalive=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.diskStorage.mkdir("assets"),this.logStream=this.diskStorage.createFileStream("assets/logs.logcat")}finished=!1;children=[];logStream;get loggerBindings(){return{runAttemptId:this.runAttemptId}}appendLogs(e){let t=e.join(`
|
|
3997
4050
|
`);this.logStream.write(t+`
|
|
3998
|
-
`)}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,status:n,results:o,beforeResults:i,afterResults:a}=e,s={...this.metadata,status:n,finishedAt:new Date,results:bc(o,t),beforeResults:i?bc(i,t):void 0,afterResults:a?bc(a,t):void 0};await Promise.all(this.children.map(c=>c.finish({status:s.status,finishedAt:s.finishedAt})));try{this.logStream.end()}catch{}this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)})}async startBeforeStepList(){let e=new Ei(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Ei(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Ei(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${tu}/${t}.jpeg`)}},Ig=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=Ez(),o={id:n,schemaVersion:Ln,runAttemptSchemaVersion:BS,startedAt:new Date,status:"RUNNING"};t.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=Tz(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new Pg(()=>void i(),this.testId,this.testName,n,o,t);return this.children.push(a),a}},ru=class r{constructor(e,t,n,o,i){this.orgId=e;this.runGroupId=t;this.metadata=n;this.client=o;this.diskStorage=i}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start({orgId:e,runGroupId:t,outputDir:n,client:o,gitMetadata:i,labels:a}){let s={...i,id:t,trigger:Kt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:rs,labels:a??[]},c=new Ya(n);return c.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)}),new r(e,t,s,o,c)}async finish(e){if(this.finished)return;this.finished=!0;let{status:t}=e,n={...this.metadata,status:t,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:n.status,finishedAt:n.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)})}async startRun(e){let t=this.diskStorage.createRunArchive(e.runId),n={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,labels:e.testLabels,trigger:"CLI",status:"RUNNING",environmentName:e.environmentName,cliVersion:rs,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 Ig(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function aC(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 sC(r){let{options:e,fixtures:t,inputs:n,metadata:o}=r,{project:i,apiClient:a,logger:s}=t,{orgId:c,runGroupId:l,gitMetadata:u}=o,{outputDir:d,parallel:p}=e;Rz(d)&&x.warn(`Output directory ${d} already exists, removing before test execution...`);let g=await aC(s,a,e.ignoreQuarantine),m=await gr(i),h=await oC({tests:n.tests,yes:e.yes,project:i,momenticFiles:m,logger:x,quarantinedTestReasons:g}),f=s.child({orgId:c,runGroupId:l,branch:u.gitBranchName}),E=await ru.start({logger:f,orgId:c,runGroupId:l,outputDir:d,client:a,gitMetadata:u,labels:[]}),S=[],R=new Date,A=new Set,v=async()=>Cz({runResults:S,startTime:R,ranTests:A,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),P=[],C=async()=>{x.warn("SIGINT received. Stopping tests and printing latest results..."),await E.finish({logger:f,status:"CANCELLED"}),await v(),await Promise.allSettled(P.map(k=>k())),process.exit(1)};process.once("SIGINT",C);let w={};for(let k=0;k<h.length;k++){let Y=Object.values(w);Y.length===p&&await Promise.race(Y.map(H=>H.promise));let Me=h[k],q=`test-${k}`;w[q]={done:!1,promise:(async({testDefinition:H})=>{A.add(q);let ie=H.relativeFilePath.includes("..")?H.fullFilePath:H.relativeFilePath;Fa({status:"START",testLogRef:ie,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length});let ae=setInterval(()=>Fa({status:"RUN",testLogRef:ie,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length}),5*60*1e3),Ie=wz(),de=f.child({testId:H.id,runId:Ie}),at=new cl({logger:de,reporter:new $c(a),runType:"mobile-test-run",runId:Ie,testMetadata:H,suiteMetadata:void 0});try{let Bt=await iC({metadata:{...o,runId:Ie},fixtures:{...t,tracer:E,logger:de,usageTracker:at},inputs:{...n,project:i,testDefinition:H,channel:n.channel??H.settings?.defaultChannel,tag:n.tag??H.settings?.defaultTag,logUpdate:(Ee,Ke)=>Fa({status:Ee,testLogRef:ie,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length,additionalText:Ke}),runSigIntHandlers:P},options:e});Fa({status:Bt.status,testLogRef:ie,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length}),S.push(Bt)}catch(Bt){let Ee=`Encountered unexpected fatal error when running test '${H.name}': ${Bt.message}`;x.error(Ee),de.error(Ee)}finally{clearInterval(ae),w[q].done=!0,delete w[q]}await at.flush(s)})({testDefinition:Me})}}await Promise.allSettled(Object.values(w).map(k=>k.promise));let D=S.some(k=>k.status==="FAILED"&&!k.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:D}),process.off("SIGINT",C),v()}async function Cz({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),s=gw({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let l=`${Mm}- ${c.filePath}`;return c.runId&&(l+=` ( link when uploaded: ${a}/runs/${c.runId} )`),l},entity:"mobile test"});return x.log(""),o?(x.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await Yc({client:n,consoleLogger:x,resultsPath:i})):x.success(`Test results have been saved to the folder ${i}. Upload them to Momentic Cloud by running 'npx momentic-mobile results upload ${i}'.`),s}async function Og(){qS(),Ew("Chromium")||(Da?(await Pc("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await Ic({rawBrowsers:["chromium"],force:!1,all:!1})):(x.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)))}sA({serviceName:"mobile-cli"});Ot.setApp("mobile-cli");var xn=new xz;xn.name("momentic-mobile").description("Momentic Mobile CLI").version(rs);var Oz=xn.command("assets").description("Manage mobile testing assets");Oz.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(Qa).addOption(es).addOption(Rg).addOption(QR).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=ou.resolve(r);nu.existsSync(a)||(x.error(`File not found: ${a}`),process.exit(1));let s=new fr({baseUrl:n,apiKey:t,logger:x});/\.apk$/i.test(a)||(x.error(`File is not an APK file: ${a}`),process.exit(1)),await is({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:s,logger:x})});xn.command("app").addOption(Qa).addOption(es).addOption(vg).addOption(Tg).addOption(xg).addOption(Ag).addOption(wg).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i}=r,a=Pm(r.logLevel);Ot.setApp("mobile-desktop-server");let s=new fr({baseUrl:t,apiKey:e,logger:Ot});await ig({client:s,skipPrompts:n}),x.debug("API key check complete");let c=Iz(import.meta.url),l=ou.dirname(c),u=ou.resolve(l,"..","static");await Og(),x.debug({appiumHome:oa},"Resolved resource paths");let d=await Ha({configFilePath:r.config}),p=JR;await XR({momenticServerUrl:t,serverPort:p,apiKey:e,staticDir:u,initialProject:d,driverLogLevel:a,logger:Ot,noCache:o,alwaysSaveCache:i});let g=`http://localhost:${p}`;x.info(`Local app started on: ${g}`),await Pz(g)});var lC=xn.command("results").description("Merge and upload test results.");lC.command("merge").description("Merge test results files.").addOption(Cg).addArgument(new Lg("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(x.error("Output directory is required."),process.exit(1)),nu.existsSync(r)||(x.warn("Results path does not exist, skipping merge."),process.exit(0)),nu.existsSync(t)&&x.warn(`Output directory ${t} already exists, removing before merging...`),Fw(Ot,t,r),Ti(),process.exit(0)});var Lz=new Lg("<results>","Path to the results archive.").argRequired();lC.command("upload").description("Upload test results to Momentic cloud.").addOption(Qa).addOption(es).addArgument(Lz).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=Ot,i=new fr({baseUrl:n,apiKey:t,logger:o});await Yc({consoleLogger:x,resultsPath:r,client:i}),Ti(),process.exit(0)});var Nz=xn.command("run").alias("test").description("Run tests on the local machine");Nz.addOption(Qa).addOption(es).addOption(Tg).addOption(vg).addOption(tC).addOption(xg).addOption(Ag).addOption(wg).addOption(Cg).addOption(rC).addOption(nC).addOption(Rg).addOption(ZR).addOption(eC).addArgument(new Lg("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional()).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i,outputDir:a}=e,s=Pm(e.logLevel);await Og(),x.debug({appiumHome:oa},"Resolved resource paths");let c=await Ha({configFilePath:e.config}),l=a??c.config.outputDir??_w,u=e.parallel??c.config.parallel??1;x.debug("Checking API key and dependencies");let d=new fr({baseUrl:n,apiKey:t,logger:x}),{orgId:p,userId:g}=await ig({client:d,skipPrompts:e.yes});x.debug("API key check and browser installation complete");let m=Mz(),h=Ot.child({runGroupId:m,orgId:p,userId:g}),f=await kc(Ot,d,c);h.debug(f,"Got local git metadata");try{let E=await sC({options:{...e,outputDir:l,parallel:u,logLevel:s,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}});Ti(),E.failed>0?process.exit(1):process.exit(0)}catch(E){x.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),x.error(E),Ot.error({err:E},"Failed to run tests locally"),Ti(),process.exit(1)}});xn.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new _z("--name <name>","Name of the project")).action(async r=>{x.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
|
|
3999
|
-
`),x.info("This wizard will help you bootstrap a new Momentic project."),
|
|
4051
|
+
`)}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,status:n,results:o,beforeResults:i,afterResults:a}=e,s={...this.metadata,status:n,finishedAt:new Date,results:kc(o,t),beforeResults:i?kc(i,t):void 0,afterResults:a?kc(a,t):void 0};await Promise.all(this.children.map(c=>c.finish({status:s.status,finishedAt:s.finishedAt})));try{this.logStream.end()}catch{}this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)})}async startBeforeStepList(){let e=new Ii(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Ii(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Ii(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${fu}/${t}.jpeg`)}},tg=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=XH(),o={id:n,schemaVersion:jn,runAttemptSchemaVersion:qy,startedAt:new Date,status:"RUNNING"};t.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=JH(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new eg(()=>void i(),this.testId,this.testName,n,o,t);return this.children.push(a),a}},Su=class r{constructor(e,t,n,o,i){this.orgId=e;this.runGroupId=t;this.metadata=n;this.client=o;this.diskStorage=i}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start({orgId:e,runGroupId:t,outputDir:n,client:o,gitMetadata:i,labels:a}){let s={...i,id:t,trigger:er.CLI,startedAt:new Date,status:"RUNNING",cliVersion:gs,labels:a??[]},c=new ls(n);return c.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)}),new r(e,t,s,o,c)}async finish(e){if(this.finished)return;this.finished=!0;let{status:t}=e,n={...this.metadata,status:t,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:n.status,finishedAt:n.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)})}async startRun(e){let t=this.diskStorage.createRunArchive(e.runId),n={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,labels:e.testLabels,trigger:"CLI",status:"RUNNING",environmentName:e.environmentName,cliVersion:gs,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 tg(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function hx(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 gx(r){let{options:e,fixtures:t,inputs:n,metadata:o}=r,{project:i,apiClient:a,logger:s}=t,{orgId:c,runGroupId:l,gitMetadata:u}=o,{outputDir:d,parallel:p}=e;tG(d)&&x.warn(`Output directory ${d} already exists, removing before test execution...`);let h=await hx(s,a,e.ignoreQuarantine),m=await vr(i),g=await px({tests:n.tests,yes:e.yes,project:i,momenticFiles:m,logger:x,quarantinedTestReasons:h}),f=s.child({orgId:c,runGroupId:l,branch:u.gitBranchName}),E=await Su.start({logger:f,orgId:c,runGroupId:l,outputDir:d,client:a,gitMetadata:u,labels:[]}),S=[],w=new Date,v=new Set,A=async()=>rG({runResults:S,startTime:w,ranTests:v,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),I=[],C=async()=>{x.warn("SIGINT received. Stopping tests and printing latest results..."),await E.finish({logger:f,status:"CANCELLED"}),await A(),await Promise.allSettled(I.map(D=>D())),setImmediate(()=>{setTimeout(()=>{process.exit(1)},2e3).unref()})};process.once("SIGINT",C);let R={};for(let D=0;D<g.length;D++){let J=Object.values(R);J.length===p&&await Promise.race(J.map(G=>G.promise));let Le=g[D],K=`test-${D}`;R[K]={done:!1,promise:(async({testDefinition:G})=>{v.add(K);let se=G.relativeFilePath.includes("..")?G.fullFilePath:G.relativeFilePath;Za({status:"START",testLogRef:se,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>g.length});let ce=setInterval(()=>Za({status:"RUN",testLogRef:se,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>g.length}),5*60*1e3),ke=eG(),fe=f.child({testId:G.id,runId:ke}),pt=new Rl({logger:fe,reporter:new au(a),runType:"mobile-test-run",runId:ke,testMetadata:G,suiteMetadata:void 0});try{let $t=await mx({metadata:{...o,runId:ke},fixtures:{...t,tracer:E,logger:fe,usageTracker:pt},inputs:{...n,project:i,testDefinition:G,channel:n.channel??G.settings?.defaultChannel,tag:n.tag??G.settings?.defaultTag,logUpdate:(we,tt)=>Za({status:we,testLogRef:se,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>g.length,additionalText:tt}),runSigIntHandlers:I},options:e});Za({status:$t.status,testLogRef:se,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>g.length}),S.push($t)}catch($t){let we=`Encountered unexpected fatal error when running test '${G.name}': ${$t.message}`;x.error(we),fe.error(we)}finally{clearInterval(ce),R[K].done=!0,delete R[K]}await pt.flush(s)})({testDefinition:Le})}}await Promise.allSettled(Object.values(R).map(D=>D.promise));let U=S.some(D=>D.status==="FAILED"&&!D.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:U}),process.off("SIGINT",C),A()}async function rG({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),s=vR({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let l=`${Qm}- ${c.filePath}`;return c.runId&&(l+=` ( link when uploaded: ${a}/runs/${c.runId} )`),l},entity:"mobile test"});return x.log(""),o?(x.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await uu({client:n,consoleLogger:x,resultsPath:i})):x.success(`Test results have been saved to the folder ${i}. Upload them to Momentic Cloud by running 'npx momentic-mobile results upload ${i}'.`),s}async function rg(){tb(),_R("Chromium")||(yo?(await $c("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await Wc({rawBrowsers:["chromium"],force:!1,all:!1})):(x.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)))}hw({serviceName:"mobile-cli"});Ft.setApp("mobile-cli");var kn=new nG;kn.name("momentic-mobile").description("Momentic Mobile CLI").version(gs);var lG=kn.command("assets").description("Manage mobile testing assets");lG.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(ps).addOption(ms).addOption(Yh).addOption(sx).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=bu.resolve(r);yu.existsSync(a)||(x.error(`File not found: ${a}`),process.exit(1));let s=new wr({baseUrl:n,apiKey:t,logger:x});/\.apk$/i.test(a)||(x.error(`File is not an APK file: ${a}`),process.exit(1)),await ys({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:s,logger:x})});kn.command("app").addOption(ps).addOption(ms).addOption(Wh).addOption($h).addOption(Jh).addOption(qh).addOption(Kh).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i}=r,a=eh(r.logLevel);Ft.setApp("mobile-desktop-server");let s=new wr({baseUrl:t,apiKey:e,logger:Ft});await Mh({client:s,skipPrompts:n}),x.debug("API key check complete");let c=sG(import.meta.url),l=bu.dirname(c),u=bu.resolve(l,"..","static");await rg(),x.debug({appiumHome:ya},"Resolved resource paths");let d=await ts({configFilePath:r.config}),p=ix;await ox({momenticServerUrl:t,serverPort:p,apiKey:e,staticDir:u,initialProject:d,driverLogLevel:a,logger:Ft,noCache:o,alwaysSaveCache:i});let h=`http://localhost:${p}`;x.info(`Local app started on: ${h}`),await aG(h)});var fx=kn.command("results").description("Merge and upload test results.");fx.command("merge").description("Merge test results files.").addOption(Xh).addArgument(new ng("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(x.error("Output directory is required."),process.exit(1)),yu.existsSync(r)||(x.warn("Results path does not exist, skipping merge."),process.exit(0)),yu.existsSync(t)&&x.warn(`Output directory ${t} already exists, removing before merging...`),WR(Ft,t,r),Oi(),process.exit(0)});var cG=new ng("<results>","Path to the results archive.").argRequired();fx.command("upload").description("Upload test results to Momentic cloud.").addOption(ps).addOption(ms).addArgument(cG).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=Ft,i=new wr({baseUrl:n,apiKey:t,logger:o});await uu({consoleLogger:x,resultsPath:r,client:i}),Oi(),process.exit(0)});var uG=kn.command("run").alias("test").description("Run tests on the local machine");uG.addOption(ps).addOption(ms).addOption($h).addOption(Wh).addOption(cx).addOption(Jh).addOption(qh).addOption(Kh).addOption(Xh).addOption(ux).addOption(dx).addOption(Yh).addOption(ax).addOption(lx).addArgument(new ng("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional()).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i,outputDir:a}=e,s=eh(e.logLevel);await rg(),x.debug({appiumHome:ya},"Resolved resource paths");let c=await ts({configFilePath:e.config}),l=a??c.config.outputDir??DR,u=e.parallel??c.config.parallel??1;x.debug("Checking API key and dependencies");let d=new wr({baseUrl:n,apiKey:t,logger:x}),{orgId:p,userId:h}=await Mh({client:d,skipPrompts:e.yes});x.debug("API key check and browser installation complete");let m=iG(),g=Ft.child({runGroupId:m,orgId:p,userId:h}),f=await Xc(Ft,d,c);g.debug(f,"Got local git metadata");try{let E=await gx({options:{...e,outputDir:l,parallel:u,logLevel:s,alwaysSaveCache:e.saveCache,noCache:e.disableCache},fixtures:{logger:g,project:c,apiClient:d},inputs:{envOverride:e.env,tag:o,channel:i,tests:r},metadata:{gitMetadata:f,runGroupId:m,orgId:p}});Oi(),E.failed>0?process.exit(1):process.exit(0)}catch(E){x.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),x.error(E),Ft.error({err:E},"Failed to run tests locally"),Oi(),process.exit(1)}});kn.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new oG("--name <name>","Name of the project")).action(async r=>{x.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
|
|
4052
|
+
`),x.info("This wizard will help you bootstrap a new Momentic project."),yu.existsSync(Ai)&&(x.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 wR("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:oh};kR(t,Ai),x.success(`Initialized Momentic project file at ${bu.resolve(Ai)}`)});kn.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: ${th.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(x.error("No browsers specified"),process.exit(1)),await Wc({rawBrowsers:r,force:e.force,all:e.all})});async function Oi(){try{await Ht.flush(),lR()}catch{}}async function dG(){try{await kn.parseAsync(process.argv),Oi()}catch(r){Ft.error({err:r},"Uncaught error in CLI"),x.error(r),Oi(),process.exit(1)}}dG();
|
|
4000
4053
|
//# sourceMappingURL=cli.js.map
|