momentic 2.17.9 → 2.17.11
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 +99 -149
- package/npm-shrinkwrap.json +116 -116
- package/package.json +1 -1
- package/static/assets/{index-8Ed0pdiv.js → index-kfes2OXz.js} +348 -348
- package/static/assets/index-wfCOQSMs.css +1 -0
- package/static/index.html +2 -2
- package/static/assets/index-LdCy1ETY.css +0 -1
package/bin/cli.js
CHANGED
|
@@ -1,51 +1,51 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
4
|
-
var I_=Object.defineProperty;var We=(r,e)=>()=>(r&&(e=r(r=0)),e);var P_=(r,e)=>{for(var t in e)I_(r,t,{get:e[t],enumerable:!0})};var Bb,Hb=We(()=>{"use strict";Bb=typeof globalThis=="object"?globalThis:global});var zb=We(()=>{"use strict";Hb()});var Gb=We(()=>{"use strict";zb()});var wn,Vm=We(()=>{"use strict";wn="1.9.0"});function ek(r){var e=new Set([r]),t=new Set,n=r.match(Vb);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(c){return c===r};function i(l){return t.add(l),!1}function a(l){return e.add(l),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var s=c.match(Vb);if(!s)return i(c);var u={major:+s[1],minor:+s[2],patch:+s[3],prerelease:s[4]};return u.prerelease!=null||o.major!==u.major?i(c):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(c):i(c):o.minor<=u.minor?a(c):i(c)}}var Vb,jb,$b=We(()=>{"use strict";Vm();Vb=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;jb=ek(wn)});function sa(r,e,t,n){var o;n===void 0&&(n=!1);var i=Is[_s]=(o=Is[_s])!==null&&o!==void 0?o:{version:wn};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!==wn){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+wn);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+wn+"."),!0}function Cn(r){var e,t,n=(e=Is[_s])===null||e===void 0?void 0:e.version;if(!(!n||!jb(n)))return(t=Is[_s])===null||t===void 0?void 0:t[r]}function la(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+wn+".");var t=Is[_s];t&&delete t[r]}var tk,_s,Is,Ps=We(()=>{"use strict";Gb();Vm();$b();tk=wn.split(".")[0],_s=Symbol.for("opentelemetry.js.api."+tk),Is=Bb});function Ms(r,e,t){var n=Cn("diag");if(n)return t.unshift(e),n[r].apply(n,nk([],rk(t),!1))}var rk,nk,Wb,qb=We(()=>{"use strict";Ps();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(l){a={error:l}}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))},Wb=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 Ms("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ms("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ms("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ms("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ms("verbose",this._namespace,e)},r}()});var Ve,$c=We(()=>{"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"})(Ve||(Ve={}))});function Kb(r,e){r<Ve.NONE?r=Ve.NONE:r>Ve.ALL&&(r=Ve.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",Ve.ERROR),warn:t("warn",Ve.WARN),info:t("info",Ve.INFO),debug:t("debug",Ve.DEBUG),verbose:t("verbose",Ve.VERBOSE)}}var Yb=We(()=>{"use strict";$c()});var ok,ik,ak,rn,Os=We(()=>{"use strict";qb();Yb();$c();Ps();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(l){a={error:l}}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))},ak="diag",rn=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var l=Cn("diag");if(l)return l[o].apply(l,ik([],ok(i),!1))}}var t=this,n=function(o,i){var a,l,c;if(i===void 0&&(i={logLevel:Ve.INFO}),o===t){var s=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((a=s.stack)!==null&&a!==void 0?a:s.message),!1}typeof i=="number"&&(i={logLevel:i});var u=Cn("diag"),d=Kb((l=i.logLevel)!==null&&l!==void 0?l:Ve.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 sa("diag",d,t,!0)};t.setLogger=n,t.disable=function(){la(ak,t)},t.createComponentLogger=function(o){return new Wb(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 Xb,Jb=We(()=>{"use strict";Xb=Symbol("BaggageEntryMetadata")});function jm(r){return typeof r!="string"&&(sk.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:Xb,toString:function(){return r}}}var sk,Qb=We(()=>{"use strict";Os();Jb();sk=rn.instance()});function $m(r){return Symbol.for(r)}var lk,Wm,qm=We(()=>{"use strict";lk=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}(),Wm=new lk});function Xm(){return Ym}var ei,ck,Wc,uk,dk,pk,mk,Km,gk,hk,fk,Ym,Sk,yk,Ek,Tk,bk,vk,Rk,Jm=We(()=>{"use strict";ei=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ck=function(){function r(){}return r.prototype.createGauge=function(e,t){return yk},r.prototype.createHistogram=function(e,t){return Ek},r.prototype.createCounter=function(e,t){return Sk},r.prototype.createUpDownCounter=function(e,t){return Tk},r.prototype.createObservableGauge=function(e,t){return vk},r.prototype.createObservableCounter=function(e,t){return bk},r.prototype.createObservableUpDownCounter=function(e,t){return Rk},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),Wc=function(){function r(){}return r}(),uk=function(r){ei(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Wc),dk=function(r){ei(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Wc),pk=function(r){ei(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Wc),mk=function(r){ei(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Wc),Km=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),gk=function(r){ei(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Km),hk=function(r){ei(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Km),fk=function(r){ei(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Km),Ym=new ck,Sk=new uk,yk=new pk,Ek=new mk,Tk=new dk,bk=new gk,vk=new hk,Rk=new fk});var tr,Zb=We(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(tr||(tr={}))});var Ak,wk,ev,tv=We(()=>{"use strict";qm();Ak=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},wk=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))},ev=function(){function r(){}return r.prototype.active=function(){return Wm},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,wk([n],Ak(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var Ck,xk,Qm,_k,rv,nv=We(()=>{"use strict";tv();Ps();Os();Ck=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},xk=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))},Qm="context",_k=new ev,rv=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return sa(Qm,e,rn.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,xk([e,t,n],Ck(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Cn(Qm)||_k},r.prototype.disable=function(){this._getContextManager().disable(),la(Qm,rn.instance())},r}()});var ca,ov=We(()=>{"use strict";nv();ca=rv.getInstance()});var z,iv=We(()=>{"use strict";Os();z=rn.instance()});var Ik,av,sv=We(()=>{"use strict";Jm();Ik=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return Ym},r}(),av=new Ik});var Zm,lv,cv=We(()=>{"use strict";sv();Ps();Os();Zm="metrics",lv=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return sa(Zm,e,rn.instance())},r.prototype.getMeterProvider=function(){return Cn(Zm)||av},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){la(Zm,rn.instance())},r}()});var qc,uv=We(()=>{"use strict";cv();qc=lv.getInstance()});var Me=We(()=>{"use strict";Qb();qm();$c();Jm();Zb();ov();iv();uv()});var Na=(r,e)=>{},Dd=!1;try{let r=await import("@sentry/node");Na=r.captureException,r.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:0}),Dd=!0}catch{}import{Command as IG,Option as Jt}from"@commander-js/extra-typings";import{execSync as PG}from"child_process";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{existsSync as VO,statSync as jO}from"fs";import{z as hf}from"zod";var jG=hf.object({input:hf.string()});import{z as pt}from"zod";var qG=pt.object({srcs:pt.array(pt.string()),urls:pt.array(pt.string()),desiredSrc:pt.string().optional(),desiredUrl:pt.string().optional()}),ff=pt.object({srcRegex:pt.string().optional(),urlRegex:pt.string().optional()}),Sf=pt.object({x:pt.number(),y:pt.number(),correlation:pt.number()}),KG=pt.object({searchImageBase64String:pt.string(),pageImageBase64String:pt.string(),id:pt.string().uuid(),timeoutMs:pt.number().max(1e4).min(0).optional()});import{z as L}from"zod";import*as F from"zod";import{extendZodWithOpenApi as M_}from"zod-openapi";M_(F);var Ln=(l=>(l.AI="AI",l.AI_HEALED="AI_HEALED",l.CLICK_TO_FIND="CLICK_TO_FIND",l.XY_PERCENT="XY_PERCENT",l.RECORDING="RECORDING",l.USER_CSS_SELECTOR="USER_CSS_SELECTOR",l.HEURISTIC_HEALED="HEURISTIC_HEALED",l))(Ln||{}),O_=F.object({mPathSelectorTokens:F.string().array(),frameSrcRegex:F.string().optional(),frameUrlRegex:F.string().optional(),indices:F.number().array()}),kd=F.object({result:F.number(),traceId:F.string()}).array(),dl=F.object({type:F.literal("GCS_TRACES"),traces:kd}),yf=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()}),L_=F.object({selectors:F.string().array(),requirements:yf.optional()}),Nn=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()),tagName:F.string(),expandShadowRoot:F.boolean().optional(),classNames:F.string().array(),nthChild:F.number()}).array().optional(),generatedSelectors:F.string().array().optional(),requirements:yf.optional(),additionalElements:L_.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:O_.optional(),inputDescription:F.string().optional().describe("the description that generated this cache"),targetSource:F.nativeEnum(Ln).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:dl.optional()}).openapi({ref:"ElementTargetCache"});function pl(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}function Ef(r){r.serializedHtml=void 0,r.nodeOnlySerializedHtml=void 0,r.screenshotUrl=void 0,r.boundingBox=void 0,r.hybridSelector=void 0,r.generatedSelectors=void 0,r.id=-1}var N_=F.object({type:F.literal("description"),elementDescriptor:F.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),D_=F.object({x:F.number(),y:F.number()}),k_=F.object({type:F.literal("coordinates"),pixels:D_}).openapi({ref:"CoordinatesTarget"});function Dn(r){return r.type==="description"}function Gr(r){return r.type==="coordinates"}var xt=F.discriminatedUnion("type",[N_,k_]).openapi({ref:"ElementTarget"});function Fd(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function _t(r){if(!r)return"";switch(r.type){case"description":return r.elementDescriptor;case"coordinates":return`x: ${r.pixels.x}, y: ${r.pixels.y}`}}function ml(r){return dl.safeParse(r).success}import{v4 as Ee}from"uuid";import*as v from"zod";import{extendZodWithOpenApi as j_}from"zod-openapi";import{z as ie}from"zod";import{extendZodWithOpenApi as F_}from"zod-openapi";import{z as Ti}from"zod";var Ud=Ti.object({result:Ti.boolean(),traceId:Ti.string()}).array(),Bd=Ti.object({type:Ti.literal("GCS_TRACES"),traces:Ud}),Hd=Ti.object({memory:Bd.optional()});F_(ie);var Tf=ie.object({plan:ie.string().optional(),evidence:ie.string().optional(),thoughts:ie.string(),result:ie.boolean(),relevantElements:ie.array(ie.number()).optional(),updatedMemory:Ud.optional()}),kn=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(kn||{});var U_=ie.object({type:ie.literal("ELEMENT_NAME"),negated:ie.boolean().optional(),operation:ie.nativeEnum(kn),value:ie.string()}).openapi({ref:"ElementNameAssertion"}),B_=ie.object({type:ie.literal("ELEMENT_STYLE"),negated:ie.boolean().optional(),operation:ie.nativeEnum(kn),property:ie.string(),value:ie.string()}).openapi({ref:"ElementStyleAssertion"}),H_=ie.object({type:ie.literal("ELEMENT_CONTENT"),negated:ie.boolean().optional(),operation:ie.nativeEnum(kn),value:ie.string()}).openapi({ref:"ElementContentAssertion"}),z_=ie.object({type:ie.literal("ELEMENT_ATTRIBUTE"),negated:ie.boolean().optional(),operation:ie.nativeEnum(kn),attr:ie.string(),value:ie.string()}).openapi({ref:"ElementAttributeValueAssertion"}),bi=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(bi||{}),G_=ie.object({type:ie.literal("ELEMENT_EXISTENCE"),negated:ie.boolean().optional(),condition:ie.nativeEnum(bi).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),bf=ie.discriminatedUnion("type",[H_,z_,G_,U_,B_]).openapi({ref:"ManualElementAssertion"});var V_=ie.object({type:ie.literal("CONTENT"),negated:ie.boolean().optional(),value:ie.string()}).openapi({ref:"PageContentAssertion"}),vf=ie.discriminatedUnion("type",[V_]).openapi({ref:"ManualPageAssertion"});import Bt from"zod";var zd=Bt.discriminatedUnion("type",[Bt.object({type:Bt.literal("SUBSTRING"),url:Bt.string()}),Bt.object({type:Bt.literal("GLOB"),glob:Bt.string()}),Bt.object({type:Bt.literal("REGEX"),regex:Bt.string()}),Bt.object({type:Bt.literal("DOMAIN"),domain:Bt.string()})]),ka=Bt.object({urlMatcher:zd,method:Bt.string().optional()});import{z as ye}from"zod";var gl=ye.object({url:ye.string(),method:ye.union([ye.literal("GET"),ye.literal("POST"),ye.literal("PUT"),ye.literal("DELETE"),ye.literal("PATCH")]),headers:ye.record(ye.string(),ye.string()).optional(),params:ye.record(ye.string(),ye.string()).optional(),body:ye.string().optional(),timeout:ye.number().int().optional().describe("Max seconds to wait for the request to complete")}),Rf=ye.object({url:ye.string(),headers:ye.record(ye.string(),ye.string()).optional(),query:ye.string(),variables:ye.string().optional(),timeout:ye.number().int().optional().describe("Max seconds to wait for the request to complete")}),hl=ye.object({code:ye.string(),fragment:ye.boolean().optional(),environment:ye.union([ye.literal("NODE"),ye.literal("BROWSER")]).optional().describe("default NODE"),timeout:ye.number().int().max(60).optional().describe("Max seconds for the code to complete")});var qe=(G=>(G.AI_EXTRACT="AI_EXTRACT",G.AI_ASSERTION="AI_ASSERTION",G.AUTH_LOAD="AUTH_LOAD",G.AUTH_SAVE="AUTH_SAVE",G.BLUR="BLUR",G.CAPTCHA="CAPTCHA",G.CLICK="CLICK",G.COOKIE="COOKIE",G.COPY="COPY",G.DIALOG="DIALOG",G.DRAG="DRAG",G.ELEMENT_CHECK="ELEMENT_CHECK",G.FILE_UPLOAD="FILE_UPLOAD",G.FOCUS="FOCUS",G.GO_BACK="GO_BACK",G.GO_FORWARD="GO_FORWARD",G.HOVER="HOVER",G.JAVASCRIPT="JAVASCRIPT",G.LOCAL_STORAGE="LOCAL_STORAGE",G.MOUSE_DRAG="MOUSE_DRAG",G.NAVIGATE="NAVIGATE",G.NEW_TAB="NEW_TAB",G.PAGE_CHECK="PAGE_CHECK",G.PASTE="PASTE",G.PRESS="PRESS",G.KEY_DOWN="KEY_DOWN",G.KEY_UP="KEY_UP",G.REFRESH="REFRESH",G.REQUEST="REQUEST",G.GRAPHQL_REQUEST="GRAPHQL_REQUEST",G.SCROLL_DOWN="SCROLL_DOWN",G.SCROLL_UP="SCROLL_UP",G.SCROLL_LEFT="SCROLL_LEFT",G.SCROLL_RIGHT="SCROLL_RIGHT",G.SELECT_OPTION="SELECT_OPTION",G.SWITCH_TAB="TAB",G.TYPE="TYPE",G.VISUAL_DIFF="VISUAL_DIFF",G.WAIT="WAIT",G.WAIT_FOR_URL="WAIT_FOR_URL",G.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",G.AWAIT_LISTENER="AWAIT_LISTENER",G.RECORD_REQUESTS="RECORD_REQUESTS",G.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",G.SET_HEADER="SET_HEADER",G.MOCK_ROUTE="MOCK_ROUTE",G.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",G.OFFLINE_MODE="OFFLINE_MODE",G.SUCCESS="SUCCESS",G))(qe||{});j_(v);var W=v.object({thoughts:v.string().optional(),id:v.string().uuid().describe("unique identifier to this step, used for step cache")}),ar=v.object({useSelector:v.boolean().optional(),force:v.boolean().optional(),disableCache:v.boolean().optional().describe("disable element caching for this step"),iframeUrl:v.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Qt=v.object({target:Nn}).optional().openapi({ref:"SingleTargetCache"});function Af(r){return Qt.safeParse(r).success}var Sl=v.object({loadTimeout:v.number().int().max(60).optional().describe("Max seconds for the page to load")}),Vd=W.merge(Sl).merge(v.object({type:v.literal("NAVIGATE"),url:v.string()})).openapi({ref:"NavigateCommand"}),yl=ar.merge(v.object({cache:Qt})),Fn=W.merge(yl.merge(v.object({target:xt.optional(),type:v.literal("SCROLL_UP"),deltaY:v.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Un=W.merge(yl.merge(v.object({target:xt.optional(),type:v.literal("SCROLL_DOWN"),deltaY:v.number().optional()}))).openapi({ref:"ScrollDownCommand"}),vi=W.merge(yl.merge(v.object({target:xt.optional(),type:v.literal("SCROLL_LEFT"),deltaX:v.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Ri=W.merge(yl.merge(v.object({target:xt.optional(),type:v.literal("SCROLL_RIGHT"),deltaX:v.number().optional()}))).openapi({ref:"ScrollRightCommand"}),EV=v.discriminatedUnion("type",[Fn,Un,vi,Ri]).openapi({ref:"AllScrollCommands"}),$_=W.merge(v.object({type:v.literal("DIALOG"),action:v.union([v.literal("ACCEPT"),v.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),W_=W.merge(v.object({type:v.literal("WAIT"),delay:v.number()})).openapi({ref:"WaitCommand"}),q_=v.object({caseInsensitive:v.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:v.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:v.number().int().optional().describe("Max seconds to wait for the URL to match")}),jd=W.extend({type:v.literal("WAIT_FOR_URL"),matcher:zd}).merge(q_).openapi({ref:"WaitUrlCommand"}),K_=W.merge(Sl).merge(v.object({type:v.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),Y_=W.merge(v.object({type:v.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),X_=W.merge(v.object({type:v.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),J_=W.extend({type:v.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),Q_=W.extend({type:v.literal("AUTH_LOAD"),storageState:v.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),$d=W.merge(ar).extend({type:v.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),Z_=W.extend({type:v.literal("COPY"),value:v.string()}).openapi({ref:"CopyCommand"}),eI=W.extend({type:v.literal("PASTE")}).openapi({ref:"PasteCommand"}),Wd=W.merge(hl).extend({type:v.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Ro=W.merge(ar).extend({type:v.literal("CLICK"),target:xt,doubleClick:v.boolean().optional(),rightClick:v.boolean().optional(),waitForDownload:v.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:v.number().optional(),downloadTimeoutMs:v.number().optional(),cache:Qt,relativePosition:v.object({x:v.number(),y:v.number()}).optional()}).openapi({ref:"ClickCommand"}),qd=v.object({fromTarget:Nn.optional(),toTarget:Nn.optional()}),Fa=W.merge(ar).merge(v.object({type:v.literal("DRAG"),fromTarget:xt,toTarget:xt,steps:v.number().optional(),hoverSeconds:v.number().optional().describe("Seconds to hover the object before dropping"),cache:qd.optional()})).openapi({ref:"DragCommand"}),Ua=W.merge(ar).merge(v.object({type:v.literal("MOUSE_DRAG"),target:xt.optional(),deltaX:v.string().describe("pixels to move horizontally, can be template"),deltaY:v.string().describe("pixels to move vertically, can be template"),steps:v.number().optional(),cache:Qt})).openapi({ref:"MouseDragCommand"}),Ao=W.merge(ar).merge(v.object({type:v.literal("HOVER"),target:xt,cache:Qt})).openapi({ref:"HoverCommand"}),Ba=W.merge(ar).merge(v.object({type:v.literal("FOCUS"),target:xt,cache:Qt})).openapi({ref:"FocusCommand"}),Ha=W.merge(ar).extend({type:v.literal("BLUR"),target:xt.optional(),cache:Qt}).openapi({ref:"BlurCommand"}),tI=v.object({type:v.literal("URL"),url:v.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),rI=v.object({type:v.literal("USER_FILE"),name:v.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),nI=W.extend({type:v.literal("FILE_UPLOAD"),fileSource:v.discriminatedUnion("type",[tI,rI]),filename:v.string().optional()}).openapi({ref:"FileUploadCommand"}),oI=v.discriminatedUnion("type",[v.object({type:v.literal("VALUE"),value:v.string()}),v.object({type:v.literal("LABEL"),label:v.string()}),v.object({type:v.literal("INDEX"),index:v.coerce.string()})]),wo=W.merge(ar).extend({type:v.literal("SELECT_OPTION"),target:xt,cache:Qt,choice:oI.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),Kd=v.union([v.literal("MULTIMODAL"),v.literal("VISION_ONLY")]),Ai=W.merge(v.object({type:v.literal("AI_ASSERTION"),assertion:v.string(),disableCache:v.boolean().optional(),iframeUrl:v.string().optional(),contextChoice:Kd.optional(),timeout:v.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Hd.optional()})).openapi({ref:"AIAssertionCommand"}),Vr=5,Yd=600,Co=W.merge(ar).extend({type:v.literal("ELEMENT_CHECK"),target:xt,assertion:bf,cache:Qt.or(Hd).optional(),timeout:v.number().int().min(0).max(Yd).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),Xd=W.extend({type:v.literal("PAGE_CHECK"),assertion:vf,iframeUrl:v.string().optional().describe("url or url regex for the iframe"),timeout:v.number().int().min(0).max(Yd).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),iI=W.merge(v.object({type:v.literal("AI_EXTRACT"),goal:v.string(),schema:v.string().optional(),envKey:v.string().optional(),disableCache:v.boolean().optional(),iframeUrl:v.string().optional()})).openapi({ref:"AIExtractCommand"}),aI=v.object({clearContent:v.boolean().optional(),forceClearContent:v.boolean().optional(),delay:v.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:v.boolean().optional(),pressEnter:v.boolean().optional()}),wf=25,xo=W.merge(ar).merge(aI).extend({type:v.literal("TYPE"),target:xt.optional(),value:v.string(),cache:Qt}).openapi({ref:"TypeCommand"}),Jd=W.merge(v.object({type:v.literal("PRESS"),value:v.string(),repeat:v.number().optional(),convertMeta:v.boolean().optional(),delayMs:v.number().optional()})).openapi({ref:"PressCommand"}),sI=W.merge(v.object({type:v.literal("KEY_DOWN"),value:v.string(),convertMeta:v.boolean().optional()})).openapi({ref:"KeyDownCommand"}),lI=W.merge(v.object({type:v.literal("KEY_UP"),value:v.string(),convertMeta:v.boolean().optional()})).openapi({ref:"KeyUpCommand"}),cI=v.object({type:v.literal("SUBSTRING"),substring:v.string()}),uI=v.object({type:v.literal("REGEX"),pattern:v.string()}),dI=v.object({type:v.literal("INDEX"),index:v.coerce.string()}),pI=v.discriminatedUnion("type",[cI,uI,dI]),mI=W.merge(Sl).merge(v.object({type:v.literal("TAB"),action:pI})).openapi({ref:"TabCommand"}),Qd=W.merge(Sl).merge(v.object({type:v.literal("NEW_TAB"),url:v.string()})).openapi({ref:"NewTabCommand"}),gI=W.merge(v.object({type:v.literal("COOKIE"),value:v.string()})).openapi({ref:"CookieCommand"}),hI=W.merge(v.object({type:v.literal("LOCAL_STORAGE"),key:v.string(),value:v.string()})).openapi({ref:"LocalStorageCommand"}),fI=W.extend({type:v.literal("REQUEST")}).merge(gl).openapi({ref:"RequestCommand"}),SI=W.extend({type:v.literal("GRAPHQL_REQUEST")}).merge(Rf).openapi({ref:"GraphQLRequestCommand"}),yI=W.merge(v.object({type:v.literal("SUCCESS"),condition:Ai.optional()})).openapi({ref:"SuccessCommand"}),EI=W.merge(v.object({type:v.literal("FAILURE")})).openapi({ref:"FailureCommand"}),TI=v.object({data:v.string().describe("location at which to find a jpg"),width:v.number(),height:v.number()}),za=W.merge(ar).merge(v.object({type:v.literal("VISUAL_DIFF"),threshold:v.number().optional().describe("default 0.1"),target:xt.optional(),screenshot:TI.optional(),cache:Qt})).openapi({ref:"VisualDiffCommand"}),bI=W.merge(v.object({type:v.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:ka,key:v.string()})).openapi({ref:"RegisterRequestListenerCommand"}),vI=W.merge(v.object({type:v.literal("AWAIT_LISTENER"),key:v.string(),timeout:v.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),RI=W.merge(v.object({type:v.literal("RECORD_REQUESTS"),requestMatcher:ka,key:v.string()})).openapi({ref:"RecordRequestsCommand"}),AI=W.merge(v.object({type:v.literal("GET_RECORDED_REQUESTS"),key:v.string()})).openapi({ref:"GetRecordedRequestsCommand"}),wI=W.merge(v.object({type:v.literal("SET_HEADER"),name:v.string(),value:v.string(),requestMatcher:ka.optional()})).openapi({ref:"SetHeaderCommand"}),CI=W.merge(v.object({type:v.literal("MOCK_ROUTE"),requestMatcher:ka,responseGenerator:v.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:v.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:v.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"})),xI=W.merge(v.object({type:v.literal("REMOVE_ROUTE_MOCK"),key:v.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),_I=W.merge(v.object({type:v.literal("OFFLINE_MODE"),enable:v.boolean()})).openapi({ref:"OfflineModeCommand"}),Cf=v.discriminatedUnion("type",[Ro,xo,Jd,sI,lI,wo,Vd,Un,Fn,Ai,Ao,W_,yI]),II=v.discriminatedUnion("type",[iI,Q_,J_,$d,gI,Z_,$_,Fa,Co,nI,Y_,X_,Wd,hI,Ua,Qd,Xd,eI,K_,fI,SI,vi,Ri,mI,za,Ba,Ha,jd,bI,vI,RI,AI,wI,CI,xI,_I]),wi=v.discriminatedUnion("type",[...Cf.options,...II.options]).openapi({ref:"Command"}),El=v.discriminatedUnion("type",[...Cf.options,EI]);function mn(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:Ee(),type:r};break;case"AUTH_LOAD":{e={id:Ee(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:Ee(),type:r,goal:""};break;case"DIALOG":e={id:Ee(),type:r,action:"DISMISS"};break;case"DRAG":e={id:Ee(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Ee(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Ee(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:Ee(),type:r,delay:1};break;case"BLUR":e={id:Ee(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:Ee(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:Ee(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:Ee(),type:r,value:""};break;case"SELECT_OPTION":e={id:Ee(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:Ee(),type:r,url:""};case"TAB":e={id:Ee(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:Ee(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:Ee(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:Ee(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:Ee(),type:r,code:""};break;case"AI_ASSERTION":e={id:Ee(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:Ee(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Ee(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Ee(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:Ee(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:Ee(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:Ee(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:Ee(),type:r,key:""};break}case"SET_HEADER":{e={id:Ee(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:Ee(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:Ee(),type:r};break}case"OFFLINE_MODE":{e={id:Ee(),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 xf(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 PI}from"zod";var AV=PI.discriminatedUnion("type",[Ha,$d,Ro,Fa,Ba,Ao,Ua,Fn,Un,vi,Ri,wo,xo,za,Co]);function _f(r){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(r)}import{z as MI}from"zod";import{z as Bn}from"zod";function Ga(r){return Bn.object({key:Bn.string(),testId:Bn.string().optional(),moduleId:Bn.string().optional(),organizationId:Bn.string(),value:r})}function Va(r){return Ga(r).extend({uniqueKey:Bn.string()})}function Tl(r){return Bn.record(Bn.string(),Va(r))}var Ht={type:!0,cache:!0},gn=MI.discriminatedUnion("type",[Ai.pick(Ht),Ha.pick(Ht),Ro.pick(Ht),Fa.pick(Ht),Co.pick(Ht),Ba.pick(Ht),Ao.pick(Ht),Ua.pick(Ht),Fn.pick(Ht),Un.pick(Ht),vi.pick(Ht),Ri.pick(Ht),wo.pick(Ht),xo.pick(Ht),za.pick(Ht)]),bl=Object.values(qe).filter(r=>gn.options.some(e=>e.shape.type.safeParse(r).success));wi.options.forEach(r=>{if("target"in r.shape&&!bl.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function If(r){return bl.includes(r.type)}var Pf=Ga(gn),Mf=Va(gn),OV=Tl(gn);import{z as Zd}from"zod";import{extendZodWithOpenApi as NI}from"zod-openapi";import{z as Of}from"zod";import{extendZodWithOpenApi as OI}from"zod-openapi";import{z as _o}from"zod";var sr=_o.object({index:_o.number().optional().describe("global index within a test (in-order traversal)"),id:_o.string(),skipped:_o.boolean().optional(),envKey:_o.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:_o.boolean().optional(),retries:_o.number().optional()});OI(Of);var LI=sr.extend({type:Of.literal("PRESET_ACTION")}),Zt=LI.extend({command:wi}).openapi({ref:"PresetAction"});NI(Zd);var Io=sr.extend({type:Zd.literal("AI_ACTION"),text:Zd.string(),steps:Zt.array().optional()}).openapi({ref:"AIAction"});import{z as zt}from"zod";import{z as vl}from"zod";import{extendZodWithOpenApi as DI}from"zod-openapi";DI(vl);var Ci=sr.extend({type:vl.literal("AI_ACTION_DYNAMIC"),text:vl.string(),retries:vl.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as Lf}from"zod";var ep=sr.extend({type:Lf.literal("CONDITIONAL"),skipped:Lf.boolean().optional()});import{z as pe}from"zod";var kI=pe.object({cacheKey:pe.string(),cacheExpiryMs:pe.number()}),tp=sr.extend({id:pe.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:pe.record(pe.string()).optional(),cacheConfig:kI.optional()}),_r=tp.extend({type:pe.literal("MODULE"),moduleId:pe.string().uuid()}),FI=pe.union([_r.pick({type:!0,moduleId:!0}),pe.record(pe.unknown())]),UI=pe.object({type:pe.literal("URL_REGEX"),regex:pe.string()}),BI=pe.object({type:pe.literal("PAGE_CHECK"),substring:pe.string()}),rp=pe.object({cacheInvalidation:pe.discriminatedUnion("type",[BI,UI]).optional()}),Wt=pe.object({moduleId:pe.string().uuid(),name:pe.string(),description:pe.string().nullish(),enabled:pe.boolean().nullish(),parameters:pe.string().array().nullish(),defaultParameters:pe.record(pe.string(),pe.string()).nullish(),parameterEnums:pe.record(pe.string(),pe.string().array()).nullish(),defaultCacheKey:pe.string().nullish(),defaultCacheTtl:pe.number().nullish(),defaultCacheAllInvocations:pe.boolean().nullish(),autoAuth:pe.boolean().nullish(),advanced:rp.nullish()});var np=r=>r.type==="AI_ACTION"||r.type==="AI_ACTION_DYNAMIC"||r.type==="PRESET_ACTION";import{z as lr}from"zod";var op=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(op||{});var HI=lr.discriminatedUnion("type",[lr.object({type:lr.literal("NAVIGATE_URL"),url:lr.string().url()}),lr.object({type:lr.literal("GO_TO_SECTION_START")})]),zI=lr.object({trigger:lr.nativeEnum(op).optional(),attempts:lr.number().int().optional(),restartBehavior:HI}),ja=sr.extend({type:lr.literal("SECTION"),description:lr.string().describe("user provided goal of what the section should accomplish"),plan:lr.string().array().optional(),autohealingConfig:zI.optional()});var Nf=Wt.merge(tp).extend({type:zt.literal("RESOLVED_MODULE"),steps:zt.lazy(()=>Ze.array())}),$a=Wt.extend({steps:zt.lazy(()=>Ze.array())}),ip=ja.extend({steps:zt.lazy(()=>Le.array())}),GI=ja.extend({steps:zt.lazy(()=>Ze.array())}),Po=ep.extend({blocks:zt.object({assertion:zt.lazy(()=>Zt),steps:zt.lazy(()=>Le.array())}).array(),elseSteps:zt.lazy(()=>Le.array().optional())}),VI=ep.extend({blocks:zt.object({assertion:zt.lazy(()=>Zt),steps:zt.lazy(()=>Ze.array())}).array(),elseSteps:zt.lazy(()=>Ze.array().optional())}),Le=zt.discriminatedUnion("type",[Zt,Io,Ci,_r,Po,ip]),Ze=zt.discriminatedUnion("type",[Zt,Io,Ci,Nf,VI,GI]);import{z as cr}from"zod";var jI=cr.object({steps:Le.array(),beforeSteps:Le.array().nullish(),afterSteps:Le.array().nullish()}),xi=cr.object({steps:Ze.array(),beforeSteps:Ze.array().nullish(),afterSteps:Ze.array().nullish()}),Mo=cr.object({steps:cr.record(cr.string(),cr.unknown()).array(),beforeSteps:cr.record(cr.string(),cr.unknown()).array().nullish(),afterSteps:cr.record(cr.string(),cr.unknown()).array().nullish()});var ue="1.0.21";var Df=L.object({phrase:L.string()}),ap=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()])}),f$=L.object({text:L.string()}),kf=L.object({attributes:L.array(L.string()).optional(),text:L.boolean().optional(),boundingBox:L.boolean().optional()}),$I=L.object({id:L.number().int(),requirements:kf}),WI=$I.array(),Ff=L.object({thoughts:L.string(),review:L.string().optional(),id:L.number().int(),updatedMemory:kd.optional(),requirements:kf.optional(),additionalElements:WI.optional()});var Rl=(m=>(m.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",m.FEW_WORDS="FEW_WORDS",m.STYLE_TAG="STYLE_TAG",m.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",m.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",m.NONE="NONE",m.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",m.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",m.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",m.PREFER_ASSERTION="PREFER_ASSERTION",m.HTML_ELEMENTS="HTML_ELEMENTS",m.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",m.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",m))(Rl||{}),sp=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(sp||{});var Uf=L.object({thoughts:L.string(),category:L.nativeEnum(Rl)}),Bf=L.object({thoughts:L.string(),category:L.nativeEnum(sp)}),qI=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()})]),S$=L.object({thoughts:L.string(),patches:qI.array()}),KI=[L.literal("add"),L.literal("replace"),L.literal("remove")],YI=L.object({op:L.union(KI),path:L.string(),value:Ze.optional()}),Hf=L.object({patches:YI.array(),thoughts:L.string()}),lp=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(lp||{}),zf=L.object({thoughts:L.string(),scenario:L.nativeEnum(lp),instructions:L.string().nullish()}),Gf=L.object({reasoning:L.string(),scenario:L.string(),patch:L.null().optional()}),y$=L.object({thoughts:L.string(),evaluation:L.number().min(0).max(10)}),E$=L.object({observations:L.string(),reasoning:L.string(),command:El});var cp=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")})])}),XI=L.object({startId:L.number().int(),endId:L.number().int()}),Vf=L.object({categoryThoughts:L.string(),category:L.string(),relevantSections:XI.array()});import{z as O}from"zod";import*as ae from"zod";var w$=ae.object({thoughts:ae.string().optional().describe("only provided if a description was provided"),target:Nn.optional().describe("only provided if a description was provided"),pageState:ae.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:ae.object({label:ae.string(),value:ae.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:ae.object({data:ae.string(),height:ae.number().int(),width:ae.number().int()}).optional().describe("only provided if returnScreenshot is true")}),jf=ae.union([ae.literal("ELEMENT_CHECK"),ae.literal("NEGATED_CHECK"),ae.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),ae.literal("SELECT_OPTION"),ae.literal("TYPE")]);function Oo(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 Wa=(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))(Wa||{}),_i=ae.object({matched:ae.boolean(),reason:ae.string().optional().describe("Human understandable description"),logs:ae.string().array().optional().describe("Logs for debugging")}),JI=_i.extend({type:ae.literal("USER_SELECTOR")}),QI=_i.extend({type:ae.literal("CSS_SELECTOR"),selectors:ae.string().array()}),ZI=_i.extend({type:ae.literal("HYBRID_SELECTOR")}),eP=_i.extend({type:ae.literal("HTML_DISTANCE"),distance:ae.number().optional(),closestElement:ae.string().optional(),savedElement:ae.string().optional()}),tP=_i.extend({type:ae.literal("TEMPLATE_MATCHING"),elementImageUrl:ae.string().url()}),rP=_i.extend({type:ae.literal("AUTO_FRAME"),logs:ae.string().array().optional()}),$f=ae.discriminatedUnion("type",[JI,QI,ZI,eP,tP,rP]);import{z as Xa}from"zod";import{z as hP}from"zod";import*as V from"zod";import{extendZodWithOpenApi as sP}from"zod-openapi";import{cloneDeep as qa}from"lodash-es";import Jf from"truncate-json";import*as Do from"zod";import{extendZodWithOpenApi as nP}from"zod-openapi";import{z as It}from"zod";import{z as Ne}from"zod";var up=Ne.object({autoFollowNewTabs:Ne.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:Ne.union([Ne.boolean(),Ne.literal("inputs-only")]).optional(),ignoreHrefForCaching:Ne.boolean().optional(),disableSecondaryCacheResolution:Ne.boolean().optional(),hybridSelectorMode:Ne.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:Ne.boolean().optional(),visualActions:Ne.boolean().optional(),autoExpandIframes:Ne.boolean().optional(),disableHtmlSnapshots:Ne.boolean().optional(),importantAttributes:Ne.string().array().optional(),importantClasses:Ne.string().array().optional(),importantStyles:Ne.string().array().optional()});var Wf=1e4,qf=6e4,Lo=up.extend({pageLoadTimeoutMs:Ne.number().optional().refine(r=>r===void 0||r<=qf&&r>=-1,{message:`Page load timeout must be between 0 and ${qf/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:Ne.number().optional().refine(r=>r===void 0||r<=Wf&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${Wf/1e3} seconds`}),localChromeExtensionPaths:Ne.string().array().optional(),extraHeaders:Ne.record(Ne.string(),Ne.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:Ne.string().optional(),disableGpu:Ne.boolean().optional(),bustCacheOnBoundingBoxChange:Ne.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:Ne.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:Ne.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 ht="BASE_URL",Al="CURRENT_URL",No="ENV_NAME",Ii="TEST_NAME",M$={[ht]:"https://www.google.com"},Kf=It.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Yf=It.object({name:It.string(),variables:It.record(It.string().describe("variable name"),It.string().describe("variable value"))}),Xf=It.object({name:It.string(),variables:It.record(It.string().describe("variable name"),It.unknown().describe("variable value")),browser:Lo.optional()});var O$=It.object({name:It.string(),variables:It.record(It.string().describe("variable name"),It.unknown().describe("variable value"))});nP(Do);var dp=Do.object({env:Do.record(Do.unknown())}).openapi({ref:"TestContextSnapshot"}),oP="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",iP=[ht,No,Ii],Qf=[Al,ht,No,Ii],qt=class r{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t=void 0,n={}){return new r({baseUrl:"about:blank",currentUrl:"about:blank",testName:e,envName:t,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[ht]??"about:blank",o=e.env[Al]??"about:blank",i=e.env[No],a=e.env[Ii],l={};for(let[s,u]of Object.entries(e.env))Qf.includes(s)||(t??{})[s]===void 0&&(l[s]=u);return new r({baseUrl:n,currentUrl:o,dynamicVariables:l,envName:i,testName:a,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=qa(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){iP.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[No]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return qa(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>Qf.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,oP]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=Jf(JSON.stringify(o),5e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=Jf(JSON.stringify(e.env),25e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}setCurrentUrl(e){this.env[Al]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=qa(e.variablesFromEnvironment),this.setMomenticSystemVariable(ht,e.baseUrl),e.envName&&this.setMomenticSystemVariable(No,e.envName),e.testName&&this.setMomenticSystemVariable(Ii,e.testName)}getDynamicVariablesCopy(){return qa(this.env)}getVariablesFromEnvironmentCopy(){return qa(this.varsFromMomenticEnvironment)}};var Ae=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Ae||{}),wl=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(wl||{});import{z as jr}from"zod";import{extendZodWithOpenApi as aP}from"zod-openapi";aP(jr);var me=(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))(me||{});var Zf=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],Cl={ActionFailureError:"Action failure",AssertionFailureError:"Assertion failure",SetupFailureError:"Setup failure",TeardownFailureError:"Teardown failure",UserInfrastructureError:"Infrastructure failure",UserConfigurationError:"Configuration error",AIProviderError:"AI provider error",InternalWebAgentError:"Momentic AI agent error",JobTimeoutError:"Job timeout",InternalPlatformError:"Unknown Momentic platform error",UnknownError:"Unknown error",ConcurrencyError:"Concurrency error"},Pi={ActionFailureError:"A browser action such as a click or type failed to execute because of the underlying page state is incorrect, suggesting a bug in the application itself.",AssertionFailureError:"An AI check failed for a legitimate reason, such as a missing element, a change in the page structure, or an unexpected state (e.g. loading state).",SetupFailureError:"A setup step failed to execute, preventing the main test from running. This indicates an issue with test preparation, prerequisite steps, or initial state. This can only apply to failures that occur before teardown.",TeardownFailureError:"A teardown step failed to execute after the main test completed. This indicates an issue with cleanup or post-test operations or an uncaught error in the test. This can only apply to failures that occur after setup.",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",UserInfrastructureError:"The user's web application exhibited an infrastructure failure, such as a page load timeout, a 5XX status code, maintenance page, or session crash.",UserConfigurationError:"The error message suggests a user-caused misconfiguration in the test, such as an undefined variable, a missing base URL, an empty test/module input parameter, or an invalid step option",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself.",InternalWebAgentError:"The AI testing framework failed to find the correct element or evaluate the assertion correctly, even though the test steps and application state look valid. In other words, the AI agent failed to understand the page.",ConcurrencyError:"The AI test executed correctly, but the application state did not match expectations because another process modified the same resource concurrently. This failure is due to a concurrency error, such as a race condition or deadlock. Commonly caused by tests running simultaneously when using constants rather than random values, or underlying operations that allow for race conditions. For example, in Notion, if multiple tests are running at the same time where one creates a page and enters text to check if it renders, but another test deletes all pages before it can validate the render, this would be a concurrency error.",UnknownError:"An unknown error occurred. Please refer to the failure details in the run for more information or reach out to Momentic Support for assistance.",InternalPlatformError:"An unknown error occurred with the Momentic platform."},pp=jr.object({reason:jr.nativeEnum(me),previousStepsDescription:jr.array(jr.string()).optional(),summary:jr.string(),rootCause:jr.string().optional()}).openapi({ref:"TestResultClassification"}),xl=jr.object({errorMessage:jr.string(),errorStack:jr.string().optional(),classification:pp.optional()}).openapi({ref:"TestFailureDetails"});sP(V);var mp=V.object({beforeUrl:V.string().optional(),afterUrl:V.string().optional(),message:V.string().optional(),beforeSnapshot:V.string().optional(),afterSnapshot:V.string().optional(),startedAt:V.coerce.date(),finishedAt:V.coerce.date()}),lP=mp.extend({viewport:V.object({height:V.number(),width:V.number()}).nullish(),status:V.nativeEnum(wl),message:V.string().optional(),elementInteracted:V.string().optional()}),ko=mp.extend({status:V.nativeEnum(Ae),message:V.string().optional(),data:V.unknown().optional(),beforeTestContext:dp.optional(),afterTestContext:dp.optional(),failureReason:V.nativeEnum(me).optional(),details:V.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"}),gp=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(gp||{}),_l=ko.merge(Zt).extend({results:lP.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:V.lazy(()=>mt.array()).optional(),failureRecoveryStatus:V.object({type:V.nativeEnum(gp),message:V.string()}).optional()}),cP=ko.merge(Io).extend({results:V.lazy(()=>_l.array()),previousAttempts:V.lazy(()=>mt.array()).optional()}),uP=ko.merge(Ci).extend({results:V.lazy(()=>_l.array()),previousAttempts:V.lazy(()=>mt.array()).optional()}),dP=ko.merge(_r).extend({moduleName:V.string().optional(),results:V.lazy(()=>mt.array()),previousAttempts:V.lazy(()=>mt.array()).optional()}),pP=ko.merge(Po).extend({assertion:_l.optional(),results:V.lazy(()=>mt.array()).describe("results for the block actually executed"),previousAttempts:V.lazy(()=>mt.array()).optional()}),mP=ko.merge(ja).extend({results:V.lazy(()=>mt.array()),healingAttempts:V.lazy(()=>mt.array().array()).optional(),previousAttempts:V.lazy(()=>mt.array()).optional()}),mt=V.discriminatedUnion("type",[cP,uP,_l,dP,pP,mP]),Il=ko.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),gP=mp.extend({index:V.number().optional(),description:V.string(),pageState:V.string().optional(),elementInteracted:V.string().optional(),startedAt:V.coerce.date().or(V.string()).optional().catch(void 0),finishedAt:V.coerce.date().or(V.string()).optional().catch(void 0)}),Pl=gP.extend({beforeScreenshot:V.string().optional(),afterScreenshot:V.string().optional()});var hp=hP.object({results:mt.array().describe("main results"),beforeResults:mt.array().optional(),afterResults:mt.array().optional()}),Ka=hp.partial();import{z as U}from"zod";import{extendZodWithOpenApi as bP}from"zod-openapi";var Mi=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(Mi||{});import{isValidCron as fP}from"cron-validator";import{z as se}from"zod";import{z as fp}from"zod";var hn=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(hn||{});var Ml=fp.object({width:fp.number().min(200).max(1e4),height:fp.number().min(200).max(1e4)}),eS={"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}},aW=Object.keys(eS);var Pt=eS["Desktop Large"],Hn="en-us",zn="America/Los_Angeles";var Gn={latitude:37.7749,longitude:-122.4194};var tS=["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 rS=2e3,Ol=Lo.extend({browserType:se.nativeEnum(hn).optional(),slowMoMs:se.number().optional().refine(r=>r===void 0||r<=rS&&r>=-1,{message:`Slow motion must be between 0 and ${rS} milliseconds`}),basicAuthorization:se.object({username:se.string().optional(),password:se.string().optional()}).optional(),geolocation:se.object({latitude:se.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:se.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:se.boolean().optional(),locale:se.string().optional(),timezone:se.enum(tS).optional(),colorScheme:se.enum(["light","dark"]).optional()}),nS=["extraHeaders","basicAuthorization","localChromeExtensionPaths"],Sp=se.object({useMemory:se.boolean().optional(),failureRecovery:se.boolean().optional().describe("undefined means inherit org settings")}),SP=Sp.extend({disableAICaching:se.boolean().optional(),failureRecoveryInstructions:se.string().optional()}),yP=se.object({viewport:Ml.optional()}),Fo=yP.merge(SP).merge(Ol),Oi=se.object({cron:se.string().refine(r=>fP(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:se.boolean().default(!1),env:se.string().optional(),timeZone:se.string().default("America/Los_Angeles"),jobKey:se.string().optional()}),Li=se.object({onSuccess:se.boolean().default(!1),failureMessage:se.string().optional(),onFailure:se.boolean().default(!0),successMessage:se.string().optional()}),EP=se.object({name:se.string(),required:se.boolean().optional(),defaultValue:se.string().describe("this is not optional because we need a value when the editor is first loaded")}),Ll=EP.array(),TP=se.object({name:se.string(),value:se.string()}),oS=TP.array(),Nl=se.object({name:se.string(),default:se.boolean().optional(),fixtures:Kf.array().optional()});bP(U);var ur={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},he=(l=>(l.PENDING="PENDING",l.RUNNING="RUNNING",l.PASSED="PASSED",l.FAILED="FAILED",l.CANCELLED="CANCELLED",l.RETRYING="RETRYING",l.WAITING_FOR_USER="WAITING_FOR_USER",l))(he||{}),Dl=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(Dl||{});var lt=U.string().pipe(U.coerce.date()).or(U.date()),Ya=U.object({id:U.string(),runKey:U.string(),organizationId:U.string(),executionType:U.nativeEnum(Mi).optional().default("WEB"),createdAt:lt,createdBy:U.string(),flake:U.boolean().nullish(),scheduledAt:lt.or(U.null()),startedAt:lt.or(U.null()),updatedAt:lt.nullish(),finishedAt:lt.or(U.null()),resolvedBaseUrl:U.string().nullish(),environmentName:U.string().nullish(),gitBranchName:U.string().nullish(),githubRepository:U.string().nullish(),gitlabProjectPath:U.string().nullish(),labels:U.array(U.string()).optional(),gitOriginUrl:U.string().nullish(),gitCommitSha:U.string().nullish(),gitCommitShaShort:U.string().nullish(),gitCommitAuthorName:U.string().nullish(),cliVersion:U.string().nullish(),section:U.nativeEnum(Dl).nullish(),status:U.nativeEnum(he),trigger:U.nativeEnum(ur),attempts:U.number(),runAttempts:U.array(U.object({id:U.string(),status:U.nativeEnum(he),startedAt:lt.or(U.null()),finishedAt:lt.or(U.null())})).optional(),videos:U.array(U.string()).optional(),failureReason:U.nativeEnum(me).nullish(),failureDetails:xl.nullish(),failureRecoveryDetails:U.record(U.string(),U.unknown()).nullish(),pipelineId:U.string().nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),quarantined:U.boolean().nullish().default(!1),quarantinedReason:U.string().nullish(),localTestId:U.string().nullish(),testId:U.string().nullish(),testName:U.string().nullish(),description:U.string().nullish(),test:U.object({name:U.string(),id:U.string()}).nullish().default(null),suiteId:U.string().nullish()}).openapi({ref:"RunMetadata"}),vP={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},kl=Ya.pick({...vP,test:!0}),iS=Ya.omit({failureReason:!0,failureDetails:!0,test:!0}),yp=Ya.extend({stepsSnapshot:U.array(U.record(U.unknown())).nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),test:U.object({name:U.string(),id:U.string(),description:U.string().nullish(),baseUrl:U.string().nullish(),advanced:Fo.nullish()}).nullish()}).merge(hp),aS=r=>r.includes("PASSED")&&r.includes("FAILED");var RP=Xa.object({id:Xa.string().uuid(),startedAt:lt.or(Xa.null()),finishedAt:lt.or(Xa.null()),status:Xa.nativeEnum(he)}).merge(Ka),_W=RP.array();var Fl=(o=>(o.JUNIT="junit",o.ALLURE="allure",o.ALLURE_JSON="allure-json",o.PLAYWRIGHT_JSON="playwright-json",o))(Fl||{});import{z as ct}from"zod";var AP=ct.object({id:ct.string(),status:ct.nativeEnum(he),trigger:ct.nativeEnum(ur),createdAt:lt,startedAt:lt.nullish(),finishedAt:lt.nullish(),gitCommitSha:ct.string().nullish(),gitCommitShaShort:ct.string().nullish(),gitCommitTimestamp:lt.nullish(),gitBranchName:ct.string().nullish(),gitOriginUrl:ct.string().nullish(),gitCommitMessage:ct.string().nullish(),gitCommitAuthorName:ct.string().nullish(),githubRepository:ct.string().nullish(),gitlabProjectPath:ct.string().nullish(),pipelineId:ct.string().nullish(),cliVersion:ct.string().nullish(),labels:ct.string().array().optional(),suite:ct.object({id:ct.string(),name:ct.string()}).nullish(),runs:ct.object({status:ct.nativeEnum(he)}).array()}).openapi({ref:"RunGroup"}),sS=AP.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:kl.array()});import{z as ft}from"zod";var wP=ft.object({type:ft.literal("TARGETING"),name:ft.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:$f.array(),pageState:ft.string().optional(),targetSource:ft.nativeEnum(Ln).optional(),targetUpdateTime:ft.string().optional()}),CP=ft.object({type:ft.literal("AI_LOCATION"),matched:ft.boolean(),pageState:ft.string().optional(),ragUsed:ft.boolean().optional(),thoughts:ft.string().optional()}),xP=ft.object({type:ft.literal("ASSERTION"),relevantElementsSerialized:ft.string().array().optional(),pageState:ft.string().optional(),ragUsed:ft.boolean().optional()}),lS=ft.discriminatedUnion("type",[wP,CP,xP]);function Ul(){return{details:[]}}import{z as rt}from"zod";var _P=rt.object({id:rt.string(),name:rt.string()}),GW=_P.merge(rt.object({createdAt:lt,createdBy:rt.string(),schedule:Oi,notification:Li,environment:rt.object({name:rt.string()}).nullish(),beforeTests:rt.object({id:rt.string()}).array().nullish(),afterTests:rt.object({id:rt.string()}).array().nullish()})),cS=rt.object({id:rt.string().uuid(),orgId:rt.string(),createdAt:lt,startedAt:lt.or(rt.null()),finishedAt:lt.or(rt.null()),status:rt.nativeEnum(he),trigger:rt.nativeEnum(ur),suite:rt.object({id:rt.string(),name:rt.string()}).nullish(),runs:Ya.array()}),VW=cS.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),uS=cS.extend({runs:kl.array()});import{z as dr}from"zod";import{cloneDeep as WW}from"lodash-es";import{z as Te}from"zod";var QW=Te.object({thoughts:Te.string(),subGoals:Te.object({instruction:Te.string()}).array()}),ZW=Te.object({thoughts:Te.string(),newPlanMarkdown:Te.string()}),eq=Te.object({thoughts:Te.string(),correct:Te.boolean(),failedActionIndex:Te.number().optional()}),IP=Te.object({type:Te.literal("PLANNING"),beforePlan:Te.string(),goalDecision:Te.string(),thoughts:Te.string()}),PP=Te.object({type:Te.literal("RUNNING"),stepDisplayName:Te.string(),status:Te.nativeEnum(Ae),results:mt.array()}),MP=Te.object({type:Te.literal("REVISING"),beforePlan:Te.string(),afterPlan:Te.string(),errString:Te.string(),diffs:Te.string(),thoughts:Te.string()}),OP=Te.object({type:Te.literal("SYSTEM"),message:Te.string()}),LP=Te.discriminatedUnion("type",[IP,PP,MP,OP]),dS=LP.array();var iq=dr.object({id:dr.string(),scheduledAt:dr.coerce.date().nullable(),startedAt:dr.coerce.date().nullable(),finishedAt:dr.coerce.date().nullable(),status:dr.nativeEnum(he),history:dS.nullable(),testPlan:dr.object({id:dr.string(),name:dr.string()}).nullable(),test:dr.object({id:dr.string(),name:dr.string()}).nullable()});import{z as Gt}from"zod";var Ep=Gt.object({content:Gt.string(),ids:Gt.string().array(),tokenLength:Gt.number()}),NP=Gt.object({chunks:Ep.array()}),vq=Gt.object({ids:Gt.string().array(),score:Gt.number(),tokenLength:Gt.number()}),Rq=NP.extend({description:Gt.string().describe("Input to pass to RAG engine"),tokenLimit:Gt.number()}),pS=Gt.object({ids:Gt.number().array()}),mS=Gt.object({indices:Gt.number().array()});var Mt=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()}),Mq=Mt.extend({chunks:Ep.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()}),DP=O.object({screenshotBase64AfterCommand:O.string(),urlAfterCommand:O.string(),serializedCommand:O.string(),elementInteracted:O.string().optional(),thoughts:O.string().optional()}),gS=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),source:jf.optional().catch(void 0),memory:O.discriminatedUnion("type",[dl,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional()}),hS=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()}),fS=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string().optional(),returnSchema:O.string().optional()}),kP=O.literal("NEGATED_CHECK"),SS=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),url:O.string(),contextChoice:Kd.optional(),memory:O.discriminatedUnion("type",[Bd,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional(),source:kP.optional()}),yS=O.object({command:wi}),ES=O.object({message:O.string()}),Tp=O.object({goal:O.string(),browserState:O.string(),startingScreenshot:O.string().optional(),screenshot:O.string(),url:O.string(),history:DP.array(),actionHint:O.string().optional(),lastError:O.string().optional()}),TS=O.object({results:Pl.array(),errorMessage:O.string(),errorStack:O.string().optional()}),bS=O.object({results:Pl.array(),goal:O.string(),errorMessage:O.string()}),vS=O.object({failedResults:Pl.array(),nextStepsSerialized:O.string().array(),currentUrl:O.string(),currentPageState:O.string(),currentScreenshot:O.string(),customInstructions:O.string().optional(),testDescription:O.string().optional()}),Oq=O.object({description:O.string(),type:O.union([O.literal("locator"),O.literal("assertion"),O.literal("ai-action")]),excerpt:O.string()}),RS=O.object({type:O.string(),browserContext:O.string(),currentStep:O.string(),screenshot:O.string()});import{z as Ja}from"zod";var Dq=Ja.object({goal:Ja.string()}),AS=Ja.object({keywords:Ja.array(Ja.string())});import{z as bp}from"zod";var Bl=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(Bl||{}),Uq=bp.nativeEnum(Bl),FP=bp.enum(["v1","v2"]),Bq=FP.or(bp.string().describe("for people with special configurations"));import{z as Ke}from"zod";var wS=Ke.object({attributesRequired:Ke.array(Ke.string()).optional(),textRequired:Ke.boolean().optional(),boundsRequired:Ke.boolean().optional()}),UP=Ke.object({id:Ke.number(),thoughts:Ke.string(),requirements:wS.optional(),additionalElements:Ke.object({id:Ke.number(),requirements:wS}).array().optional()}),CS=Ke.object({description:Ke.string(),screenXml:Ke.string(),screenshot:Ke.string()}),xS=Ke.object({assertion:Ke.string(),screenXml:Ke.string(),screenshot:Ke.string()}),BP=Ke.object({thoughts:Ke.string(),result:Ke.boolean(),relevantElements:Ke.array(Ke.number()).optional()});var _S=r=>!(!r.org_id||!r.user_id||!r.platform);import{z as Uo}from"zod";var IS=Uo.object({id:Uo.string().uuid(),skipped:Uo.boolean().optional(),envKey:Uo.string().optional().describe("key in the environment to save the result of this step to")}),vp=IS.merge(gl).extend({type:Uo.literal("REQUEST")}),Rp=IS.merge(hl).extend({type:Uo.literal("JAVASCRIPT")}),Ap=Uo.discriminatedUnion("type",[Rp,vp]);import{z as pr}from"zod";import{z as Bo}from"zod";var HP=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,_e=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 Ni=Bo.string().min(1).max(255).superRefine((r,e)=>{try{Vn(r)}catch(t){return e.addIssue({code:Bo.ZodIssueCode.custom,message:t.message,fatal:!0}),Bo.NEVER}});function Vn(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(HP))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Hl=Bo.preprocess(r=>r===null?"":r,Bo.union([Bo.string().url(),Bo.literal("")])).optional();var PS=pr.object({id:pr.string(),name:Ni,description:pr.string().optional().nullish(),baseUrl:Hl.nullish(),schemaVersion:pr.string(),advanced:pr.unknown().optional(),retries:pr.number(),envs:pr.array(Nl).nullish(),parameters:Ll.nullish()}),zP=pr.object({createdAt:pr.coerce.date(),updatedAt:pr.coerce.date(),schedule:Oi.nullish(),notification:Li.nullish(),createdBy:pr.string(),organizationId:pr.string()}),GP=PS.merge(zP),d2=GP.extend({steps:Ap.array()}),p2=PS.extend({steps:Ap.array()});import{z as Kt}from"zod";var MS=Kt.object({startedAt:Kt.coerce.date(),finishedAt:Kt.coerce.date(),status:Kt.nativeEnum(Ae),message:Kt.string().optional(),data:Kt.unknown().optional()}),VP=MS.merge(Rp).extend({type:Kt.literal("JAVASCRIPT")}),jP=MS.merge(vp).extend({type:Kt.literal("REQUEST")}),$P=Kt.discriminatedUnion("type",[VP,jP]),OS=Kt.object({startedAt:Kt.coerce.date(),finishedAt:Kt.coerce.date().nullish(),status:Kt.nativeEnum(he),results:$P.array(),failureReason:Kt.string().nullish(),failureDetails:xl.nullish()});import{z as Yt}from"zod";var WP=Yt.object({id:Yt.string(),organizationId:Yt.string(),createdAt:Yt.coerce.date(),updatedAt:Yt.coerce.date(),createdBy:Yt.string(),scheduledAt:Yt.coerce.date().nullish(),startedAt:Yt.coerce.date().nullish(),finishedAt:Yt.coerce.date().nullish(),status:Yt.nativeEnum(he),trigger:Yt.nativeEnum(ur),results:OS.array().nullish(),apiTestName:Yt.string().nullish(),apiTestPath:Yt.string().nullish(),apiTestId:Yt.string().nullish()}),v2=WP.pick({status:!0,startedAt:!0,finishedAt:!0});var Qa=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(Qa||{}),LS=3;function qP(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function wp(r){if(!qP(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 Cp(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return LS;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 Di=class{trackStepExecution(){}async flush(){}};import{parseString as KP,splitCookiesString as YP}from"set-cookie-parser";import{z as we}from"zod";var xp=we.object({name:we.string(),value:we.string(),url:we.string().optional(),domain:we.string().optional(),path:we.string().optional(),expires:we.number().default(Date.now()/1e3+60*60*24*365),httpOnly:we.boolean().optional(),secure:we.boolean().default(!0),sameSite:we.union([we.literal("Strict"),we.literal("Lax"),we.literal("None")]).default("None")});function zl(r,e){let t=[],n=YP(r);for(let o of n){let i=KP(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let l=xp.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(l);let c=[l.name,...Object.keys(l)].map(u=>u.toLowerCase()),s=o.match(/\b(\S+)=([^;]*)/g);if(s)for(let u of s){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...l,name:d,value:p})}}return t}var XP=we.object({origin:we.string(),localStorage:we.array(we.object({name:we.string(),value:we.string()}))}),JP=we.object({entries:we.record(we.string(),we.array(we.tuple([we.unknown(),we.unknown()]))),version:we.number().optional()}),Gl=we.object({cookies:xp.array().optional(),origins:XP.array().optional(),idb:we.record(we.string(),JP).optional().describe("key is db name")});function NS(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=xp.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 lM from"zod";import{v4 as $2}from"uuid";import{z as be}from"zod";import*as De from"zod";var DS=De.object({requiredText:De.string().optional(),requiredAttributes:De.record(De.string(),De.string()).optional(),requiredBounds:De.boolean().optional()}),QP=De.object({xPath:De.string(),requirements:DS.optional()}),ZP=De.object({type:De.literal("NATIVE"),bounds:De.number().array(),resolvedDescription:De.string(),xPath:De.string(),elementOnlySerializedXml:De.string(),requirements:DS.optional(),requiredRelatedElements:QP.array().optional()}),eM=De.object({type:De.literal("WEBVIEW"),resolvedDescription:De.string(),xPath:De.string(),browserCache:Nn.optional()}),kS=De.discriminatedUnion("type",[ZP,eM]);var ki=(s=>(s.AI_CHECK="AI_CHECK",s.TAP="TAP",s.TYPE="TYPE",s.PRESS="PRESS",s.OPEN_APP="OPEN_APP",s.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",s.JAVASCRIPT="JAVASCRIPT",s.ADB="ADB",s.STATE="STATE",s))(ki||{}),FS=(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))(FS||{}),US=be.discriminatedUnion("type",[be.object({type:be.literal("description"),description:be.string()}),be.object({type:be.literal("coordinates"),xPercent:be.number(),yPercent:be.number()})]),fn=be.object({id:be.string().uuid(),disableCache:be.boolean().optional()}),tM=fn.extend({type:be.literal("STATE")}),BS=be.object({target:kS}),_p=fn.extend({type:be.literal("TAP"),target:US,cache:BS.optional()}),Ip=fn.extend({type:be.literal("TYPE"),target:US.optional(),cache:BS.optional(),text:be.string()}),rM=fn.extend({type:be.literal("OPEN_NOTIFICATION_DRAWER")}),nM=fn.extend({type:be.literal("PRESS"),key:be.nativeEnum(FS)}),oM=fn.extend({type:be.literal("OPEN_APP"),packageName:be.string(),activityName:be.string().optional()}),iM=fn.extend({type:be.literal("AI_CHECK"),assertion:be.string(),timeoutSecs:be.number().optional()}),aM=fn.extend({type:be.literal("JAVASCRIPT"),code:be.string(),timeout:be.number().int().max(60).optional().describe("Max seconds for the code to complete")}),sM=fn.extend({type:be.literal("ADB"),command:be.string()}),HS=be.discriminatedUnion("type",[_p,Ip,nM,oM,rM,iM,aM,sM,tM]);var zS={type:!0,cache:!0},Fi=lM.discriminatedUnion("type",[_p.pick(zS),Ip.pick(zS)]),Z2=Object.values(ki).filter(r=>Fi.options.some(e=>e.shape.type.safeParse(r).success));var GS=Ga(Fi),VS=Va(Fi),eK=Tl(Fi);import{cloneDeep as nK}from"lodash-es";import iK from"truncate-json";import jn from"zod";import Za from"zod";var cM=Za.object({id:Za.string().uuid(),envKey:Za.string().optional()}),Sn=cM.extend({type:Za.literal("MOBILE_PRESET_STEP"),command:HS}),uK=Za.discriminatedUnion("type",[Sn]);import Ye from"zod";var Ui=Ye.object({startTime:Ye.number(),endTime:Ye.number().optional(),error:Ye.string().optional()});var Pp=Ui.extend({type:Ye.literal("SECTION"),name:Ye.string(),subSpans:Ye.lazy(()=>hM.array())}),uM=Ui.extend({type:Ye.literal("AI_LOCATOR_CALL"),result:Ye.object({serializedElement:Ye.string(),id:Ye.number(),thoughts:Ye.string()}).optional()}),dM=Ui.extend({type:Ye.literal("AI_ASSERTION_CALL"),result:Ye.object({thoughts:Ye.string(),result:Ye.boolean()}).optional()}),pM=Ui.extend({type:Ye.literal("WAIT_FOR_STABILITY"),reason:Ye.string().optional()}),mM=Ui.extend({type:Ye.literal("RESOLVE_TARGET_CACHE"),result:Ye.object({serializedElement:Ye.string()}).optional()}),gM=Ui.extend({type:Ye.literal("GET_EMULATOR_STATE")}),hM=Ye.discriminatedUnion("type",[Pp,uM,dM,pM,mM,gM]);var fM=jn.object({message:jn.string().optional(),startTime:jn.number(),endTime:jn.number(),status:jn.nativeEnum(Ae),trace:Pp.optional().catch(void 0),beforeSnapshot:jn.string().optional(),afterSnapshot:jn.string().optional()}),SM=Sn.merge(fM).extend({data:jn.unknown().optional().describe("output data from the step")}),Vl=SM;import ut from"zod";import{z as Ir}from"zod";import{z as je}from"zod";var Ot=je.object({id:je.string(),name:Ni,baseUrl:Hl,description:je.string().optional().nullish(),schemaVersion:je.string(),advanced:Fo,retries:je.number(),envs:je.array(Nl).nullish(),parameters:Ll.nullish(),disabled:je.boolean().optional(),labels:je.array(je.string()).optional().catch([])}),RK=je.enum(["INHERIT","ENABLED","DISABLED"]);var yM=Fo.extend({failureRecovery:je.boolean().or(je.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:je.boolean().or(je.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var AK=Ot.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:yM}),wK=Ot.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),EM=je.object({labels:je.array(je.string()).optional(),outputs:oS.nullish()}),mr=Ot.merge(EM),TM=je.object({createdAt:je.coerce.date(),updatedAt:je.coerce.date(),updatedBy:je.string().nullable(),schedule:Oi,notification:Li,createdBy:je.string(),organizationId:je.string(),folderId:je.string().nullable().optional()}),bM=Ot.merge(TM),CK=bM.merge(xi),jl=Ot.merge(xi),xK=Ot.merge(Mo);var jS="test",$S="module",vM="mobile-test",St=(t=>(t.TEST=`${jS}.yaml`,t.MODULE=`${$S}.yaml`,t))(St||{}),Se=(n=>(n.TEST=`momentic/${jS}`,n.MODULE=`momentic/${$S}`,n.MOBILE_TEST=`momentic/${vM}`,n))(Se||{}),NK=Ot.merge(Mo),Mp=Wt.extend({steps:Ir.array(Ir.record(Ir.string(),Ir.unknown())),schemaVersion:Ir.string()}),DK=Mp.extend({fileType:Ir.literal(Se.MODULE)}),kK=Ir.object({test:Ir.string().describe("YAML for the test, including metadata and steps"),modules:Ir.record(Ir.string(),Ir.string()).describe("Map of module name to YAML for the module")});var es=(t=>(t.USWest1="us-west1",t.EUNorth1="eu-north1",t))(es||{});var RM=ut.object({disableDefaultWebviewAccessibilityTree:ut.boolean().optional(),autoGrantPermissions:ut.boolean().optional()}),Op=RM.extend({region:ut.nativeEnum(es).optional()}),ts=ut.object({retries:ut.number().optional().describe("number of retries to run"),defaultChannel:ut.string().optional().describe("default channel to use"),defaultTag:ut.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:ut.string().optional(),emulator:Op.optional()}),Lp=ut.object({id:ut.string().uuid(),description:ut.string(),schemaVersion:ut.string(),settings:ts.optional()}),AM=Lp.merge(ut.object({steps:ut.array(Sn)})),WS=ut.object({fileType:ut.literal(Se.MOBILE_TEST)}).merge(AM),VK=ut.object({name:ut.string(),steps:ut.array(Sn).optional(),settings:ts.optional()});var sY=new Set(Object.values(qe));var wM={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"},lY={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:[]},cY={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."},uY={AI_CHECK:"AI check",TAP:"Tap",TYPE:"Type",PRESS:"Press",OPEN_APP:"Open app",JAVASCRIPT:"JavaScript",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",ADB:"ADB command",STATE:"Debug state"},dY={AI_CHECK:"Ask AI to verify whether something is true on the screen.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a button on the device or on the screen.",OPEN_APP:"Open an app on the device.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device."};import CM from"semver";import{z as xM}from"zod";var hY=xM.string().refine(r=>CM.valid(r),{message:"must be a valid semver string"});import{Faker as yY,en as EY}from"@faker-js/faker";import{z as D}from"zod";var Bi=55555,bY=D.object({body:D.string(),to:D.string(),from:D.string()}),vY=D.object({from:D.string().optional(),to:D.string(),timeout:D.number().optional(),beforeDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional()}),RY=D.object({to:D.string().email(),from:D.string(),subject:D.string(),body:D.string(),html:D.string().optional()}),AY=D.object({inbox:D.string().transform(r=>r.toLowerCase()),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),timeout:D.number().optional(),trimWhitespace:D.boolean().optional()}),wY=D.object({inbox:D.string(),limit:D.number().optional(),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),trimWhitespace:D.boolean().optional()});var $l=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))($l||{}),qS=D.object({body:D.string().nullish(),status:D.number().optional(),headers:D.array(D.tuple([D.string(),D.string()])).optional()}),_M=D.object({url:D.string(),options:D.object({method:D.string(),body:D.string().nullish(),headers:D.array(D.tuple([D.string(),D.string()])).optional()}).optional()}).optional(),IM=D.object({body:D.string().nullish(),options:D.object({status:D.number(),statusText:D.string().optional(),headers:D.array(D.tuple([D.string(),D.string()])).optional()}).optional()}).optional(),KS=D.object({result:D.unknown(),variableUpdates:D.record(D.string(),D.unknown()).optional(),persistentVariableUpdates:D.record(D.string(),D.unknown()).optional(),error:D.string().optional(),success:D.boolean()}),CY=D.object({id:D.string().optional(),orgId:D.string(),momenticLambdaAuthHash:D.string(),code:D.string(),fragment:D.boolean(),state:D.object({env:D.record(D.string(),D.unknown()),request:_M,response:IM,additionalBindings:D.record(D.string(),D.unknown()).optional()}),timeoutMs:D.number().optional(),disallowVariableUpdates:D.boolean().optional(),responseSerialization:D.nativeEnum($l).optional()}),$n=15e3;import*as Lt from"zod";import{extendZodWithOpenApi as PM}from"zod-openapi";PM(Lt);var MM=Lt.object({url:Lt.string(),lineNumber:Lt.number(),columnNumber:Lt.number()}).openapi({ref:"CodeLocation"}),Wl=Lt.object({timestamp:Lt.number(),text:Lt.string(),type:Lt.string(),tabIndex:Lt.number(),args:Lt.unknown().array().optional(),url:Lt.string().optional(),location:MM.optional()}).openapi({ref:"ConsoleLog"}),YS=Wl.array(),OM=YS.array();import*as Dp from"zod";import{extendZodWithOpenApi as QM}from"zod-openapi";import{z as P}from"zod";var LM=P.object({name:P.string(),version:P.string(),comment:P.string().optional()}),NM=P.object({name:P.string(),version:P.string(),comment:P.string().optional()}),DM=P.object({onContentLoad:P.number().optional(),onLoad:P.number().optional(),comment:P.string().optional()}),JS=P.object({startedDateTime:P.string(),id:P.string(),title:P.string().optional(),pageTimings:DM,comment:P.string().optional()}),kM=P.array(JS),FM=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()}),QS=P.array(FM),UM=P.object({name:P.string(),value:P.string(),comment:P.string().optional()}),ZS=P.array(UM),BM=P.object({name:P.string(),value:P.string(),comment:P.string().optional()}),HM=P.array(BM),zM=P.object({name:P.string(),value:P.string().optional(),fileName:P.string().optional(),contentType:P.string().optional(),comment:P.string().optional()}),GM=P.array(zM),VM=P.object({mimeType:P.string(),params:GM,text:P.string(),comment:P.string().optional()}),jM=P.object({method:P.string(),url:P.string(),httpVersion:P.string().optional(),cookies:QS,headers:ZS,queryString:HM,postData:VM.optional(),headersSize:P.number().optional(),bodySize:P.number().optional(),comment:P.string().optional()}),$M=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()}),WM=P.object({status:P.number(),statusText:P.string(),httpVersion:P.string().optional(),cookies:QS,headers:ZS,content:$M,redirectURL:P.string().optional(),headersSize:P.number().optional(),bodySize:P.number().optional(),comment:P.string().optional(),_mocked:P.boolean().optional()}),XS=P.object({expires:P.string().optional(),lastAccess:P.string(),eTag:P.string(),hitCount:P.number(),comment:P.string().optional()}),qM=P.object({beforeRequest:XS.optional(),afterRequest:XS.optional(),comment:P.string().optional()}),KM=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()}),ey=P.object({pageref:P.string().optional(),startedDateTime:P.string(),time:P.number().optional(),request:jM,response:WM.optional(),cache:qM.optional(),timings:KM,serverIPAddress:P.string().optional(),connection:P.string().optional(),comment:P.string().optional(),_resourceType:P.string().optional()}),YM=P.array(ey),XM=P.object({version:P.string().default("1.1"),creator:LM.optional(),browser:NM.optional(),pages:kM.optional(),entries:YM,comment:P.string().optional()}),JM=P.object({log:XM}),ty=P.record(P.string(),JS),ry=P.record(P.string(),ey);function Np(r,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(r).sort((t,n)=>new Date(t.startedDateTime).getTime()-new Date(n.startedDateTime).getTime()),entries:Object.values(e).sort((t,n)=>new Date(t.startedDateTime).getTime()-new Date(n.startedDateTime).getTime())}}}QM(Dp);var ZM=Dp.object({logsPerPage:Wl.array().array(),harPages:ty.optional(),harEntries:ry.optional()}).openapi({ref:"DebugData"});var rs=class{async getConsoleLogsForRunAttempt(e,t,n){}async getNetworkLogsForRunAttempt(e,t,n){}async getHtmlSnapshot(e,t){}async getA11yTreeSnapshot(e,t){}async getScreenshot(e,t){}async storeConsoleLogsForRunAttempt(e,t,n,o){}async storeNetworkLogsForRunAttempt(e,t,n,o){}async storeScreenshot(e,t,n){}async storeHtmlSnapshot(e,t,n){}};var Ie=class extends Error{constructor(e,t={}){super(e,t),this.name="ValidationError"}};var ql=class extends Error{constructor(e,t,n,o={}){super(`The ${n} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};function ny(r){for(let e of Object.values(me))if(r.includes(e))return e}var C=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(me))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}}},Hi=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},$r=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
|
|
3
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="bf42114a-a45b-5cd4-a429-d5942e4bdd43")}catch(e){}}();
|
|
4
|
+
var V_=Object.defineProperty;var je=(r,e)=>()=>(r&&(e=r(r=0)),e);var j_=(r,e)=>{for(var t in e)V_(r,t,{get:e[t],enumerable:!0})};var ev,tv=je(()=>{"use strict";ev=typeof globalThis=="object"?globalThis:global});var rv=je(()=>{"use strict";tv()});var nv=je(()=>{"use strict";rv()});var Cn,eg=je(()=>{"use strict";Cn="1.9.0"});function wk(r){var e=new Set([r]),t=new Set,n=r.match(ov);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(c){return c===r};function i(l){return t.add(l),!1}function a(l){return e.add(l),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var s=c.match(ov);if(!s)return i(c);var u={major:+s[1],minor:+s[2],patch:+s[3],prerelease:s[4]};return u.prerelease!=null||o.major!==u.major?i(c):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(c):i(c):o.minor<=u.minor?a(c):i(c)}}var ov,iv,av=je(()=>{"use strict";eg();ov=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;iv=wk(Cn)});function ua(r,e,t,n){var o;n===void 0&&(n=!1);var i=ks[Ds]=(o=ks[Ds])!==null&&o!==void 0?o:{version:Cn};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!==Cn){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Cn);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Cn+"."),!0}function xn(r){var e,t,n=(e=ks[Ds])===null||e===void 0?void 0:e.version;if(!(!n||!iv(n)))return(t=ks[Ds])===null||t===void 0?void 0:t[r]}function da(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Cn+".");var t=ks[Ds];t&&delete t[r]}var Ck,Ds,ks,Fs=je(()=>{"use strict";nv();eg();av();Ck=Cn.split(".")[0],Ds=Symbol.for("opentelemetry.js.api."+Ck),ks=ev});function Us(r,e,t){var n=xn("diag");if(n)return t.unshift(e),n[r].apply(n,_k([],xk(t),!1))}var xk,_k,sv,lv=je(()=>{"use strict";Fs();xk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},_k=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))},sv=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 Us("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Us("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Us("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Us("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Us("verbose",this._namespace,e)},r}()});var Be,ou=je(()=>{"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"})(Be||(Be={}))});function cv(r,e){r<Be.NONE?r=Be.NONE:r>Be.ALL&&(r=Be.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",Be.ERROR),warn:t("warn",Be.WARN),info:t("info",Be.INFO),debug:t("debug",Be.DEBUG),verbose:t("verbose",Be.VERBOSE)}}var uv=je(()=>{"use strict";ou()});var Ik,Mk,Pk,on,Bs=je(()=>{"use strict";lv();uv();ou();Fs();Ik=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Mk=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))},Pk="diag",on=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var l=xn("diag");if(l)return l[o].apply(l,Mk([],Ik(i),!1))}}var t=this,n=function(o,i){var a,l,c;if(i===void 0&&(i={logLevel:Be.INFO}),o===t){var s=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((a=s.stack)!==null&&a!==void 0?a:s.message),!1}typeof i=="number"&&(i={logLevel:i});var u=xn("diag"),d=cv((l=i.logLevel)!==null&&l!==void 0?l:Be.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 ua("diag",d,t,!0)};t.setLogger=n,t.disable=function(){da(Pk,t)},t.createComponentLogger=function(o){return new sv(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 dv,pv=je(()=>{"use strict";dv=Symbol("BaggageEntryMetadata")});function tg(r){return typeof r!="string"&&(Ok.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:dv,toString:function(){return r}}}var Ok,mv=je(()=>{"use strict";Bs();pv();Ok=on.instance()});function rg(r){return Symbol.for(r)}var Lk,ng,og=je(()=>{"use strict";Lk=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}(),ng=new Lk});function sg(){return ag}var ri,Nk,iu,Dk,kk,Fk,Uk,ig,Bk,zk,Hk,ag,Gk,Vk,jk,$k,Wk,qk,Kk,lg=je(()=>{"use strict";ri=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)}}(),Nk=function(){function r(){}return r.prototype.createGauge=function(e,t){return Vk},r.prototype.createHistogram=function(e,t){return jk},r.prototype.createCounter=function(e,t){return Gk},r.prototype.createUpDownCounter=function(e,t){return $k},r.prototype.createObservableGauge=function(e,t){return qk},r.prototype.createObservableCounter=function(e,t){return Wk},r.prototype.createObservableUpDownCounter=function(e,t){return Kk},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),iu=function(){function r(){}return r}(),Dk=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(iu),kk=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(iu),Fk=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(iu),Uk=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(iu),ig=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),Bk=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ig),zk=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ig),Hk=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(ig),ag=new Nk,Gk=new Dk,Vk=new Fk,jk=new Uk,$k=new kk,Wk=new Bk,qk=new zk,Kk=new Hk});var rr,gv=je(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(rr||(rr={}))});var Yk,Xk,hv,fv=je(()=>{"use strict";og();Yk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Xk=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))},hv=function(){function r(){}return r.prototype.active=function(){return ng},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,Xk([n],Yk(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var Jk,Qk,cg,Zk,Sv,yv=je(()=>{"use strict";fv();Fs();Bs();Jk=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Qk=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))},cg="context",Zk=new hv,Sv=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return ua(cg,e,on.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,Qk([e,t,n],Jk(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return xn(cg)||Zk},r.prototype.disable=function(){this._getContextManager().disable(),da(cg,on.instance())},r}()});var pa,Ev=je(()=>{"use strict";yv();pa=Sv.getInstance()});var z,Tv=je(()=>{"use strict";Bs();z=on.instance()});var e0,bv,vv=je(()=>{"use strict";lg();e0=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return ag},r}(),bv=new e0});var ug,Rv,Av=je(()=>{"use strict";vv();Fs();Bs();ug="metrics",Rv=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return ua(ug,e,on.instance())},r.prototype.getMeterProvider=function(){return xn(ug)||bv},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){da(ug,on.instance())},r}()});var au,wv=je(()=>{"use strict";Av();au=Rv.getInstance()});var Ie=je(()=>{"use strict";mv();og();ou();lg();gv();Ev();Tv();wv()});var ka=(r,e)=>{},$d=!1;try{let r=await import("@sentry/node");ka=r.captureException,r.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:0}),$d=!0}catch{}import{Command as JG,Option as Qt}from"@commander-js/extra-typings";import{execSync as QG}from"child_process";var Fa=!!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{existsSync as gL,statSync as hL}from"fs";import{z as Cf}from"zod";var pV=Cf.object({input:Cf.string()});import{z as dt}from"zod";var hV=dt.object({srcs:dt.array(dt.string()),urls:dt.array(dt.string()),desiredSrc:dt.string().optional(),desiredUrl:dt.string().optional()}),xf=dt.object({srcRegex:dt.string().optional(),urlRegex:dt.string().optional()}),_f=dt.object({x:dt.number(),y:dt.number(),correlation:dt.number()}),fV=dt.object({searchImageBase64String:dt.string(),pageImageBase64String:dt.string(),id:dt.string().uuid(),timeoutMs:dt.number().max(1e4).min(0).optional()});import{z as L}from"zod";import*as F from"zod";import{extendZodWithOpenApi as $_}from"zod-openapi";$_(F);var kn=(l=>(l.AI="AI",l.AI_HEALED="AI_HEALED",l.CLICK_TO_FIND="CLICK_TO_FIND",l.XY_PERCENT="XY_PERCENT",l.RECORDING="RECORDING",l.USER_CSS_SELECTOR="USER_CSS_SELECTOR",l.HEURISTIC_HEALED="HEURISTIC_HEALED",l))(kn||{}),W_=F.object({mPathSelectorTokens:F.string().array(),frameSrcRegex:F.string().optional(),frameUrlRegex:F.string().optional(),indices:F.number().array()}),Wd=F.object({result:F.number(),traceId:F.string()}).array(),yl=F.object({type:F.literal("GCS_TRACES"),traces:Wd}),If=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()}),q_=F.object({selectors:F.string().array(),requirements:If.optional()}),Fn=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()),tagName:F.string(),expandShadowRoot:F.boolean().optional(),classNames:F.string().array(),nthChild:F.number()}).array().optional(),generatedSelectors:F.string().array().optional(),requirements:If.optional(),additionalElements:q_.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:W_.optional(),inputDescription:F.string().optional().describe("the description that generated this cache"),targetSource:F.nativeEnum(kn).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:yl.optional()}).openapi({ref:"ElementTargetCache"});function El(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}function qd(r){r.serializedHtml=void 0,r.nodeOnlySerializedHtml=void 0,r.screenshotUrl=void 0,r.boundingBox=void 0,r.hybridSelector=void 0,r.generatedSelectors=void 0,r.id=-1}var K_=F.object({type:F.literal("description"),elementDescriptor:F.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),Y_=F.object({x:F.number(),y:F.number()}),X_=F.object({type:F.literal("coordinates"),pixels:Y_}).openapi({ref:"CoordinatesTarget"});function Un(r){return r.type==="description"}function Vr(r){return r.type==="coordinates"}var xt=F.discriminatedUnion("type",[K_,X_]).openapi({ref:"ElementTarget"});function Kd(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function _t(r){if(!r)return"";switch(r.type){case"description":return r.elementDescriptor;case"coordinates":return`x: ${r.pixels.x}, y: ${r.pixels.y}`}}function Tl(r){return yl.safeParse(r).success}import{v4 as be}from"uuid";import*as v from"zod";import{extendZodWithOpenApi as oI}from"zod-openapi";import{z as oe}from"zod";import{extendZodWithOpenApi as J_}from"zod-openapi";import{z as vi}from"zod";var Yd=vi.object({result:vi.boolean(),traceId:vi.string()}).array(),Xd=vi.object({type:vi.literal("GCS_TRACES"),traces:Yd}),Jd=vi.object({memory:Xd.optional()});J_(oe);var Mf=oe.object({plan:oe.string().optional(),evidence:oe.string().optional(),thoughts:oe.string(),result:oe.boolean(),relevantElements:oe.array(oe.number()).optional(),updatedMemory:Yd.optional()}),Bn=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Bn||{});var Q_=oe.object({type:oe.literal("ELEMENT_NAME"),negated:oe.boolean().optional(),operation:oe.nativeEnum(Bn),value:oe.string()}).openapi({ref:"ElementNameAssertion"}),Z_=oe.object({type:oe.literal("ELEMENT_STYLE"),negated:oe.boolean().optional(),operation:oe.nativeEnum(Bn),property:oe.string(),value:oe.string()}).openapi({ref:"ElementStyleAssertion"}),eI=oe.object({type:oe.literal("ELEMENT_CONTENT"),negated:oe.boolean().optional(),operation:oe.nativeEnum(Bn),value:oe.string()}).openapi({ref:"ElementContentAssertion"}),tI=oe.object({type:oe.literal("ELEMENT_ATTRIBUTE"),negated:oe.boolean().optional(),operation:oe.nativeEnum(Bn),attr:oe.string(),value:oe.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Ri=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Ri||{}),rI=oe.object({type:oe.literal("ELEMENT_EXISTENCE"),negated:oe.boolean().optional(),condition:oe.nativeEnum(Ri).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Pf=oe.discriminatedUnion("type",[eI,tI,rI,Q_,Z_]).openapi({ref:"ManualElementAssertion"});var nI=oe.object({type:oe.literal("CONTENT"),negated:oe.boolean().optional(),value:oe.string()}).openapi({ref:"PageContentAssertion"}),Of=oe.discriminatedUnion("type",[nI]).openapi({ref:"ManualPageAssertion"});import Bt from"zod";var Qd=Bt.discriminatedUnion("type",[Bt.object({type:Bt.literal("SUBSTRING"),url:Bt.string()}),Bt.object({type:Bt.literal("GLOB"),glob:Bt.string()}),Bt.object({type:Bt.literal("REGEX"),regex:Bt.string()}),Bt.object({type:Bt.literal("DOMAIN"),domain:Bt.string()})]),Ua=Bt.object({urlMatcher:Qd,method:Bt.string().optional()});import{z as Te}from"zod";var bl=Te.object({url:Te.string(),method:Te.union([Te.literal("GET"),Te.literal("POST"),Te.literal("PUT"),Te.literal("DELETE"),Te.literal("PATCH")]),headers:Te.record(Te.string(),Te.string()).optional(),params:Te.record(Te.string(),Te.string()).optional(),body:Te.string().optional(),timeout:Te.number().int().optional().describe("Max seconds to wait for the request to complete")}),Lf=Te.object({url:Te.string(),headers:Te.record(Te.string(),Te.string()).optional(),query:Te.string(),variables:Te.string().optional(),timeout:Te.number().int().optional().describe("Max seconds to wait for the request to complete")}),vl=Te.object({code:Te.string(),fragment:Te.boolean().optional(),environment:Te.union([Te.literal("NODE"),Te.literal("BROWSER")]).optional().describe("default NODE"),timeout:Te.number().int().max(60).optional().describe("Max seconds for the code to complete")});var $e=(G=>(G.AI_EXTRACT="AI_EXTRACT",G.AI_ASSERTION="AI_ASSERTION",G.AUTH_LOAD="AUTH_LOAD",G.AUTH_SAVE="AUTH_SAVE",G.BLUR="BLUR",G.CAPTCHA="CAPTCHA",G.CLICK="CLICK",G.COOKIE="COOKIE",G.COPY="COPY",G.DIALOG="DIALOG",G.DRAG="DRAG",G.ELEMENT_CHECK="ELEMENT_CHECK",G.FILE_UPLOAD="FILE_UPLOAD",G.FOCUS="FOCUS",G.GO_BACK="GO_BACK",G.GO_FORWARD="GO_FORWARD",G.HOVER="HOVER",G.JAVASCRIPT="JAVASCRIPT",G.LOCAL_STORAGE="LOCAL_STORAGE",G.MOUSE_DRAG="MOUSE_DRAG",G.NAVIGATE="NAVIGATE",G.NEW_TAB="NEW_TAB",G.PAGE_CHECK="PAGE_CHECK",G.PASTE="PASTE",G.PRESS="PRESS",G.KEY_DOWN="KEY_DOWN",G.KEY_UP="KEY_UP",G.REFRESH="REFRESH",G.REQUEST="REQUEST",G.GRAPHQL_REQUEST="GRAPHQL_REQUEST",G.SCROLL_DOWN="SCROLL_DOWN",G.SCROLL_UP="SCROLL_UP",G.SCROLL_LEFT="SCROLL_LEFT",G.SCROLL_RIGHT="SCROLL_RIGHT",G.SELECT_OPTION="SELECT_OPTION",G.SWITCH_TAB="TAB",G.TYPE="TYPE",G.VISUAL_DIFF="VISUAL_DIFF",G.WAIT="WAIT",G.WAIT_FOR_URL="WAIT_FOR_URL",G.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",G.AWAIT_LISTENER="AWAIT_LISTENER",G.RECORD_REQUESTS="RECORD_REQUESTS",G.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",G.SET_HEADER="SET_HEADER",G.MOCK_ROUTE="MOCK_ROUTE",G.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",G.OFFLINE_MODE="OFFLINE_MODE",G.SUCCESS="SUCCESS",G))($e||{});oI(v);var $=v.object({thoughts:v.string().optional(),id:v.string().uuid().describe("unique identifier to this step, used for step cache")}),lr=v.object({useSelector:v.boolean().optional(),force:v.boolean().optional(),disableCache:v.boolean().optional().describe("disable element caching for this step"),iframeUrl:v.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Zt=v.object({target:Fn}).optional().openapi({ref:"SingleTargetCache"});function Nf(r){return Zt.safeParse(r).success}var Al=v.object({loadTimeout:v.number().int().max(60).optional().describe("Max seconds for the page to load")}),ep=$.merge(Al).merge(v.object({type:v.literal("NAVIGATE"),url:v.string()})).openapi({ref:"NavigateCommand"}),wl=lr.merge(v.object({cache:Zt})),zn=$.merge(wl.merge(v.object({target:xt.optional(),type:v.literal("SCROLL_UP"),deltaY:v.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Hn=$.merge(wl.merge(v.object({target:xt.optional(),type:v.literal("SCROLL_DOWN"),deltaY:v.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Ai=$.merge(wl.merge(v.object({target:xt.optional(),type:v.literal("SCROLL_LEFT"),deltaX:v.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),wi=$.merge(wl.merge(v.object({target:xt.optional(),type:v.literal("SCROLL_RIGHT"),deltaX:v.number().optional()}))).openapi({ref:"ScrollRightCommand"}),HV=v.discriminatedUnion("type",[zn,Hn,Ai,wi]).openapi({ref:"AllScrollCommands"}),iI=$.merge(v.object({type:v.literal("DIALOG"),action:v.union([v.literal("ACCEPT"),v.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),aI=$.merge(v.object({type:v.literal("WAIT"),delay:v.number()})).openapi({ref:"WaitCommand"}),sI=v.object({caseInsensitive:v.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:v.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:v.number().int().optional().describe("Max seconds to wait for the URL to match")}),tp=$.extend({type:v.literal("WAIT_FOR_URL"),matcher:Qd}).merge(sI).openapi({ref:"WaitUrlCommand"}),lI=$.merge(Al).merge(v.object({type:v.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),cI=$.merge(v.object({type:v.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),uI=$.merge(v.object({type:v.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),dI=$.extend({type:v.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),pI=$.extend({type:v.literal("AUTH_LOAD"),storageState:v.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),rp=$.merge(lr).extend({type:v.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),mI=$.extend({type:v.literal("COPY"),value:v.string()}).openapi({ref:"CopyCommand"}),gI=$.extend({type:v.literal("PASTE")}).openapi({ref:"PasteCommand"}),np=$.merge(vl).extend({type:v.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Co=$.merge(lr).extend({type:v.literal("CLICK"),target:xt,doubleClick:v.boolean().optional(),rightClick:v.boolean().optional(),waitForDownload:v.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:v.number().optional(),downloadTimeoutMs:v.number().optional(),cache:Zt,relativePosition:v.object({x:v.number(),y:v.number()}).optional()}).openapi({ref:"ClickCommand"}),op=v.object({fromTarget:Fn.optional(),toTarget:Fn.optional()}),Ba=$.merge(lr).merge(v.object({type:v.literal("DRAG"),fromTarget:xt,toTarget:xt,steps:v.number().optional(),hoverSeconds:v.number().optional().describe("Seconds to hover the object before dropping"),cache:op.optional()})).openapi({ref:"DragCommand"}),za=$.merge(lr).merge(v.object({type:v.literal("MOUSE_DRAG"),target:xt.optional(),deltaX:v.string().describe("pixels to move horizontally, can be template"),deltaY:v.string().describe("pixels to move vertically, can be template"),steps:v.number().optional(),cache:Zt})).openapi({ref:"MouseDragCommand"}),xo=$.merge(lr).merge(v.object({type:v.literal("HOVER"),target:xt,cache:Zt})).openapi({ref:"HoverCommand"}),Ha=$.merge(lr).merge(v.object({type:v.literal("FOCUS"),target:xt,cache:Zt})).openapi({ref:"FocusCommand"}),Ga=$.merge(lr).extend({type:v.literal("BLUR"),target:xt.optional(),cache:Zt}).openapi({ref:"BlurCommand"}),hI=v.object({type:v.literal("URL"),url:v.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),fI=v.object({type:v.literal("USER_FILE"),name:v.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),SI=$.extend({type:v.literal("FILE_UPLOAD"),fileSource:v.discriminatedUnion("type",[hI,fI]),filename:v.string().optional()}).openapi({ref:"FileUploadCommand"}),yI=v.discriminatedUnion("type",[v.object({type:v.literal("VALUE"),value:v.string()}),v.object({type:v.literal("LABEL"),label:v.string()}),v.object({type:v.literal("INDEX"),index:v.coerce.string()})]),_o=$.merge(lr).extend({type:v.literal("SELECT_OPTION"),target:xt,cache:Zt,choice:yI.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),ip=v.union([v.literal("MULTIMODAL"),v.literal("VISION_ONLY")]),Ci=$.merge(v.object({type:v.literal("AI_ASSERTION"),assertion:v.string(),disableCache:v.boolean().optional(),iframeUrl:v.string().optional(),contextChoice:ip.optional(),timeout:v.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Jd.optional()})).openapi({ref:"AIAssertionCommand"}),jr=5,ap=600,Io=$.merge(lr).extend({type:v.literal("ELEMENT_CHECK"),target:xt,assertion:Pf,cache:Zt.or(Jd).optional(),timeout:v.number().int().min(0).max(ap).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),sp=$.extend({type:v.literal("PAGE_CHECK"),assertion:Of,iframeUrl:v.string().optional().describe("url or url regex for the iframe"),timeout:v.number().int().min(0).max(ap).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),EI=$.merge(v.object({type:v.literal("AI_EXTRACT"),goal:v.string(),schema:v.string().optional(),envKey:v.string().optional(),disableCache:v.boolean().optional(),iframeUrl:v.string().optional()})).openapi({ref:"AIExtractCommand"}),TI=v.object({clearContent:v.boolean().optional(),forceClearContent:v.boolean().optional(),delay:v.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:v.boolean().optional(),pressEnter:v.boolean().optional()}),Df=25,Mo=$.merge(lr).merge(TI).extend({type:v.literal("TYPE"),target:xt.optional(),value:v.string(),cache:Zt}).openapi({ref:"TypeCommand"}),lp=$.merge(v.object({type:v.literal("PRESS"),value:v.string(),repeat:v.number().optional(),convertMeta:v.boolean().optional(),delayMs:v.number().optional()})).openapi({ref:"PressCommand"}),bI=$.merge(v.object({type:v.literal("KEY_DOWN"),value:v.string(),convertMeta:v.boolean().optional()})).openapi({ref:"KeyDownCommand"}),vI=$.merge(v.object({type:v.literal("KEY_UP"),value:v.string(),convertMeta:v.boolean().optional()})).openapi({ref:"KeyUpCommand"}),RI=v.object({type:v.literal("SUBSTRING"),substring:v.string()}),AI=v.object({type:v.literal("REGEX"),pattern:v.string()}),wI=v.object({type:v.literal("INDEX"),index:v.coerce.string()}),CI=v.discriminatedUnion("type",[RI,AI,wI]),xI=$.merge(Al).merge(v.object({type:v.literal("TAB"),action:CI})).openapi({ref:"TabCommand"}),cp=$.merge(Al).merge(v.object({type:v.literal("NEW_TAB"),url:v.string()})).openapi({ref:"NewTabCommand"}),_I=$.merge(v.object({type:v.literal("COOKIE"),value:v.string()})).openapi({ref:"CookieCommand"}),II=$.merge(v.object({type:v.literal("LOCAL_STORAGE"),key:v.string(),value:v.string()})).openapi({ref:"LocalStorageCommand"}),MI=$.extend({type:v.literal("REQUEST")}).merge(bl).openapi({ref:"RequestCommand"}),PI=$.extend({type:v.literal("GRAPHQL_REQUEST")}).merge(Lf).openapi({ref:"GraphQLRequestCommand"}),OI=$.merge(v.object({type:v.literal("SUCCESS"),condition:Ci.optional()})).openapi({ref:"SuccessCommand"}),LI=$.merge(v.object({type:v.literal("FAILURE")})).openapi({ref:"FailureCommand"}),NI=v.object({data:v.string().describe("location at which to find a jpg"),width:v.number(),height:v.number()}),Va=$.merge(lr).merge(v.object({type:v.literal("VISUAL_DIFF"),threshold:v.number().optional().describe("default 0.1"),target:xt.optional(),screenshot:NI.optional(),cache:Zt})).openapi({ref:"VisualDiffCommand"}),DI=$.merge(v.object({type:v.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Ua,key:v.string()})).openapi({ref:"RegisterRequestListenerCommand"}),kI=$.merge(v.object({type:v.literal("AWAIT_LISTENER"),key:v.string(),timeout:v.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),FI=$.merge(v.object({type:v.literal("RECORD_REQUESTS"),requestMatcher:Ua,key:v.string()})).openapi({ref:"RecordRequestsCommand"}),UI=$.merge(v.object({type:v.literal("GET_RECORDED_REQUESTS"),key:v.string()})).openapi({ref:"GetRecordedRequestsCommand"}),BI=$.merge(v.object({type:v.literal("SET_HEADER"),name:v.string(),value:v.string(),requestMatcher:Ua.optional()})).openapi({ref:"SetHeaderCommand"}),zI=$.merge(v.object({type:v.literal("MOCK_ROUTE"),requestMatcher:Ua,responseGenerator:v.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:v.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:v.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"})),HI=$.merge(v.object({type:v.literal("REMOVE_ROUTE_MOCK"),key:v.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),GI=$.merge(v.object({type:v.literal("OFFLINE_MODE"),enable:v.boolean()})).openapi({ref:"OfflineModeCommand"}),kf=v.discriminatedUnion("type",[Co,Mo,lp,bI,vI,_o,ep,Hn,zn,Ci,xo,aI,OI]),VI=v.discriminatedUnion("type",[EI,pI,dI,rp,_I,mI,iI,Ba,Io,SI,cI,uI,np,II,za,cp,sp,gI,lI,MI,PI,Ai,wi,xI,Va,Ha,Ga,tp,DI,kI,FI,UI,BI,zI,HI,GI]),xi=v.discriminatedUnion("type",[...kf.options,...VI.options]).openapi({ref:"Command"}),Cl=v.discriminatedUnion("type",[...kf.options,LI]);function fn(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:be(),type:r};break;case"AUTH_LOAD":{e={id:be(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:be(),type:r,goal:""};break;case"DIALOG":e={id:be(),type:r,action:"DISMISS"};break;case"DRAG":e={id:be(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:be(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:be(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:be(),type:r,delay:1};break;case"BLUR":e={id:be(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:be(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:be(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:be(),type:r,value:""};break;case"SELECT_OPTION":e={id:be(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:be(),type:r,url:""};case"TAB":e={id:be(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:be(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:be(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:be(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:be(),type:r,code:""};break;case"AI_ASSERTION":e={id:be(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:be(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:be(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:be(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:be(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:be(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:be(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:be(),type:r,key:""};break}case"SET_HEADER":{e={id:be(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:be(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:be(),type:r};break}case"OFFLINE_MODE":{e={id:be(),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 Ff(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 jI}from"zod";var WV=jI.discriminatedUnion("type",[Ga,rp,Co,Ba,Ha,xo,za,zn,Hn,Ai,wi,_o,Mo,Va,Io]);function Uf(r){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(r)}import{z as $I}from"zod";import{z as Gn}from"zod";function ja(r){return Gn.object({key:Gn.string(),testId:Gn.string().optional(),moduleId:Gn.string().optional(),organizationId:Gn.string(),value:r})}function $a(r){return ja(r).extend({uniqueKey:Gn.string()})}function xl(r){return Gn.record(Gn.string(),$a(r))}var zt={type:!0,cache:!0},Sn=$I.discriminatedUnion("type",[Ci.pick(zt),Ga.pick(zt),Co.pick(zt),Ba.pick(zt),Io.pick(zt),Ha.pick(zt),xo.pick(zt),za.pick(zt),zn.pick(zt),Hn.pick(zt),Ai.pick(zt),wi.pick(zt),_o.pick(zt),Mo.pick(zt),Va.pick(zt)]),_l=Object.values($e).filter(r=>Sn.options.some(e=>e.shape.type.safeParse(r).success));xi.options.forEach(r=>{if("target"in r.shape&&!_l.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function Bf(r){return _l.includes(r.type)}var zf=ja(Sn),Hf=$a(Sn),ej=xl(Sn);import{z as up}from"zod";import{extendZodWithOpenApi as KI}from"zod-openapi";import{z as Gf}from"zod";import{extendZodWithOpenApi as WI}from"zod-openapi";import{z as Po}from"zod";var cr=Po.object({index:Po.number().optional().describe("global index within a test (in-order traversal)"),id:Po.string(),skipped:Po.boolean().optional(),envKey:Po.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Po.boolean().optional(),retries:Po.number().optional()});WI(Gf);var qI=cr.extend({type:Gf.literal("PRESET_ACTION")}),er=qI.extend({command:xi}).openapi({ref:"PresetAction"});KI(up);var Oo=cr.extend({type:up.literal("AI_ACTION"),text:up.string(),steps:er.array().optional()}).openapi({ref:"AIAction"});import{z as Ht}from"zod";import{z as Il}from"zod";import{extendZodWithOpenApi as YI}from"zod-openapi";YI(Il);var _i=cr.extend({type:Il.literal("AI_ACTION_DYNAMIC"),text:Il.string(),retries:Il.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as Vf}from"zod";var dp=cr.extend({type:Vf.literal("CONDITIONAL"),skipped:Vf.boolean().optional()});import{z as ge}from"zod";var XI=ge.object({cacheKey:ge.string(),cacheExpiryMs:ge.number()}),pp=cr.extend({id:ge.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ge.record(ge.string()).optional(),cacheConfig:XI.optional()}),_r=pp.extend({type:ge.literal("MODULE"),moduleId:ge.string().uuid()}),JI=ge.union([_r.pick({type:!0,moduleId:!0}),ge.record(ge.unknown())]),QI=ge.object({type:ge.literal("URL_REGEX"),regex:ge.string()}),ZI=ge.object({type:ge.literal("PAGE_CHECK"),substring:ge.string()}),mp=ge.object({cacheInvalidation:ge.discriminatedUnion("type",[ZI,QI]).optional()}),Wt=ge.object({moduleId:ge.string().uuid(),name:ge.string(),description:ge.string().nullish(),enabled:ge.boolean().nullish(),parameters:ge.string().array().nullish(),defaultParameters:ge.record(ge.string(),ge.string()).nullish(),parameterEnums:ge.record(ge.string(),ge.string().array()).nullish(),defaultCacheKey:ge.string().nullish(),defaultCacheTtl:ge.number().nullish(),defaultCacheAllInvocations:ge.boolean().nullish(),autoAuth:ge.boolean().nullish(),advanced:mp.nullish()});var gp=r=>r.type==="AI_ACTION"||r.type==="AI_ACTION_DYNAMIC"||r.type==="PRESET_ACTION";import{z as ur}from"zod";var hp=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(hp||{});var eM=ur.discriminatedUnion("type",[ur.object({type:ur.literal("NAVIGATE_URL"),url:ur.string().url()}),ur.object({type:ur.literal("GO_TO_SECTION_START")})]),tM=ur.object({trigger:ur.nativeEnum(hp).optional(),attempts:ur.number().int().optional(),restartBehavior:eM}),Wa=cr.extend({type:ur.literal("SECTION"),description:ur.string().describe("user provided goal of what the section should accomplish"),plan:ur.string().array().optional(),autohealingConfig:tM.optional()});var jf=Wt.merge(pp).extend({type:Ht.literal("RESOLVED_MODULE"),steps:Ht.lazy(()=>Ze.array())}),qa=Wt.extend({steps:Ht.lazy(()=>Ze.array())}),fp=Wa.extend({steps:Ht.lazy(()=>Pe.array())}),rM=Wa.extend({steps:Ht.lazy(()=>Ze.array())}),Lo=dp.extend({blocks:Ht.object({assertion:Ht.lazy(()=>er),steps:Ht.lazy(()=>Pe.array())}).array(),elseSteps:Ht.lazy(()=>Pe.array().optional())}),nM=dp.extend({blocks:Ht.object({assertion:Ht.lazy(()=>er),steps:Ht.lazy(()=>Ze.array())}).array(),elseSteps:Ht.lazy(()=>Ze.array().optional())}),Pe=Ht.discriminatedUnion("type",[er,Oo,_i,_r,Lo,fp]),Ze=Ht.discriminatedUnion("type",[er,Oo,_i,jf,nM,rM]);import{z as dr}from"zod";var oM=dr.object({steps:Pe.array(),beforeSteps:Pe.array().nullish(),afterSteps:Pe.array().nullish()}),Ii=dr.object({steps:Ze.array(),beforeSteps:Ze.array().nullish(),afterSteps:Ze.array().nullish()}),No=dr.object({steps:dr.record(dr.string(),dr.unknown()).array(),beforeSteps:dr.record(dr.string(),dr.unknown()).array().nullish(),afterSteps:dr.record(dr.string(),dr.unknown()).array().nullish()});var se="1.0.21";var $f=L.object({phrase:L.string()}),Sp=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()])}),U$=L.object({text:L.string()}),Wf=L.object({attributes:L.array(L.string()).optional(),text:L.boolean().optional(),boundingBox:L.boolean().optional()}),iM=L.object({id:L.number().int(),requirements:Wf}),aM=iM.array(),qf=L.object({thoughts:L.string(),review:L.string().optional(),id:L.number().int(),updatedMemory:Wd.optional(),requirements:Wf.optional(),additionalElements:aM.optional()});var Ml=(m=>(m.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",m.FEW_WORDS="FEW_WORDS",m.STYLE_TAG="STYLE_TAG",m.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",m.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",m.NONE="NONE",m.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",m.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",m.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",m.PREFER_ASSERTION="PREFER_ASSERTION",m.HTML_ELEMENTS="HTML_ELEMENTS",m.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",m.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",m))(Ml||{}),yp=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(yp||{});var Kf=L.object({thoughts:L.string(),category:L.nativeEnum(Ml)}),Yf=L.object({thoughts:L.string(),category:L.nativeEnum(yp)}),sM=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()})]),B$=L.object({thoughts:L.string(),patches:sM.array()}),lM=[L.literal("add"),L.literal("replace"),L.literal("remove")],cM=L.object({op:L.union(lM),path:L.string(),value:Ze.optional()}),Xf=L.object({patches:cM.array(),thoughts:L.string()}),Ep=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(Ep||{}),Jf=L.object({thoughts:L.string(),scenario:L.nativeEnum(Ep),instructions:L.string().nullish()}),Qf=L.object({reasoning:L.string(),scenario:L.string(),patch:L.null().optional()}),z$=L.object({thoughts:L.string(),evaluation:L.number().min(0).max(10)}),H$=L.object({observations:L.string(),reasoning:L.string(),command:Cl});var Tp=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")})])}),uM=L.object({startId:L.number().int(),endId:L.number().int()}),Zf=L.object({categoryThoughts:L.string(),category:L.string(),relevantSections:uM.array()});import{z as O}from"zod";import*as ie from"zod";var q$=ie.object({thoughts:ie.string().optional().describe("only provided if a description was provided"),target:Fn.optional().describe("only provided if a description was provided"),pageState:ie.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:ie.object({label:ie.string(),value:ie.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:ie.object({data:ie.string(),height:ie.number().int(),width:ie.number().int()}).optional().describe("only provided if returnScreenshot is true")}),eS=ie.union([ie.literal("ELEMENT_CHECK"),ie.literal("NEGATED_CHECK"),ie.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),ie.literal("SELECT_OPTION"),ie.literal("TYPE")]);function Do(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 Ka=(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))(Ka||{}),Mi=ie.object({matched:ie.boolean(),reason:ie.string().optional().describe("Human understandable description"),logs:ie.string().array().optional().describe("Logs for debugging")}),dM=Mi.extend({type:ie.literal("USER_SELECTOR")}),pM=Mi.extend({type:ie.literal("CSS_SELECTOR"),selectors:ie.string().array()}),mM=Mi.extend({type:ie.literal("HYBRID_SELECTOR")}),gM=Mi.extend({type:ie.literal("HTML_DISTANCE"),distance:ie.number().optional(),closestElement:ie.string().optional(),savedElement:ie.string().optional()}),hM=Mi.extend({type:ie.literal("TEMPLATE_MATCHING"),elementImageUrl:ie.string().url()}),fM=Mi.extend({type:ie.literal("AUTO_FRAME"),logs:ie.string().array().optional()}),tS=ie.discriminatedUnion("type",[dM,pM,mM,gM,hM,fM]);import{z as Qa}from"zod";import{z as IM}from"zod";import*as j from"zod";import{extendZodWithOpenApi as bM}from"zod-openapi";import{cloneDeep as Ya}from"lodash-es";import sS from"truncate-json";import*as Uo from"zod";import{extendZodWithOpenApi as SM}from"zod-openapi";import{z as It}from"zod";import{z as Oe}from"zod";var bp=Oe.object({autoFollowNewTabs:Oe.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:Oe.union([Oe.boolean(),Oe.literal("inputs-only")]).optional(),ignoreHrefForCaching:Oe.boolean().optional(),disableSecondaryCacheResolution:Oe.boolean().optional(),hybridSelectorMode:Oe.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:Oe.boolean().optional(),visualActions:Oe.boolean().optional(),autoExpandIframes:Oe.boolean().optional(),disableHtmlSnapshots:Oe.boolean().optional(),importantAttributes:Oe.string().array().optional(),importantClasses:Oe.string().array().optional(),importantStyles:Oe.string().array().optional()});var rS=1e4,nS=6e4,ko=bp.extend({pageLoadTimeoutMs:Oe.number().optional().refine(r=>r===void 0||r<=nS&&r>=-1,{message:`Page load timeout must be between 0 and ${nS/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:Oe.number().optional().refine(r=>r===void 0||r<=rS&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${rS/1e3} seconds`}),localChromeExtensionPaths:Oe.string().array().optional(),extraHeaders:Oe.record(Oe.string(),Oe.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:Oe.string().optional(),disableGpu:Oe.boolean().optional(),bustCacheOnBoundingBoxChange:Oe.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:Oe.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:Oe.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 ht="BASE_URL",Pl="CURRENT_URL",Fo="ENV_NAME",Pi="TEST_NAME",Z$={[ht]:"https://www.google.com"},oS=It.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),iS=It.object({name:It.string(),variables:It.record(It.string().describe("variable name"),It.string().describe("variable value"))}),aS=It.object({name:It.string(),variables:It.record(It.string().describe("variable name"),It.unknown().describe("variable value")),browser:ko.optional()});var eW=It.object({name:It.string(),variables:It.record(It.string().describe("variable name"),It.unknown().describe("variable value"))});SM(Uo);var vp=Uo.object({env:Uo.record(Uo.unknown())}).openapi({ref:"TestContextSnapshot"}),yM="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",EM=[ht,Fo,Pi],lS=[Pl,ht,Fo,Pi],qt=class r{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t=void 0,n={}){return new r({baseUrl:"about:blank",currentUrl:"about:blank",testName:e,envName:t,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[ht]??"about:blank",o=e.env[Pl]??"about:blank",i=e.env[Fo],a=e.env[Pi],l={};for(let[s,u]of Object.entries(e.env))lS.includes(s)||(t??{})[s]===void 0&&(l[s]=u);return new r({baseUrl:n,currentUrl:o,dynamicVariables:l,envName:i,testName:a,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=Ya(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){EM.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[Fo]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return Ya(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>lS.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,yM]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=sS(JSON.stringify(o),5e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=sS(JSON.stringify(e.env),25e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}setCurrentUrl(e){this.env[Pl]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=Ya(e.variablesFromEnvironment),this.setMomenticSystemVariable(ht,e.baseUrl),e.envName&&this.setMomenticSystemVariable(Fo,e.envName),e.testName&&this.setMomenticSystemVariable(Pi,e.testName)}getDynamicVariablesCopy(){return Ya(this.env)}getVariablesFromEnvironmentCopy(){return Ya(this.varsFromMomenticEnvironment)}};var ve=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(ve||{}),Ol=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(Ol||{});import{z as $r}from"zod";import{extendZodWithOpenApi as TM}from"zod-openapi";TM($r);var he=(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))(he||{});var cS=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],Ll={ActionFailureError:"Action failure",AssertionFailureError:"Assertion failure",SetupFailureError:"Setup failure",TeardownFailureError:"Teardown failure",UserInfrastructureError:"Infrastructure failure",UserConfigurationError:"Configuration error",AIProviderError:"AI provider error",InternalWebAgentError:"Momentic AI agent error",JobTimeoutError:"Job timeout",InternalPlatformError:"Unknown Momentic platform error",UnknownError:"Unknown error",ConcurrencyError:"Concurrency error"},Oi={ActionFailureError:"A browser action such as a click or type failed to execute because of the underlying page state is incorrect, suggesting a bug in the application itself.",AssertionFailureError:"An AI check failed for a legitimate reason, such as a missing element, a change in the page structure, or an unexpected state (e.g. loading state).",SetupFailureError:"A setup step failed to execute, preventing the main test from running. This indicates an issue with test preparation, prerequisite steps, or initial state. This can only apply to failures that occur before teardown.",TeardownFailureError:"A teardown step failed to execute after the main test completed. This indicates an issue with cleanup or post-test operations or an uncaught error in the test. This can only apply to failures that occur after setup.",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",UserInfrastructureError:"The user's web application exhibited an infrastructure failure, such as a page load timeout, a 5XX status code, maintenance page, or session crash.",UserConfigurationError:"The error message suggests a user-caused misconfiguration in the test, such as an undefined variable, a missing base URL, an empty test/module input parameter, or an invalid step option",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself.",InternalWebAgentError:"The AI testing framework failed to find the correct element or evaluate the assertion correctly, even though the test steps and application state look valid. In other words, the AI agent failed to understand the page.",ConcurrencyError:"The AI test executed correctly, but the application state did not match expectations because another process modified the same resource concurrently. This failure is due to a concurrency error, such as a race condition or deadlock. Commonly caused by tests running simultaneously when using constants rather than random values, or underlying operations that allow for race conditions. For example, in Notion, if multiple tests are running at the same time where one creates a page and enters text to check if it renders, but another test deletes all pages before it can validate the render, this would be a concurrency error.",UnknownError:"An unknown error occurred. Please refer to the failure details in the run for more information or reach out to Momentic Support for assistance.",InternalPlatformError:"An unknown error occurred with the Momentic platform."},Rp=$r.object({reason:$r.nativeEnum(he),previousStepsDescription:$r.array($r.string()).optional(),summary:$r.string(),rootCause:$r.string().optional()}).openapi({ref:"TestResultClassification"}),Nl=$r.object({errorMessage:$r.string(),errorStack:$r.string().optional(),classification:Rp.optional()}).openapi({ref:"TestFailureDetails"});bM(j);var Ap=j.object({beforeUrl:j.string().optional(),afterUrl:j.string().optional(),message:j.string().optional(),beforeSnapshot:j.string().optional(),afterSnapshot:j.string().optional(),startedAt:j.coerce.date(),finishedAt:j.coerce.date()}),vM=Ap.extend({viewport:j.object({height:j.number(),width:j.number()}).nullish(),status:j.nativeEnum(Ol),message:j.string().optional(),elementInteracted:j.string().optional()}),Bo=Ap.extend({status:j.nativeEnum(ve),message:j.string().optional(),data:j.unknown().optional(),beforeTestContext:vp.optional(),afterTestContext:vp.optional(),failureReason:j.nativeEnum(he).optional(),details:j.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"}),wp=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(wp||{}),Dl=Bo.merge(er).extend({results:vM.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:j.lazy(()=>pt.array()).optional(),failureRecoveryStatus:j.object({type:j.nativeEnum(wp),message:j.string()}).optional()}),RM=Bo.merge(Oo).extend({results:j.lazy(()=>Dl.array()),previousAttempts:j.lazy(()=>pt.array()).optional()}),AM=Bo.merge(_i).extend({results:j.lazy(()=>Dl.array()),previousAttempts:j.lazy(()=>pt.array()).optional()}),wM=Bo.merge(_r).extend({moduleName:j.string().optional(),results:j.lazy(()=>pt.array()),previousAttempts:j.lazy(()=>pt.array()).optional()}),CM=Bo.merge(Lo).extend({assertion:Dl.optional(),results:j.lazy(()=>pt.array()).describe("results for the block actually executed"),previousAttempts:j.lazy(()=>pt.array()).optional()}),xM=Bo.merge(Wa).extend({results:j.lazy(()=>pt.array()),healingAttempts:j.lazy(()=>pt.array().array()).optional(),previousAttempts:j.lazy(()=>pt.array()).optional()}),pt=j.discriminatedUnion("type",[RM,AM,Dl,wM,CM,xM]),kl=Bo.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),_M=Ap.extend({index:j.number().optional(),description:j.string(),pageState:j.string().optional(),elementInteracted:j.string().optional(),startedAt:j.coerce.date().or(j.string()).optional().catch(void 0),finishedAt:j.coerce.date().or(j.string()).optional().catch(void 0)}),Fl=_M.extend({beforeScreenshot:j.string().optional(),afterScreenshot:j.string().optional()});var Cp=IM.object({results:pt.array().describe("main results"),beforeResults:pt.array().optional(),afterResults:pt.array().optional()}),Xa=Cp.partial();import{z as U}from"zod";import{extendZodWithOpenApi as DM}from"zod-openapi";var Li=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(Li||{});import{isValidCron as MM}from"cron-validator";import{z as le}from"zod";import{z as xp}from"zod";var yn=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(yn||{});var Ul=xp.object({width:xp.number().min(200).max(1e4),height:xp.number().min(200).max(1e4)}),uS={"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}},_W=Object.keys(uS);var Mt=uS["Desktop Large"],Vn="en-us",jn="America/Los_Angeles";var $n={latitude:37.7749,longitude:-122.4194};var dS=["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 pS=2e3,Bl=ko.extend({browserType:le.nativeEnum(yn).optional(),slowMoMs:le.number().optional().refine(r=>r===void 0||r<=pS&&r>=-1,{message:`Slow motion must be between 0 and ${pS} milliseconds`}),basicAuthorization:le.object({username:le.string().optional(),password:le.string().optional()}).optional(),geolocation:le.object({latitude:le.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:le.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:le.boolean().optional(),locale:le.string().optional(),timezone:le.enum(dS).optional(),colorScheme:le.enum(["light","dark"]).optional()}),mS=["extraHeaders","basicAuthorization","localChromeExtensionPaths"],_p=le.object({useMemory:le.boolean().optional(),failureRecovery:le.boolean().optional().describe("undefined means inherit org settings")}),PM=_p.extend({disableAICaching:le.boolean().optional(),failureRecoveryInstructions:le.string().optional()}),OM=le.object({viewport:Ul.optional()}),zo=OM.merge(PM).merge(Bl),Ni=le.object({cron:le.string().refine(r=>MM(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:le.boolean().default(!1),env:le.string().optional(),timeZone:le.string().default("America/Los_Angeles"),jobKey:le.string().optional()}),Di=le.object({onSuccess:le.boolean().default(!1),failureMessage:le.string().optional(),onFailure:le.boolean().default(!0),successMessage:le.string().optional()}),LM=le.object({name:le.string(),required:le.boolean().optional(),defaultValue:le.string().describe("this is not optional because we need a value when the editor is first loaded")}),zl=LM.array(),NM=le.object({name:le.string(),value:le.string()}),gS=NM.array(),Hl=le.object({name:le.string(),default:le.boolean().optional(),fixtures:oS.array().optional()});DM(U);var pr={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},Se=(l=>(l.PENDING="PENDING",l.RUNNING="RUNNING",l.PASSED="PASSED",l.FAILED="FAILED",l.CANCELLED="CANCELLED",l.RETRYING="RETRYING",l.WAITING_FOR_USER="WAITING_FOR_USER",l))(Se||{}),Gl=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(Gl||{});var at=U.string().pipe(U.coerce.date()).or(U.date()),Ja=U.object({id:U.string(),runKey:U.string(),organizationId:U.string(),executionType:U.nativeEnum(Li).optional().default("WEB"),createdAt:at,createdBy:U.string(),flake:U.boolean().nullish(),scheduledAt:at.or(U.null()),startedAt:at.or(U.null()),updatedAt:at.nullish(),finishedAt:at.or(U.null()),resolvedBaseUrl:U.string().nullish(),environmentName:U.string().nullish(),gitBranchName:U.string().nullish(),githubRepository:U.string().nullish(),gitlabProjectPath:U.string().nullish(),labels:U.array(U.string()).optional(),gitOriginUrl:U.string().nullish(),gitCommitSha:U.string().nullish(),gitCommitShaShort:U.string().nullish(),gitCommitAuthorName:U.string().nullish(),cliVersion:U.string().nullish(),section:U.nativeEnum(Gl).nullish(),status:U.nativeEnum(Se),trigger:U.nativeEnum(pr),attempts:U.number(),runAttempts:U.array(U.object({id:U.string(),status:U.nativeEnum(Se),startedAt:at.or(U.null()),finishedAt:at.or(U.null())})).optional(),videos:U.array(U.string()).optional(),failureReason:U.nativeEnum(he).nullish(),failureDetails:Nl.nullish(),failureRecoveryDetails:U.record(U.string(),U.unknown()).nullish(),pipelineId:U.string().nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),quarantined:U.boolean().nullish().default(!1),quarantinedReason:U.string().nullish(),localTestId:U.string().nullish(),testId:U.string().nullish(),testName:U.string().nullish(),description:U.string().nullish(),test:U.object({name:U.string(),id:U.string()}).nullish().default(null),suiteId:U.string().nullish()}).openapi({ref:"RunMetadata"}),kM={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Vl=Ja.pick({...kM,test:!0}),hS=Ja.omit({failureReason:!0,failureDetails:!0,test:!0}),Ip=Ja.extend({stepsSnapshot:U.array(U.record(U.unknown())).nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),test:U.object({name:U.string(),id:U.string(),description:U.string().nullish(),baseUrl:U.string().nullish(),advanced:zo.nullish()}).nullish()}).merge(Cp),fS=r=>r.includes("PASSED")&&r.includes("FAILED");var FM=Qa.object({id:Qa.string().uuid(),startedAt:at.or(Qa.null()),finishedAt:at.or(Qa.null()),status:Qa.nativeEnum(Se)}).merge(Xa),XW=FM.array();var jl=(o=>(o.JUNIT="junit",o.ALLURE="allure",o.ALLURE_JSON="allure-json",o.PLAYWRIGHT_JSON="playwright-json",o))(jl||{});import{z as st}from"zod";var UM=st.object({id:st.string(),status:st.nativeEnum(Se),trigger:st.nativeEnum(pr),createdAt:at,startedAt:at.nullish(),finishedAt:at.nullish(),gitCommitSha:st.string().nullish(),gitCommitShaShort:st.string().nullish(),gitCommitTimestamp:at.nullish(),gitBranchName:st.string().nullish(),gitOriginUrl:st.string().nullish(),gitCommitMessage:st.string().nullish(),gitCommitAuthorName:st.string().nullish(),githubRepository:st.string().nullish(),gitlabProjectPath:st.string().nullish(),pipelineId:st.string().nullish(),cliVersion:st.string().nullish(),labels:st.string().array().optional(),suite:st.object({id:st.string(),name:st.string()}).nullish(),runs:st.object({status:st.nativeEnum(Se)}).array()}).openapi({ref:"RunGroup"}),SS=UM.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Vl.array()});import{z as ft}from"zod";var BM=ft.object({type:ft.literal("TARGETING"),name:ft.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:tS.array(),pageState:ft.string().optional(),targetSource:ft.nativeEnum(kn).optional(),targetUpdateTime:ft.string().optional()}),zM=ft.object({type:ft.literal("AI_LOCATION"),matched:ft.boolean(),pageState:ft.string().optional(),ragUsed:ft.boolean().optional(),thoughts:ft.string().optional()}),HM=ft.object({type:ft.literal("ASSERTION"),relevantElementsSerialized:ft.string().array().optional(),pageState:ft.string().optional(),ragUsed:ft.boolean().optional()}),yS=ft.discriminatedUnion("type",[BM,zM,HM]);function $l(){return{details:[]}}import{z as tt}from"zod";var GM=tt.object({id:tt.string(),name:tt.string()}),uq=GM.merge(tt.object({createdAt:at,createdBy:tt.string(),schedule:Ni,notification:Di,environment:tt.object({name:tt.string()}).nullish(),beforeTests:tt.object({id:tt.string()}).array().nullish(),afterTests:tt.object({id:tt.string()}).array().nullish()})),ES=tt.object({id:tt.string().uuid(),orgId:tt.string(),createdAt:at,startedAt:at.or(tt.null()),finishedAt:at.or(tt.null()),status:tt.nativeEnum(Se),trigger:tt.nativeEnum(pr),suite:tt.object({id:tt.string(),name:tt.string()}).nullish(),runs:Ja.array()}),dq=ES.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),TS=ES.extend({runs:Vl.array()});import{z as mr}from"zod";import{cloneDeep as gq}from"lodash-es";import{z as Re}from"zod";var Tq=Re.object({thoughts:Re.string(),subGoals:Re.object({instruction:Re.string()}).array()}),bq=Re.object({thoughts:Re.string(),newPlanMarkdown:Re.string()}),vq=Re.object({thoughts:Re.string(),correct:Re.boolean(),failedActionIndex:Re.number().optional()}),VM=Re.object({type:Re.literal("PLANNING"),beforePlan:Re.string(),goalDecision:Re.string(),thoughts:Re.string()}),jM=Re.object({type:Re.literal("RUNNING"),stepDisplayName:Re.string(),status:Re.nativeEnum(ve),results:pt.array()}),$M=Re.object({type:Re.literal("REVISING"),beforePlan:Re.string(),afterPlan:Re.string(),errString:Re.string(),diffs:Re.string(),thoughts:Re.string()}),WM=Re.object({type:Re.literal("SYSTEM"),message:Re.string()}),qM=Re.discriminatedUnion("type",[VM,jM,$M,WM]),bS=qM.array();var xq=mr.object({id:mr.string(),scheduledAt:mr.coerce.date().nullable(),startedAt:mr.coerce.date().nullable(),finishedAt:mr.coerce.date().nullable(),status:mr.nativeEnum(Se),history:bS.nullable(),testPlan:mr.object({id:mr.string(),name:mr.string()}).nullable(),test:mr.object({id:mr.string(),name:mr.string()}).nullable()});import{z as Gt}from"zod";var Mp=Gt.object({content:Gt.string(),ids:Gt.string().array(),tokenLength:Gt.number()}),KM=Gt.object({chunks:Mp.array()}),jq=Gt.object({ids:Gt.string().array(),score:Gt.number(),tokenLength:Gt.number()}),$q=KM.extend({description:Gt.string().describe("Input to pass to RAG engine"),tokenLimit:Gt.number()}),vS=Gt.object({ids:Gt.number().array()}),RS=Gt.object({indices:Gt.number().array()});var Pt=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()}),Zq=Pt.extend({chunks:Mp.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()}),YM=O.object({screenshotBase64AfterCommand:O.string(),urlAfterCommand:O.string(),serializedCommand:O.string(),elementInteracted:O.string().optional(),thoughts:O.string().optional()}),AS=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),source:eS.optional().catch(void 0),memory:O.discriminatedUnion("type",[yl,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional()}),wS=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()}),CS=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string().optional(),returnSchema:O.string().optional()}),XM=O.literal("NEGATED_CHECK"),xS=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),url:O.string(),contextChoice:ip.optional(),memory:O.discriminatedUnion("type",[Xd,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional(),source:XM.optional()}),_S=O.object({command:xi}),IS=O.object({message:O.string()}),Pp=O.object({goal:O.string(),browserState:O.string(),startingScreenshot:O.string().optional(),screenshot:O.string(),url:O.string(),history:YM.array(),actionHint:O.string().optional(),lastError:O.string().optional()}),MS=O.object({results:Fl.array(),errorMessage:O.string(),errorStack:O.string().optional()}),PS=O.object({results:Fl.array(),goal:O.string(),errorMessage:O.string()}),OS=O.object({failedResults:Fl.array(),nextStepsSerialized:O.string().array(),currentUrl:O.string(),currentPageState:O.string(),currentScreenshot:O.string(),customInstructions:O.string().optional(),testDescription:O.string().optional()}),e2=O.object({description:O.string(),type:O.union([O.literal("locator"),O.literal("assertion"),O.literal("ai-action")]),excerpt:O.string()}),LS=O.object({type:O.string(),browserContext:O.string(),currentStep:O.string(),screenshot:O.string()});import{z as Za}from"zod";var n2=Za.object({goal:Za.string()}),NS=Za.object({keywords:Za.array(Za.string())});import{z as Op}from"zod";var Wl=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(Wl||{}),a2=Op.nativeEnum(Wl),JM=Op.enum(["v1","v2"]),s2=JM.or(Op.string().describe("for people with special configurations"));import{z as We}from"zod";var DS=We.object({attributesRequired:We.array(We.string()).optional(),textRequired:We.boolean().optional(),boundsRequired:We.boolean().optional()}),QM=We.object({id:We.number(),thoughts:We.string(),requirements:DS.optional(),additionalElements:We.object({id:We.number(),requirements:DS}).array().optional()}),kS=We.object({description:We.string(),screenXml:We.string(),screenshot:We.string()}),FS=We.object({assertion:We.string(),screenXml:We.string(),screenshot:We.string()}),ZM=We.object({thoughts:We.string(),result:We.boolean(),relevantElements:We.array(We.number()).optional()});var US=r=>!(!r.org_id||!r.user_id||!r.platform);import{z as Ho}from"zod";var BS=Ho.object({id:Ho.string().uuid(),skipped:Ho.boolean().optional(),envKey:Ho.string().optional().describe("key in the environment to save the result of this step to")}),Lp=BS.merge(bl).extend({type:Ho.literal("REQUEST")}),Np=BS.merge(vl).extend({type:Ho.literal("JAVASCRIPT")}),Dp=Ho.discriminatedUnion("type",[Np,Lp]);import{z as gr}from"zod";import{z as Go}from"zod";var eP=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,xe=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 ki=Go.string().min(1).max(255).superRefine((r,e)=>{try{Wn(r)}catch(t){return e.addIssue({code:Go.ZodIssueCode.custom,message:t.message,fatal:!0}),Go.NEVER}});function Wn(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(eP))throw new Error("Name cannot be a UUID. Please choose a different name.")}var ql=Go.preprocess(r=>r===null?"":r,Go.union([Go.string().url(),Go.literal("")])).optional();var zS=gr.object({id:gr.string(),name:ki,description:gr.string().optional().nullish(),baseUrl:ql.nullish(),schemaVersion:gr.string(),advanced:gr.unknown().optional(),retries:gr.number(),envs:gr.array(Hl).nullish(),parameters:zl.nullish()}),tP=gr.object({createdAt:gr.coerce.date(),updatedAt:gr.coerce.date(),schedule:Ni.nullish(),notification:Di.nullish(),createdBy:gr.string(),organizationId:gr.string()}),rP=zS.merge(tP),L2=rP.extend({steps:Dp.array()}),N2=zS.extend({steps:Dp.array()});import{z as Kt}from"zod";var HS=Kt.object({startedAt:Kt.coerce.date(),finishedAt:Kt.coerce.date(),status:Kt.nativeEnum(ve),message:Kt.string().optional(),data:Kt.unknown().optional()}),nP=HS.merge(Np).extend({type:Kt.literal("JAVASCRIPT")}),oP=HS.merge(Lp).extend({type:Kt.literal("REQUEST")}),iP=Kt.discriminatedUnion("type",[nP,oP]),GS=Kt.object({startedAt:Kt.coerce.date(),finishedAt:Kt.coerce.date().nullish(),status:Kt.nativeEnum(Se),results:iP.array(),failureReason:Kt.string().nullish(),failureDetails:Nl.nullish()});import{z as Yt}from"zod";var aP=Yt.object({id:Yt.string(),organizationId:Yt.string(),createdAt:Yt.coerce.date(),updatedAt:Yt.coerce.date(),createdBy:Yt.string(),scheduledAt:Yt.coerce.date().nullish(),startedAt:Yt.coerce.date().nullish(),finishedAt:Yt.coerce.date().nullish(),status:Yt.nativeEnum(Se),trigger:Yt.nativeEnum(pr),results:GS.array().nullish(),apiTestName:Yt.string().nullish(),apiTestPath:Yt.string().nullish(),apiTestId:Yt.string().nullish()}),j2=aP.pick({status:!0,startedAt:!0,finishedAt:!0});var es=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(es||{}),VS=3;function sP(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function kp(r){if(!sP(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 Fp(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return VS;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 Fi=class{trackStepExecution(){}async flush(){}};import{parseString as lP,splitCookiesString as cP}from"set-cookie-parser";import{z as Ce}from"zod";var Up=Ce.object({name:Ce.string(),value:Ce.string(),url:Ce.string().optional(),domain:Ce.string().optional(),path:Ce.string().optional(),expires:Ce.number().default(Date.now()/1e3+60*60*24*365),httpOnly:Ce.boolean().optional(),secure:Ce.boolean().default(!0),sameSite:Ce.union([Ce.literal("Strict"),Ce.literal("Lax"),Ce.literal("None")]).default("None")});function Kl(r,e){let t=[],n=cP(r);for(let o of n){let i=lP(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let l=Up.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(l);let c=[l.name,...Object.keys(l)].map(u=>u.toLowerCase()),s=o.match(/\b(\S+)=([^;]*)/g);if(s)for(let u of s){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...l,name:d,value:p})}}return t}var uP=Ce.object({origin:Ce.string(),localStorage:Ce.array(Ce.object({name:Ce.string(),value:Ce.string()}))}),dP=Ce.object({entries:Ce.record(Ce.string(),Ce.array(Ce.tuple([Ce.unknown(),Ce.unknown()]))),version:Ce.number().optional()}),Yl=Ce.object({cookies:Up.array().optional(),origins:uP.array().optional(),idb:Ce.record(Ce.string(),dP).optional().describe("key is db name")});function jS(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Up.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 AP from"zod";import{v4 as mK}from"uuid";import{z as ce}from"zod";import*as Le from"zod";var $S=Le.object({requiredText:Le.string().optional(),requiredAttributes:Le.record(Le.string(),Le.string()).optional(),requiredBounds:Le.boolean().optional()}),pP=Le.object({xPath:Le.string(),requirements:$S.optional()}),mP=Le.object({type:Le.literal("NATIVE"),bounds:Le.number().array(),resolvedDescription:Le.string(),xPath:Le.string(),elementOnlySerializedXml:Le.string(),requirements:$S.optional(),requiredRelatedElements:pP.array().optional()}),gP=Le.object({type:Le.literal("WEBVIEW"),resolvedDescription:Le.string(),xPath:Le.string(),browserCache:Fn.optional()}),WS=Le.discriminatedUnion("type",[mP,gP]);var Ui=(u=>(u.AI_CHECK="AI_CHECK",u.TAP="TAP",u.TYPE="TYPE",u.PRESS="PRESS",u.PRESS_KEYBOARD="PRESS_KEYBOARD",u.OPEN_APP="OPEN_APP",u.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",u.JAVASCRIPT="JAVASCRIPT",u.ADB="ADB",u.STATE="STATE",u))(Ui||{}),qS=(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))(qS||{}),KS=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(KS||{}),YS=ce.discriminatedUnion("type",[ce.object({type:ce.literal("description"),description:ce.string()}),ce.object({type:ce.literal("coordinates"),xPercent:ce.number(),yPercent:ce.number()})]),hP=ce.object({updatedAt:ce.coerce.date().optional()}),Wr=ce.object({id:ce.string().uuid(),disableCache:ce.boolean().optional()}),fP=Wr.extend({type:ce.literal("STATE")}),XS=hP.extend({target:WS}),Bp=Wr.extend({type:ce.literal("TAP"),target:YS,cache:XS.optional(),longPress:ce.boolean().optional(),longPressDurationMs:ce.number().optional()}),zp=Wr.extend({type:ce.literal("TYPE"),target:YS.optional(),cache:XS.optional(),keyPressDelayMs:ce.number().optional(),text:ce.string(),clearContent:ce.boolean().optional()}),SP=Wr.extend({type:ce.literal("OPEN_NOTIFICATION_DRAWER")}),yP=Wr.extend({type:ce.literal("PRESS"),key:ce.nativeEnum(qS),longPress:ce.boolean().optional()}),EP=Wr.extend({type:ce.literal("PRESS_KEYBOARD"),key:ce.nativeEnum(KS)}),TP=Wr.extend({type:ce.literal("OPEN_APP"),packageName:ce.string(),activityName:ce.string().optional()}),bP=Wr.extend({type:ce.literal("AI_CHECK"),assertion:ce.string(),timeoutSecs:ce.number().optional()}),vP=Wr.extend({type:ce.literal("JAVASCRIPT"),code:ce.string(),timeout:ce.number().int().max(60).optional().describe("Max seconds for the code to complete")}),RP=Wr.extend({type:ce.literal("ADB"),command:ce.string()}),JS=ce.discriminatedUnion("type",[Bp,zp,yP,TP,SP,bP,vP,EP,RP,fP]);var QS={type:!0,cache:!0},Bi=AP.discriminatedUnion("type",[Bp.pick(QS),zp.pick(QS)]),bK=Object.values(Ui).filter(r=>Bi.options.some(e=>e.shape.type.safeParse(r).success));var ZS=ja(Bi),ey=$a(Bi),vK=xl(Bi);import{cloneDeep as wK}from"lodash-es";import xK from"truncate-json";var ts=(t=>(t.USWest1="us-west1",t.EUNorth1="eu-north1",t))(ts||{});import lt from"zod";import{z as Ir}from"zod";import{z as ze}from"zod";var Ot=ze.object({id:ze.string(),name:ki,baseUrl:ql,description:ze.string().optional().nullish(),schemaVersion:ze.string(),advanced:zo,retries:ze.number(),envs:ze.array(Hl).nullish(),parameters:zl.nullish(),disabled:ze.boolean().optional(),labels:ze.array(ze.string()).optional().catch([])}),DK=ze.enum(["INHERIT","ENABLED","DISABLED"]);var wP=zo.extend({failureRecovery:ze.boolean().or(ze.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:ze.boolean().or(ze.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var kK=Ot.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:wP}),FK=Ot.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),CP=ze.object({labels:ze.array(ze.string()).optional(),outputs:gS.nullish()}),hr=Ot.merge(CP),xP=ze.object({createdAt:ze.coerce.date(),updatedAt:ze.coerce.date(),updatedBy:ze.string().nullable(),schedule:Ni,notification:Di,createdBy:ze.string(),organizationId:ze.string(),folderId:ze.string().nullable().optional()}),_P=Ot.merge(xP),UK=_P.merge(Ii),Xl=Ot.merge(Ii),BK=Ot.merge(No);var IP="test",MP="module",PP="mobile-test",OP="mobile-module";var de=(o=>(o.TEST=`momentic/${IP}`,o.MODULE=`momentic/${MP}`,o.MOBILE_TEST=`momentic/${PP}`,o.MOBILE_MODULE=`momentic/${OP}`,o))(de||{}),WK=Ot.merge(No),Hp=Wt.extend({steps:Ir.array(Ir.record(Ir.string(),Ir.unknown())),schemaVersion:Ir.string()}),qK=Hp.extend({fileType:Ir.literal(de.MODULE)}),KK=Ir.object({test:Ir.string().describe("YAML for the test, including metadata and steps"),modules:Ir.record(Ir.string(),Ir.string()).describe("Map of module name to YAML for the module")});var Gp=lt.object({parameterNames:lt.string().array(),defaultParameters:lt.record(lt.string(),lt.string()).optional(),parameterEnums:lt.record(lt.string(),lt.string().array()).optional()}),LP=lt.object({moduleId:lt.string().uuid(),name:lt.string(),description:lt.string().nullish(),parameters:Gp.optional(),enabled:lt.boolean().nullish(),schemaVersion:lt.string()}),Jl=LP.omit({name:!0}),ty=Jl.extend({steps:lt.array(lt.record(lt.string(),lt.unknown()))}),NP=lt.object({fileType:lt.literal(de.MOBILE_MODULE)}).merge(ty);import Xt from"zod";var qn=(t=>(t.PRESET="MOBILE_PRESET_STEP",t.MODULE="MOBILE_MODULE_STEP",t))(qn||{}),Ql=Xt.object({id:Xt.string().uuid(),envKey:Xt.string().optional(),skipped:Xt.boolean().optional()}),rs=Ql.extend({type:Xt.literal("MOBILE_PRESET_STEP"),command:JS,keyPressDelayMs:Xt.number().optional()}),ns=Xt.object({moduleId:Xt.string(),inputs:Xt.record(Xt.string(),Xt.string()).optional(),parameters:Gp.optional()}),Zl=Ql.merge(ns.extend({type:Xt.literal("MOBILE_MODULE_STEP")})),rY=ns.extend({steps:Xt.lazy(()=>Vo.array())}),Vo=Xt.discriminatedUnion("type",[rs,Zl]);import ct from"zod";import ec from"zod";var Kn=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(Kn||{}),DP=ns.extend({steps:ec.lazy(()=>os.array()),name:ec.string().describe("name of the module")}),kP=Ql.merge(DP).extend({type:ec.literal("RESOLVED_MOBILE_MODULE")}),os=ec.discriminatedUnion("type",[kP,rs]);function ry(r){return Object.values(Kn).includes(r)||Object.values(qn).includes(r)}var FP=ct.object({disableDefaultWebviewAccessibilityTree:ct.boolean().optional(),autoGrantPermissions:ct.boolean().optional()}),Vp=FP.extend({region:ct.nativeEnum(ts).optional()}),is=ct.object({retries:ct.number().optional().describe("number of retries to run"),defaultChannel:ct.string().optional().describe("default channel to use"),defaultTag:ct.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:ct.string().optional(),emulator:Vp.optional()}),as=ct.object({id:ct.string().uuid(),description:ct.string(),schemaVersion:ct.string(),settings:is.optional()}),UP=as.merge(ct.object({steps:ct.array(Vo)})),BP=ct.object({fileType:ct.literal(de.MOBILE_TEST)}).merge(UP),fY=ct.object({name:ct.string(),steps:ct.array(Vo).optional(),settings:is.optional()}),zP=as.extend({steps:os.array()});import qe from"zod";var zi=qe.object({startTime:qe.number(),endTime:qe.number().optional(),error:qe.string().optional()});var HP=zi.extend({type:qe.literal("SECTION"),name:qe.string(),subSpans:qe.lazy(()=>qP.array())}),GP=zi.extend({type:qe.literal("AI_LOCATOR_CALL"),result:qe.object({serializedElement:qe.string(),id:qe.number(),thoughts:qe.string()}).optional()}),VP=zi.extend({type:qe.literal("AI_ASSERTION_CALL"),result:qe.object({thoughts:qe.string(),result:qe.boolean()}).optional()}),jP=zi.extend({type:qe.literal("WAIT_FOR_STABILITY"),reason:qe.string().optional()}),$P=zi.extend({type:qe.literal("RESOLVE_TARGET_CACHE"),result:qe.object({serializedElement:qe.string()}).optional()}),WP=zi.extend({type:qe.literal("GET_EMULATOR_STATE")}),qP=qe.discriminatedUnion("type",[HP,GP,VP,jP,$P,WP]);import Mr from"zod";var ny=Mr.object({message:Mr.string().optional(),startTime:Mr.number(),endTime:Mr.number(),status:Mr.nativeEnum(ve),trace:Mr.unknown(),beforeSnapshot:Mr.string().optional(),afterSnapshot:Mr.string().optional(),data:Mr.unknown().optional().describe("output data from the step")}),KP=ny.merge(rs),YP=ny.merge(Zl).extend({steps:Mr.lazy(()=>ss.array())}),ss=Mr.discriminatedUnion("type",[KP,YP]);var VY=new Set(Object.values($e));var XP={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"},jY={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:[]},$Y={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."},WY={AI_CHECK:"AI check",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",OPEN_APP:"Open app",JAVASCRIPT:"JavaScript",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",ADB:"ADB command",STATE:"Debug state",RESOLVED_MOBILE_MODULE:"Module"},qY={AI_CHECK:"Ask AI to verify whether something is true on the screen.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a special key on the keyboard.",OPEN_APP:"Open an app on the device.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests."};import JP from"semver";import{z as QP}from"zod";var JY=QP.string().refine(r=>JP.valid(r),{message:"must be a valid semver string"});import{Faker as e5,en as t5}from"@faker-js/faker";import{z as D}from"zod";var Hi=55555,n5=D.object({body:D.string(),to:D.string(),from:D.string()}),o5=D.object({from:D.string().optional(),to:D.string(),timeout:D.number().optional(),beforeDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional()}),i5=D.object({to:D.string().email(),from:D.string(),subject:D.string(),body:D.string(),html:D.string().optional()}),a5=D.object({inbox:D.string().transform(r=>r.toLowerCase()),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),timeout:D.number().optional(),trimWhitespace:D.boolean().optional()}),s5=D.object({inbox:D.string(),limit:D.number().optional(),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),trimWhitespace:D.boolean().optional()});var tc=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(tc||{}),oy=D.object({body:D.string().nullish(),status:D.number().optional(),headers:D.array(D.tuple([D.string(),D.string()])).optional()}),ZP=D.object({url:D.string(),options:D.object({method:D.string(),body:D.string().nullish(),headers:D.array(D.tuple([D.string(),D.string()])).optional()}).optional()}).optional(),eO=D.object({body:D.string().nullish(),options:D.object({status:D.number(),statusText:D.string().optional(),headers:D.array(D.tuple([D.string(),D.string()])).optional()}).optional()}).optional(),iy=D.object({result:D.unknown(),variableUpdates:D.record(D.string(),D.unknown()).optional(),persistentVariableUpdates:D.record(D.string(),D.unknown()).optional(),error:D.string().optional(),success:D.boolean()}),l5=D.object({id:D.string().optional(),orgId:D.string(),momenticLambdaAuthHash:D.string(),code:D.string(),fragment:D.boolean(),state:D.object({env:D.record(D.string(),D.unknown()),request:ZP,response:eO,additionalBindings:D.record(D.string(),D.unknown()).optional()}),timeoutMs:D.number().optional(),disallowVariableUpdates:D.boolean().optional(),responseSerialization:D.nativeEnum(tc).optional()}),Yn=15e3;import*as Lt from"zod";import{extendZodWithOpenApi as tO}from"zod-openapi";tO(Lt);var rO=Lt.object({url:Lt.string(),lineNumber:Lt.number(),columnNumber:Lt.number()}).openapi({ref:"CodeLocation"}),rc=Lt.object({timestamp:Lt.number(),text:Lt.string(),type:Lt.string(),tabIndex:Lt.number(),args:Lt.unknown().array().optional(),url:Lt.string().optional(),location:rO.optional()}).openapi({ref:"ConsoleLog"}),ay=rc.array(),nO=ay.array();import*as $p from"zod";import{extendZodWithOpenApi as RO}from"zod-openapi";import{z as M}from"zod";var oO=M.object({name:M.string(),version:M.string(),comment:M.string().optional()}),iO=M.object({name:M.string(),version:M.string(),comment:M.string().optional()}),aO=M.object({onContentLoad:M.number().optional(),onLoad:M.number().optional(),comment:M.string().optional()}),ly=M.object({startedDateTime:M.string(),id:M.string(),title:M.string().optional(),pageTimings:aO,comment:M.string().optional()}),sO=M.array(ly),lO=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()}),cy=M.array(lO),cO=M.object({name:M.string(),value:M.string(),comment:M.string().optional()}),uy=M.array(cO),uO=M.object({name:M.string(),value:M.string(),comment:M.string().optional()}),dO=M.array(uO),pO=M.object({name:M.string(),value:M.string().optional(),fileName:M.string().optional(),contentType:M.string().optional(),comment:M.string().optional()}),mO=M.array(pO),gO=M.object({mimeType:M.string(),params:mO,text:M.string(),comment:M.string().optional()}),hO=M.object({method:M.string(),url:M.string(),httpVersion:M.string().optional(),cookies:cy,headers:uy,queryString:dO,postData:gO.optional(),headersSize:M.number().optional(),bodySize:M.number().optional(),comment:M.string().optional()}),fO=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()}),SO=M.object({status:M.number(),statusText:M.string(),httpVersion:M.string().optional(),cookies:cy,headers:uy,content:fO,redirectURL:M.string().optional(),headersSize:M.number().optional(),bodySize:M.number().optional(),comment:M.string().optional(),_mocked:M.boolean().optional()}),sy=M.object({expires:M.string().optional(),lastAccess:M.string(),eTag:M.string(),hitCount:M.number(),comment:M.string().optional()}),yO=M.object({beforeRequest:sy.optional(),afterRequest:sy.optional(),comment:M.string().optional()}),EO=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()}),dy=M.object({pageref:M.string().optional(),startedDateTime:M.string(),time:M.number().optional(),request:hO,response:SO.optional(),cache:yO.optional(),timings:EO,serverIPAddress:M.string().optional(),connection:M.string().optional(),comment:M.string().optional(),_resourceType:M.string().optional()}),TO=M.array(dy),bO=M.object({version:M.string().default("1.1"),creator:oO.optional(),browser:iO.optional(),pages:sO.optional(),entries:TO,comment:M.string().optional()}),vO=M.object({log:bO}),py=M.record(M.string(),ly),my=M.record(M.string(),dy);function jp(r,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(r).sort((t,n)=>new Date(t.startedDateTime).getTime()-new Date(n.startedDateTime).getTime()),entries:Object.values(e).sort((t,n)=>new Date(t.startedDateTime).getTime()-new Date(n.startedDateTime).getTime())}}}RO($p);var AO=$p.object({logsPerPage:rc.array().array(),harPages:py.optional(),harEntries:my.optional()}).openapi({ref:"DebugData"});var ls=class{async getConsoleLogsForRunAttempt(e,t,n){}async getNetworkLogsForRunAttempt(e,t,n){}async getHtmlSnapshot(e,t){}async getA11yTreeSnapshot(e,t){}async getScreenshot(e,t){}async storeConsoleLogsForRunAttempt(e,t,n,o){}async storeNetworkLogsForRunAttempt(e,t,n,o){}async storeScreenshot(e,t,n){}async storeHtmlSnapshot(e,t,n){}};var _e=class extends Error{constructor(e,t={}){super(e,t),this.name="ValidationError"}};var nc=class extends Error{constructor(e,t,n,o={}){super(`The ${n} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};function gy(r){for(let e of Object.values(he))if(r.includes(e))return e}var C=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(he))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}}},Gi=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},qr=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
|
|
5
5
|
Decisions:
|
|
6
6
|
${this.decisions.map(e=>e.toString()).join(`
|
|
7
|
-
`)}`}};function oy(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function kp(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 Wr=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},Kl=class extends Wr{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},Yl=class extends Wr{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function Fp(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function Up(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 Bp(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 ns=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};import{cloneDeep as eO}from"lodash-es";import{z as qr}from"zod";var Wn=(g=>(g.DisableClickhouseCaches="disable_clickhouse_caches",g.DisableClickHouseLastUpdatedEndpoint="disable_clickhouse_last_updated_endpoint",g.IconKnowledgeBase="icon_knowledge_base",g.MiniModelInitialAssertion="mini_model_initial_assertion",g.MiniModelInitialLocator="mini_model_initial_locator",g.ShowTestPlans="show_test_plans",g.AiPageSummary="ai_page_summary",g.ShowZeroOpacityElements="show_zero_opacity_elements",g.VisualActions="visual_actions",g.RagV2="rag_v2",g.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",g.GlobalLocatorRedirect="global_locator_redirect",g.FakerConstantSeed="faker_constant_seed",g.AutoExpandIframes="auto_expand_iframes",g))(Wn||{});var iy=qr.union([qr.string(),qr.number(),qr.boolean(),qr.null(),qr.record(qr.string(),qr.lazy(()=>iy)),qr.array(qr.lazy(()=>iy))]),os=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=eO(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(Wn).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")}},h5=new os({},{});var Hp={".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"},ay=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],S5=Object.keys(Hp);import*as sy from"zod";var E5=sy.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as qn}from"zod";var v5=qn.object({id:qn.string(),name:qn.string(),createdAt:qn.coerce.date(),createdBy:qn.string(),updatedAt:qn.coerce.date(),updatedBy:qn.string().nullable(),organizationId:qn.string()});import{z as N}from"zod";import Kn from"zod";var zi=Kn.object({platformSep:Kn.string(),fullPathSegments:Kn.string().array(),relativePathSegments:Kn.string().array(),relativePath:Kn.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:Kn.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:Kn.coerce.date(),createdAt:Kn.coerce.date()});var tO=N.array(zi.extend({id:N.string(),name:N.string(),description:N.string().optional(),labels:N.string().array().optional()})),rO=N.array(zi.extend({id:N.string(),name:N.string(),description:N.string().optional(),content:$a})),D5=N.object({tests:tO,modules:rO,labels:N.string().array()}),k5=jl.merge(mr),ly=N.object({schemaVersion:N.string(),stepLists:xi}),cy=mr.partial().merge(Ot.pick({id:!0})),zp={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(hn).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Ml.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.")},uy=N.object(zp),F5=jl.merge(N.object({relativeFilePath:N.string().describe("relative to project root")})),dy=N.object({name:N.string()}),U5=N.object({relativeFilePath:N.string()}),py=N.object({name:N.string()}),B5=N.object({relativeFilePath:N.string()}),my=N.object({name:N.string(),description:N.string(),enabled:N.boolean(),steps:N.lazy(()=>Ze.array()),testFilePath:N.string().describe("relative to the project root"),folderPath:N.string().optional().describe("user selected folder path")}),gy=N.object({name:N.string(),description:N.string(),enabled:N.boolean()}).partial();var H5=N.array(Xf),hy=N.object({defaultEnv:N.string().optional().describe("name of the default env, or undefined to unset")}),fy=N.object({configFilePath:N.string().describe("full path on disk")}),z5=N.string().array(),G5=N.object({message:N.string(),newRelativeTestPath:N.string().optional()}),Gp=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()}),Sy=N.object({pathSegments:N.array(N.string())}),V5=N.object({absolutePath:N.string(),pathSegments:N.array(N.string()),contents:N.array(Gp)}),yy=N.object({pathSegments:N.array(N.string())}),Ey=N.object({pathSegments:N.array(N.string()),newPathSegments:N.array(N.string())}),Ty=N.object({pathSegments:N.array(N.string()),recursive:N.boolean().optional()}),j5=N.object({success:N.boolean(),message:N.string(),pathSegments:N.array(N.string()).optional()});var Xl=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],Jl=Xl.map(r=>`**/${r}/**`),by=!0,yn=!1;import Kr from"chalk";import nO from"safe-stable-stringify";import oO from"truncate-json";import iO from"zod";var Gi=nO.configure({deterministic:!1});function vy(r){let e=Gi(r),{jsonString:t}=oO(e,1e4);return t}var aO=["app","version","env","namespace","host"];function Pe(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!aO.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var Vp=iO.enum(["debug","info","warn","error"]);var is={debug:20,info:30,warn:40,error:50},Zl={20:"debug",30:"info",40:"warn",50:"error"},as=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=is[e]:this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...n){try{this.logWithLevelHelper(e,t,...n)}catch(o){console.error(`Failed to log to console: ${o}`)}}logWithLevelHelper(e,t,...n){if(e<this.minLogLevel)return;let o;Array.isArray(n[0])?(o=n[0],n=n.slice(1)):typeof n[0]=="object"&&!(n[0]instanceof Error)&&Object.entries(n[0]).length&&(o={...n[0],...this.logBindings},n=n.slice(1));let i=[];if(i.push(...n),console.log(t(...i)),o&&!Array.isArray(o)){let a=Object.entries(o);for(let[l,c]of a){let s=c;c instanceof Error?(s=c.message,console.log(t(` ${l}:`,s)),console.log(t(" stack:",c.stack))):typeof c=="object"&&(s=Gi(c,void 0,2),s=s.split(`
|
|
7
|
+
`)}`}};function hy(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function Wp(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 Kr=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},oc=class extends Kr{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},ic=class extends Kr{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function qp(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function Kp(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 Yp(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 cs=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};import{cloneDeep as wO}from"lodash-es";import{z as Yr}from"zod";var Xp=(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))(Xp||{});var fy=Yr.union([Yr.string(),Yr.number(),Yr.boolean(),Yr.null(),Yr.record(Yr.string(),Yr.lazy(()=>fy)),Yr.array(Yr.lazy(()=>fy))]),us=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=wO(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(Xp).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")}},J5=new us({},{});var Jp={".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"},Sy=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],Z5=Object.keys(Jp);import*as yy from"zod";var t3=yy.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as Xn}from"zod";var o3=Xn.object({id:Xn.string(),name:Xn.string(),createdAt:Xn.coerce.date(),createdBy:Xn.string(),updatedAt:Xn.coerce.date(),updatedBy:Xn.string().nullable(),organizationId:Xn.string()});import{z as N}from"zod";import Jn from"zod";var Vi=Jn.object({platformSep:Jn.string(),fullPathSegments:Jn.string().array(),relativePathSegments:Jn.string().array(),relativePath:Jn.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:Jn.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:Jn.coerce.date(),createdAt:Jn.coerce.date()});var CO=N.array(Vi.extend({id:N.string(),name:N.string(),description:N.string().optional(),labels:N.string().array().optional()})),xO=N.array(Vi.extend({id:N.string(),name:N.string(),description:N.string().optional(),content:qa})),S3=N.object({tests:CO,modules:xO,labels:N.string().array()}),y3=Xl.merge(hr),Ey=N.object({schemaVersion:N.string(),stepLists:Ii}),Ty=hr.partial().merge(Ot.pick({id:!0})),Qp={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(yn).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Ul.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.")},by=N.object(Qp),E3=Xl.merge(N.object({relativeFilePath:N.string().describe("relative to project root")})),vy=N.object({name:N.string()}),T3=N.object({relativeFilePath:N.string()}),Ry=N.object({name:N.string()}),b3=N.object({relativeFilePath:N.string()}),Ay=N.object({name:N.string(),description:N.string(),enabled:N.boolean(),steps:N.lazy(()=>Ze.array()),testFilePath:N.string().describe("relative to the project root"),folderPath:N.string().optional().describe("user selected folder path")}),wy=N.object({name:N.string(),description:N.string(),enabled:N.boolean()}).partial();var v3=N.array(aS),Cy=N.object({defaultEnv:N.string().optional().describe("name of the default env, or undefined to unset")}),xy=N.object({configFilePath:N.string().describe("full path on disk")}),R3=N.string().array(),A3=N.object({message:N.string(),newRelativeTestPath:N.string().optional()}),Zp=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()}),_y=N.object({pathSegments:N.array(N.string())}),w3=N.object({absolutePath:N.string(),pathSegments:N.array(N.string()),contents:N.array(Zp)}),Iy=N.object({pathSegments:N.array(N.string())}),My=N.object({pathSegments:N.array(N.string()),newPathSegments:N.array(N.string())}),Py=N.object({pathSegments:N.array(N.string()),recursive:N.boolean().optional()}),C3=N.object({success:N.boolean(),message:N.string(),pathSegments:N.array(N.string()).optional()});var ac=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],sc=ac.map(r=>`**/${r}/**`),Oy=!0,En=!1;import Xr from"chalk";import _O from"safe-stable-stringify";import IO from"truncate-json";import MO from"zod";var ji=_O.configure({deterministic:!1});function Ly(r){let e=ji(r),{jsonString:t}=IO(e,1e4);return t}var PO=["app","version","env","namespace","host"];function Ne(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!PO.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var em=MO.enum(["debug","info","warn","error"]);var ds={debug:20,info:30,warn:40,error:50},cc={20:"debug",30:"info",40:"warn",50:"error"},ps=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=ds[e]:this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...n){try{this.logWithLevelHelper(e,t,...n)}catch(o){console.error(`Failed to log to console: ${o}`)}}logWithLevelHelper(e,t,...n){if(e<this.minLogLevel)return;let o;Array.isArray(n[0])?(o=n[0],n=n.slice(1)):typeof n[0]=="object"&&!(n[0]instanceof Error)&&Object.entries(n[0]).length&&(o={...n[0],...this.logBindings},n=n.slice(1));let i=[];if(i.push(...n),console.log(t(...i)),o&&!Array.isArray(o)){let a=Object.entries(o);for(let[l,c]of a){let s=c;c instanceof Error?(s=c.message,console.log(t(` ${l}:`,s)),console.log(t(" stack:",c.stack))):typeof c=="object"&&(s=ji(c,void 0,2),s=s.split(`
|
|
8
8
|
`).map((u,d)=>d>0?` ${u}`:u).join(`
|
|
9
|
-
`),console.log(t(` ${l}:`,s)))}}else if(o)for(let a of o){let l=a;typeof a=="object"&&(l=
|
|
9
|
+
`),console.log(t(` ${l}:`,s)))}}else if(o)for(let a of o){let l=a;typeof a=="object"&&(l=ji(a,void 0,2),l=l.split(`
|
|
10
10
|
`).map((c,s)=>s>0?` ${c}`:c).join(`
|
|
11
|
-
`)),console.log(" ",t(l))}}getLevel(){return Zl[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=is[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,Kr.reset,...e)}info(...e){this.logWithLevel(30,Kr.white,...e)}debug(...e){this.logWithLevel(20,Kr.dim,...e)}warn(...e){this.logWithLevel(40,Kr.yellow,...e)}error(...e){this.logWithLevel(50,Kr.red,...e)}success(...e){this.logWithLevel(1/0,Kr.green,...e)}dimmed(...e){this.logWithLevel(30,Kr.dim,...e)}underline(...e){this.logWithLevel(40,Kr.underline,...e)}bold(...e){this.logWithLevel(40,Kr.bold,...e)}grey(...e){this.logWithLevel(20,Kr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},jp=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},Q5=new jp,sO=typeof window>"u"&&typeof process<"u"&&Vp.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?Vp.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,T=new as(sO,{}),En={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>En,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},Ql={},ec=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let l=Ql[e];l?clearTimeout(l.timer):(l={count:0,totalCount:0},Ql[e]=l),l.totalCount++,l.count<t&&(l.count++,r.debug(o,i,...a)),l.timer=setTimeout(()=>{let c=Ql[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete Ql[e]},n)};import{z as Ce}from"zod";var lO=Ce.array(zi.extend({id:Ce.string(),name:Ce.string(),description:Ce.string().optional(),labels:Ce.string().array().optional()})),cO=Ce.array(zi.extend({id:Ce.string(),name:Ce.string(),description:Ce.string().optional(),content:$a})),o3=Ce.object({name:Ce.string(),description:Ce.string().optional(),steps:Ce.array(Sn).optional(),settings:ts.optional(),pathSegments:Ce.string().array()}),i3=Ce.object({id:Ce.string(),fileName:Ce.string(),fullPath:Ce.string(),relativeFilePath:Ce.string().describe("relative to project root")});var a3=Ce.object({steps:Ce.array(Sn).optional(),settings:ts.optional()}),s3=Ce.object({message:Ce.literal("ok")}),l3=Ce.object({tag:Ce.string(),channel:Ce.string(),filePath:Ce.string()}),c3=Ce.object({tests:lO,modules:cO,labels:Ce.string().array()});import{z as nt}from"zod";var Ry=nt.object({id:nt.string(),createdAt:nt.coerce.date(),createdBy:nt.string(),organizationId:nt.string(),name:nt.string(),description:nt.string().nullish(),enabled:nt.boolean(),schemaVersion:nt.string().describe("Schema version for steps"),parameters:nt.string().array().nullish().describe("Parameter list"),parameterEnums:nt.record(nt.string(),nt.string().array()).nullish(),defaultParameters:nt.record(nt.string(),nt.string()).nullish(),defaultCacheKey:nt.string().nullish(),defaultCacheTtl:nt.number().nullish(),defaultCacheAllInvocations:nt.boolean().nullish(),autoAuth:nt.boolean().nullish(),advanced:rp.nullish()}),y3=Ry.extend({steps:nt.lazy(()=>Le.array())}),Ay=5*60*1e3,$p=Wt.merge(Ry.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as b3}from"date-fns-tz";import{z as ke}from"zod";var Wp=Sp.extend({aiAction:ke.boolean().optional(),stepLintSuggestions:ke.boolean().optional(),agentConfig:ke.record(ke.string(),ke.string()).optional(),aiFailureAnalysis:ke.boolean().optional(),aiPageFiltering:ke.boolean().optional().describe("rag v2 feature flag")}),qp=ke.object({fakerConstantSeed:ke.boolean().optional()}),wy=ke.object({ai:Wp.optional(),githubAppInstallationId:ke.number().nullish(),githubAppSummaryMessageEnabled:ke.boolean().nullish(),githubReleaseAppInstallationId:ke.number().nullish(),gitlabAppAccessToken:ke.string().nullish(),gitlabAppBaseUrl:ke.string().nullish(),qaseAccessToken:ke.string().nullish(),testSuggestionsEnabled:ke.boolean().nullish(),browser:up.optional(),advanced:qp.optional()}),x3=ke.object({globalOverrides:ke.record(ke.string()).optional(),agentConfig:ke.record(ke.string(),ke.string()).optional()}),_3=ke.record(ke.string(),ke.string()).nullish();import*as b from"zod";import{z as et}from"zod";var Kp=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(Kp||{});var uO=et.object({type:et.literal("DESCRIPTION_UPDATE"),thoughts:et.string()}),tc=et.discriminatedUnion("type",[uO]),dO=et.object({testId:et.string(),name:et.string(),orgId:et.string(),runId:et.string(),steps:Ze.array(),purpose:et.nativeEnum(Kp),details:tc.or(tc.array()).optional()});var O3=dO.pick({name:!0,orgId:!0}),pO=et.object({id:et.string(),name:et.string().nullish(),createdAt:et.string().pipe(et.coerce.date()).or(et.date()),organizationId:et.string(),schemaVersion:et.string(),runId:et.string().nullish(),purpose:et.nativeEnum(Kp),details:tc.or(tc.array()).optional(),applied:et.boolean().nullish(),appliedAt:et.coerce.date().nullish()}),Cy=pO.extend({steps:Ze.array()});var xy="x-momentic-cli-version",_y="x-momentic-cli-type",mO="x-momentic-main-branch-name",gO="x-momentic-branch-name",hO="x-momentic-commit-timestamp",fO="x-momentic-last-commit-on-main",SO="x-momentic-last-commit-on-main-timestamp",yO="x-momentic-merged-branch-name",Iy="x-momentic-session-id",Y3=b.object({error:b.boolean(),reason:b.string(),message:b.string()}),X3=Mt.merge(Tp),Py=El,J3=Mt.merge(Tp);var Q3=Mt.merge(SS).extend({useConsensus:b.boolean().optional(),attemptNumber:b.number().optional()}),Yp=Tf,Z3=Mt.merge(ES),My=Bf,eX=Mt.merge(yS),Oy=Uf,tX=Mt.merge(gS),Ly=Ff,rX=Mt.merge(hS),Ny=Df,nX=Mt.merge(fS);var oX=Mt.merge(RS),iX=b.object({testPaths:b.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:b.string().optional(),all:b.boolean().optional(),urlOverride:b.string().optional(),customHeaders:b.record(b.string(),b.string()).optional(),testInputMatrix:b.record(b.string(),b.string()).array().optional()}),Dy=b.object({queuedTests:b.unknown().array(),runIds:b.string().uuid().array(),runGroupId:b.string().optional()});var aX=b.string().array(),sX=b.union([b.object({paths:b.string().array().describe("run specific test paths (e.g. todo-test)"),all:b.boolean().describe("run all tests").optional()}),b.object({path:b.string().describe("deprecated; present for backcompat")})]),ky=b.object({tests:b.record(b.string().describe("Test name"),b.string().describe("Test YAML")),modules:b.record(b.string().describe("Module name"),b.string().describe("Module YAML"))}),EO=b.object({test:b.string().describe("test YAML"),modules:b.record(b.string().describe("moduleId"),b.string().describe("module YAML"))}),lX=EO.array(),cX=b.object({testId:b.string(),schemaVersion:b.string()}).merge(Mo);function Xp(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[mO]=encodeURIComponent(e)),t&&(a[gO]=encodeURIComponent(t)),n&&(a[hO]=n.toISOString()),o&&(a[fO]=encodeURIComponent(o)),i&&(a[SO]=i.toISOString()),r.mergedGitBranchName&&(a[yO]=encodeURIComponent(r.mergedGitBranchName)),a}var uX=b.object({entries:b.array(Pf),testId:b.string()}),dX=b.object({entries:b.array(GS),testId:b.string()}),pX=b.object({testId:b.string()});function Fy(r){return b.record(b.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 Uy=Fy(Mf),By=Fy(VS),Hy=b.object({trigger:b.nativeEnum(ur),status:b.nativeEnum(he),startedAt:b.coerce.date().optional(),gitCommitSha:b.string().optional(),gitCommitShaShort:b.string().optional(),gitCommitTimestamp:b.coerce.date().optional(),gitBranchName:b.string().optional(),gitOriginUrl:b.string().optional(),gitCommitMessage:b.string().optional(),gitCommitAuthorName:b.string().optional(),githubRepository:b.string().optional(),gitlabProjectPath:b.string().optional(),pipelineId:b.string().optional(),cliVersion:b.string().optional()}),mX=b.object({id:b.string()}),zy=b.object({status:b.nativeEnum(he),updatedAt:b.coerce.date().optional(),finishedAt:b.coerce.date().optional()}),Gy=b.object({stepsSnapshot:b.array(b.record(b.unknown())).optional(),runGroupId:b.string().optional(),testId:b.string(),testName:b.string(),resolvedBaseUrl:b.string().optional(),environmentName:b.string().optional(),labels:b.array(b.string()).optional(),cliVersion:b.string().optional(),trigger:b.nativeEnum(ur),schemaVersion:b.string().optional(),section:b.nativeEnum(Dl).optional(),resolvedInputs:b.record(b.string(),b.string()).optional(),quarantined:b.boolean().optional().default(!1),quarantinedReason:b.string().optional()}),gX=b.object({id:b.string()}),TO=yp.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Vy=TO.array(),jy=yp.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(),hX=b.object({id:b.string()}),$y=b.object({status:b.nativeEnum(he),finishedAt:b.coerce.date().optional(),schemaVersion:b.string().optional().default("1.0.19"),results:b.record(b.string(),b.unknown()).array().optional(),beforeResults:b.record(b.string(),b.unknown()).array().optional(),afterResults:b.record(b.string(),b.unknown()).array().optional()}),fX=b.object({screenshot:b.string()}),Wy=b.object({key:b.string()}),qy=b.object({orgId:b.string(),userId:b.string()}),Ky=b.array(Yf),SX=b.record(b.string(),b.union([b.string(),b.boolean()])),yX=b.object({paths:b.string().array(),env:b.string().optional(),urlOverride:b.string().optional(),customHeaders:b.record(b.string(),b.string()).optional()}),Yy=b.object({suiteRunIds:b.string().array(),runGroupIds:b.string().array()}),EX=b.object({suiteRunIds:b.string().array()}),TX=uS.array(),bX=b.object({runGroupIds:b.string().array()}),bO=b.object({uploadUrl:b.string()}),vX=Mt.merge(TS),RX=Mt.merge(vS),AX=Mt.merge(bS),vO=b.object({testId:b.string().optional().default(""),testName:b.string().optional().default(""),suiteId:b.string().optional().default(""),suiteName:b.string().optional().default(""),creditsUsed:b.number().optional()}),RO=b.object({transactionId:b.string(),timestamp:b.string(),event:b.nativeEnum(Qa),properties:vO}),wX=RO.array(),Xy=Cy.omit({steps:!0}).extend({steps:b.array(b.record(b.string(),b.unknown())).describe("unparsed ResolvedStep[]")}),CX=b.object({limit:b.number().max(10).optional(),afterTime:b.number().optional()}),Jy=iS.array(),xX=b.object({applied:b.boolean().optional(),appliedAt:b.coerce.date().optional()}),Qy=bO.extend({id:b.string()}),_X=b.object({runGroupId:b.string().uuid().optional()}),Zy=b.object({runGroupId:b.string().uuid()}),eE=b.object({quarantined:b.object({testId:b.string().uuid(),quarantinedAt:b.coerce.date(),quarantinedBy:b.string().optional(),quarantinedReason:b.string()}).array()}),IX=b.object({testId:b.string().uuid(),testName:b.string().optional(),reason:b.string(),gitLocalUsername:b.string().optional(),gitLocalEmail:b.string().optional(),gitLocalName:b.string().optional()}),PX=b.object({testName:b.string().optional(),reason:b.string().optional(),gitLocalUsername:b.string().optional(),gitLocalEmail:b.string().optional(),gitLocalName:b.string().optional()}),MX=Mt.merge(CS),OX=Mt.merge(xS),LX=b.object({apkToInstall:b.object({channel:b.string(),tag:b.string().optional()}).optional(),hostname:b.string().optional(),region:b.nativeEnum(es).optional()}),tE=b.object({name:b.string(),webRtcUrl:b.string(),adbUrl:b.string(),token:b.string(),apkDownloadUrl:b.string().optional(),region:b.string().optional()}),NX=b.object({channel:b.string(),tag:b.string(),md5:b.string()}),rE=b.object({id:b.string(),uploadUrl:b.string().optional(),downloadUrl:b.string(),md5:b.string().optional()}),nE=b.object({assets:b.array(b.object({channel:b.string(),tag:b.string(),md5:b.string(),createdAt:b.number().describe("Unix timestamp in milliseconds")}))});import{z as J}from"zod";var AO=3,FX=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()})),oE=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(oE||{});var Jp=J.object({name:J.string(),description:J.string().nullish(),effect:J.nativeEnum(oE),labels:J.array(J.string()),githubRepository:J.string().nullish(),gitlabProjectPath:J.string().nullish(),gitBranchName:J.string().nullish()}),wO=J.object({type:J.literal("LAST_N_RUNS"),lastN:J.number().min(AO).max(10)}),CO=J.object({type:J.literal("LAST_N_HOURS"),lastN:J.number().min(1).max(24)}),xO=J.object({type:J.literal("LAST_N_DAYS"),lastN:J.number().min(1).max(7)}),Qp=J.discriminatedUnion("type",[wO,CO,xO]),_O=J.object({flakeRateThreshold:J.number().min(1).max(100),evaluationWindow:Qp}),IO=Jp.extend({type:J.literal("FLAKE_RATE"),config:_O}),PO=J.object({passRateThreshold:J.number().min(1).max(100),evaluationWindow:Qp}),MO=Jp.extend({type:J.literal("PASS_RATE"),config:PO}),OO=J.object({failureCountThreshold:J.number().min(0),evaluationWindow:Qp}),LO=Jp.extend({type:J.literal("FAILURE_COUNT"),config:OO}),UX=J.discriminatedUnion("type",[IO,MO,LO]);import{z as ot}from"zod";var zX=ot.object({repositoriesIndexed:ot.boolean(),indexingInProgress:ot.boolean(),indexesOutdated:ot.boolean()}),iE=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(iE||{}),aE=(l=>(l.Success="success",l.Failure="failure",l.Neutral="neutral",l.Cancelled="cancelled",l.Skipped="skipped",l.TimedOut="timed_out",l.ActionRequired="action_required",l))(aE||{}),GX=ot.object({name:ot.string(),status:ot.nativeEnum(iE),conclusion:ot.nativeEnum(aE).nullable()}),ss=ot.object({sha:ot.string(),message:ot.string(),author:ot.object({name:ot.string().optional(),email:ot.string().optional(),date:ot.coerce.date().optional()}),committer:ot.object({name:ot.string().optional(),email:ot.string().optional(),date:ot.coerce.date().optional()})}),Zp=ot.object({mergedBranch:ot.string().optional()});import{z as $e}from"zod";var sE=$e.object({orgId:$e.string(),cacheKeys:$e.string().array()}),$X=$e.object({keyParams:sE,clientMetadata:$e.string(),lockAcquisitionTimeoutMs:$e.number().optional()}),lE=$e.object({acquired:$e.boolean(),acquiredByMetadata:$e.string(),keyPrefix:$e.string()}),WX=$e.object({keyPrefix:$e.string(),result:$e.string(),ttlMs:$e.number()}),qX=$e.union([$e.object({keyPrefix:$e.string()}),sE]),NO=$e.object({remainingTtlMs:$e.number(),value:$e.string().nullish()}),KX=$e.object({results:$e.record($e.string(),NO),activeLocks:$e.string().array()}),cE=0,uE=5*60*1e3;var QX=90*24*60*60*1e3,ZX=7*24*60*60*1e3;import{z as dE}from"zod";var r4=dE.object({quarantineNotifications:dE.string().nullish()});import{z as Rt}from"zod";var DO=Rt.object({version:Rt.string(),json:Rt.record(Rt.unknown()),hash:Rt.string()}),pE=Rt.record(Rt.unknown()),a4=Rt.object({newSvgs:Rt.array(DO),metadata:pE.optional()}),kO=Rt.object({version:Rt.string(),json:Rt.record(Rt.unknown()).nullish(),hash:Rt.string(),description:Rt.string().nullish(),metadata:pE.nullish()}),mE=Rt.record(Rt.string().describe("icon hash"),kO);import{z as Xe}from"zod";var em=Xe.object({assertion:Xe.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),FO=Xe.object({instruction:Xe.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:em.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.")}),gE=FO.extend({subSteps:Xe.lazy(()=>gE.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),hE=Xe.object({name:Xe.string().describe("Short name describing the test plan"),description:Xe.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),fE=hE.extend({id:Xe.string(),createdAt:Xe.coerce.date(),updatedAt:Xe.coerce.date(),updatedBy:Xe.string(),createdBy:Xe.string(),test:Xe.object({id:Xe.string(),name:Xe.string()}).nullish().transform(r=>r??void 0)}),u4=fE.extend({testGenRuns:Xe.tuple([]).or(Xe.tuple([Xe.object({id:Xe.string(),startedAt:Xe.coerce.date(),status:Xe.nativeEnum(he)})]))}),SE=Xe.object({preConditions:em.array().nullish().transform(r=>r??[]),postConditions:em.array().nullish().transform(r=>r??[]),steps:gE.array().nullish().transform(r=>r??[])}),d4=fE.extend({plan:SE.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),UO=hE.extend({plan:SE.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),p4=UO.array().nullish().transform(r=>r??[]);import{validator as BO}from"@exodus/schemasafe";function yE(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{BO(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var EE=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as I4}from"zod";var rc=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};var tm=class{getParentStepIdChain(){return[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}async finish(){}async startSubSteps(){return new ls}},ls=class{getParentStepIdChain(){return[]}async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new tm}};import{z as X}from"zod";var HO=X.object({step:Ze,status:X.nativeEnum(Ae),startedAt:X.coerce.date(),finishedAt:X.coerce.date().optional(),healMetadata:X.object({healType:X.nativeEnum(Wa).or(X.literal("AI")),healedAt:X.coerce.date()}).optional(),beforeSnapshotId:X.string().uuid().optional(),afterSnapshotId:X.string().uuid().optional(),message:X.string().optional()}),q4=HO.extend({finishedAt:X.coerce.date().optional().transform(r=>r??new Date)}),TE="1.0.0",rm=$y.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()}),bE=rm.extend({finishedAt:X.coerce.date().optional().transform(r=>r??new Date)}),K4=rm.merge(Ka),Y4=bE.merge(Ka),vE=X.object({results:X.array(Vl),beforeResults:X.array(Vl).optional(),afterResults:X.array(Vl).optional()}),X4=rm.merge(vE),J4=bE.merge(vE),zO=jy.merge(Gy).extend({executionType:X.nativeEnum(Mi).optional().default("WEB"),testId:X.string().uuid(),testDescription:X.string().optional(),runGroupId:X.string().uuid(),status:X.nativeEnum(he),startedAt:X.coerce.date(),attempts:X.number(),failureRecoveryDetails:X.record(X.unknown()).optional()}),Q4=zO.extend({finishedAt:X.coerce.date().optional().transform(r=>r??new Date)}),GO=Hy.merge(zy).extend({id:X.string().uuid().optional(),startedAt:X.coerce.date(),cliVersion:X.string(),labels:X.string().array().optional().default([])}),cs=GO.extend({updatedAt:X.coerce.date().optional().transform(r=>r??new Date),finishedAt:X.coerce.date().optional().transform(r=>r??new Date)});function RE(r){try{return VO(r)&&jO(r).isDirectory()}catch(e){return T.error({err:e},`Error reading path ${r} during directory existence check`),!1}}import{confirm as oL,input as iL}from"@inquirer/prompts";import{existsSync as aL,mkdirSync as sL,statSync as lL}from"fs";import{dirname as cL}from"path";import Yr,{supportsColor as rL}from"chalk";import{Console as AE}from"console";import{format as us}from"util";var nm=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}},nc=class r extends AE{_buffer=[];_groupDepth=0;Console=AE;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new nm(void 0,r.write).stack;if(!i)return e;let a=i.split(`
|
|
11
|
+
`)),console.log(" ",t(l))}}getLevel(){return cc[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=ds[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,Xr.reset,...e)}info(...e){this.logWithLevel(30,Xr.white,...e)}debug(...e){this.logWithLevel(20,Xr.dim,...e)}warn(...e){this.logWithLevel(40,Xr.yellow,...e)}error(...e){this.logWithLevel(50,Xr.red,...e)}success(...e){this.logWithLevel(1/0,Xr.green,...e)}dimmed(...e){this.logWithLevel(30,Xr.dim,...e)}underline(...e){this.logWithLevel(40,Xr.underline,...e)}bold(...e){this.logWithLevel(40,Xr.bold,...e)}grey(...e){this.logWithLevel(20,Xr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},tm=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},N3=new tm,OO=typeof window>"u"&&typeof process<"u"&&em.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?em.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,T=new ps(OO,{}),Tn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Tn,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},lc={},uc=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let l=lc[e];l?clearTimeout(l.timer):(l={count:0,totalCount:0},lc[e]=l),l.totalCount++,l.count<t&&(l.count++,r.debug(o,i,...a)),l.timer=setTimeout(()=>{let c=lc[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete lc[e]},n)};import{z as Ae}from"zod";var LO=Ae.array(Vi.extend({id:Ae.string(),name:Ae.string(),description:Ae.string().optional(),labels:Ae.string().array().optional()})),NO=Ae.array(Vi.extend({id:Ae.string(),name:Ae.string(),description:Ae.string().optional(),content:qa})),z3=Ae.object({name:Ae.string(),description:Ae.string().optional(),settings:is.optional(),pathSegments:Ae.string().array()}),H3=Ae.object({id:Ae.string(),fileName:Ae.string(),fullPath:Ae.string(),relativeFilePath:Ae.string().describe("relative to project root")});var G3=Ae.object({steps:os.array().optional(),settings:is.optional()}),V3=Ae.object({message:Ae.literal("ok")}),j3=Ae.object({tag:Ae.string(),channel:Ae.string(),filePath:Ae.string()}),$3=Ae.object({tests:LO,modules:NO,labels:Ae.string().array()}),W3=Ae.object({name:Ae.string(),description:Ae.string(),enabled:Ae.boolean()}).partial();import{z as rt}from"zod";var Ny=rt.object({id:rt.string(),createdAt:rt.coerce.date(),createdBy:rt.string(),organizationId:rt.string(),name:rt.string(),description:rt.string().nullish(),enabled:rt.boolean(),schemaVersion:rt.string().describe("Schema version for steps"),parameters:rt.string().array().nullish().describe("Parameter list"),parameterEnums:rt.record(rt.string(),rt.string().array()).nullish(),defaultParameters:rt.record(rt.string(),rt.string()).nullish(),defaultCacheKey:rt.string().nullish(),defaultCacheTtl:rt.number().nullish(),defaultCacheAllInvocations:rt.boolean().nullish(),autoAuth:rt.boolean().nullish(),advanced:mp.nullish()}),tX=Ny.extend({steps:rt.lazy(()=>Pe.array())}),Dy=5*60*1e3,rm=Wt.merge(Ny.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as oX}from"date-fns-tz";import{z as De}from"zod";var nm=_p.extend({aiAction:De.boolean().optional(),stepLintSuggestions:De.boolean().optional(),agentConfig:De.record(De.string(),De.string()).optional(),aiFailureAnalysis:De.boolean().optional(),aiPageFiltering:De.boolean().optional().describe("rag v2 feature flag")}),om=De.object({fakerConstantSeed:De.boolean().optional()}),ky=De.object({ai:nm.optional(),githubAppInstallationId:De.number().nullish(),githubAppSummaryMessageEnabled:De.boolean().nullish(),githubReleaseAppInstallationId:De.number().nullish(),gitlabAppAccessToken:De.string().nullish(),gitlabAppBaseUrl:De.string().nullish(),qaseAccessToken:De.string().nullish(),testSuggestionsEnabled:De.boolean().nullish(),browser:bp.optional(),advanced:om.optional()}),uX=De.object({globalOverrides:De.record(De.string()).optional(),agentConfig:De.record(De.string(),De.string()).optional()}),dX=De.record(De.string(),De.string()).nullish();import*as b from"zod";import{z as et}from"zod";var im=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(im||{});var DO=et.object({type:et.literal("DESCRIPTION_UPDATE"),thoughts:et.string()}),dc=et.discriminatedUnion("type",[DO]),kO=et.object({testId:et.string(),name:et.string(),orgId:et.string(),runId:et.string(),steps:Ze.array(),purpose:et.nativeEnum(im),details:dc.or(dc.array()).optional()});var hX=kO.pick({name:!0,orgId:!0}),FO=et.object({id:et.string(),name:et.string().nullish(),createdAt:et.string().pipe(et.coerce.date()).or(et.date()),organizationId:et.string(),schemaVersion:et.string(),runId:et.string().nullish(),purpose:et.nativeEnum(im),details:dc.or(dc.array()).optional(),applied:et.boolean().nullish(),appliedAt:et.coerce.date().nullish()}),Fy=FO.extend({steps:Ze.array()});var Uy="x-momentic-cli-version",By="x-momentic-cli-type",UO="x-momentic-main-branch-name",BO="x-momentic-branch-name",zO="x-momentic-commit-timestamp",HO="x-momentic-last-commit-on-main",GO="x-momentic-last-commit-on-main-timestamp",VO="x-momentic-merged-branch-name",zy="x-momentic-session-id",OX=b.object({error:b.boolean(),reason:b.string(),message:b.string()}),LX=Pt.merge(Pp),Hy=Cl,NX=Pt.merge(Pp);var DX=Pt.merge(xS).extend({useConsensus:b.boolean().optional(),attemptNumber:b.number().optional()}),am=Mf,kX=Pt.merge(IS),Gy=Yf,FX=Pt.merge(_S),Vy=Kf,UX=Pt.merge(AS),jy=qf,BX=Pt.merge(wS),$y=$f,zX=Pt.merge(CS);var HX=Pt.merge(LS),GX=b.object({testPaths:b.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:b.string().optional(),all:b.boolean().optional(),urlOverride:b.string().optional(),customHeaders:b.record(b.string(),b.string()).optional(),testInputMatrix:b.record(b.string(),b.string()).array().optional()}),Wy=b.object({queuedTests:b.unknown().array(),runIds:b.string().uuid().array(),runGroupId:b.string().optional()});var VX=b.string().array(),jX=b.union([b.object({paths:b.string().array().describe("run specific test paths (e.g. todo-test)"),all:b.boolean().describe("run all tests").optional()}),b.object({path:b.string().describe("deprecated; present for backcompat")})]),qy=b.object({tests:b.record(b.string().describe("Test name"),b.string().describe("Test YAML")),modules:b.record(b.string().describe("Module name"),b.string().describe("Module YAML"))}),jO=b.object({test:b.string().describe("test YAML"),modules:b.record(b.string().describe("moduleId"),b.string().describe("module YAML"))}),$X=jO.array(),WX=b.object({testId:b.string(),schemaVersion:b.string()}).merge(No);function sm(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[UO]=encodeURIComponent(e)),t&&(a[BO]=encodeURIComponent(t)),n&&(a[zO]=n.toISOString()),o&&(a[HO]=encodeURIComponent(o)),i&&(a[GO]=i.toISOString()),r.mergedGitBranchName&&(a[VO]=encodeURIComponent(r.mergedGitBranchName)),a}var qX=b.object({entries:b.array(zf),testId:b.string()}),KX=b.object({entries:b.array(ZS),testId:b.string()}),YX=b.object({testId:b.string()});function Ky(r){return b.record(b.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 Yy=Ky(Hf),Xy=Ky(ey),Jy=b.object({trigger:b.nativeEnum(pr),status:b.nativeEnum(Se),startedAt:b.coerce.date().optional(),gitCommitSha:b.string().optional(),gitCommitShaShort:b.string().optional(),gitCommitTimestamp:b.coerce.date().optional(),gitBranchName:b.string().optional(),gitOriginUrl:b.string().optional(),gitCommitMessage:b.string().optional(),gitCommitAuthorName:b.string().optional(),githubRepository:b.string().optional(),gitlabProjectPath:b.string().optional(),pipelineId:b.string().optional(),cliVersion:b.string().optional()}),XX=b.object({id:b.string()}),Qy=b.object({status:b.nativeEnum(Se),updatedAt:b.coerce.date().optional(),finishedAt:b.coerce.date().optional()}),Zy=b.object({stepsSnapshot:b.array(b.record(b.unknown())).optional(),runGroupId:b.string().optional(),testId:b.string(),testName:b.string(),resolvedBaseUrl:b.string().optional(),environmentName:b.string().optional(),labels:b.array(b.string()).optional(),cliVersion:b.string().optional(),trigger:b.nativeEnum(pr),schemaVersion:b.string().optional(),section:b.nativeEnum(Gl).optional(),resolvedInputs:b.record(b.string(),b.string()).optional(),quarantined:b.boolean().optional().default(!1),quarantinedReason:b.string().optional()}),JX=b.object({id:b.string()}),$O=Ip.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),eE=$O.array(),tE=Ip.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(),QX=b.object({id:b.string()}),rE=b.object({status:b.nativeEnum(Se),finishedAt:b.coerce.date().optional(),schemaVersion:b.string().optional().default("1.0.19"),results:b.record(b.string(),b.unknown()).array().optional(),beforeResults:b.record(b.string(),b.unknown()).array().optional(),afterResults:b.record(b.string(),b.unknown()).array().optional()}),ZX=b.object({screenshot:b.string()}),nE=b.object({key:b.string()}),oE=b.object({orgId:b.string(),userId:b.string()}),iE=b.array(iS),e4=b.record(b.string(),b.union([b.string(),b.boolean()])),t4=b.object({paths:b.string().array(),env:b.string().optional(),urlOverride:b.string().optional(),customHeaders:b.record(b.string(),b.string()).optional()}),aE=b.object({suiteRunIds:b.string().array(),runGroupIds:b.string().array()}),r4=b.object({suiteRunIds:b.string().array()}),n4=TS.array(),o4=b.object({runGroupIds:b.string().array()}),WO=b.object({uploadUrl:b.string()}),i4=Pt.merge(MS),a4=Pt.merge(OS),s4=Pt.merge(PS),qO=b.object({testId:b.string().optional().default(""),testName:b.string().optional().default(""),suiteId:b.string().optional().default(""),suiteName:b.string().optional().default(""),creditsUsed:b.number().optional()}),KO=b.object({transactionId:b.string(),timestamp:b.string(),event:b.nativeEnum(es),properties:qO}),l4=KO.array(),sE=Fy.omit({steps:!0}).extend({steps:b.array(b.record(b.string(),b.unknown())).describe("unparsed ResolvedStep[]")}),c4=b.object({limit:b.number().max(10).optional(),afterTime:b.number().optional()}),lE=hS.array(),u4=b.object({applied:b.boolean().optional(),appliedAt:b.coerce.date().optional()}),cE=WO.extend({id:b.string()}),d4=b.object({runGroupId:b.string().uuid().optional()}),uE=b.object({runGroupId:b.string().uuid()}),dE=b.object({quarantined:b.object({testId:b.string().uuid(),quarantinedAt:b.coerce.date(),quarantinedBy:b.string().optional(),quarantinedReason:b.string()}).array()}),p4=b.object({testId:b.string().uuid(),testName:b.string().optional(),reason:b.string(),gitLocalUsername:b.string().optional(),gitLocalEmail:b.string().optional(),gitLocalName:b.string().optional()}),m4=b.object({testName:b.string().optional(),reason:b.string().optional(),gitLocalUsername:b.string().optional(),gitLocalEmail:b.string().optional(),gitLocalName:b.string().optional()}),g4=Pt.merge(kS),h4=Pt.merge(FS),f4=b.object({apkToInstall:b.object({channel:b.string(),tag:b.string().optional()}).optional(),hostname:b.string().optional(),region:b.nativeEnum(ts).optional()}),pE=b.object({name:b.string(),webRtcUrl:b.string(),adbUrl:b.string(),token:b.string(),apkDownloadUrl:b.string().optional(),region:b.string().optional()}),S4=b.object({channel:b.string(),tag:b.string(),md5:b.string()}),mE=b.object({id:b.string(),uploadUrl:b.string().optional(),downloadUrl:b.string(),md5:b.string().optional()}),gE=b.object({assets:b.array(b.object({channel:b.string(),tag:b.string(),md5:b.string(),createdAt:b.number().describe("Unix timestamp in milliseconds")}))});import{z as J}from"zod";var YO=3,T4=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()})),hE=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(hE||{});var lm=J.object({name:J.string(),description:J.string().nullish(),effect:J.nativeEnum(hE),labels:J.array(J.string()),githubRepository:J.string().nullish(),gitlabProjectPath:J.string().nullish(),gitBranchName:J.string().nullish()}),XO=J.object({type:J.literal("LAST_N_RUNS"),lastN:J.number().min(YO).max(10)}),JO=J.object({type:J.literal("LAST_N_HOURS"),lastN:J.number().min(1).max(24)}),QO=J.object({type:J.literal("LAST_N_DAYS"),lastN:J.number().min(1).max(7)}),cm=J.discriminatedUnion("type",[XO,JO,QO]),ZO=J.object({flakeRateThreshold:J.number().min(1).max(100),evaluationWindow:cm}),eL=lm.extend({type:J.literal("FLAKE_RATE"),config:ZO}),tL=J.object({passRateThreshold:J.number().min(1).max(100),evaluationWindow:cm}),rL=lm.extend({type:J.literal("PASS_RATE"),config:tL}),nL=J.object({failureCountThreshold:J.number().min(0),evaluationWindow:cm}),oL=lm.extend({type:J.literal("FAILURE_COUNT"),config:nL}),b4=J.discriminatedUnion("type",[eL,rL,oL]);import{z as nt}from"zod";var A4=nt.object({repositoriesIndexed:nt.boolean(),indexingInProgress:nt.boolean(),indexesOutdated:nt.boolean()}),fE=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(fE||{}),SE=(l=>(l.Success="success",l.Failure="failure",l.Neutral="neutral",l.Cancelled="cancelled",l.Skipped="skipped",l.TimedOut="timed_out",l.ActionRequired="action_required",l))(SE||{}),w4=nt.object({name:nt.string(),status:nt.nativeEnum(fE),conclusion:nt.nativeEnum(SE).nullable()}),ms=nt.object({sha:nt.string(),message:nt.string(),author:nt.object({name:nt.string().optional(),email:nt.string().optional(),date:nt.coerce.date().optional()}),committer:nt.object({name:nt.string().optional(),email:nt.string().optional(),date:nt.coerce.date().optional()})}),um=nt.object({mergedBranch:nt.string().optional()});import{z as He}from"zod";var yE=He.object({orgId:He.string(),cacheKeys:He.string().array()}),_4=He.object({keyParams:yE,clientMetadata:He.string(),lockAcquisitionTimeoutMs:He.number().optional()}),EE=He.object({acquired:He.boolean(),acquiredByMetadata:He.string(),keyPrefix:He.string()}),I4=He.object({keyPrefix:He.string(),result:He.string(),ttlMs:He.number()}),M4=He.union([He.object({keyPrefix:He.string()}),yE]),iL=He.object({remainingTtlMs:He.number(),value:He.string().nullish()}),P4=He.object({results:He.record(He.string(),iL),activeLocks:He.string().array()}),TE=0,bE=5*60*1e3;var D4=90*24*60*60*1e3,k4=7*24*60*60*1e3;import{z as vE}from"zod";var B4=vE.object({quarantineNotifications:vE.string().nullish()});import{z as Rt}from"zod";var aL=Rt.object({version:Rt.string(),json:Rt.record(Rt.unknown()),hash:Rt.string()}),RE=Rt.record(Rt.unknown()),V4=Rt.object({newSvgs:Rt.array(aL),metadata:RE.optional()}),sL=Rt.object({version:Rt.string(),json:Rt.record(Rt.unknown()).nullish(),hash:Rt.string(),description:Rt.string().nullish(),metadata:RE.nullish()}),AE=Rt.record(Rt.string().describe("icon hash"),sL);import{z as Ke}from"zod";var dm=Ke.object({assertion:Ke.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),lL=Ke.object({instruction:Ke.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:dm.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.")}),wE=lL.extend({subSteps:Ke.lazy(()=>wE.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),CE=Ke.object({name:Ke.string().describe("Short name describing the test plan"),description:Ke.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),xE=CE.extend({id:Ke.string(),createdAt:Ke.coerce.date(),updatedAt:Ke.coerce.date(),updatedBy:Ke.string(),createdBy:Ke.string(),test:Ke.object({id:Ke.string(),name:Ke.string()}).nullish().transform(r=>r??void 0)}),q4=xE.extend({testGenRuns:Ke.tuple([]).or(Ke.tuple([Ke.object({id:Ke.string(),startedAt:Ke.coerce.date(),status:Ke.nativeEnum(Se)})]))}),_E=Ke.object({preConditions:dm.array().nullish().transform(r=>r??[]),postConditions:dm.array().nullish().transform(r=>r??[]),steps:wE.array().nullish().transform(r=>r??[])}),K4=xE.extend({plan:_E.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),cL=CE.extend({plan:_E.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),Y4=cL.array().nullish().transform(r=>r??[]);import{validator as uL}from"@exodus/schemasafe";function IE(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{uL(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var ME=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as pJ}from"zod";var pc=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};var mm="browser-crash-dump.zip",pm=class{getParentStepIdChain(){return[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}async finish(){}async startSubSteps(){return new gs}},gs=class{getParentStepIdChain(){return[]}async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new pm}};import{z as Y}from"zod";var dL=Y.object({step:Ze,status:Y.nativeEnum(ve),startedAt:Y.coerce.date(),finishedAt:Y.coerce.date().optional(),healMetadata:Y.object({healType:Y.nativeEnum(Ka).or(Y.literal("AI")),healedAt:Y.coerce.date()}).optional(),beforeSnapshotId:Y.string().uuid().optional(),afterSnapshotId:Y.string().uuid().optional(),message:Y.string().optional()}),MJ=dL.extend({finishedAt:Y.coerce.date().optional().transform(r=>r??new Date)}),PE="1.0.0",gm=rE.extend({id:Y.string().uuid().optional(),startedAt:Y.coerce.date(),runAttemptSchemaVersion:Y.string().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()}),OE=gm.extend({finishedAt:Y.coerce.date().optional().transform(r=>r??new Date)}),PJ=gm.merge(Xa),OJ=OE.merge(Xa),LE=Y.object({results:Y.array(ss),beforeResults:Y.array(ss).optional(),afterResults:Y.array(ss).optional()}),LJ=gm.merge(LE),NJ=OE.merge(LE),pL=tE.merge(Zy).extend({executionType:Y.nativeEnum(Li).optional().default("WEB"),testId:Y.string().uuid(),testDescription:Y.string().optional(),runGroupId:Y.string().uuid(),status:Y.nativeEnum(Se),startedAt:Y.coerce.date(),attempts:Y.number(),failureRecoveryDetails:Y.record(Y.unknown()).optional()}),DJ=pL.extend({finishedAt:Y.coerce.date().optional().transform(r=>r??new Date)}),mL=Jy.merge(Qy).extend({id:Y.string().uuid().optional(),startedAt:Y.coerce.date(),cliVersion:Y.string(),labels:Y.string().array().optional().default([])}),hs=mL.extend({updatedAt:Y.coerce.date().optional().transform(r=>r??new Date),finishedAt:Y.coerce.date().optional().transform(r=>r??new Date)});function NE(r){try{return gL(r)&&hL(r).isDirectory()}catch(e){return T.error({err:e},`Error reading path ${r} during directory existence check`),!1}}import{confirm as IL,input as ML}from"@inquirer/prompts";import{existsSync as PL,mkdirSync as OL,statSync as LL}from"fs";import{dirname as NL}from"path";import Jr,{supportsColor as xL}from"chalk";import{Console as DE}from"console";import{format as fs}from"util";var hm=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 DE{_buffer=[];_groupDepth=0;Console=DE;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new hm(void 0,r.write).stack;if(!i)return e;let a=i.split(`
|
|
12
12
|
`).slice(o).filter(Boolean).join(`
|
|
13
|
-
`);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",
|
|
13
|
+
`);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",fs(e,...t))}error(e,...t){this._log("error",fs(e,...t))}info(e,...t){this._log("info",fs(e,...t))}log(e,...t){this._log("log",fs(e,...t))}warn(e,...t){this._log("warn",fs(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function kE(r){let e=globalThis.console,t=new mc;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
|
|
14
14
|
`);process.stderr.write(`${o}
|
|
15
|
-
`),globalThis.console=e}}var
|
|
15
|
+
`),globalThis.console=e}}var ot=" ".repeat(6);function FE(r,e="",t=!1){let n=process.stdout?.columns||process.stderr?.columns||80,o=Math.max(n-e.length,20),i=r.split(`
|
|
16
16
|
`),a=[];for(let l of i)if(t){let c=l;for(;c.length>o;){let u=c.slice(0,o+1).lastIndexOf(" "),d=u>-1?u:o;a.push(e+c.slice(0,d)),c=c.slice(d).trimStart()}a.push(e+c)}else{let c=l.split(" "),s="";for(let u of c){if(!s.length){s=u;continue}let d=`${s} ${u}`;d.length<=o?s=d:(a.push(e+s),s=u)}a.push(e+s)}return a.join(`
|
|
17
|
-
`)}import WO from"fetch-retry";import qO from"os";import xE,{multistream as KO}from"pino";import YO from"pino-pretty";import XO from"pino-std-serializers";var Vi=new Map,JO=!0,_E="Log throttle exceeded",QO=100,ZO=5e3,eL=WO(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}}),om=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??qO.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=JO?xE(a):xE(a,KO([{stream:YO({colorize:!0})}]))}getLevel(){return Zl[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 eL(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Gi(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===_E)return!0;let t=Date.now();return t-this.lastWindowStart>ZO&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,_E),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<QO?(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(is[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=XO.err(t.err));let i={...this.bindingAttributes,...t&&typeof t=="object"?t:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let l={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:vy({message:n||"",...i})};this.buffer.push(l),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let t=this.bindingAttributes.app;this.bindingAttributes.app=e,Vi.set("app",this),Vi.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=Zl[e]):(this.minLevelValue=is[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},oc=({app:r,hostname:e,disableConsoleLogs:t})=>(Vi.has(r)||Vi.set(r,new om({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Vi.get(r));function IE(){for(let r of Vi.values())r.flush()}import{hostname as tL}from"os";var Q=oc({app:"cli",hostname:tL(),disableConsoleLogs:!0}).child({cliVersion:"2.17.9"});var nL=5;async function ac({getResults:r,checkDone:e,name:t,timeoutMs:n=18e5}){let o=Date.now(),i=0;for(;Date.now()-o<n;){let a;i>nL&&(T.error(`Failed to fetch ${t} status too many times.`),process.exit(1));try{a=await r(),i=0}catch(s){i++,Q.warn({err:s},"Failed to fetch run status, retrying..."),T.warn({err:s},"Failed to fetch run status, retrying..."),await new Promise(u=>setTimeout(u,1500*i));continue}if(e(a))return a;let c=Math.max(1e4,Math.floor(n/100));await new Promise(s=>setTimeout(s,c))}T.error(`Timeout elapsed waiting for ${t} to complete (${Math.floor(n/1e3)}s).`),process.exit(1)}function ji({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),l=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),s=r.filter(u=>u.status==="CANCELLED");return wE(()=>{if(c.forEach(u=>{T.log(""),o(u)}),c.length){T.log("");let u=c.length===1?"":"s";T.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{T.dimmed(n(d))})}if(s.length){T.log("");let u=s.length===1?"":"s";T.warn(`${s.length} ${t}${u} cancelled:`),s.forEach(d=>{T.dimmed(n(d))})}if(a.length){T.log("");let u=a.length===1?"":"s";T.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{T.dimmed(n(d))})}if(l.length){T.log("");let u=l.length===1?"":"s";T.warn(`${l.length} quarantined ${t}${u} failed:`),l.forEach(d=>{T.dimmed(n(d))})}if(i.length){T.log("");let u=i.length===1?"":"s";T.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{T.dimmed(n(d))})}T.log(""),T.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:l.length,failed:c.length,cancelled:s.length}}var sc=(r,e)=>{if(!r.failureDetails||!r.failureReason)return;let t=Cl[r.failureDetails?.classification?.reason||r.failureReason],n=r.failureDetails?.classification?.summary||Pi[r.failureReason],o=r.failureDetails.classification?.rootCause;if(T.error(e),o){T.log(`${it}- Error type: ${Yr.dim(t)}`);let i="- Root cause analysis:",a=CE(`${i} ${o}`,`${it} `,!1),l=a.indexOf(":");T.log(`${it}${i} ${Yr.dim(a.slice(l+1))}`)}else T.log(`${it}Reason: ${Yr.red(t)}`),T.log(`${it}Description: ${Yr.red(n)}`)},ds=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=Yr.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=Yr.bgGreen.white("PASS"),a=3):r.includes("START")?(i=Yr.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=Yr.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=Yr.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=Yr.bgMagenta.white("RUNNING"),a=0):(T.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),rL||(i=`${i}`),T.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};var uL=!1,ME=(()=>{try{return lL("/.dockerenv"),!0}catch{return!1}})();async function Nt(r,e){return Da||uL||ME?!0:(T.flush(),Q.flush(),await new Promise(n=>setTimeout(n,500)),await oL({message:r}))}async function im(r){let e=cL(r);return RE(e)?aL(r)?Nt(`File '${PE(r)}' already exists. Overwrite existing content?`,!0):!0:await Nt(`Directory '${PE(e)}' doesn't exist. Create it now?`,!0)?(sL(e,{recursive:!0}),!0):!1}function PE(r){return r.replace(/(\s+)/g,"\\$1")}async function OE(r,e){return Da||ME?e:(await iL({message:r,default:e})).trim()||e}import dL from"fs";import{tmpdir as pL}from"os";import mL from"path";import{registry as ps}from"playwright-core/lib/server";import LE from"proper-lockfile";var NE=mL.join(pL(),"momenticBrowserInstallation");var am=["chrome","chromium","chrome-for-testing"],gL={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},DE={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function kE(r){let e=DE[gL[r]??""]??"",t=ps.findExecutable(e);return!t||t.installType==="none"?!1:sm(t)}function sm(r){let e=r.executablePath();return dL.existsSync(e)}function hL(r,e){let t=DE[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=ps.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&sm(n)))return n}async function fL({browser:r,force:e}){let t=hL(r,e);if(!t){T.info(`Browser '${r}' is already installed, skipping...`);return}T.info(`Installing browser '${r}'...`);try{await ps.installDeps([t],!1),await ps.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){T.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=ps.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!sm(o);)T.info("Waiting for browser to finish installing..."),await new Promise(l=>setTimeout(l,5e3))}else throw n}}async function FE({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?am:Array.from(new Set(r));try{await LE.lock(NE,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){T.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 fL({browser:i,force:e})}catch(a){o=a,T.error(`Failed to install the ${i} browser: ${a}`)}}finally{await LE.unlock(NE,{realpath:!1})}if(o)throw o}import{randomUUID as MG}from"crypto";import gx from"body-parser";import b1 from"cors";import v1 from"dedent";import{Router as oN}from"express";import Vt from"fs";import{globSync as iN}from"glob";import Et from"path";import vm from"fs";import{z as um}from"zod";var B="v1",lm="cli",ms="2.17.9";var Yn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var UE=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 H(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,l;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((c,s)=>{if(e.signal){let{signal:d}=e;if(d.aborted)return s(UE(d));l=()=>s(UE(d)),d.addEventListener("abort",l)}let u=()=>{if(n)try{c(n())}catch(d){s(d)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let d=o instanceof Error?o:new Yn(o??`Promise timed out after ${t}ms`);s(d)}};a=i.setTimeout(u,t),Promise.resolve(r).then(d=>c(d)).catch(d=>s(d))}).finally(()=>{i.clearTimeout(a),e.signal&&l&&e.signal.removeEventListener("abort",l)})}var lc=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(l=>n-l<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(n),!1)}};var SL=9e4,yL=3,EL=1500,TL=15e3,Pr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function bL(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var cm=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return ms&&(e[xy]=ms),lm&&(e[_y]=lm),e}async sendRequest(e,t){let{retries:n=yL,requestTimeoutMs:o=SL,initialRetryDelayMs:i=EL,maxRetryDelayMs:a=TL}=t,l=n,c=n,s,u={path:e,baseUrl:this.baseUrl,method:t.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(e,t,o)}catch(d){if(s=d,d instanceof Pr&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError"&&(s=new Yn),l===0)throw s;let p=c-l,m=Math.min(i*Math.pow(2,p-1),a);await new Promise(g=>setTimeout(g,m))}throw this.logger.warn({...u,err:s},"Got fatal error response from Momentic server"),s}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),l=()=>i.abort();t.signal&&t.signal.addEventListener("abort",l);let c={...this.getHeaders(),...t.extraHeaders};try{let s=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:c,signal:i.signal});if(!s.ok){let d=await bL(s);throw new Pr(s.status,d,`Request to ${t.method} ${e} failed with status ${s.status}: ${d}`)}let u;if(s.status===204)u={};else{let d=await s.text();try{u=JSON.parse(d)}catch{u=d}}return this.logger&&t.logResponse===!0&&u&&this.logger.debug({result:u,status:s.status,...o},"Got response from Momentic server"),u}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",l)}}},At=class extends cm{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Je=class extends At{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 qy.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${B}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Vy.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${B}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return ky.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 Uy.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 By.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${B}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Dy.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${B}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Wy.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${B}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Ky.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 lE.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 Yy.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 sS.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 Xy.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 Jy.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${B}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Qy.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 Zy.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${B}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return mE.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 ss.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 ss.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 Zp.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 ss.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 ss.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 Zp.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${B}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return um.record(um.string(),um.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${B}/quarantine`,{method:"GET"});return eE.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 tE.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 rE.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 nE.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${B}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function dm(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(T.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),T.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return T.debug("Got auth info from API"),n}var cc=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var $i=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 vL,en as RL}from"@faker-js/faker";var Wi="v1",Xr=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 vL({locale:RL}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Wi}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Pr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Wi}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Wi}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Wi}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Wi}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Wi}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as AL}from"zod";var Tn=class extends At{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 mS.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${B}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ms,...e},signal:t.abortSignal});return pS.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${B}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return AL.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 Ly.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 Yp.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 Oy.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 My.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 Yp.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 Py.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 cp.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 Ny.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 ap.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 Vf.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 pp.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 AS.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 Hf.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 Gf.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 zf.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${B}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return ff.parse(n)}};var Xn=class extends At{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 Sf.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function BE(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var uc=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await BE(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}};import{diff as jE}from"deep-object-diff";function gs(r){let e={parentChain:[]};return dc(r,e),e}function dc(r,e){let{onPresetAction:t,onSimpleStepContainer:n,onConditional:o,earlyStop:i}=r;for(let a of r.steps)switch(a.type){case"PRESET_ACTION":if(t(a,e)&&i)return!0;break;case"CONDITIONAL":if(o?.(a,e)&&i)return!0;e.parentChain.push(a);for(let c of a.blocks)if(t(c.assertion,e)&&i||dc({...r,steps:c.steps},e)&&i)return!0;if(dc({...r,steps:a.elseSteps??[]},e)&&i)return!0;e.parentChain.pop();break;case"RESOLVED_MODULE":case"SECTION":case"AI_ACTION":if(n?.(a,e)&&i)return!0;if(a.steps){if(e.parentChain.push(a),dc({...r,steps:a.steps},e)&&i)return!0;e.parentChain.pop()}break;case"AI_ACTION_DYNAMIC":{if(n?.(a,e)&&i)return!0;break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(a)}}function HE(r,e,t,n){let o=Array.from(e),i=Array.from(n);for(let l=0;l<o.length;l++){if(o[l]!==i[l])return!1;i.shift()}return!!wL([r],t,i).result}function wL(r,e,t=[]){let n,o=[],i=(a,l)=>{let c=JSON.stringify(l.parentChain.map(u=>u.id)),s=t.length===0?!0:JSON.stringify(t)===c;return a.id===e&&s?(n=a,o=l.parentChain,!0):!1};return gs({steps:r,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:n,parentChain:o}}function zE(r,e){e(r);for(let t in r){let n=r[t];n&&(Array.isArray(n)?mc(n,e):typeof n=="object"&&zE(n,e))}}function mc(r,e){for(let t of r)t&&(Array.isArray(t)?mc(t,e):typeof t=="object"&&zE(t,e))}function pm(r,e){if(r.length>e.length)return pm(e,r);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function pc(r){for(let e of r.results)switch(e.type){case"PRESET_ACTION":r.onPresetAction(e);break;case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":r.onSimpleStepContainer?.(e),pc({...r,results:e.results});break;case"CONDITIONAL":r.onConditional?.(e),e.assertionResult&&r.onPresetAction(e.assertionResult),pc({...r,results:e.results});break;default:throw new Error(`Unsupported result type: ${e.type}`)}}import{cloneDeep as GE}from"lodash-es";import{v4 as mm}from"uuid";async function Ge(r){let e=new Map,t=new Set,n=GE(r.stepLists.steps),o=await Ho({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t}),i={stepsToSave:{steps:o.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates};for(let a of["beforeSteps","afterSteps"]){let l=GE(r.stepLists[a]);if(!l)continue;let c=await Ho({...r,steps:l,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});i.cachesToSave.push(...c.cachesToSave),i.moduleUpdates.push(...c.moduleUpdates),i.stepsToSave[a]=c.stepsToSave}return i}async function Ho({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:l,createNewCacheIds:c}=e,s={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of r)switch(delete u.index,delete u.aiSuggested,u.id=c?mm():u.id,u.type){case"PRESET_ACTION":{let p=u.command;p.id=c?mm():p.id,"cache"in p&&p.cache&&(n&&(s.cachesToSave=s.cachesToSave.concat(gm({id:p.id,orgId:n.orgId,testId:n.testId,value:gn.parse(p),moduleIdParents:o,moduleStepParents:i}))),delete p.cache),p.thoughts&&delete p.thoughts,s.stepsToSave.push({...u,command:p});break}case"RESOLVED_MODULE":{let p=c?mm():u.id,m=u.moduleId;a.has(m)?m=a.get(m):l!==void 0&&(m=await l(u),a.set(u.moduleId,m));let{cachesToSave:g,stepsToSave:h,moduleUpdates:f}=await Ho({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,p],moduleIdParents:[...o,m],skipCacheIntermediateEntries:c});s.moduleUpdates=s.moduleUpdates.concat(f),s.cachesToSave=s.cachesToSave.concat(g),t.has(m)||(t.add(m),s.moduleUpdates.push({...Wt.parse(u),steps:Le.array().parse(h),moduleId:m}));let E=_r.parse({...u,type:"MODULE",moduleId:m,inputs:u.inputs,id:p,skipped:u.skipped,cacheConfig:u.cacheConfig,envKey:u.envKey});s.stepsToSave.push(E);break}case"AI_ACTION":{if(!u.steps){s.stepsToSave.push(u);break}let{stepsToSave:p,cachesToSave:m}=await Ho({...e,steps:u.steps});try{u.steps=Zt.array().parse(p)}catch(g){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${g}`)}s.stepsToSave.push(u),s.cachesToSave=s.cachesToSave.concat(m);break}case"AI_ACTION_DYNAMIC":{s.stepsToSave.push(u);break}case"CONDITIONAL":{let p=[];for(let g of u.blocks){let{stepsToSave:h,cachesToSave:f,moduleUpdates:E}=await Ho({...e,steps:g.steps});p.push({...g,steps:h}),s.cachesToSave=s.cachesToSave.concat(f),s.moduleUpdates=s.moduleUpdates.concat(E)}let m={...u,elseSteps:void 0,blocks:p};if(u.elseSteps){let{stepsToSave:g,cachesToSave:h,moduleUpdates:f}=await Ho({...e,steps:u.elseSteps});m.elseSteps=g,s.cachesToSave=s.cachesToSave.concat(h),s.moduleUpdates=s.moduleUpdates.concat(f)}s.stepsToSave.push(m);break}case"SECTION":{let{stepsToSave:p,cachesToSave:m,moduleUpdates:g}=await Ho({...e,steps:u.steps}),h={...u,steps:p};s.moduleUpdates=s.moduleUpdates.concat(g),s.stepsToSave.push(h),s.cachesToSave=s.cachesToSave.concat(m);break}default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(u)}return s}function qi({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],l=[],c=[],s=0,u=(p,m)=>{try{let g=gn.parse(m.value);if(g.type!==p.type){o.warn({parsedCacheEntry:g,command:p},"Not using step cache due to type mismatch"),l.push(m.key);return}p.cache=g.cache,a.push(m.key),c.push(m.uniqueKey)}catch(g){l.push(m.key),o.error({err:g,cacheEntry:m},"Not using step cache due to parsing error")}},d=(p,m)=>{let g=CL(p.id,m),h=g.find(f=>!!n[f]);if(h)u(p,n[h]);else{if(p.type==="AI_ASSERTION")return;l.push(g[0])}};for(let p of r)switch(p.type){case"RESOLVED_MODULE":{s+=p.steps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=qi({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...m),l.push(...g),c.push(...h);break}case"SECTION":case"AI_ACTION":{if(s+=p.steps?.length??0,!p.steps?.length)break;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=qi({...t,steps:p.steps,topLevel:!1});a.push(...m),l.push(...g),c.push(...h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!bl.includes(p.command.type)||(p.command.type==="TYPE"||p.command.type==="MOUSE_DRAG"||p.command.type==="VISUAL_DIFF"||p.command.type==="SCROLL_DOWN"||p.command.type==="SCROLL_UP"||p.command.type==="SCROLL_LEFT"||p.command.type==="SCROLL_RIGHT")&&!p.command.target||"cache"in p.command&&p.command.cache)continue;s++,d(p.command,i);break}case"CONDITIONAL":{for(let m of p.blocks){s++,d(m.assertion.command,i),s+=m.steps.length;let{cacheKeysHit:g,cacheKeysMissed:h,uniqueKeysHit:f}=qi({...t,steps:m.steps,topLevel:!1});a.push(...g),l.push(...h),c.push(...f)}if(p.elseSteps){s+=p.elseSteps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=qi({...t,steps:p.elseSteps,topLevel:!1});a.push(...m),l.push(...g),c.push(...h)}break}default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(p)}return e&&s&&l.length>0&&o.warn({totalSteps:s,cacheKeysMissed:l,cacheKeysHit:a,uniqueKeysHit:c,cacheEntries:n.length},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:l,uniqueKeysHit:c}}function $E(r,e){return e?`${e}:${r}`:r}function CL(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 gm(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
18
|
-
${JSON.stringify(t)}`);let n=[];return n.push({key:$E(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function WE(r){let e=new Set;return mc(r,t=>{if("type"in t&&t.type==="RESOLVED_MODULE"&&"moduleId"in t){let n=t.moduleId;typeof n=="string"&&!e.has(n)&&e.add(n)}}),e}function zo({cmd:r,newTarget:e,key:t,logger:n}){r.type==="DRAG"?t!=="fromTarget"&&t!=="toTarget"?n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command"):r.cache={...r.cache,[t]:e}:t==="target"&&If(r)?r.cache={...r.cache,target:e}:n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function gc(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;return JSON.stringify(n)===JSON.stringify(e)?{changed:!1}:(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e}},{changed:!0})}async function hc({logger:r,cacheStorage:e,orgId:t,testId:n,originalSteps:o,updatedSteps:i}){let a=jE(o,i);if(Object.keys(a).length!==0){r.debug("Updating step caches post-success");try{let{cachesToSave:l}=await Ge({stepLists:i,cacheCreationParams:{testId:n,orgId:t}});await e.saveStepCacheEntries({logger:r,testId:n,entries:l})}catch(l){r.error({err:l},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async function fc({logger:r,cacheStorage:e,orgId:t,testId:n,originalSteps:o,updatedSteps:i}){let a=jE(o,i);if(Object.keys(a).length===0)return;r.debug({changes:a},"Updating memory post-run failure");let l={};for(let u of["steps","beforeSteps","afterSteps"]){let d=o[u];if(!d||!d.length)continue;let p=xL({steps:d});for(let[m,g]of Object.entries(p))l[m]=g}let{cachesToSave:c}=await Ge({stepLists:i,cacheCreationParams:{testId:n,orgId:t}}),s=_L({newEntries:c,originalCachesMap:l,logger:r});if(s.length){r.debug({prunedCaches:s},"Saving pruned memory post-failure");try{await e.saveStepCacheEntries({logger:r,testId:n,entries:c})}catch(u){r.error({err:u},"Failed to save memory after successful execution. This is not critical, but can impact future performance.")}}}function xL({steps:r}){let e={};return gs({steps:r,onPresetAction:(t,n)=>{let o=t.command;if(!("cache"in o)||!o.cache)return;let i=n.parentChain.filter(c=>c.type==="RESOLVED_MODULE").map(c=>c.id).join(":"),a=$E(t.id,i),l=gn.parse(o);e[a]=l},onSimpleStepContainer:(t,n)=>{},onConditional:(t,n)=>{}}),e}function _L({newEntries:r,originalCachesMap:e,logger:t}){let n=[];for(let o of r){let i=e[o.key];if(!i||!i.cache||o.value.type!==i.type)continue;let a=o.value.cache;if(o.value={...i},!a){n.push(o);continue}if("memory"in a&&a.memory)t.debug({cacheKey:o.key,newCacheMemory:a.memory,originalCache:i},"Overwriting assertion cache memory"),o.value.cache={...o.value.cache,memory:a.memory};else if("target"in a&&a.target.memory){let l=Qt.parse(o.value.cache);if(!l)continue;t.debug({cacheKey:o.key,newCacheMemory:a.target.memory,originalCache:i},"Overwriting target cache memory"),l.target.memory=a.target.memory,o.value.cache=l}else if("fromTarget"in a||"toTarget"in a){let l=qd.optional().parse(o.value.cache);if(!l)continue;l.fromTarget&&a.fromTarget&&(l.fromTarget.memory=a.fromTarget.memory),l.toTarget&&a.toTarget&&(l.toTarget.memory=a.toTarget.memory),t.debug({cacheKey:o.key,fromTargetMemory:a.fromTarget?.memory,toTargetMemory:a.toTarget?.memory,originalCache:i},"Overwriting drag cache memory"),o.value.cache=l}n.push(o)}return n}function Qe(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var gr={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},hr={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},hm={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},fm={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function IL(r){switch(r.type){case"ELEMENT_CONTENT":return`content ${r.negated?hr[r.operation]:gr[r.operation]} '${r.value}'`;case"ELEMENT_ATTRIBUTE":{let t=r.negated?hr[r.operation]:gr[r.operation];return r.operation==="EXISTS"?`attribute '${r.attr}' ${t}`:`attribute '${r.attr}' ${t} '${r.value}'`}case"ELEMENT_NAME":{let t=r.negated?hr[r.operation]:gr[r.operation];return r.operation==="EXISTS"?`tag name ${t}`:`tag name ${t} '${r.value}'`}case"ELEMENT_STYLE":{let t=r.negated?hr[r.operation]:gr[r.operation];return r.operation==="EXISTS"?`style property '${r.property}' ${t}`:`style property '${r.property}' ${t} '${r.value}'`}case"ELEMENT_EXISTENCE":return r.negated?fm[r.condition]:hm[r.condition];default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var SZ={CONTENT:"The page"};function PL(r){switch(r.type){case"VALUE":return`the option with value ${r.value}`;case"LABEL":return`the option with label ${r.label}`;case"INDEX":return`the option at index ${r.index}`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function yc(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 Sc(r){let e="";return r.method&&(e=` with method ${r.method}`),`${yc(r.urlMatcher)}${e}`}function ML(r){switch(r.type){case"CONTENT":return`${r.negated?hr.CONTAINS:gr.CONTAINS} '${r.value}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function bn(r,e=!0){switch(r.type){case"SUCCESS":return r.condition?.assertion?`Check success condition: ${r.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${r.goal}`;case"NAVIGATE":return`Go to URL: ${e?Qe(r.url,30):r.url}`;case"DIALOG":return`Automatically ${r.action.toLowerCase()} the next dialog`;case"CAPTCHA":return"Solve captchas on the page";case"GO_BACK":return"Go back to the previous page";case"GO_FORWARD":return"Go forward to the next page";case"SCROLL_DOWN":return`Scroll down ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${_t(r.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${_t(r.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${_t(r.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${_t(r.target)}`:""}`;case"WAIT":return`Wait for ${r.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(r.target?.type==="coordinates")return`Click at coordinates: ${_t(r.target)}`;let n="";return r.target?.elementDescriptor.length?n=` on element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` on element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Click${n}`}case"FOCUS":return`Focus ${_t(r.target)}`;case"BLUR":return`Focus ${_t(r.target)}`;case"DRAG":return`Drag ${_t(r.fromTarget)} onto ${_t(r.toTarget)}`;case"MOUSE_DRAG":return r.target?.type==="description"&&r.target.elementDescriptor?`Click and drag ${_t(r.target)} by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`:`Click and drag mouse by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`;case"TYPE":{let n="";return r.target?.type==="coordinates"?n=` in element at coordinates: ${_t(r.target)}`:r.target?.elementDescriptor.length?n=` in element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` in element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Type '${r.value}'${n||""}`}case"HOVER":{let n="";return r.target.type==="coordinates"?n=` over coordinates: ${_t(r.target)}`:r.target.elementDescriptor.length>0?n=` over element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` over element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Hover${n}`}case"PRESS":return`Press ${r.value}`;case"KEY_DOWN":return`Hold down ${r.value} on the keyboard`;case"KEY_UP":return`Release ${r.value} on the keyboard`;case"SELECT_OPTION":{let n="",o=PL(r.choice);return r.target.type==="coordinates"?n=` from element at coordinates: ${_t(r.target)}`:r.target.elementDescriptor.length>0?n=` from: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` from: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${o}'${n}`}case"TAB":switch(r.action.type){case"SUBSTRING":return`Switch to tab with substring: ${r.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${r.action.pattern}`;case"INDEX":return`Switch to tab at index: ${r.action.index}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${r.url}`;case"REQUEST":return`Send ${r.method} request to ${r.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${r.url}`;case"COOKIE":return`Set cookie: ${r.value}`;case"LOCAL_STORAGE":return`Set local storage: ${r.key}: ${r.value}`;case"JAVASCRIPT":return`Run JavaScript: ${e?Qe(r.code,30):r.code}`;case"AI_ASSERTION":return`Assertion: '${r.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${r.target?`for element: ${_t(r.target)}`:"for entire page"}`;case"FILE_UPLOAD":return r.fileSource.type==="URL"?`Upload file: ${r.fileSource.url}`:`Upload file: ${r.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Check the element ${_t(r.target)} ${IL(r.assertion)}`;case"PAGE_CHECK":return`Check the page ${ML(r.assertion)}`;case"WAIT_FOR_URL":return`Wait for page URL to ${yc(r.matcher)}`;case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return r.requestMatcher?`Register a listener for network requests that ${Sc(r.requestMatcher)}`:"Register a listener for network requests";case"AWAIT_LISTENER":return r.key?`Wait for the listener ${r.key} to resolve`:"Wait for a listener to resolve";case"RECORD_REQUESTS":return r.requestMatcher?`Start recording requests that match ${Sc(r.requestMatcher)}`:"Start recording network requests";case"GET_RECORDED_REQUESTS":return r.key?`Get the requests that were recorded for ${r.key}`:"Get the requests that were recorded";case"SET_HEADER":return r.name?r.requestMatcher?`Set a ${r.name} header for requests that match ${Sc(r.requestMatcher)}`:`Set a ${r.name} header for all requests`:"Set a header";case"MOCK_ROUTE":return r.requestMatcher?`Mock requests that ${Sc(r.requestMatcher)}`:"Mock a network route";case"REMOVE_ROUTE_MOCK":return r.key?`Remove the mock with key ${r.key}`:"Remove all route mocks";case"OFFLINE_MODE":return r.enable?"Enable offline mode":"Disable offline mode";default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function qE(r){let e=[];for(let t of r){t.sort((a,l)=>a.timestamp-l.timestamp);let n=[],o,i=1;for(let a of t)o&&o.text===a.text&&o.type===a.type&&JSON.stringify(o.args??null)===JSON.stringify(a.args??null)?i++:(o&&(i>1?o.args&&o.args.length?o.args.push(`(repeated ${i} times)`):o.text+=` (repeated ${i} times)`:n.push(o)),o=a,i=1);o&&n.push(o),e.push(n)}return e}import{cloneDeep as bZ}from"lodash-es";import{v4 as xZ}from"uuid";import{cloneDeep as OL}from"lodash-es";import ZE from"truncate-json";import{v4 as KE}from"uuid";import{cloneDeep as MZ,unset as OZ}from"lodash-es";function Jn(r){switch(r.type){case"AI_ACTION":return`AI action: ${Qe(r.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${Qe(r.text,100)}`;case"PRESET_ACTION":return bn(r.command);case"MODULE":return`Module: ${r.id}`;case"RESOLVED_MODULE":return`Module: ${r.name}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section${r.description?`with goal: ${Qe(r.description,100)}`:""}`;default:return(t=>{throw new Error("You missed a case in the switch above")})(r)}}function Go(r,e){return r.split(`
|
|
17
|
+
`)}import SL from"fetch-retry";import yL from"os";import UE,{multistream as EL}from"pino";import TL from"pino-pretty";import bL from"pino-std-serializers";var $i=new Map,vL=!0,BE="Log throttle exceeded",RL=100,AL=5e3,wL=SL(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}}),fm=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??yL.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=vL?UE(a):UE(a,EL([{stream:TL({colorize:!0})}]))}getLevel(){return cc[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 wL(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:ji(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===BE)return!0;let t=Date.now();return t-this.lastWindowStart>AL&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,BE),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<RL?(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(ds[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=bL.err(t.err));let i={...this.bindingAttributes,...t&&typeof t=="object"?t:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let l={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:Ly({message:n||"",...i})};this.buffer.push(l),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let t=this.bindingAttributes.app;this.bindingAttributes.app=e,$i.set("app",this),$i.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=cc[e]):(this.minLevelValue=ds[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},gc=({app:r,hostname:e,disableConsoleLogs:t})=>($i.has(r)||$i.set(r,new fm({bindings:{app:r},hostname:e,disableConsoleLogs:t})),$i.get(r));function zE(){for(let r of $i.values())r.flush()}import{hostname as CL}from"os";var Z=gc({app:"cli",hostname:CL(),disableConsoleLogs:!0}).child({cliVersion:"2.17.11"});var _L=5;async function fc({getResults:r,checkDone:e,name:t,timeoutMs:n=18e5}){let o=Date.now(),i=0;for(;Date.now()-o<n;){let a;i>_L&&(T.error(`Failed to fetch ${t} status too many times.`),process.exit(1));try{a=await r(),i=0}catch(s){i++,Z.warn({err:s},"Failed to fetch run status, retrying..."),T.warn({err:s},"Failed to fetch run status, retrying..."),await new Promise(u=>setTimeout(u,1500*i));continue}if(e(a))return a;let c=Math.max(1e4,Math.floor(n/100));await new Promise(s=>setTimeout(s,c))}T.error(`Timeout elapsed waiting for ${t} to complete (${Math.floor(n/1e3)}s).`),process.exit(1)}function Wi({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),l=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),s=r.filter(u=>u.status==="CANCELLED");return kE(()=>{if(c.forEach(u=>{T.log(""),o(u)}),c.length){T.log("");let u=c.length===1?"":"s";T.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{T.dimmed(n(d))})}if(s.length){T.log("");let u=s.length===1?"":"s";T.warn(`${s.length} ${t}${u} cancelled:`),s.forEach(d=>{T.dimmed(n(d))})}if(a.length){T.log("");let u=a.length===1?"":"s";T.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{T.dimmed(n(d))})}if(l.length){T.log("");let u=l.length===1?"":"s";T.warn(`${l.length} quarantined ${t}${u} failed:`),l.forEach(d=>{T.dimmed(n(d))})}if(i.length){T.log("");let u=i.length===1?"":"s";T.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{T.dimmed(n(d))})}T.log(""),T.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:l.length,failed:c.length,cancelled:s.length}}var Sc=(r,e)=>{if(!r.failureDetails||!r.failureReason)return;let t=Ll[r.failureDetails?.classification?.reason||r.failureReason],n=r.failureDetails?.classification?.summary||Oi[r.failureReason],o=r.failureDetails.classification?.rootCause;if(T.error(e),o){T.log(`${ot}- Error type: ${Jr.dim(t)}`);let i="- Root cause analysis:",a=FE(`${i} ${o}`,`${ot} `,!1),l=a.indexOf(":");T.log(`${ot}${i} ${Jr.dim(a.slice(l+1))}`)}else T.log(`${ot}Reason: ${Jr.red(t)}`),T.log(`${ot}Description: ${Jr.red(n)}`)},Ss=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=Jr.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=Jr.bgGreen.white("PASS"),a=3):r.includes("START")?(i=Jr.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=Jr.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=Jr.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=Jr.bgMagenta.white("RUNNING"),a=0):(T.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),xL||(i=`${i}`),T.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};var DL=!1,GE=(()=>{try{return LL("/.dockerenv"),!0}catch{return!1}})();async function Nt(r,e){return Fa||DL||GE?!0:(T.flush(),Z.flush(),await new Promise(n=>setTimeout(n,500)),await IL({message:r}))}async function Sm(r){let e=NL(r);return NE(e)?PL(r)?Nt(`File '${HE(r)}' already exists. Overwrite existing content?`,!0):!0:await Nt(`Directory '${HE(e)}' doesn't exist. Create it now?`,!0)?(OL(e,{recursive:!0}),!0):!1}function HE(r){return r.replace(/(\s+)/g,"\\$1")}async function VE(r,e){return Fa||GE?e:(await ML({message:r,default:e})).trim()||e}import kL from"fs";import{tmpdir as FL}from"os";import UL from"path";import{registry as ys}from"playwright-core/lib/server";import jE from"proper-lockfile";var $E=UL.join(FL(),"momenticBrowserInstallation");var ym=["chrome","chromium","chrome-for-testing"],BL={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},WE={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function qE(r){let e=WE[BL[r]??""]??"",t=ys.findExecutable(e);return!t||t.installType==="none"?!1:Em(t)}function Em(r){let e=r.executablePath();return kL.existsSync(e)}function zL(r,e){let t=WE[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=ys.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&Em(n)))return n}async function HL({browser:r,force:e}){let t=zL(r,e);if(!t){T.info(`Browser '${r}' is already installed, skipping...`);return}T.info(`Installing browser '${r}'...`);try{await ys.installDeps([t],!1),await ys.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){T.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=ys.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Em(o);)T.info("Waiting for browser to finish installing..."),await new Promise(l=>setTimeout(l,5e3))}else throw n}}async function KE({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?ym:Array.from(new Set(r));try{await jE.lock($E,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){T.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 HL({browser:i,force:e})}catch(a){o=a,T.error(`Failed to install the ${i} browser: ${a}`)}}finally{await jE.unlock($E,{realpath:!1})}if(o)throw o}import{randomUUID as ZG}from"crypto";import Ix from"body-parser";import V1 from"cors";import j1 from"dedent";import{Router as CN}from"express";import Vt from"fs";import{globSync as xN}from"glob";import yt from"path";import Nm from"fs";import{z as vm}from"zod";var B="v1",Tm="cli",Es="2.17.11";var Qn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var YE=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 H(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,l;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((c,s)=>{if(e.signal){let{signal:d}=e;if(d.aborted)return s(YE(d));l=()=>s(YE(d)),d.addEventListener("abort",l)}let u=()=>{if(n)try{c(n())}catch(d){s(d)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let d=o instanceof Error?o:new Qn(o??`Promise timed out after ${t}ms`);s(d)}};a=i.setTimeout(u,t),Promise.resolve(r).then(d=>c(d)).catch(d=>s(d))}).finally(()=>{i.clearTimeout(a),e.signal&&l&&e.signal.removeEventListener("abort",l)})}var yc=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(l=>n-l<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(n),!1)}};var GL=9e4,VL=3,jL=1500,$L=15e3,Pr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function WL(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var bm=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Es&&(e[Uy]=Es),Tm&&(e[By]=Tm),e}async sendRequest(e,t){let{retries:n=VL,requestTimeoutMs:o=GL,initialRetryDelayMs:i=jL,maxRetryDelayMs:a=$L}=t,l=n,c=n,s,u={path:e,baseUrl:this.baseUrl,method:t.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(e,t,o)}catch(d){if(s=d,d instanceof Pr&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError"&&(s=new Qn),l===0)throw s;let p=c-l,m=Math.min(i*Math.pow(2,p-1),a);await new Promise(g=>setTimeout(g,m))}throw this.logger.warn({...u,err:s},"Got fatal error response from Momentic server"),s}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),l=()=>i.abort();t.signal&&t.signal.addEventListener("abort",l);let c={...this.getHeaders(),...t.extraHeaders};try{let s=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:c,signal:i.signal});if(!s.ok){let d=await WL(s);throw new Pr(s.status,d,`Request to ${t.method} ${e} failed with status ${s.status}: ${d}`)}let u;if(s.status===204)u={};else{let d=await s.text();try{u=JSON.parse(d)}catch{u=d}}return this.logger&&t.logResponse===!0&&u&&this.logger.debug({result:u,status:s.status,...o},"Got response from Momentic server"),u}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",l)}}},At=class extends bm{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Ye=class extends At{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 oE.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${B}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return eE.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${B}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return qy.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 Yy.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 Xy.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${B}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Wy.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${B}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return nE.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${B}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return iE.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 EE.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 aE.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 SS.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 sE.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 lE.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${B}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return cE.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 uE.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${B}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return AE.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 ms.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 ms.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 um.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 ms.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 ms.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 um.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${B}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return vm.record(vm.string(),vm.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${B}/quarantine`,{method:"GET"});return dE.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 pE.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 mE.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 gE.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${B}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function Rm(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(T.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),T.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return T.debug("Got auth info from API"),n}var Ec=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var qi=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 qL,en as KL}from"@faker-js/faker";var Ki="v1",Qr=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 qL({locale:KL}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Ki}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Pr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Ki}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Ki}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Ki}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Ki}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Ki}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as YL}from"zod";var bn=class extends At{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 RS.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${B}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Es,...e},signal:t.abortSignal});return vS.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${B}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return YL.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 jy.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 am.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 Vy.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 Gy.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 am.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 Hy.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 Tp.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 $y.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 Sp.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 Zf.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 Rp.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 NS.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 Xf.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 Qf.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 Jf.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${B}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return xf.parse(n)}};var Zn=class extends At{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 _f.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function XE(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Tc=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await XE(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}};function Ts(r){let e={parentChain:[]};return bc(r,e),e}function bc(r,e){let{onPresetAction:t,onSimpleStepContainer:n,onConditional:o,earlyStop:i}=r;for(let a of r.steps)switch(a.type){case"PRESET_ACTION":if(t(a,e)&&i)return!0;break;case"CONDITIONAL":if(o?.(a,e)&&i)return!0;e.parentChain.push(a);for(let c of a.blocks)if(t(c.assertion,e)&&i||bc({...r,steps:c.steps},e)&&i)return!0;if(bc({...r,steps:a.elseSteps??[]},e)&&i)return!0;e.parentChain.pop();break;case"RESOLVED_MODULE":case"SECTION":case"AI_ACTION":if(n?.(a,e)&&i)return!0;if(a.steps){if(e.parentChain.push(a),bc({...r,steps:a.steps},e)&&i)return!0;e.parentChain.pop()}break;case"AI_ACTION_DYNAMIC":{if(n?.(a,e)&&i)return!0;break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(a)}}function JE(r,e,t,n){let o=Array.from(e),i=Array.from(n);for(let l=0;l<o.length;l++){if(o[l]!==i[l])return!1;i.shift()}return!!XL([r],t,i).result}function XL(r,e,t=[]){let n,o=[],i=(a,l)=>{let c=JSON.stringify(l.parentChain.map(u=>u.id)),s=t.length===0?!0:JSON.stringify(t)===c;return a.id===e&&s?(n=a,o=l.parentChain,!0):!1};return Ts({steps:r,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:n,parentChain:o}}function QE(r,e){e(r);for(let t in r){let n=r[t];n&&(Array.isArray(n)?Rc(n,e):typeof n=="object"&&QE(n,e))}}function Rc(r,e){for(let t of r)t&&(Array.isArray(t)?Rc(t,e):typeof t=="object"&&QE(t,e))}function Am(r,e){if(r.length>e.length)return Am(e,r);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function vc(r){for(let e of r.results)switch(e.type){case"PRESET_ACTION":r.onPresetAction(e);break;case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":r.onSimpleStepContainer?.(e),vc({...r,results:e.results});break;case"CONDITIONAL":r.onConditional?.(e),e.assertionResult&&r.onPresetAction(e.assertionResult),vc({...r,results:e.results});break;default:throw new Error(`Unsupported result type: ${e.type}`)}}function Yi({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],l=[],c=[],s=0,u=(p,m)=>{try{let g=Sn.parse(m.value);if(g.type!==p.type){o.warn({parsedCacheEntry:g,command:p},"Not using step cache due to type mismatch"),l.push(m.key);return}p.cache=g.cache,a.push(m.key),c.push(m.uniqueKey)}catch(g){l.push(m.key),o.error({err:g,cacheEntry:m},"Not using step cache due to parsing error")}},d=(p,m)=>{let g=JL(p.id,m),h=g.find(f=>!!n[f]);if(h)u(p,n[h]);else{if(p.type==="AI_ASSERTION")return;l.push(g[0])}};for(let p of r)switch(p.type){case"RESOLVED_MODULE":{s+=p.steps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=Yi({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...m),l.push(...g),c.push(...h);break}case"SECTION":case"AI_ACTION":{if(s+=p.steps?.length??0,!p.steps?.length)break;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=Yi({...t,steps:p.steps,topLevel:!1});a.push(...m),l.push(...g),c.push(...h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!_l.includes(p.command.type)||(p.command.type==="TYPE"||p.command.type==="MOUSE_DRAG"||p.command.type==="VISUAL_DIFF"||p.command.type==="SCROLL_DOWN"||p.command.type==="SCROLL_UP"||p.command.type==="SCROLL_LEFT"||p.command.type==="SCROLL_RIGHT")&&!p.command.target||"cache"in p.command&&p.command.cache)continue;s++,d(p.command,i);break}case"CONDITIONAL":{for(let m of p.blocks){s++,d(m.assertion.command,i),s+=m.steps.length;let{cacheKeysHit:g,cacheKeysMissed:h,uniqueKeysHit:f}=Yi({...t,steps:m.steps,topLevel:!1});a.push(...g),l.push(...h),c.push(...f)}if(p.elseSteps){s+=p.elseSteps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=Yi({...t,steps:p.elseSteps,topLevel:!1});a.push(...m),l.push(...g),c.push(...h)}break}default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(p)}return e&&s&&l.length>0&&o.warn({totalSteps:s,cacheKeysMissed:l,cacheKeysHit:a,uniqueKeysHit:c,cacheEntries:n.length},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:l,uniqueKeysHit:c}}function ZE(r,e){return e?`${e}:${r}`:r}function JL(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 wm(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
18
|
+
${JSON.stringify(t)}`);let n=[];return n.push({key:ZE(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function eT(r){let e=new Set;return Rc(r,t=>{if("type"in t&&t.type==="RESOLVED_MODULE"&&"moduleId"in t){let n=t.moduleId;typeof n=="string"&&!e.has(n)&&e.add(n)}}),e}function Ac({cmd:r,newTarget:e,key:t,logger:n}){r.type==="DRAG"?t!=="fromTarget"&&t!=="toTarget"?n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command"):r.cache={...r.cache,[t]:e}:t==="target"&&Bf(r)?r.cache={...r.cache,target:e}:n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function wc(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;return JSON.stringify(n)===JSON.stringify(e)?{changed:!1}:(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e}},{changed:!0})}function tT({steps:r}){let e={};return Ts({steps:r,onPresetAction:(t,n)=>{let o=t.command;if(!("cache"in o)||!o.cache)return;let i=n.parentChain.filter(c=>c.type==="RESOLVED_MODULE").map(c=>c.id).join(":"),a=ZE(t.id,i),l=Sn.parse(o);e[a]=l},onSimpleStepContainer:(t,n)=>{},onConditional:(t,n)=>{}}),e}function rT({newEntries:r,originalCachesMap:e,logger:t}){let n=[];for(let o of r){let i=e[o.key];if(!i||!i.cache||o.value.type!==i.type)continue;let a=o.value.cache;if(o.value={...i},!a){n.push(o);continue}if("memory"in a&&a.memory)t.debug({cacheKey:o.key,newCacheMemory:a.memory,originalCache:i},"Overwriting assertion cache memory"),o.value.cache={...o.value.cache,memory:a.memory};else if("target"in a&&a.target.memory){let l=Zt.parse(o.value.cache);if(!l)continue;t.debug({cacheKey:o.key,newCacheMemory:a.target.memory,originalCache:i},"Overwriting target cache memory"),l.target.memory=a.target.memory,o.value.cache=l}else if("fromTarget"in a||"toTarget"in a){let l=op.optional().parse(o.value.cache);if(!l)continue;l.fromTarget&&a.fromTarget&&(l.fromTarget.memory=a.fromTarget.memory),l.toTarget&&a.toTarget&&(l.toTarget.memory=a.toTarget.memory),t.debug({cacheKey:o.key,fromTargetMemory:a.fromTarget?.memory,toTargetMemory:a.toTarget?.memory,originalCache:i},"Overwriting drag cache memory"),o.value.cache=l}n.push(o)}return n}function Xe(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var fr={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},Sr={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},Cm={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},xm={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function QL(r){switch(r.type){case"ELEMENT_CONTENT":return`content ${r.negated?Sr[r.operation]:fr[r.operation]} '${r.value}'`;case"ELEMENT_ATTRIBUTE":{let t=r.negated?Sr[r.operation]:fr[r.operation];return r.operation==="EXISTS"?`attribute '${r.attr}' ${t}`:`attribute '${r.attr}' ${t} '${r.value}'`}case"ELEMENT_NAME":{let t=r.negated?Sr[r.operation]:fr[r.operation];return r.operation==="EXISTS"?`tag name ${t}`:`tag name ${t} '${r.value}'`}case"ELEMENT_STYLE":{let t=r.negated?Sr[r.operation]:fr[r.operation];return r.operation==="EXISTS"?`style property '${r.property}' ${t}`:`style property '${r.property}' ${t} '${r.value}'`}case"ELEMENT_EXISTENCE":return r.negated?xm[r.condition]:Cm[r.condition];default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var DZ={CONTENT:"The page"};function ZL(r){switch(r.type){case"VALUE":return`the option with value ${r.value}`;case"LABEL":return`the option with label ${r.label}`;case"INDEX":return`the option at index ${r.index}`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function xc(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 Cc(r){let e="";return r.method&&(e=` with method ${r.method}`),`${xc(r.urlMatcher)}${e}`}function eN(r){switch(r.type){case"CONTENT":return`${r.negated?Sr.CONTAINS:fr.CONTAINS} '${r.value}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function vn(r,e=!0){switch(r.type){case"SUCCESS":return r.condition?.assertion?`Check success condition: ${r.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${r.goal}`;case"NAVIGATE":return`Go to URL: ${e?Xe(r.url,30):r.url}`;case"DIALOG":return`Automatically ${r.action.toLowerCase()} the next dialog`;case"CAPTCHA":return"Solve captchas on the page";case"GO_BACK":return"Go back to the previous page";case"GO_FORWARD":return"Go forward to the next page";case"SCROLL_DOWN":return`Scroll down ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${_t(r.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${_t(r.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${_t(r.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${_t(r.target)}`:""}`;case"WAIT":return`Wait for ${r.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(r.target?.type==="coordinates")return`Click at coordinates: ${_t(r.target)}`;let n="";return r.target?.elementDescriptor.length?n=` on element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` on element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Click${n}`}case"FOCUS":return`Focus ${_t(r.target)}`;case"BLUR":return`Focus ${_t(r.target)}`;case"DRAG":return`Drag ${_t(r.fromTarget)} onto ${_t(r.toTarget)}`;case"MOUSE_DRAG":return r.target?.type==="description"&&r.target.elementDescriptor?`Click and drag ${_t(r.target)} by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`:`Click and drag mouse by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`;case"TYPE":{let n="";return r.target?.type==="coordinates"?n=` in element at coordinates: ${_t(r.target)}`:r.target?.elementDescriptor.length?n=` in element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` in element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Type '${r.value}'${n||""}`}case"HOVER":{let n="";return r.target.type==="coordinates"?n=` over coordinates: ${_t(r.target)}`:r.target.elementDescriptor.length>0?n=` over element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` over element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Hover${n}`}case"PRESS":return`Press ${r.value}`;case"KEY_DOWN":return`Hold down ${r.value} on the keyboard`;case"KEY_UP":return`Release ${r.value} on the keyboard`;case"SELECT_OPTION":{let n="",o=ZL(r.choice);return r.target.type==="coordinates"?n=` from element at coordinates: ${_t(r.target)}`:r.target.elementDescriptor.length>0?n=` from: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` from: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${o}'${n}`}case"TAB":switch(r.action.type){case"SUBSTRING":return`Switch to tab with substring: ${r.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${r.action.pattern}`;case"INDEX":return`Switch to tab at index: ${r.action.index}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${r.url}`;case"REQUEST":return`Send ${r.method} request to ${r.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${r.url}`;case"COOKIE":return`Set cookie: ${r.value}`;case"LOCAL_STORAGE":return`Set local storage: ${r.key}: ${r.value}`;case"JAVASCRIPT":return`Run JavaScript: ${e?Xe(r.code,30):r.code}`;case"AI_ASSERTION":return`Assertion: '${r.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${r.target?`for element: ${_t(r.target)}`:"for entire page"}`;case"FILE_UPLOAD":return r.fileSource.type==="URL"?`Upload file: ${r.fileSource.url}`:`Upload file: ${r.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Check the element ${_t(r.target)} ${QL(r.assertion)}`;case"PAGE_CHECK":return`Check the page ${eN(r.assertion)}`;case"WAIT_FOR_URL":return`Wait for page URL to ${xc(r.matcher)}`;case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return r.requestMatcher?`Register a listener for network requests that ${Cc(r.requestMatcher)}`:"Register a listener for network requests";case"AWAIT_LISTENER":return r.key?`Wait for the listener ${r.key} to resolve`:"Wait for a listener to resolve";case"RECORD_REQUESTS":return r.requestMatcher?`Start recording requests that match ${Cc(r.requestMatcher)}`:"Start recording network requests";case"GET_RECORDED_REQUESTS":return r.key?`Get the requests that were recorded for ${r.key}`:"Get the requests that were recorded";case"SET_HEADER":return r.name?r.requestMatcher?`Set a ${r.name} header for requests that match ${Cc(r.requestMatcher)}`:`Set a ${r.name} header for all requests`:"Set a header";case"MOCK_ROUTE":return r.requestMatcher?`Mock requests that ${Cc(r.requestMatcher)}`:"Mock a network route";case"REMOVE_ROUTE_MOCK":return r.key?`Remove the mock with key ${r.key}`:"Remove all route mocks";case"OFFLINE_MODE":return r.enable?"Enable offline mode":"Disable offline mode";default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function tN(r){return typeof r=="object"&&r!==null}function Zr(r){if(Array.isArray(r))return r.map(Zr);if(tN(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=Zr(n))}),e}return r}function nT(r){let e=[];for(let t of r){t.sort((a,l)=>a.timestamp-l.timestamp);let n=[],o,i=1;for(let a of t)o&&o.text===a.text&&o.type===a.type&&JSON.stringify(o.args??null)===JSON.stringify(a.args??null)?i++:(o&&(i>1?o.args&&o.args.length?o.args.push(`(repeated ${i} times)`):o.text+=` (repeated ${i} times)`:n.push(o)),o=a,i=1);o&&n.push(o),e.push(n)}return e}import{cloneDeep as $Z}from"lodash-es";import{cloneDeep as ree}from"lodash-es";import{v4 as uee}from"uuid";import{cloneDeep as rN}from"lodash-es";import cT from"truncate-json";import{v4 as oT}from"uuid";import{cloneDeep as Aee,unset as wee}from"lodash-es";function eo(r){switch(r.type){case"AI_ACTION":return`AI action: ${Xe(r.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${Xe(r.text,100)}`;case"PRESET_ACTION":return vn(r.command);case"MODULE":return`Module: ${r.id}`;case"RESOLVED_MODULE":return`Module: ${r.name}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section${r.description?`with goal: ${Xe(r.description,100)}`:""}`;default:return(t=>{throw new Error("You missed a case in the switch above")})(r)}}function jo(r,e){return r.split(`
|
|
19
19
|
`).map(t=>" ".repeat(e)+t).join(`
|
|
20
|
-
`)}function
|
|
21
|
-
${
|
|
22
|
-
${
|
|
23
|
-
${
|
|
20
|
+
`)}function _m(r){switch(r.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":{let e="results"in r&&Array.isArray(r.results)?r.results.length:0;return`AI action: ${r.text}
|
|
21
|
+
${jo(`Sub-steps: ${e}`,2)}`}case"PRESET_ACTION":return vn(r.command,!1);case"MODULE":{let e="results"in r&&Array.isArray(r.results)?r.results.length:0;if("moduleName"in r){let t=r.moduleName;return`Module: ${r.id} ModuleName: ${t}
|
|
22
|
+
${jo(`Sub-steps: ${e}`,2)}`}return`Module: ${r.id}
|
|
23
|
+
${jo(`Sub-steps: ${e}`,2)}`}case"RESOLVED_MODULE":return`Module: ${r.name}`;case"CONDITIONAL":{let e=["Conditional step"];if("assertionResult"in r&&r.assertionResult&&(e.push(jo("Conditional check:",2)),e.push(jo(_m(r.assertionResult),2))),"results"in r&&Array.isArray(r.results)){let t=r.results.length,n="assertionResult"in r&&r.assertionResult?"Branch steps":"Else branch steps";e.push(jo(`${n}: ${t}`,2))}return e.join(`
|
|
24
24
|
`)}case"SECTION":{let e="results"in r&&Array.isArray(r.results)?r.results.length:0;return`Section${r.description?`with goal: ${r.description}`:""}
|
|
25
|
-
${
|
|
26
|
-
${o}`:o)(Sm(r))}function Tc(r,e={}){let t=e.followingStepStart??e.precedingStepEnd??new Date;return{type:"PRESET_ACTION",id:KE(),message:`Starting the ${r.replace("-"," ")} section`,startedAt:t,finishedAt:t,status:"SUCCESS",command:{id:KE(),type:"SUCCESS"},results:[]}}function Ec(r,e={}){let{index:t,includeDomState:n=!1,header:o}=e,i=NL(r,o),a;r.type==="PRESET_ACTION"&&(a=r.results?.[0]?.elementInteracted);let l=r.message!=="Successfully executed preset action."?r.message:void 0,c=i;r.status==="FAILED"&&(c=`${LL} ${c}`);let s={description:c,startedAt:r.startedAt.toISOString(),finishedAt:r.finishedAt.toISOString(),beforeUrl:r.beforeUrl,afterUrl:r.afterUrl,beforeSnapshot:r.beforeSnapshot,afterSnapshot:r.afterSnapshot,elementInteracted:a,message:l,index:t};if(r.status==="FAILED"&&n)try{let u=lS.array().parse(r.details);for(let d of u)"pageState"in d&&(s.pageState=d.pageState)}catch{}return s}async function eT(r,e,t,{addIndices:n=!0,includeDomState:o=!1,flatten:i=!0,maxItemsFromEnd:a=15,indexOffset:l=0}){let c,s=[];for(let u=0;u<t.length;u++){let d=t[u],p=n?u+l:void 0;switch(d.type){case"PRESET_ACTION":{s.push(Ec(d,{index:p,includeDomState:o,header:void 0})),d.status==="FAILED"&&(c=p);break}case"CONDITIONAL":case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":case"SECTION":{if(i){s.push(Ec(d,{index:n?p:void 0,includeDomState:o,header:"start"})),l+=1;let{failureIndex:m,results:g}=await eT(r,e,d.results,{addIndices:n,includeDomState:o,flatten:i,maxItemsFromEnd:a,indexOffset:l+u});s.push(...g),m!==void 0&&(c=m),l+=g.length,s.push(Ec(d,{index:n?l+u:void 0,includeDomState:o,header:"end"})),l+=1}else s.push(Ec(d,{index:n?l+u:void 0,includeDomState:o,header:void 0}));break}default:return(g=>{throw new Error("You missed a case in the switch above")})(d)}}return{results:s,failureIndex:c}}async function Ki(r,e,t,{numStepsWithScreenshots:n=5,addIndices:o=!0,includeBeforeScreenshots:i=!1,includeDomState:a=!1,flatten:l=!0,maxItemsFromEnd:c=20}){let s=await eT(r,e,t,{addIndices:o,includeDomState:a,flatten:l,maxItemsFromEnd:c,indexOffset:0}),{results:u}=s,{failureIndex:d}=s;d!==void 0&&u.length>0&&(u=u.slice(0,d+1));let p=[],m=0;if(c!==void 0&&u.length>c&&(m=u.length-c),d!==void 0&&d<u.length-1&&r.warn("PROCESS_RESULTS_FOR_LLM: Failure index check - should not be possible",{failureIndex:d,flattenedResultsLength:u.length,lastIndex:u.length-1,isLastIndex:d===u.length-1,offset:m}),d!==void 0&&m>d)throw new Error("Failure index is out of bounds");for(let g=m;g<u.length;g++){let h=u[g],f={description:h.description,startedAt:h.startedAt,finishedAt:h.finishedAt,beforeUrl:h.beforeUrl,afterUrl:h.afterUrl,elementInteracted:h.elementInteracted,message:h.message,pageState:h.pageState,index:h.index},E,S;(n===void 0||n>0&&g>=u.length-n)&&(h.afterSnapshot&&(S=await JE(r,e,h.afterSnapshot)),i&&h.beforeSnapshot&&(E=await JE(r,e,h.beforeSnapshot))),f.beforeScreenshot=E,f.afterScreenshot=S,p.push(f)}return{results:p,failureIndex:d!==void 0?d-m:void 0}}function Yi({json:r,keysToRedact:e,maxJsonStringSize:t}){try{if(!r)return r;if(typeof r=="string")return Qe(r,t??2e4);if(typeof r=="object"){let{jsonString:n}=ZE(JSON.stringify(r,(o,i)=>e?.includes(o)||typeof i=="string"&&i.length>3e4?"REDACTED":i),t??2e4);return JSON.parse(n)}return r}catch{return r}}function ym(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=ZE(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.details&&(n.details=void 0),n.type){case"PRESET_ACTION":QE(n);break;case"CONDITIONAL":n.assertionResult&&QE(n.assertionResult),ym(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{ym(n.results,e);break}default:return(i=>{throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")})(n)}}}function QE(r){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}function bc(r,e){let t=OL(r);if(ym(t,e),t.length>YE)return e.error("Results too long, truncating before insertion"),t.slice(t.length-YE,t.length);let n=JSON.stringify(t);if(n.length>XE)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>XE;)t.splice(0,1),n=JSON.stringify(t);try{return mt.array().parse(JSON.parse(n))}catch(o){throw e.error({serialized:n,err:o},"Could not parse serialized results into JSON structure after processing"),o}}import{cloneDeep as ZZ}from"lodash-es";var DL=/^(?!.*\S+\s+\S+).*$/,kL=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,FL=/style="([^"]*)/g,UL=/data-[\w-]+/g,BL=r=>{switch(r.type){case"AI_ASSERTION":return{type:r.type,assertion:r.assertion};case"DRAG":if(r.fromTarget.type==="description")return{type:r.type,description:r.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(r.target?.type==="description")return{type:r.type,description:r.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function tT(r){let e=BL(r),t=e.type==="AI_ASSERTION"?e.assertion:e.description;return!t||t==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:DL.test(t)&&kL.test(t)?{thoughts:"The target description is too short. Please provide more details.",category:"FEW_WORDS"}:FL.test(t)?{thoughts:"Style tags are not recommended in the command description as they change frequently. Please remove them and describe the target in a different way.",category:"STYLE_TAG"}:UL.test(t)?{thoughts:"Hardcoded data attributes are not recommended in the command description as they change frequently.",category:"HARDCODED_ATTRIBUTE"}:new RegExp(`\\b${e.type}\\b`,"gi").test(t)?{thoughts:`The element description you provided starts with the command type (${e.type}). This can confuse our AI agents since the element itself is unrelated to the desired action.`,category:"TYPE_IN_DESCRIPTION"}:{thoughts:"NONE",category:"NONE"}}function rT(r,e){if(!(!r.envs||!r.envs.length)){for(let t of r.envs){let n=t;e in t&&(n[e]&&(t.default=!0),delete n.defaultOnCloud,delete n.defaultOnLocal)}r.envs.some(t=>t.default)||(r.envs[0].default=!0)}}import{cloneDeep as IT}from"lodash-es";import jL from"diff-lines";import Rc,{gte as $L}from"semver";var nT={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 oT={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 HL=["target","fromTarget","toTarget"];function iT(r){for(let e of HL){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var aT={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 iT(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])iT(n);return e}default:return e}})};import{v4 as zL}from"uuid";var sT={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=zL()),e;default:return e}})};import{v4 as lT}from"uuid";var cT={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??lT(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??lT()}})),delete e.commands),e;default:return e}})};var uT={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 GL}from"uuid";var dT={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=GL()),e))};import{v4 as pT}from"uuid";var mT={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=pT())}return e.id=pT(),e})};var gT={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 VL}from"uuid";var hT={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=VL()),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 fT={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 ST={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&&yT(t),e})};function yT(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){yT(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 ET={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 TT={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 bT={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 vT={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 RT={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 AT={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 vc=new Set(["CLICK","TYPE","SELECT_OPTION"]),wT={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||vc.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let l=a?.elementDescriptor,c=a?.type;(l!==void 0||vc.has(c))&&(a.target={elementDescriptor:l??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let l=a.command,c=l?.elementDescriptor,s=l?.type;(c!==void 0||vc.has(s))&&(l.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,m=d?.type;(p!==void 0||vc.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var CT={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 xT={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.type=n.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,l=a?.type;l?.startsWith("PRESET_")&&(a.type=l.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(s=>{let u=s.type;u?.startsWith("PRESET_")&&(s.type=u.slice(7))})}),e}),stopOnFailure:!0};var Vo=[AT,CT,xT,wT,nT,oT,aT,sT,cT,uT,dT,mT,gT,hT,fT,ST,ET,TT,bT,vT,RT];if(ue!==Vo[Vo.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");Vo.forEach((r,e)=>{if(!Rc.valid(r.toVersion)||!Rc.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!Rc.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(Vo[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});function WL(r){return r.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var hs=async({metadata:r,steps:e,logger:t,toVersion:n})=>{let o=e,{schemaVersion:i,id:a}=r,l=Vo.findIndex(u=>Rc.gt(u.toVersion,i));if(l===-1)return{steps:o,newVersion:i};let c=i;for(let u=l;u<Vo.length;u++){if(n&&$L(c,n)){t.debug("Stopping migration early because toVersion was reached");break}let d=Vo[u],p={id:a,migration:d.name,toVersion:d.toVersion};try{o=await _T(o,d),c=d.toVersion}catch(m){throw t.error({err:m,...p},"Migration failed"),new Error(`Step migration ${d.name} failed: ${m}`)}}let s=jL(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return s.trim()&&t.debug({diffs:s,id:a},"Migration diffs"),{newVersion:c,steps:o}};async function _T(r,e){let t=await e.execute(r);for(let n of t)for(let o of Object.keys(n)){if(!e.recursiveKeys.has(o))continue;let i=n[o];!i||!Array.isArray(i)||WL(i)&&(n[o]=await _T(i,e))}return t}async function PT({rawSteps:r,metadata:e,logger:t,callbacks:n}){rT(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await Ac({rawSteps:r.steps,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o}),l={...e,steps:i,schemaVersion:a};for(let c of["beforeSteps","afterSteps"]){let s=r[c];if(!s)continue;let{resolvedSteps:u}=await Ac({rawSteps:s,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o});l[c]=u}return{resolvedTest:l,moduleIds:Array.from(Object.keys(o))}}async function jo(r,e,t){let{newVersion:n,steps:o}=await hs({metadata:r,steps:e,logger:t});try{return{steps:Le.array().parse(o),newVersion:n}}catch(i){throw t.error({type:"zod",err:i,newVersion:n,id:r.id,steps:o},"Failed to parse test steps while migrating test"),new ql(`Failed to parse test steps while migrating test: ${i}`,r.id,"entity",{cause:i})}}async function Ac({rawSteps:r,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await jo(e,r,t),l=[];for(let c of a)l.push(await fs({step:c,callbacks:n,logger:t,resolvedModuleCache:o}));return{resolvedSteps:l,newSchemaVersion:i}}async function fs({step:r,callbacks:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"AI_ACTION":return r;case"AI_ACTION_DYNAMIC":return r;case"PRESET_ACTION":return r;case"MODULE":{let c=r.moduleId,s=n[c];if(s)return{...IT(s),...r,type:"RESOLVED_MODULE"};let u=await e.onFetchModule({id:c,logger:t});if(!u)throw new Error(`Could not find module with id ${c}`);let{newVersion:d,steps:p}=await hs({metadata:{id:c,schemaVersion:u.schemaVersion},steps:u.steps,logger:t}),m;try{m=Le.array().parse(p)}catch(f){throw t.error({type:"zod",err:f,steps:p,newVersion:d,id:c},"Module failed to parse"),f}let g;try{g=await Promise.all(m.map(f=>fs({step:f,callbacks:e,logger:t,resolvedModuleCache:n})))}catch(f){throw t.error({err:f,...r},`Failed to recursively resolve module '${u.name}': ${f}`),f}let h={...u,steps:g};return n[c]=IT(h),{...h,...r,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let c of r.blocks){let s=[];for(let u of c.steps)s.push(await fs({step:u,callbacks:e,logger:t,resolvedModuleCache:n}));o.push({...c,steps:s})}let i;if(r.elseSteps){i=[];for(let c of r.elseSteps)i.push(await fs({step:c,callbacks:e,logger:t,resolvedModuleCache:n}))}return{...r,blocks:o,elseSteps:i};case"SECTION":let a=[];for(let c of r.steps)a.push(await fs({step:c,callbacks:e,logger:t,resolvedModuleCache:n}));return{...r,steps:a};default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function qL(r){return typeof r=="object"&&r!==null}function vn(r){if(Array.isArray(r))return r.map(vn);if(qL(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=vn(n))}),e}return r}import{cloneDeep as KL}from"lodash-es";import{stringify as MT}from"yaml";async function OT({test:r,processedModuleNames:e=new Set,createNewCacheIds:t=!1}){let n={id:r.id,name:r.name,description:r.description,baseUrl:r.baseUrl,schemaVersion:r.schemaVersion,advanced:r.advanced,retries:r.retries,envs:r.envs,disabled:r.disabled,labels:r.labels},o={},i=await YL({originalStepLists:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:t}),a={fileType:Se.TEST,...n,beforeSteps:i.beforeSteps&&i.beforeSteps.length>0?i.beforeSteps:void 0,steps:i.steps,afterSteps:i.afterSteps&&i.afterSteps.length>0?i.afterSteps:void 0};return{test:MT(a),modules:o}}async function YL({originalStepLists:r,modules:e,processedModuleNames:t,createNewCacheIds:n}){let o=KL(r);Object.values(o).forEach(l=>{XL(l??[])});let{stepsToSave:i,moduleUpdates:a}=await Ge({stepLists:o,createNewCacheIds:n});for(let l of a)t.has(l.name)||(e[l.name]=JL(l),t.add(l.name));return i}function XL(r){gs({steps:r,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function JL(r){let e=Wt.parse(r),t={fileType:Se.MODULE,...e,schemaVersion:ue,steps:r.steps};return MT(t)}async function Z(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function Ss({promiseGenerator:r,signal:e,codePath:t,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((l,c)=>{function s(){clearInterval(a),e?.removeEventListener("abort",s),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",s),(async()=>{try{l(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",s)}})()})}async function $o({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,l=()=>{a.abort()},c=setTimeout(()=>{i||a.abort()},e);o?.addEventListener("abort",l);try{return await Ss({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",l),clearTimeout(c)}}function LT(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}function wc(r){let e=[];for(let t of r)switch(t.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(t);break;case"RESOLVED_MODULE":{let n={...t,type:"MODULE"};e.push(_r.parse(n));break}case"SECTION":{let n={...t,steps:wc(t.steps)};e.push(Le.parse(n));break}case"CONDITIONAL":{let n={...t,blocks:t.blocks.map(o=>({assertion:o.assertion,steps:wc(o.steps)})),elseSteps:t.elseSteps?wc(t.elseSteps):void 0};e.push(Po.parse(n));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function Cc(r){return wc([r])[0]}import QL from"picomatch";var xc=(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||QL(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},_c=(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}},Xi=r=>{try{return new URL(r),!0}catch{return!1}},NT=r=>!r.toLowerCase().startsWith("http"),Ji=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function Wo(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}async function ZL(r){let{logger:e,browserStateStorage:t,generator:n,results:o,error:i,maxItemsFromEnd:a,numStepsWithScreenshots:l,disableCache:c}=r,s=[];if(o.length>0){let{results:d}=await Ki(e,t,o,{numStepsWithScreenshots:l,maxItemsFromEnd:a,includeBeforeScreenshots:!0,includeContainerTagsInDescription:!0});s=d}return await n.getTestResultClassification({results:s,errorMessage:i.message,errorStack:i.stack},{disableCache:c??!1})}async function DT(r){let{logger:e,browserStateStorage:t,generator:n,fullResults:o,failureReason:i,error:a,maxItemsFromEnd:l,numStepsWithScreenshots:c,disableCache:s}=r,u=o?.results??[];if(i==="SetupFailureError"){let d=(o?.beforeResults??[]).at(0);u=[Tc("setup",{followingStepStart:d?.startedAt}),...o?.beforeResults??[]]}else if(i==="TeardownFailureError"){let d=u.at(-1),p=(o?.afterResults??[])[0],m=Tc("teardown",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...u,m,...o?.afterResults??[]]}else if(u.length<20){let d=(o?.beforeResults??[]).at(-1),p=u.at(0),m=Tc("main-test-body",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...o?.beforeResults??[],m,...u]}if(!t||!u||u.length===0)return{};try{let d=await ZL({logger:e,browserStateStorage:t,generator:n,results:u,error:a,maxItemsFromEnd:l,numStepsWithScreenshots:c,disableCache:s});return{classification:d,aiFailureReason:d.reason}}catch(d){return e.error({err:d},"Failed to classify test result"),{}}}import{v4 as kT}from"uuid";function Em(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var Ic=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:Em({},this.metadata)}]).catch(l=>e.error({err:l},"Failed to report billable event"))]}trackStepExecution(e){if(e.type==="MOBILE_PRESET_STEP"){this.creditsUsedV2+=1;return}let t=wp(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Cp(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:kT(),properties:Em({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:kT(),properties:Em({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};function Qi({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new rc:new Tm(r,e,t,n)}var Tm=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=Xp(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:t,beforeSteps:n,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}for(let l of[t,n,o])l&&qi({steps:l,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await Ge({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import tN from"path";var rN=new lc(30,60*1e3),Am="https://api.momentic.ai",FT,UT=r=>{Am=r},Mr=()=>Am;var Zi,Rm,Pc,BT=async r=>{if(FT&&Zi&&Pc)return Zi;let e=new Je({baseUrl:Am,apiKey:r,logger:T});FT=e;try{let t=await e.getAuthInfo();return Zi=t.orgId,Rm=t.userId,Pc=r,Zi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},yt=()=>{if(!Zi)throw new Error("Your organization ID is invalid.");return Zi},ea=()=>{if(!Rm)throw new Error("Your user ID is invalid.");return Rm},qo=()=>{if(!Pc)throw new Error("Your API key is invalid.");return Pc},wm,bm,Mc=(r,e)=>{wm=r,bm?.abort(),bm=new AbortController;let t=bm.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=tN.resolve(r.rootDir,o.envFile);try{if(vm.lstatSync(i).isSymbolicLink())return;vm.existsSync(i)&&n.push(i)}catch(a){T.warn({err:a},`Failed to check if env file ${i} exists`)}});try{nN({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){T.error({err:o},"Failed to start config file watchers")}},te=()=>wm;function nN({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{vm.watch(o,{signal:t,persistent:!1,recursive:!1},(i,a)=>{a&&(rN.increment("setLocalProject")&&T.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.`),wm=e(n.configFilePath))})})}function fe(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Es=oN();function ys(r){let e=te(),t=Et.dirname(e.configFilePath);return Et.join(t,...r)}function aN(r){let e=te(),t=Et.dirname(e.configFilePath),n=Et.relative(t,r);return n?n.split(Et.sep):[]}function sN(r,e){let t=Vt.statSync(r),n=aN(r);return Gp.parse({name:e,absolutePath:r,relativePath:n.join(Et.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}Es.post("/",fe(async(r,e,t)=>{let n;try{n=Sy.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=ys(n);if(!Vt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(Et.sep)}`});return}if(!Vt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(Et.sep)}`});return}let a=te(),l=Array.from(a.config.exclude??[]).concat(Jl),s=iN("*",{absolute:!1,cwd:o,ignore:l,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=Et.join(o,d);return sN(p,d)}),u={absolutePath:o,pathSegments:n,contents:s};e.status(200).json(u)}));Es.put("/",fe(async(r,e,t)=>{let n;try{n=yy.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=ys(n);if(Vt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(Et.sep)}`,pathSegments:n});return}Vt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(Et.sep)}`,pathSegments:n};e.status(201).json(i)}));Es.patch("/",fe(async(r,e,t)=>{let n,o;try{let s=Ey.parse(r.body);n=s.pathSegments,o=s.newPathSegments}catch(s){e.status(400).json({error:`Failed to parse folder update body: ${s}`});return}let i=ys(n),a=ys(o);if(!Vt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(Et.sep)}`});return}if(Vt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(Et.sep)}`});return}let l=Et.dirname(a);Vt.existsSync(l)||Vt.mkdirSync(l,{recursive:!0}),Vt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(Et.sep)} to ${o.join(Et.sep)}`,pathSegments:o};e.status(200).json(c)}));Es.delete("/",fe(async(r,e,t)=>{let n,o=!0;try{let c=Ty.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=ys(n);if(!Vt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(Et.sep)}`,pathSegments:n});return}if(!Vt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(Et.sep)}`});return}if(o)Vt.rmSync(i,{recursive:!0,force:!0});else{if(Vt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Vt.rmdirSync(i)}let l={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(l)}));var Cm=Es;import R1 from"events";import hx,{Router as A1}from"express";import{diff as dN}from"deep-object-diff";import Or from"fs";import Yo from"path";import ta from"yaml";import{z as GT}from"zod";import{execSync as lN}from"child_process";function Ko(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,T.debug({postSaveCommand:n},"Executing post-save hook command");try{lN(n,{encoding:"utf-8"})}catch(o){T.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as HT}from"deep-object-diff";import Jr from"fs";import{cloneDeep as cN}from"lodash-es";import Ts from"path";import{v4 as uN}from"uuid";import bs from"yaml";function jt({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.modules[r.moduleId]?.fullFilePath;if(!i||!Jr.existsSync(i))throw new Error(`Tried to update module ${r.moduleId} that could not be found on disk`);let a=Jr.readFileSync(i,"utf-8"),l=bs.parse(a),c;if(r.name&&r.name!==l.name){let m=`${_e(r.name)}.${St.MODULE}`;if(c=Ts.join(Ts.dirname(i),m),Jr.existsSync(c))throw new Error(`Module with name '${r.name}' already exists at path '${c}'`)}let s={...r,schemaVersion:e},u=vn({fileType:Se.MODULE,...$p.parse(s),steps:Le.array().parse(r.steps)}),d=HT(u,l);if(d&&Object.keys(d).length===0&&!o){T.debug(`Skipping save for module ${r.moduleId} since there are no changes`);return}let p=bs.stringify(u);Jr.writeFileSync(i,p,"utf-8"),c&&Jr.renameSync(i,c),Ko(c||i,n.config)}function zT({moduleId:r,content:e,momenticFiles:t,project:n,logger:o}){let i=t.modules[r]?.fullFilePath;if(!i)throw new Error(`Tried to update module ${r} that could not be found on disk`);let a=Rn(i,o),l={...a,...e},c=vn({fileType:Se.MODULE,...$p.parse(l),steps:a.steps}),s=HT(c,a);if(s&&Object.keys(s).length===0){T.debug(`Skipping save for module ${r} since there are no changes`);return}let u=bs.stringify(c);Jr.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${_e(e.name)}.${St.MODULE}`;if(d=Ts.join(Ts.dirname(i),p),Jr.existsSync(d))throw new Error(`Module with name '${e.name}' already exists at path '${d}'`);Jr.renameSync(i,d)}Ko(d||i,n.config)}async function Oc({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=_e(r),l=Ts.join(o,`${a}.module.yaml`),c=uN(),{stepsToSave:s}=await Ge({stepLists:{steps:n}}),u={fileType:Se.MODULE,schemaVersion:ue,moduleId:c,name:r,description:e,enabled:t,steps:s.steps},d=bs.stringify(u);return Jr.writeFileSync(l,d,"utf-8"),Ko(l,i.config),{moduleId:c,name:r,description:e,enabled:t,steps:n}}function Rn(r,e){let t=Jr.readFileSync(r,"utf-8"),n=bs.parse(t);try{return Mp.parse(n)}catch(o){throw e.error({err:o,moduleFilePath:r,moduleContents:t},`${r} does not parse as a valid Momentic module`),o}}async function fr(r,e,t,n){let o=Rn(r.fullFilePath,t),{resolvedSteps:i}=await Ac({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:n,logger:t,callbacks:{onFetchModule:async({id:l})=>{let c=e.modules[l]?.fullFilePath;if(c)return Rn(c,t)}}}),a={...o,steps:i};return n&&(n[r.id]=cN(a)),a}async function Lc(r,e){let t={};return await Promise.all(Object.values(r.modules).map(async n=>{await fr(n,r,e,t)})),Array.from(Object.values(t))}async function VT({test:r,name:e,folder:t}){let n=await OT({test:r});if(Object.keys(n.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${_e(e)}.${St.TEST}`,a=Yo.join(t,i);return Or.writeFileSync(a,n.test,"utf-8"),a}function xm(r,e,t){let n=Yo.join(t.rootDir,r);if(!Or.existsSync(n))throw new Error(`Test not found at path '${r}' in project '${t.rootDir}'`);let o=Or.readFileSync(n,"utf-8"),i=ta.parse(o),a,l;if(e.name&&e.name!==i.name){let p=`${_e(e.name)}.${St.TEST}`;if(a=Yo.join(Yo.dirname(r),p),l=Yo.join(t.rootDir,a),Or.existsSync(l))throw new Error(`Test with name '${e.name}' already exists at path '${l}'`)}let c={...i,...e},s=mr.parse(c),u={fileType:Se.TEST,...mr.parse(s),beforeSteps:i.beforeSteps??void 0,steps:i.steps,afterSteps:i.afterSteps??void 0},d=ta.stringify(u);return Or.writeFileSync(n,d,"utf-8"),l&&Or.renameSync(n,l),Ko(n,t.config),{newRelativeTestPath:a}}function Dt({relativeTestPath:r,steps:e,schemaVersion:t,project:n,forceSaveOnNoDiffs:o}){let i=Yo.join(n.rootDir,r);if(!Or.existsSync(i))throw new Error(`Test not found at path '${r}' in project '${n.rootDir}'`);let a=Or.readFileSync(i,"utf-8"),l=ta.parse(a),c=mr.parse({...l,schemaVersion:t}),s=Le.array().or(GT.undefined()).parse(e.beforeSteps),u=Le.array().parse(e.steps),d=Le.array().or(GT.undefined()).parse(e.afterSteps),p=vn({fileType:Se.TEST,...c,beforeSteps:s&&s.length>0?s:void 0,steps:u,afterSteps:d&&d.length>0?d:void 0}),m=dN(p,l);if(m&&Object.keys(m).length===0&&!o){T.debug(`Skipping save for test ${c.name} since there are no changes`);return}let g=ta.stringify(p);Or.writeFileSync(i,g,"utf-8"),T.debug(`Saving test ${c.name} to ${i}`),Ko(i,n.config)}function vs(r,e){let t=Yo.join(e.rootDir,r);if(!t)throw new Error(`Could not find test with path ${r} in Momentic project (${e.rootDir})`);let n;try{n=Or.readFileSync(t,"utf8"),n=n.replace(/\r\n|\r/g,`
|
|
27
|
-
`)}catch(i){throw new Error(`Could not read test file ${t}: ${i}`)}let o;try{o=
|
|
28
|
-
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return T.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}function
|
|
29
|
-
`)){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 $N(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 tb("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),l=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(l?.[1])return l[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await tb("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function WN(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return $N(r,e,t);if(o)return}catch{}}function Dc(r){if(r.startsWith("git@")){let e=r.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let n=t[0],o=t[1];return`${n}/${o}`}}}else if(r.startsWith("http")||r.startsWith("https")){let t=new URL(r).pathname.split("/").filter(Boolean);if(t.length>=2){let n=t[0],o=t[1].replace(".git","");return`${n}/${o}`}}}async function Be(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function qN(){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 KN(r){let[e,t,n]=await Promise.all([Be(r,Ue.show(["--no-patch","--format=%ci"])),Be(r,Ue.show(["-s","--pretty=%B"])),Be(r,Ue.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 YN(r){let[e,t,n]=await Promise.all([Be(r,Ue.listRemote(["--get-url","origin"])),Be(r,Ue.show(["-s","--pretty=%B"])),Be(r,Ue.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 XN(r){let[e,t,n,o]=await Promise.all([Be(r,Ue.show(["--no-patch","--format=%ci"])),Be(r,Ue.listRemote(["--get-url","origin"])),Be(r,Ue.show(["-s","--pretty=%B"])),Be(r,Ue.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),l=t?Dc(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function JN(r){let[e,t,n]=await Promise.all([Be(r,Ue.show(["--no-patch","--format=%ci"])),Be(r,Ue.show(["-s","--pretty=%B"])),Be(r,Ue.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Dc(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function QN(r){let[e,t,n]=await Promise.all([Be(r,Ue.show(["--no-patch","--format=%ci"])),Be(r,Ue.show(["-s","--pretty=%B"])),Be(r,Ue.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Dc(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function ZN(r,e){let[t,n,o,i,a,l,c,s,u]=await Promise.all([Be(r,Ue.revparse(["HEAD"])),Be(r,Ue.revparse(["--short","HEAD"])),Be(r,Ue.revparse(["--abbrev-ref","HEAD"])),Be(r,Ue.listRemote(["--get-url","origin"])),Be(r,Ue.show(["--no-patch","--format=%ci"])),Be(r,Ue.show(["-s","--pretty=%B"])),Be(r,Ue.show(["-s","--pretty=%an"])),e?Be(r,Ue.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),jN(r)]),d=s?await Be(r,Ue.show(["--no-patch","--format=%ci",s])):void 0,p=i?.includes("github.com"),m=i?.includes("gitlab.com"),g=i?Dc(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,S=await WN(r,i,u)??E??void 0;return r.debug({userUsername:S,gitLocalUserLogin:E,gitLocalUserEmail:h,gitLocalUserName:f},"Resolved local git identity"),{gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:S,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?g:void 0,gitlabProjectPath:m?g:void 0,pipelineId:void 0}}async function eD(){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 tD(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function Fm(r,e){let t=qN();if(!t)return ZN(r,e);switch(t){case"GithubActions":return KN(r);case"GitlabCI":return YN(r);case"CircleCI":return XN(r);case"Buildkite":return JN(r);case"AzureDevOps":return QN(r);case"GCPCloudBuild":return eD()}}async function rD(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 nD(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 oD(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await nD(r,e,n,o,t)}else if(t.gitlabProjectPath)return await rD(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Qn(r,e,t){let n=await tD(t),o=await Fm(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 oD(r,e,i);return{...n,...o,...a}}import kie from"yaml";import{randomUUID as iD}from"crypto";import An from"fs";import Qo from"path";var rb={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 aD(r,e,t){if(rb[t]){let i=rb[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 nb=new Set([".DS_Store","__MACOSX"]);function ob(r,e,t){let n=iD(),o=r.child({runGroupId:n});An.rmSync(e,{recursive:!0,force:!0});let i=An.readdirSync(t).filter(s=>!nb.has(s)).map(s=>Qo.join(t,s));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);An.mkdirSync(e,{recursive:!0});let a=Qo.join(i[0],"metadata.json"),l={...cs.parse(JSON.parse(An.readFileSync(a,"utf-8"))),id:n};for(let s of i){let u=Qo.join(s,"runs");if(!An.existsSync(u))continue;let d=An.readdirSync(u);for(let g of d){if(nb.has(g))continue;let h=Qo.join(u,g),f=Qo.join(e,"runs",g);An.cpSync(h,f,{recursive:!0})}let p=Qo.join(s,"metadata.json"),m=cs.parse(JSON.parse(An.readFileSync(p,"utf-8")));o.info({oldRunGroupId:m.id},"Merging metadata from run groups");for(let g in m){if(g==="id")continue;let h=g;l[h]=aD(l,m,h)}}let c=Qo.join(e,"metadata.json");An.writeFileSync(c,JSON.stringify(l,null,2))}import ib from"adm-zip";import Um from"fs";import kc from"path";function sD(r){let e=new ib,t=kc.join(r,"metadata.json"),n=cs.parse(JSON.parse(Um.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of Um.readdirSync(kc.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new ib(kc.join(r,"runs",o));for(let l of a.getEntries())l.isDirectory||e.addFile(kc.join("runs",i,l.entryName),l.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Fc(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!Um.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new uc(e);try{let{runGroupId:i,buffer:a}=sD(n),l=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${l}`;t.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`);return}catch(i){let a;i instanceof Error?a=i.message:typeof i=="string"?a=i:a="Unknown error",t.error(`Failed to upload test results: ${a}.`);return}}import lD from"adm-zip";import $t from"fs";import Lr from"path";var ws=class r{constructor(e){this.filePath=e;$t.rmSync(this.filePath,{recursive:!0,force:!0}),$t.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Lr.join(this.filePath,e))}mkdir(e){$t.mkdirSync(Lr.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Lr.join(this.filePath,e);if($t.existsSync(t))return $t.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Lr.join(this.filePath,t);try{$t.writeFileSync(o,n)}catch{}}createRunArchive(e){return new Bm(Lr.join(this.filePath,"runs"),e)}},Bm=class{constructor(e,t){this.filePath=e;this.tempPath=Lr.join(e,`.${t}`),this.finalPath=Lr.join(e,`${t}.zip`),$t.rmSync(this.tempPath,{recursive:!0,force:!0}),$t.rmSync(this.finalPath,{recursive:!0,force:!0}),$t.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Lr.join(this.tempPath,e);if($t.existsSync(t))return $t.readFileSync(t)}mkdir(e){$t.mkdirSync(Lr.join(this.tempPath,e),{recursive:!0})}cd(e){return new ws(Lr.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=Lr.join(this.tempPath,t);$t.writeFileSync(o,n)}close(){let e=new lD;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();$t.writeFileSync(this.finalPath,t),$t.rmSync(this.tempPath,{recursive:!0,force:!0})}};import w1 from"http";import C1 from"path";import{Server as cz}from"socket.io";var cD=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async()=>{e.info({sessionId:n},"Cancel event received");let o=t.getSession(n);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},ab={event:"cancel",createHandler:cD};var uD=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async(o,i)=>{let a=t.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let l=a.controller.browser;try{let s=(await l.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:s},"Fetched a11y tree from the browser"),i({a11yTree:s})}catch(c){e.error({err:c},"Error fetching a11y tree from the browser"),i({err:c.message})}}},sb={event:"fetchA11yTree",createHandler:uD};var dD=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async(o,i)=>{let a=t.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let l=a.controller.browser;try{let c=await l.html();i({html:c})}catch(c){e.error({err:c},"Error fetching DOM from the browser"),c.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:c.message})}}},lb={event:"fetchDom",createHandler:dD};var pD=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return o=>{e.info({sessionId:n,reason:o},`Disconnect event received (${o})`),t.removeSession(n,e)}},cb={event:"disconnect",createHandler:pD};function Zr(r){let{result:e,nestedResults:t}=r;if(!r.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=mD(t);gD(e,n,o);let i=[...r.asyncTasks];r.asyncTasks.push((async()=>{try{await hD(i,e,n,o)}catch(a){r.logger.error({result:r.result,err:a},"Error hoisting scalar result metadata")}})())}function mD(r){let e=r[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertionResult){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let n=r[r.length-1],o;for(;;){switch(n.type){case"PRESET_ACTION":{o=n;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":if(!n.results.length){o=n;break}n=n.results[n.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function gD(r,e,t){e&&(r.beforeUrl=e.beforeUrl),t&&(r.afterUrl=t.afterUrl,r.data=t.data,t.status!=="SUCCESS"&&(r.message=t.message))}async function hD(r,e,t,n){await Promise.allSettled(r),t&&(e.beforeSnapshot=t.beforeSnapshot),n&&(e.afterSnapshot=n.afterSnapshot)}import Cs from"os";import fD from"v8";var ub,en,SD=Cs.platform(),yD=Cs.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 db(r){if(yn)return;let e=()=>{try{let t=!1,n=ED(),o=TD();n.freeMemory<1e6&&(t=!0),o&&o?.total>70&&(t=!0);let i=fD.getHeapStatistics(),a=i.used_heap_size,l=i.heap_size_limit;a/l>.9&&(t=!0),t?r.warn({memory:n,cpu:o,heapStats:i},"Critical resource usage metrics detected"):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,2e4),cpuMetadata:yD,platform:SD}}function ED(){let r=Cs.totalmem(),e=Cs.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function TD(){let r=Cs.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,!en)return en=t,null;let n={user:t.user-en.user,nice:t.nice-en.nice,sys:t.sys-en.sys,idle:t.idle-en.idle,irq:t.irq-en.irq,total:t.total-en.total};return ub={measurementTime:e,intervalMs:e-en.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},en=t,ub}import{randomUUID as MD}from"crypto";import{faker as bD}from"@faker-js/faker";import vD from"assert";import RD from"axios";import*as AD from"child_process";import wD from"moment";import*as CD from"otpauth";import xD from"pg";async function pb(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=zl(n,e);t.push(...o)}),t}function _D(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 ID(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 PD=Object.getPrototypeOf(async function(){}).constructor;async function mb(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:l}=e.bindings,c=e.tools,s={},u=(y,A)=>{o[y]=A,s[y]=A},d={},p=(y,A)=>{o[y]=A,d[y]=A},m;n.includes("Octokit")&&(m=(await import("@octokit/rest")).Octokit);let g;n.includes("createAppAuth")&&(g=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new PD("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(RD,wD,c.fakerInstance??bD,vD,xD,m,g,CD,AD,pb,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,_D(a,l),...Object.values(i??{}))),f=!0,E,S;try{let y=await H(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});E=await ID(e.options.responseSerialization??"RAW",y)}catch(y){t.error({err:y,env:o,evalCode:n},`[${r}] Error executing code: ${y}`),f=!1,y instanceof Yn?S=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:S=y instanceof Error?y.message:`${y}`}return{result:E,variableUpdates:s,persistentVariableUpdates:d,success:f,error:S}}async function gb({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=$n,disallowVariableUpdates:l,additionalBindings:c,responseSerialization:s,mock:u}){let d=MD(),p=await mb(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:l,responseSerialization:s},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return T.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as OD,randomUUID as LD}from"crypto";import ND from"fetch-retry";var DD=ND(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}}),hb=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,fb=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function Sb({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=$n,retries:i=2,signal:a,logger:l,additionalBindings:c,disallowVariableUpdates:s,responseSerialization:u,mock:d}){if(!hb)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,g=0;if(!fb)throw new Error("Missing lambda auth secret.");let h=OD("sha256",fb).update(r).digest("hex");for(;g<=i;){g++,a?.throwIfAborted();let E={id:LD(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:s,responseSerialization:u};try{if(p=await H(DD(hb,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!p)throw new Error("Got empty response from code evaluation server");if(!p.ok)throw new Error(`Code evaluation server returned error code ${p.status}`);m=void 0;break}catch(S){m=S}}if(m)throw l.error({err:m},"Failed to evaluate code remotely"),m;if(!p)throw new Error(`An unexpected code evaluation error occurred${m?`: ${m}`:""}`);let f;try{f=KS.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 Zn(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Sb(r);else if(r.localTools)e=await gb({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
25
|
+
${jo(`Sub-steps: ${e}`,2)}`}default:return(t=>{throw new Error("You missed a case in the switch above")})(r)}}var iT=1e3,aT=5e7,nN="[FAILED]";async function sT(r,e,t){if(t){let n=await e.getScreenshot(r,t);if(n)return`data:image/jpeg;base64,${Buffer.from(n).toString("base64")}`}}function oN(r,e){let t=(()=>{switch(r.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":return"AI action";case"PRESET_ACTION":return"Preset action";case"MODULE":return"Module";case"CONDITIONAL":return"Conditional step";case"SECTION":return"Section";default:return(i=>{throw new Error("You missed a case in the switch above")})(r)}})();return(o=>e?`${e==="start"?"Start":"End"} of ${t}
|
|
26
|
+
${o}`:o)(_m(r))}function Ic(r,e={}){let t=e.followingStepStart??e.precedingStepEnd??new Date;return{type:"PRESET_ACTION",id:oT(),message:`Starting the ${r.replace("-"," ")} section`,startedAt:t,finishedAt:t,status:"SUCCESS",command:{id:oT(),type:"SUCCESS"},results:[]}}function _c(r,e={}){let{index:t,includeDomState:n=!1,header:o}=e,i=oN(r,o),a;r.type==="PRESET_ACTION"&&(a=r.results?.[0]?.elementInteracted);let l=r.message!=="Successfully executed preset action."?r.message:void 0,c=i;r.status==="FAILED"&&(c=`${nN} ${c}`);let s={description:c,startedAt:r.startedAt.toISOString(),finishedAt:r.finishedAt.toISOString(),beforeUrl:r.beforeUrl,afterUrl:r.afterUrl,beforeSnapshot:r.beforeSnapshot,afterSnapshot:r.afterSnapshot,elementInteracted:a,message:l,index:t};if(r.status==="FAILED"&&n)try{let u=yS.array().parse(r.details);for(let d of u)"pageState"in d&&(s.pageState=d.pageState)}catch{}return s}async function uT(r,e,t,{addIndices:n=!0,includeDomState:o=!1,flatten:i=!0,maxItemsFromEnd:a=15,indexOffset:l=0}){let c,s=[];for(let u=0;u<t.length;u++){let d=t[u],p=n?u+l:void 0;switch(d.type){case"PRESET_ACTION":{s.push(_c(d,{index:p,includeDomState:o,header:void 0})),d.status==="FAILED"&&(c=p);break}case"CONDITIONAL":case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":case"SECTION":{if(i){s.push(_c(d,{index:n?p:void 0,includeDomState:o,header:"start"})),l+=1;let{failureIndex:m,results:g}=await uT(r,e,d.results,{addIndices:n,includeDomState:o,flatten:i,maxItemsFromEnd:a,indexOffset:l+u});s.push(...g),m!==void 0&&(c=m),l+=g.length,s.push(_c(d,{index:n?l+u:void 0,includeDomState:o,header:"end"})),l+=1}else s.push(_c(d,{index:n?l+u:void 0,includeDomState:o,header:void 0}));break}default:return(g=>{throw new Error("You missed a case in the switch above")})(d)}}return{results:s,failureIndex:c}}async function Xi(r,e,t,{numStepsWithScreenshots:n=5,addIndices:o=!0,includeBeforeScreenshots:i=!1,includeDomState:a=!1,flatten:l=!0,maxItemsFromEnd:c=20}){let s=await uT(r,e,t,{addIndices:o,includeDomState:a,flatten:l,maxItemsFromEnd:c,indexOffset:0}),{results:u}=s,{failureIndex:d}=s;d!==void 0&&u.length>0&&(u=u.slice(0,d+1));let p=[],m=0;if(c!==void 0&&u.length>c&&(m=u.length-c),d!==void 0&&d<u.length-1&&r.warn("PROCESS_RESULTS_FOR_LLM: Failure index check - should not be possible",{failureIndex:d,flattenedResultsLength:u.length,lastIndex:u.length-1,isLastIndex:d===u.length-1,offset:m}),d!==void 0&&m>d)throw new Error("Failure index is out of bounds");for(let g=m;g<u.length;g++){let h=u[g],f={description:h.description,startedAt:h.startedAt,finishedAt:h.finishedAt,beforeUrl:h.beforeUrl,afterUrl:h.afterUrl,elementInteracted:h.elementInteracted,message:h.message,pageState:h.pageState,index:h.index},S,E;(n===void 0||n>0&&g>=u.length-n)&&(h.afterSnapshot&&(E=await sT(r,e,h.afterSnapshot)),i&&h.beforeSnapshot&&(S=await sT(r,e,h.beforeSnapshot))),f.beforeScreenshot=S,f.afterScreenshot=E,p.push(f)}return{results:p,failureIndex:d!==void 0?d-m:void 0}}function Ji({json:r,keysToRedact:e,maxJsonStringSize:t}){try{if(!r)return r;if(typeof r=="string")return Xe(r,t??2e4);if(typeof r=="object"){let{jsonString:n}=cT(JSON.stringify(r,(o,i)=>e?.includes(o)||typeof i=="string"&&i.length>3e4?"REDACTED":i),t??2e4);return JSON.parse(n)}return r}catch{return r}}function Im(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=cT(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.details&&(n.details=void 0),n.type){case"PRESET_ACTION":lT(n);break;case"CONDITIONAL":n.assertionResult&&lT(n.assertionResult),Im(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{Im(n.results,e);break}default:return(i=>{throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")})(n)}}}function lT(r){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}function Mc(r,e){let t=rN(r);if(Im(t,e),t.length>iT)return e.error("Results too long, truncating before insertion"),t.slice(t.length-iT,t.length);let n=JSON.stringify(t);if(n.length>aT)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>aT;)t.splice(0,1),n=JSON.stringify(t);try{return pt.array().parse(JSON.parse(n))}catch(o){throw e.error({serialized:n,err:o},"Could not parse serialized results into JSON structure after processing"),o}}import{cloneDeep as Wee}from"lodash-es";var iN=/^(?!.*\S+\s+\S+).*$/,aN=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,sN=/style="([^"]*)/g,lN=/data-[\w-]+/g,cN=r=>{switch(r.type){case"AI_ASSERTION":return{type:r.type,assertion:r.assertion};case"DRAG":if(r.fromTarget.type==="description")return{type:r.type,description:r.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(r.target?.type==="description")return{type:r.type,description:r.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function dT(r){let e=cN(r),t=e.type==="AI_ASSERTION"?e.assertion:e.description;return!t||t==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:iN.test(t)&&aN.test(t)?{thoughts:"The target description is too short. Please provide more details.",category:"FEW_WORDS"}:sN.test(t)?{thoughts:"Style tags are not recommended in the command description as they change frequently. Please remove them and describe the target in a different way.",category:"STYLE_TAG"}:lN.test(t)?{thoughts:"Hardcoded data attributes are not recommended in the command description as they change frequently.",category:"HARDCODED_ATTRIBUTE"}:new RegExp(`\\b${e.type}\\b`,"gi").test(t)?{thoughts:`The element description you provided starts with the command type (${e.type}). This can confuse our AI agents since the element itself is unrelated to the desired action.`,category:"TYPE_IN_DESCRIPTION"}:{thoughts:"NONE",category:"NONE"}}function pT(r,e){if(!(!r.envs||!r.envs.length)){for(let t of r.envs){let n=t;e in t&&(n[e]&&(t.default=!0),delete n.defaultOnCloud,delete n.defaultOnLocal)}r.envs.some(t=>t.default)||(r.envs[0].default=!0)}}import{cloneDeep as BT}from"lodash-es";import gN from"diff-lines";import Oc,{gte as hN}from"semver";var mT={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 gT={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 uN=["target","fromTarget","toTarget"];function hT(r){for(let e of uN){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var fT={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 hT(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])hT(n);return e}default:return e}})};import{v4 as dN}from"uuid";var ST={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=dN()),e;default:return e}})};import{v4 as yT}from"uuid";var ET={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??yT(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??yT()}})),delete e.commands),e;default:return e}})};var TT={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 pN}from"uuid";var bT={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=pN()),e))};import{v4 as vT}from"uuid";var RT={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=vT())}return e.id=vT(),e})};var AT={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 mN}from"uuid";var wT={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=mN()),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 CT={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 xT={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&&_T(t),e})};function _T(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){_T(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 IT={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 MT={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 PT={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 OT={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 LT={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 NT={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 Pc=new Set(["CLICK","TYPE","SELECT_OPTION"]),DT={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||Pc.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let l=a?.elementDescriptor,c=a?.type;(l!==void 0||Pc.has(c))&&(a.target={elementDescriptor:l??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let l=a.command,c=l?.elementDescriptor,s=l?.type;(c!==void 0||Pc.has(s))&&(l.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,m=d?.type;(p!==void 0||Pc.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var kT={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 FT={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.type=n.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,l=a?.type;l?.startsWith("PRESET_")&&(a.type=l.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(s=>{let u=s.type;u?.startsWith("PRESET_")&&(s.type=u.slice(7))})}),e}),stopOnFailure:!0};var $o=[NT,kT,FT,DT,mT,gT,fT,ST,ET,TT,bT,RT,AT,wT,CT,xT,IT,MT,PT,OT,LT];if(se!==$o[$o.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");$o.forEach((r,e)=>{if(!Oc.valid(r.toVersion)||!Oc.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!Oc.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if($o[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});function fN(r){return r.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var bs=async({metadata:r,steps:e,logger:t,toVersion:n})=>{let o=e,{schemaVersion:i,id:a}=r,l=$o.findIndex(u=>Oc.gt(u.toVersion,i));if(l===-1)return{steps:o,newVersion:i};let c=i;for(let u=l;u<$o.length;u++){if(n&&hN(c,n)){t.debug("Stopping migration early because toVersion was reached");break}let d=$o[u],p={id:a,migration:d.name,toVersion:d.toVersion};try{o=await UT(o,d),c=d.toVersion}catch(m){throw t.error({err:m,...p},"Migration failed"),new Error(`Step migration ${d.name} failed: ${m}`)}}let s=gN(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return s.trim()&&t.debug({diffs:s,id:a},"Migration diffs"),{newVersion:c,steps:o}};async function UT(r,e){let t=await e.execute(r);for(let n of t)for(let o of Object.keys(n)){if(!e.recursiveKeys.has(o))continue;let i=n[o];!i||!Array.isArray(i)||fN(i)&&(n[o]=await UT(i,e))}return t}async function zT({rawSteps:r,metadata:e,logger:t,callbacks:n}){pT(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await Lc({rawSteps:r.steps,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o}),l={...e,steps:i,schemaVersion:a};for(let c of["beforeSteps","afterSteps"]){let s=r[c];if(!s)continue;let{resolvedSteps:u}=await Lc({rawSteps:s,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o});l[c]=u}return{resolvedTest:l,moduleIds:Array.from(Object.keys(o))}}async function Wo(r,e,t){let{newVersion:n,steps:o}=await bs({metadata:r,steps:e,logger:t});try{return{steps:Pe.array().parse(o),newVersion:n}}catch(i){throw t.error({type:"zod",err:i,newVersion:n,id:r.id,steps:o},"Failed to parse test steps while migrating test"),new nc(`Failed to parse test steps while migrating test: ${i}`,r.id,"entity",{cause:i})}}async function Lc({rawSteps:r,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await Wo(e,r,t),l=[];for(let c of a)l.push(await vs({step:c,callbacks:n,logger:t,resolvedModuleCache:o}));return{resolvedSteps:l,newSchemaVersion:i}}async function vs({step:r,callbacks:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"AI_ACTION":return r;case"AI_ACTION_DYNAMIC":return r;case"PRESET_ACTION":return r;case"MODULE":{let c=r.moduleId,s=n[c];if(s)return{...BT(s),...r,type:"RESOLVED_MODULE"};let u=await e.onFetchModule({id:c,logger:t});if(!u)throw new Error(`Could not find module with id ${c}`);let{newVersion:d,steps:p}=await bs({metadata:{id:c,schemaVersion:u.schemaVersion},steps:u.steps,logger:t}),m;try{m=Pe.array().parse(p)}catch(f){throw t.error({type:"zod",err:f,steps:p,newVersion:d,id:c},"Module failed to parse"),f}let g;try{g=await Promise.all(m.map(f=>vs({step:f,callbacks:e,logger:t,resolvedModuleCache:n})))}catch(f){throw t.error({err:f,...r},`Failed to recursively resolve module '${u.name}': ${f}`),f}let h={...u,steps:g};return n[c]=BT(h),{...h,...r,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let c of r.blocks){let s=[];for(let u of c.steps)s.push(await vs({step:u,callbacks:e,logger:t,resolvedModuleCache:n}));o.push({...c,steps:s})}let i;if(r.elseSteps){i=[];for(let c of r.elseSteps)i.push(await vs({step:c,callbacks:e,logger:t,resolvedModuleCache:n}))}return{...r,blocks:o,elseSteps:i};case"SECTION":let a=[];for(let c of r.steps)a.push(await vs({step:c,callbacks:e,logger:t,resolvedModuleCache:n}));return{...r,steps:a};default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{diff as GT}from"deep-object-diff";import{cloneDeep as HT}from"lodash-es";import{v4 as Mm}from"uuid";async function Ge(r){let e=new Map,t=new Set,n=HT(r.stepLists.steps),o=await qo({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t}),i={stepsToSave:{steps:o.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates};for(let a of["beforeSteps","afterSteps"]){let l=HT(r.stepLists[a]);if(!l)continue;let c=await qo({...r,steps:l,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});i.cachesToSave.push(...c.cachesToSave),i.moduleUpdates.push(...c.moduleUpdates),i.stepsToSave[a]=c.stepsToSave}return i}async function qo({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:l,createNewCacheIds:c}=e,s={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of r)switch(delete u.index,delete u.aiSuggested,u.id=c?Mm():u.id,u.type){case"PRESET_ACTION":{let p=u.command;p.id=c?Mm():p.id,"cache"in p&&p.cache&&(n&&(s.cachesToSave=s.cachesToSave.concat(wm({id:p.id,orgId:n.orgId,testId:n.testId,value:Sn.parse(p),moduleIdParents:o,moduleStepParents:i}))),delete p.cache),p.thoughts&&delete p.thoughts,s.stepsToSave.push({...u,command:p});break}case"RESOLVED_MODULE":{let p=c?Mm():u.id,m=u.moduleId;a.has(m)?m=a.get(m):l!==void 0&&(m=await l(u),a.set(u.moduleId,m));let{cachesToSave:g,stepsToSave:h,moduleUpdates:f}=await qo({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,p],moduleIdParents:[...o,m],skipCacheIntermediateEntries:c});s.moduleUpdates=s.moduleUpdates.concat(f),s.cachesToSave=s.cachesToSave.concat(g),t.has(m)||(t.add(m),s.moduleUpdates.push({...Wt.parse(u),steps:Pe.array().parse(h),moduleId:m}));let S=_r.parse({...u,type:"MODULE",moduleId:m,inputs:u.inputs,id:p,skipped:u.skipped,cacheConfig:u.cacheConfig,envKey:u.envKey});s.stepsToSave.push(S);break}case"AI_ACTION":{if(!u.steps){s.stepsToSave.push(u);break}let{stepsToSave:p,cachesToSave:m}=await qo({...e,steps:u.steps});try{u.steps=er.array().parse(p)}catch(g){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${g}`)}s.stepsToSave.push(u),s.cachesToSave=s.cachesToSave.concat(m);break}case"AI_ACTION_DYNAMIC":{s.stepsToSave.push(u);break}case"CONDITIONAL":{let p=[];for(let g of u.blocks){let{stepsToSave:h,cachesToSave:f,moduleUpdates:S}=await qo({...e,steps:g.steps});p.push({...g,steps:h}),s.cachesToSave=s.cachesToSave.concat(f),s.moduleUpdates=s.moduleUpdates.concat(S)}let m={...u,elseSteps:void 0,blocks:p};if(u.elseSteps){let{stepsToSave:g,cachesToSave:h,moduleUpdates:f}=await qo({...e,steps:u.elseSteps});m.elseSteps=g,s.cachesToSave=s.cachesToSave.concat(h),s.moduleUpdates=s.moduleUpdates.concat(f)}s.stepsToSave.push(m);break}case"SECTION":{let{stepsToSave:p,cachesToSave:m,moduleUpdates:g}=await qo({...e,steps:u.steps}),h={...u,steps:p};s.moduleUpdates=s.moduleUpdates.concat(g),s.stepsToSave.push(h),s.cachesToSave=s.cachesToSave.concat(m);break}default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(u)}return s}async function Nc({logger:r,cacheStorage:e,orgId:t,testId:n,originalSteps:o,updatedSteps:i}){let a=GT(o,i);if(Object.keys(a).length!==0){r.debug("Updating step caches post-success");try{let{cachesToSave:l}=await Ge({stepLists:i,cacheCreationParams:{testId:n,orgId:t}});await e.saveStepCacheEntries({logger:r,testId:n,entries:l})}catch(l){r.error({err:l},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async function Dc({logger:r,cacheStorage:e,orgId:t,testId:n,originalSteps:o,updatedSteps:i}){let a=GT(o,i);if(Object.keys(a).length===0)return;r.debug({changes:a},"Updating memory post-run failure");let l={};for(let u of["steps","beforeSteps","afterSteps"]){let d=o[u];if(!d||!d.length)continue;let p=tT({steps:d});for(let[m,g]of Object.entries(p))l[m]=g}let{cachesToSave:c}=await Ge({stepLists:i,cacheCreationParams:{testId:n,orgId:t}}),s=rT({newEntries:c,originalCachesMap:l,logger:r});if(s.length){r.debug({prunedCaches:s},"Saving pruned memory post-failure");try{await e.saveStepCacheEntries({logger:r,testId:n,entries:c})}catch(u){r.error({err:u},"Failed to save memory after successful execution. This is not critical, but can impact future performance.")}}}import{cloneDeep as SN}from"lodash-es";import{stringify as VT}from"yaml";async function jT({test:r,processedModuleNames:e=new Set,createNewCacheIds:t=!1}){let n={id:r.id,name:r.name,description:r.description,baseUrl:r.baseUrl,schemaVersion:r.schemaVersion,advanced:r.advanced,retries:r.retries,envs:r.envs,disabled:r.disabled,labels:r.labels},o={},i=await yN({originalStepLists:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:t}),a={fileType:de.TEST,...n,beforeSteps:i.beforeSteps&&i.beforeSteps.length>0?i.beforeSteps:void 0,steps:i.steps,afterSteps:i.afterSteps&&i.afterSteps.length>0?i.afterSteps:void 0};return{test:VT(a),modules:o}}async function yN({originalStepLists:r,modules:e,processedModuleNames:t,createNewCacheIds:n}){let o=SN(r);Object.values(o).forEach(l=>{EN(l??[])});let{stepsToSave:i,moduleUpdates:a}=await Ge({stepLists:o,createNewCacheIds:n});for(let l of a)t.has(l.name)||(e[l.name]=TN(l),t.add(l.name));return i}function EN(r){Ts({steps:r,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function TN(r){let e=Wt.parse(r),t={fileType:de.MODULE,...e,schemaVersion:se,steps:r.steps};return VT(t)}async function ee(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function Rs({promiseGenerator:r,signal:e,codePath:t,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((l,c)=>{function s(){clearInterval(a),e?.removeEventListener("abort",s),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",s),(async()=>{try{l(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",s)}})()})}async function Ko({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,l=()=>{a.abort()},c=setTimeout(()=>{i||a.abort()},e);o?.addEventListener("abort",l);try{return await Rs({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",l),clearTimeout(c)}}function $T(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}function kc(r){let e=[];for(let t of r)switch(t.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(t);break;case"RESOLVED_MODULE":{let n={...t,type:"MODULE"};e.push(_r.parse(n));break}case"SECTION":{let n={...t,steps:kc(t.steps)};e.push(Pe.parse(n));break}case"CONDITIONAL":{let n={...t,blocks:t.blocks.map(o=>({assertion:o.assertion,steps:kc(o.steps)})),elseSteps:t.elseSteps?kc(t.elseSteps):void 0};e.push(Lo.parse(n));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function Fc(r){return kc([r])[0]}import bN from"picomatch";var Uc=(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||bN(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},Bc=(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}},Qi=r=>{try{return new URL(r),!0}catch{return!1}},WT=r=>!r.toLowerCase().startsWith("http"),Zi=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function Yo(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}async function vN(r){let{logger:e,browserStateStorage:t,generator:n,results:o,error:i,maxItemsFromEnd:a,numStepsWithScreenshots:l,disableCache:c}=r,s=[];if(o.length>0){let{results:d}=await Xi(e,t,o,{numStepsWithScreenshots:l,maxItemsFromEnd:a,includeBeforeScreenshots:!0,includeContainerTagsInDescription:!0});s=d}return await n.getTestResultClassification({results:s,errorMessage:i.message,errorStack:i.stack},{disableCache:c??!1})}async function qT(r){let{logger:e,browserStateStorage:t,generator:n,fullResults:o,failureReason:i,error:a,maxItemsFromEnd:l,numStepsWithScreenshots:c,disableCache:s}=r,u=o?.results??[];if(i==="SetupFailureError"){let d=(o?.beforeResults??[]).at(0);u=[Ic("setup",{followingStepStart:d?.startedAt}),...o?.beforeResults??[]]}else if(i==="TeardownFailureError"){let d=u.at(-1),p=(o?.afterResults??[])[0],m=Ic("teardown",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...u,m,...o?.afterResults??[]]}else if(u.length<20){let d=(o?.beforeResults??[]).at(-1),p=u.at(0),m=Ic("main-test-body",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...o?.beforeResults??[],m,...u]}if(!t||!u||u.length===0)return{};try{let d=await vN({logger:e,browserStateStorage:t,generator:n,results:u,error:a,maxItemsFromEnd:l,numStepsWithScreenshots:c,disableCache:s});return{classification:d,aiFailureReason:d.reason}}catch(d){return e.error({err:d},"Failed to classify test result"),{}}}import{v4 as KT}from"uuid";function Pm(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var zc=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:Pm({},this.metadata)}]).catch(l=>e.error({err:l},"Failed to report billable event"))]}trackStepExecution(e){if(ry(e.type)){this.creditsUsedV2+=1;return}let t=kp(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Fp(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:KT(),properties:Pm({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:KT(),properties:Pm({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};function ea({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new pc:new Om(r,e,t,n)}var Om=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=sm(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:t,beforeSteps:n,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}for(let l of[t,n,o])l&&Yi({steps:l,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await Ge({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import RN from"path";var AN=new yc(30,60*1e3),km="https://api.momentic.ai",XT,JT=r=>{km=r},Or=()=>km;var ta,Dm,Hc,QT=async r=>{if(XT&&ta&&Hc)return ta;let e=new Ye({baseUrl:km,apiKey:r,logger:T});XT=e;try{let t=await e.getAuthInfo();return ta=t.orgId,Dm=t.userId,Hc=r,ta}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},St=()=>{if(!ta)throw new Error("Your organization ID is invalid.");return ta},ra=()=>{if(!Dm)throw new Error("Your user ID is invalid.");return Dm},Xo=()=>{if(!Hc)throw new Error("Your API key is invalid.");return Hc},Fm,Lm,Gc=(r,e)=>{Fm=r,Lm?.abort(),Lm=new AbortController;let t=Lm.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=RN.resolve(r.rootDir,o.envFile);try{if(Nm.lstatSync(i).isSymbolicLink())return;Nm.existsSync(i)&&n.push(i)}catch(a){T.warn({err:a},`Failed to check if env file ${i} exists`)}});try{wN({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){T.error({err:o},"Failed to start config file watchers")}},ae=()=>Fm;function wN({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{Nm.watch(o,{signal:t,persistent:!1,recursive:!1},(i,a)=>{a&&(AN.increment("setLocalProject")&&T.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.`),Fm=e(n.configFilePath))})})}function ye(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var ws=CN();function As(r){let e=ae(),t=yt.dirname(e.configFilePath);return yt.join(t,...r)}function _N(r){let e=ae(),t=yt.dirname(e.configFilePath),n=yt.relative(t,r);return n?n.split(yt.sep):[]}function IN(r,e){let t=Vt.statSync(r),n=_N(r);return Zp.parse({name:e,absolutePath:r,relativePath:n.join(yt.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}ws.post("/",ye(async(r,e,t)=>{let n;try{n=_y.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=As(n);if(!Vt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(yt.sep)}`});return}if(!Vt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(yt.sep)}`});return}let a=ae(),l=Array.from(a.config.exclude??[]).concat(sc),s=xN("*",{absolute:!1,cwd:o,ignore:l,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=yt.join(o,d);return IN(p,d)}),u={absolutePath:o,pathSegments:n,contents:s};e.status(200).json(u)}));ws.put("/",ye(async(r,e,t)=>{let n;try{n=Iy.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=As(n);if(Vt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(yt.sep)}`,pathSegments:n});return}Vt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(yt.sep)}`,pathSegments:n};e.status(201).json(i)}));ws.patch("/",ye(async(r,e,t)=>{let n,o;try{let s=My.parse(r.body);n=s.pathSegments,o=s.newPathSegments}catch(s){e.status(400).json({error:`Failed to parse folder update body: ${s}`});return}let i=As(n),a=As(o);if(!Vt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(yt.sep)}`});return}if(Vt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(yt.sep)}`});return}let l=yt.dirname(a);Vt.existsSync(l)||Vt.mkdirSync(l,{recursive:!0}),Vt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(yt.sep)} to ${o.join(yt.sep)}`,pathSegments:o};e.status(200).json(c)}));ws.delete("/",ye(async(r,e,t)=>{let n,o=!0;try{let c=Py.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=As(n);if(!Vt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(yt.sep)}`,pathSegments:n});return}if(!Vt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(yt.sep)}`});return}if(o)Vt.rmSync(i,{recursive:!0,force:!0});else{if(Vt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Vt.rmdirSync(i)}let l={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(l)}));var Um=ws;import $1 from"events";import Mx,{Router as W1}from"express";import{diff as LN}from"deep-object-diff";import Lr from"fs";import Jo from"path";import oa from"yaml";import{z as tb}from"zod";import{execSync as MN}from"child_process";function Rn(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,T.debug({postSaveCommand:n},"Executing post-save hook command");try{MN(n,{encoding:"utf-8"})}catch(o){T.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as ZT}from"deep-object-diff";import en from"fs";import{cloneDeep as PN}from"lodash-es";import Cs from"path";import{v4 as ON}from"uuid";import xs from"yaml";function jt({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.modules[r.moduleId]?.fullFilePath;if(!i||!en.existsSync(i))throw new Error(`Tried to update module ${r.moduleId} that could not be found on disk`);let a=en.readFileSync(i,"utf-8"),l=xs.parse(a),c;if(r.name&&r.name!==l.name){let m=`${xe(r.name)}.module.yaml`;if(c=Cs.join(Cs.dirname(i),m),en.existsSync(c))throw new Error(`A conflicting file '${r.name}' already exists at path '${c}'`)}let s={...r,schemaVersion:e},u=Zr({fileType:de.MODULE,...rm.parse(s),steps:Pe.array().parse(r.steps)}),d=ZT(u,l);if(d&&Object.keys(d).length===0&&!o){T.debug(`Skipping save for module ${r.moduleId} since there are no changes`);return}let p=xs.stringify(u);en.writeFileSync(i,p,"utf-8"),c&&en.renameSync(i,c),Rn(c||i,n.config)}function eb({moduleId:r,content:e,momenticFiles:t,project:n,logger:o}){let i=t.modules[r]?.fullFilePath;if(!i)throw new Error(`Tried to update module ${r} that could not be found on disk`);let a=An(i,o),l={...a,...e},c=Zr({fileType:de.MODULE,...rm.parse(l),steps:a.steps}),s=ZT(c,a);if(s&&Object.keys(s).length===0){T.debug(`Skipping save for module ${r} since there are no changes`);return}let u=xs.stringify(c);en.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${xe(e.name)}.module.yaml`;if(d=Cs.join(Cs.dirname(i),p),en.existsSync(d))throw new Error(`Module with name '${e.name}' already exists at path '${d}'`);en.renameSync(i,d)}Rn(d||i,n.config)}async function Vc({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=xe(r),l=Cs.join(o,`${a}.module.yaml`),c=ON(),{stepsToSave:s}=await Ge({stepLists:{steps:n}}),u={fileType:de.MODULE,schemaVersion:se,moduleId:c,name:r,description:e,enabled:t,steps:s.steps},d=xs.stringify(u);return en.writeFileSync(l,d,"utf-8"),Rn(l,i.config),{moduleId:c,name:r,description:e,enabled:t,steps:n}}function An(r,e){let t=en.readFileSync(r,"utf-8"),n=xs.parse(t);try{return Hp.parse(n)}catch(o){throw e.error({err:o,moduleFilePath:r,moduleContents:t},`${r} does not parse as a valid Momentic module`),o}}async function yr(r,e,t,n){let o=An(r.fullFilePath,t),{resolvedSteps:i}=await Lc({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:n,logger:t,callbacks:{onFetchModule:async({id:l})=>{let c=e.modules[l]?.fullFilePath;if(c)return An(c,t)}}}),a={...o,steps:i};return n&&(n[r.id]=PN(a)),a}async function jc(r,e){let t={};return await Promise.all(Object.values(r.modules).map(async n=>{await yr(n,r,e,t)})),Array.from(Object.values(t))}async function rb({test:r,name:e,folder:t}){let n=await jT({test:r});if(Object.keys(n.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${xe(e)}.test.yaml`,a=Jo.join(t,i);return Lr.writeFileSync(a,n.test,"utf-8"),a}function Bm(r,e,t){let n=Jo.join(t.rootDir,r);if(!Lr.existsSync(n))throw new Error(`Test not found at path '${r}' in project '${t.rootDir}'`);let o=Lr.readFileSync(n,"utf-8"),i=oa.parse(o),a,l;if(e.name&&e.name!==i.name){let p=`${xe(e.name)}.test.yaml`;if(a=Jo.join(Jo.dirname(r),p),l=Jo.join(t.rootDir,a),Lr.existsSync(l))throw new Error(`Test with name '${e.name}' already exists at path '${l}'`)}let c={...i,...e},s=hr.parse(c),u={fileType:de.TEST,...hr.parse(s),beforeSteps:i.beforeSteps??void 0,steps:i.steps,afterSteps:i.afterSteps??void 0},d=oa.stringify(u);return Lr.writeFileSync(n,d,"utf-8"),l&&Lr.renameSync(n,l),Rn(n,t.config),{newRelativeTestPath:a}}function Dt({relativeTestPath:r,steps:e,schemaVersion:t,project:n,forceSaveOnNoDiffs:o}){let i=Jo.join(n.rootDir,r);if(!Lr.existsSync(i))throw new Error(`Test not found at path '${r}' in project '${n.rootDir}'`);let a=Lr.readFileSync(i,"utf-8"),l=oa.parse(a),c=hr.parse({...l,schemaVersion:t}),s=Pe.array().or(tb.undefined()).parse(e.beforeSteps),u=Pe.array().parse(e.steps),d=Pe.array().or(tb.undefined()).parse(e.afterSteps),p=Zr({fileType:de.TEST,...c,beforeSteps:s&&s.length>0?s:void 0,steps:u,afterSteps:d&&d.length>0?d:void 0}),m=LN(p,l);if(m&&Object.keys(m).length===0&&!o){T.debug(`Skipping save for test ${c.name} since there are no changes`);return}let g=oa.stringify(p);Lr.writeFileSync(i,g,"utf-8"),T.debug(`Saving test ${c.name} to ${i}`),Rn(i,n.config)}function _s(r,e){let t=Jo.join(e.rootDir,r);if(!t)throw new Error(`Could not find test with path ${r} in Momentic project (${e.rootDir})`);let n;try{n=Lr.readFileSync(t,"utf8"),n=n.replace(/\r\n|\r/g,`
|
|
27
|
+
`)}catch(i){throw new Error(`Could not read test file ${t}: ${i}`)}let o;try{o=oa.parse(n)}catch(i){throw new Error(`Could not parse test file ${t} as YAML: ${i}`)}return Ot.parse(o)}function Qo(r,e,t){let n=t.project.rootDir,o;try{o=Lr.readFileSync(r,"utf-8")}catch(a){throw e.error({err:a,projectRoot:n},a.message),new Error(a.message)}let i=oa.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${r} is missing steps`);return i}async function it(r,e,t){let n=Qo(r,e,t),o;try{o=hr.parse(n)}catch(a){throw new Error(`Test ${r} is missing metadata or has invalid metadata: ${a}`)}let{resolvedTest:i}=await zT({rawSteps:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:a,logger:l})=>{let c=t.modules[a]?.fullFilePath;if(c)return An(c,l)}}});return i}import NN from"@dotenvx/dotenvx";import DN from"fs";import nb from"path";function $c(r,e){return(r.config.environments??[]).map(t=>Is(t.name,r,e))}function ob(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 kN(r){let{envVariables:e,project:t}=r;if(!e)return{};let n={};for(let[o,i]of Object.entries(e)){if(typeof i=="string"){let l=ob(i);l&&(n[o]=l);continue}let a;try{a=DN.readFileSync(nb.resolve(t.rootDir,i.fromFile),"utf-8")}catch(l){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${l}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(l){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${l}`)}else n[o]=a}return Object.keys(n).length>0&&T.debug(n,"Set environment variables with interpolation from project configuration"),n}function FN(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=NN.config({path:nb.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 Is(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`);if(!n.baseUrl)throw new Error(`Browser environment ${r} does not have a baseUrl configured`);let o={[ht]:ob(n.baseUrl)},i=kN({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=FN({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,browser:n.browser}}import{existsSync as XN,readFileSync as JN,readdirSync as QN,writeFileSync as ZN}from"fs";import{globSync as eD}from"glob";import Zo,{dirname as lb}from"path";import{cwd as jm}from"process";import cb from"yaml";import{z as ke}from"zod";import ib from"fs";import{globSync as UN}from"glob";import Ms from"path";import BN from"yaml";import{z as zm}from"zod";var ab=!1,Hm=["**/*.test.yaml","**/*.module.yaml"],Gm=zm.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),Vm=50,zN=zm.object({fileType:zm.nativeEnum(de)});function W(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??Hm,o=Array.from(r.config.exclude??[]).concat(sc),i=UN(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:Vm,nodir:!0});for(let a of i){let l=HN(r.rootDir,a,t,e?Tn:T);l&&(t.duplicateEntities[l.id]=l.paths)}return ab=!0,t}function HN(r,e,t,n){let o=Ms.join(r,e),i=GN(o,n);if(!i)return;let a=VN(i,o,n);if(!a)return;let l=zN.safeParse(a);if(l.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${l.error}`);return}let c=l.data.fileType,s=jN(o,n);if(!s)return;let u=$N(e,o,s);switch(c){case de.TEST:try{return WN(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case de.MODULE:try{return qN(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case de.MOBILE_TEST:try{return YN(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case de.MOBILE_MODULE:try{return KN(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 GN(r,e){try{return ib.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function VN(r,e,t){try{let n=BN.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 jN(r,e){try{return ib.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function $N(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:Ms.sep,fullPathSegments:e.split(Ms.sep),relativePathSegments:r.split(Ms.sep),fileName:Ms.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function WN(r,e,t,n,o){let i=hr.parse(r),a;if(e.tests[i.id]){let l=e.tests[i.id].fullFilePath;a={id:i.id,paths:[l,n]}}return e.tests[i.id]={type:de.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function qN(r,e,t,n,o){let i=Wt.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:de.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let l=t.fileName.replace(".module.yaml","");return!ab&&xe(i.name)!==l&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${l}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function KN(r,e,t,n,o){let i=Jl.parse(r),a;if(e.mobileModules[i.moduleId]){let c=e.mobileModules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}let l=t.fileName.replace(".module.yaml","");return e.mobileModules[i.moduleId]={type:de.MOBILE_MODULE,name:l,id:i.moduleId,description:i.description??void 0,...t},a}function YN(r,e,t,n,o){let i=as.parse(r),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let l=t.fileName.replace(".test.yaml","");return e.mobileTests[i.id]={type:de.MOBILE_TEST,name:l,id:i.id,description:i.description??void 0,...t},a}var ia="momentic.config.yaml",sb="momentic.workspace.yaml",tD=ke.object({projects:ke.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),rD=ke.union([ke.string(),ke.object({fromFile:ke.string(),json:ke.boolean().optional()})]),nD=ke.object({name:Gm,baseUrl:ke.string().optional().describe("Optional for mobile tests"),envFile:ke.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:ke.record(ke.string(),rD).optional(),inheritFromShell:ke.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:ko.optional().describe("deprecated: use project-level configuration only")}),oD=ke.object({postSave:ke.string().optional()}),iD=ke.object({name:Gm,include:ke.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:ke.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:ke.string().optional(),reporterDir:ke.string().optional(),outputDir:ke.string().optional(),retries:ke.number().optional().describe("number of retries per test"),parallel:ke.number().optional().describe("degree of parallelism"),environments:ke.array(nD).optional(),gitMainBranch:ke.string().optional(),gitProtectedBranches:ke.string().array().optional(),ai:nm.optional(),browser:ko.optional(),emulator:Vp.optional(),advanced:om.optional(),hooks:oD.optional()});function ub(r,e){let t;try{t=JN(r,"utf-8")}catch(o){T.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=cb.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){T.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function $m(r){let e=ub(r,"project configuration");if(e!==void 0)try{return iD.parse(e)}catch(t){T.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function aD(r){let e=ub(r,"workspace configuration");if(e!==void 0)try{return tD.parse(e)}catch(t){T.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function sD(){let r=[],e=jm(),t=Zo.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=Zo.basename(e);if(ac.includes(i))return T.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of QN(e))if(a.endsWith(ia)){let l=Zo.join(e,a),c=$m(l);c&&r.push({configFilePath:l,config:c,rootDir:lb(l)})}if(r.length)return r;if(e=Zo.dirname(e),e===t)break}return r}function Et(r={}){let{configFilePath:e,nameFilter:t}=r,n=Wm(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:
|
|
28
|
+
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return T.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}function lD(r){let e=aD(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${ia}`)),n=eD(t,{absolute:!1,cwd:jm(),dotRelative:!1,maxDepth:Vm,nodir:!0}),o=[];for(let i of n){let a=Zo.join(jm(),i),l=$m(a);l&&o.push({configFilePath:a,config:l,rootDir:lb(a)})}return o}function Wm(r){if(r){r=Zo.resolve(r);let t=$m(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:Zo.dirname(r)}]}if(XN(sb)){let t=lD(sb);if(t)return t}return sD()}function aa(r,e){let t=cb.stringify(r);ZN(e,t)}import sa from"fs";import qm from"path";import{z as Km}from"zod";var db="golden/visual-diff",pb="reports",mb="test-results";var cD=Km.object({width:Km.number(),height:Km.number()}),la=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let n=qm.join(e.rootDir,e.config.goldenFileDir??db);this.defaultGoldenScreenshotDir=n,this.regenerateGoldenFiles=t}async prepareGoldenScreenshotForComparison(e,t,n){if(t.screenshot?.data?.startsWith("https://")){let a=await fetch(t.screenshot.data);return{buffer:Buffer.from(await a.arrayBuffer()),width:t.screenshot.width,height:t.screenshot.height}}let o=t.screenshot?.data;o||(o=qm.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return sa.mkdirSync(qm.dirname(o),{recursive:!0}),sa.writeFileSync(o,n.buffer),sa.writeFileSync(i,JSON.stringify({width:n.width,height:n.height})),{buffer:Buffer.from(n.buffer),width:n.width,height:n.height};if(sa.existsSync(o)){let a=sa.readFileSync(o),l=cD.parse(JSON.parse(sa.readFileSync(i,"utf-8")));return{buffer:a,width:l.width,height:l.height}}else throw new C("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};import{execFile as uD}from"node:child_process";import{promisify as dD}from"node:util";import pD from"simple-git";var Fe=pD(),gb=dD(uD);async function mD(r){let e=await Ue(r,Fe.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
|
|
29
|
+
`)){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 gD(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 gb("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),l=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(l?.[1])return l[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await gb("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function hD(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return gD(r,e,t);if(o)return}catch{}}function Wc(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 Ue(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function fD(){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 SD(r){let[e,t,n]=await Promise.all([Ue(r,Fe.show(["--no-patch","--format=%ci"])),Ue(r,Fe.show(["-s","--pretty=%B"])),Ue(r,Fe.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 yD(r){let[e,t,n]=await Promise.all([Ue(r,Fe.listRemote(["--get-url","origin"])),Ue(r,Fe.show(["-s","--pretty=%B"])),Ue(r,Fe.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 ED(r){let[e,t,n,o]=await Promise.all([Ue(r,Fe.show(["--no-patch","--format=%ci"])),Ue(r,Fe.listRemote(["--get-url","origin"])),Ue(r,Fe.show(["-s","--pretty=%B"])),Ue(r,Fe.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),l=t?Wc(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function TD(r){let[e,t,n]=await Promise.all([Ue(r,Fe.show(["--no-patch","--format=%ci"])),Ue(r,Fe.show(["-s","--pretty=%B"])),Ue(r,Fe.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Wc(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function bD(r){let[e,t,n]=await Promise.all([Ue(r,Fe.show(["--no-patch","--format=%ci"])),Ue(r,Fe.show(["-s","--pretty=%B"])),Ue(r,Fe.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Wc(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function vD(r,e){let[t,n,o,i,a,l,c,s,u]=await Promise.all([Ue(r,Fe.revparse(["HEAD"])),Ue(r,Fe.revparse(["--short","HEAD"])),Ue(r,Fe.revparse(["--abbrev-ref","HEAD"])),Ue(r,Fe.listRemote(["--get-url","origin"])),Ue(r,Fe.show(["--no-patch","--format=%ci"])),Ue(r,Fe.show(["-s","--pretty=%B"])),Ue(r,Fe.show(["-s","--pretty=%an"])),e?Ue(r,Fe.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),mD(r)]),d=s?await Ue(r,Fe.show(["--no-patch","--format=%ci",s])):void 0,p=i?.includes("github.com"),m=i?.includes("gitlab.com"),g=i?Wc(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,S=u["user.username"]||void 0,E=await hD(r,i,u)??S??void 0;return{gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:E,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?g:void 0,gitlabProjectPath:m?g:void 0,pipelineId:void 0}}async function RD(){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 AD(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function Ps(r,e){let t=fD();if(!t)return vD(r,e);switch(t){case"GithubActions":return SD(r);case"GitlabCI":return yD(r);case"CircleCI":return ED(r);case"Buildkite":return TD(r);case"AzureDevOps":return bD(r);case"GCPCloudBuild":return RD()}}async function wD(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 CD(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 xD(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await CD(r,e,n,o,t)}else if(t.gitlabProjectPath)return await wD(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function to(r,e,t){let n=await AD(t),o=await Ps(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 xD(r,e,i);return{...n,...o,...a}}import{diff as Bae}from"deep-object-diff";import{cloneDeep as Hae}from"lodash-es";import{v4 as Zae}from"uuid";import tse from"yaml";import Sse from"yaml";import{randomUUID as _D}from"crypto";import wn from"fs";import ei from"path";var hb={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 ID(r,e,t){if(hb[t]){let i=hb[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 fb=new Set([".DS_Store","__MACOSX"]);function Sb(r,e,t){let n=_D(),o=r.child({runGroupId:n});wn.rmSync(e,{recursive:!0,force:!0});let i=wn.readdirSync(t).filter(s=>!fb.has(s)).map(s=>ei.join(t,s));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);wn.mkdirSync(e,{recursive:!0});let a=ei.join(i[0],"metadata.json"),l={...hs.parse(JSON.parse(wn.readFileSync(a,"utf-8"))),id:n};for(let s of i){let u=ei.join(s,"runs");if(!wn.existsSync(u))continue;let d=wn.readdirSync(u);for(let g of d){if(fb.has(g))continue;let h=ei.join(u,g),f=ei.join(e,"runs",g);wn.cpSync(h,f,{recursive:!0})}let p=ei.join(s,"metadata.json"),m=hs.parse(JSON.parse(wn.readFileSync(p,"utf-8")));o.info({oldRunGroupId:m.id},"Merging metadata from run groups");for(let g in m){if(g==="id")continue;let h=g;l[h]=ID(l,m,h)}}let c=ei.join(e,"metadata.json");wn.writeFileSync(c,JSON.stringify(l,null,2))}import yb from"adm-zip";import Ym from"fs";import qc from"path";function MD(r){let e=new yb,t=qc.join(r,"metadata.json"),n=hs.parse(JSON.parse(Ym.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of Ym.readdirSync(qc.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new yb(qc.join(r,"runs",o));for(let l of a.getEntries())l.isDirectory||e.addFile(qc.join("runs",i,l.entryName),l.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Kc(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!Ym.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new Tc(e);try{let{runGroupId:i,buffer:a}=MD(n),l=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${l}`;t.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`);return}catch(i){let a;i instanceof Error?a=i.message:typeof i=="string"?a=i:a="Unknown error",t.error(`Failed to upload test results: ${a}.`);return}}import PD from"adm-zip";import $t from"fs";import Nr from"path";var Os=class r{constructor(e){this.filePath=e;$t.rmSync(this.filePath,{recursive:!0,force:!0}),$t.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Nr.join(this.filePath,e))}mkdir(e){$t.mkdirSync(Nr.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Nr.join(this.filePath,e);if($t.existsSync(t))return $t.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Nr.join(this.filePath,t);try{$t.writeFileSync(o,n)}catch{}}createRunArchive(e){return new Xm(Nr.join(this.filePath,"runs"),e)}},Xm=class{constructor(e,t){this.filePath=e;this.tempPath=Nr.join(e,`.${t}`),this.finalPath=Nr.join(e,`${t}.zip`),$t.rmSync(this.tempPath,{recursive:!0,force:!0}),$t.rmSync(this.finalPath,{recursive:!0,force:!0}),$t.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Nr.join(this.tempPath,e);if($t.existsSync(t))return $t.readFileSync(t)}mkdir(e){$t.mkdirSync(Nr.join(this.tempPath,e),{recursive:!0})}cd(e){return new Os(Nr.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=Nr.join(this.tempPath,t);$t.writeFileSync(o,n)}close(){let e=new PD;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();$t.writeFileSync(this.finalPath,t),$t.rmSync(this.tempPath,{recursive:!0,force:!0})}};import q1 from"http";import K1 from"path";import{Server as LH}from"socket.io";var OD=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async()=>{e.info({sessionId:n},"Cancel event received");let o=t.getSession(n);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},Eb={event:"cancel",createHandler:OD};var LD=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async(o,i)=>{let a=t.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let l=a.controller.browser;try{let s=(await l.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:s},"Fetched a11y tree from the browser"),i({a11yTree:s})}catch(c){e.error({err:c},"Error fetching a11y tree from the browser"),i({err:c.message})}}},Tb={event:"fetchA11yTree",createHandler:LD};var ND=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async(o,i)=>{let a=t.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let l=a.controller.browser;try{let c=await l.html();i({html:c})}catch(c){e.error({err:c},"Error fetching DOM from the browser"),c.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:c.message})}}},bb={event:"fetchDom",createHandler:ND};var DD=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return o=>{e.info({sessionId:n,reason:o},`Disconnect event received (${o})`),t.removeSession(n,e)}},vb={event:"disconnect",createHandler:DD};function tn(r){let{result:e,nestedResults:t}=r;if(!r.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=kD(t);FD(e,n,o);let i=[...r.asyncTasks];r.asyncTasks.push((async()=>{try{await UD(i,e,n,o)}catch(a){r.logger.error({result:r.result,err:a},"Error hoisting scalar result metadata")}})())}function kD(r){let e=r[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertionResult){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){t=e;break}e=e.results[0];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let n=r[r.length-1],o;for(;;){switch(n.type){case"PRESET_ACTION":{o=n;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":if(!n.results.length){o=n;break}n=n.results[n.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function FD(r,e,t){e&&(r.beforeUrl=e.beforeUrl),t&&(r.afterUrl=t.afterUrl,r.data=t.data,t.status!=="SUCCESS"&&(r.message=t.message))}async function UD(r,e,t,n){await Promise.allSettled(r),t&&(e.beforeSnapshot=t.beforeSnapshot),n&&(e.afterSnapshot=n.afterSnapshot)}import{randomUUID as YD}from"crypto";import{faker as BD}from"@faker-js/faker";import zD from"assert";import HD from"axios";import*as GD from"child_process";import VD from"moment";import*as jD from"otpauth";import $D from"pg";async function Rb(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Kl(n,e);t.push(...o)}),t}function WD(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 qD(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 KD=Object.getPrototypeOf(async function(){}).constructor;async function Ab(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:l}=e.bindings,c=e.tools,s={},u=(y,A)=>{o[y]=A,s[y]=A},d={},p=(y,A)=>{o[y]=A,d[y]=A},m;n.includes("Octokit")&&(m=(await import("@octokit/rest")).Octokit);let g;n.includes("createAppAuth")&&(g=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new KD("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(HD,VD,c.fakerInstance??BD,zD,$D,m,g,jD,GD,Rb,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,WD(a,l),...Object.values(i??{}))),f=!0,S,E;try{let y=await H(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});S=await qD(e.options.responseSerialization??"RAW",y)}catch(y){t.error({err:y,env:o,evalCode:n},`[${r}] Error executing code: ${y}`),f=!1,y instanceof Qn?E=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:E=y instanceof Error?y.message:`${y}`}return{result:S,variableUpdates:s,persistentVariableUpdates:d,success:f,error:E}}async function wb({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=Yn,disallowVariableUpdates:l,additionalBindings:c,responseSerialization:s,mock:u}){let d=YD(),p=await Ab(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:l,responseSerialization:s},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return T.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as XD,randomUUID as JD}from"crypto";import QD from"fetch-retry";var ZD=QD(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}}),Cb=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,xb=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function _b({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=Yn,retries:i=2,signal:a,logger:l,additionalBindings:c,disallowVariableUpdates:s,responseSerialization:u,mock:d}){if(!Cb)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,g=0;if(!xb)throw new Error("Missing lambda auth secret.");let h=XD("sha256",xb).update(r).digest("hex");for(;g<=i;){g++,a?.throwIfAborted();let S={id:JD(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:s,responseSerialization:u};try{if(p=await H(ZD(Cb,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!p)throw new Error("Got empty response from code evaluation server");if(!p.ok)throw new Error(`Code evaluation server returned error code ${p.status}`);m=void 0;break}catch(E){m=E}}if(m)throw l.error({err:m},"Failed to evaluate code remotely"),m;if(!p)throw new Error(`An unexpected code evaluation error occurred${m?`: ${m}`:""}`);let f;try{f=iy.parse(await p.json())}catch(S){throw new Error(`Code evaluation server returned invalid response: ${S}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function ro(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await _b(r);else if(r.localTools)e=await wb({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
30
30
|
${e.error}
|
|
31
31
|
Code received:
|
|
32
|
-
${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 kD}from"lodash-es";async function er(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:l=$n,allowUndefined:c=!1}=r,s=/{{(.*?)}}/g,u=t.matchAll(s),d=t;for(let p of u){if(p.length<2)continue;let m=p[1].trim(),g;try{g=await Zn({orgId:e,code:m,fragment:!0,context:n,timeoutMs:l,logger:o,retries:a,localTools:r.localTools,signal:i})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(g===void 0&&!c)throw new C("UserConfigurationError",`Template fragment '${m}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let h=typeof g=="string"?g:`${g}`;h=h.replaceAll(/\$/g,"$$$$"),d=d.replace(p[0],h)}return d}async function Uc(r){return yb(r)}async function yb({obj:r,bannedKeys:e,allowList:t,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let l in r){if(e.includes(l))continue;let c=!1;if(t)if(t.includes(l))c=!0;else continue;let s=r[l],u=[...o,l];if(typeof s=="string"&&s.includes("{{")){let d=await er({s,context:n,...a});if(s===d)continue;i.push({path:u,original:s}),r[l]=d}else typeof s=="object"&&s!==null&&!Array.isArray(s)&&await yb({obj:s,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function Eb(r,e){for(let{path:t,original:n}of e)kD(r,t,n)}import FD from"fetch-retry";var Mse=process.env.MAILINATOR_API_KEY,Ose=FD(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import{hostname as $D}from"os";import{cloneDeep as UD}from"lodash-es";async function bb(r){let{command:e,timeoutMs:t,fixtures:n}=r,{logger:o,abortSignal:i}=n,a=Af(e.cache)?e.cache:void 0,l=Date.now(),c=0,s,u=500,d=!1;for(;c<2||Date.now()-l<t;){c++,c>1&&await Z(u,i),i?.throwIfAborted();let{result:p,updatedCache:m,elementWasFound:g}=await Tb({cacheToUse:a,params:r});if(s=p,d=g,p.success){m?.target&&zo({cmd:e,key:"target",newTarget:m?.target,logger:o});break}m?.target?.memory&&a?.target&&(a.target.memory=m.target.memory),u=Math.min(u*2,1e4)}if(!s)throw new C("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(i?.throwIfAborted(),!s.success&&a?.target&&pl(a.target)){let p=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:m,updatedCache:g}=await Tb({cacheToUse:p,params:r});s=m,m.success&&g?.target&&zo({cmd:e,key:"target",newTarget:g.target,logger:o})}return s.success&&a?.target&&!d&&Ef(a.target),s}async function Tb({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:l}=o;if(t.target&&!Dn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=HD(t.assertion),s,u=!1,d=UD(r);try{let{elementInteractedDisplayString:p,result:m,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>BD(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:Oo(t),targetName:"target"}});return s={success:m.success,data:m.data,err:m.err,elementInteractedDisplayString:p,thoughts:g},u=!0,m.success||(l.warn({aiThoughts:g,elementString:p,err:m.err},"Element check found an element but failed"),s={...m,thoughts:g}),{result:s,elementWasFound:u,updatedCache:d}}catch(p){if(c)return s={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:s,elementWasFound:u,updatedCache:d};if(!(p instanceof C)||p.reason!="ActionFailureError")throw p;return s={success:!1,err:p,data:void 0,thoughts:void 0},l.warn({err:p},"Element check did not find an element and failed"),{result:s,elementWasFound:u,updatedCache:d}}}async function BD(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:Qe(c,500,!0)},!Bc(c,n.value,n.operation,!!n.negated)){let s=n.negated?gr[n.operation]:hr[n.operation];o=!1,i=new C("AssertionFailureError",`The content ${s} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:Qe(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(s){i=new C("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${s}`),o=!1;break}if(!Bc(c,n.value,n.operation,!!n.negated)){let s=n.negated?gr[n.operation]:hr[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The attribute ${n.attr} ${s}`):i=new C("AssertionFailureError",`The attribute ${n.attr} ${s} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(s,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(m=>setTimeout(m,250));let p=s.getBoundingClientRect();if(!(p.width===0||p.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},Vr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:Vr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:Vr*1e3});break}case"FOCUSED":{o=await r.evaluate(s=>s===document.activeElement);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?hm[n.condition]:fm[n.condition];i=new C("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(s=>s.tagName);if(!Bc(c,n.value,n.operation,!!n.negated)){let s=n.negated?gr[n.operation]:hr[n.operation];o=!1,i=new C("AssertionFailureError",`The element tag name ${s} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((s,u)=>window.getComputedStyle(s).getPropertyValue(u),n.property);if(!Bc(c,n.value,n.operation,!!n.negated)){let s=n.negated?gr[n.operation]:hr[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The style property ${n.property} ${s}`):i=new C("AssertionFailureError",`The style property ${n.property} ${s} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function Bc(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 HD(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function vb(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as zD}from"jimp";async function xs(r,e){let t=await r.screenshot(e),n=await zD.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as Rb}from"jimp";import Hm from"jpeg-js";import GD from"pixelmatch";async function Ab({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:l}){if(t.target&&!Dn(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let c={clearHighlights:!0,hideCaret:!0},s;t.target?.elementDescriptor?s=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async $=>xs(o,{locator:$.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:s=await xs(o,c);let u=await l.prepareGoldenScreenshotForComparison(a,t,s);if((s.height!==u.height||s.width!==u.width)&&a.warn({currHeight:s.height,currWidth:s.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(s.height-u.height)>10||Math.abs(s.width-u.width)>10){let K=`${s.width}x${s.height}`,$=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${K}) does not match saved screenshot dimensions (${$}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:s.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await Rb.fromBuffer(s.buffer),p={width:s.width,height:s.height},m=await Rb.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=p.width*p.height,E=g.width*g.height,S=Math.abs(p.height-g.height),y=Math.abs(p.width-g.width);if(f>E){let K=d.cover({w:g.width,h:g.height});s.buffer=await K.getBuffer("image/jpeg"),h="current",s.width=g.width,s.height=g.height}else if(E>f){let K=m.cover({w:p.width,h:p.height});u.buffer=await K.getBuffer("image/jpeg"),h="saved"}let A={data:Buffer.alloc(s.width*s.height*4),width:s.width,height:s.height},R=t.threshold??.1,x=GD(Hm.decode(u.buffer).data,Hm.decode(s.buffer).data,A.data,s.width,s.height,{threshold:R,diffColorAlt:[0,255,0]})/(s.width*s.height)*100,_=x>R*100,M=`Visual diff of ${x.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${R*100}%.`;if(h&&(M+=` The ${h} screenshot was cropped since it was taller by ${S} pixels and wider by ${y} pixels.`),_)throw new C("ActionFailureError",M);return{fail:_,thoughts:M,beforeScreenshotOverride:s.buffer,afterScreenshotOverride:Hm.encode(A,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var VD=3e4;async function wb({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??VD/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([m,g])=>m&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([m,g])=>m&&g).forEach(([m,g])=>{a.append(m,g)});let l=a.toString(),c;if(Xi(r.url)&&(c=r.url),t&&Ji(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:l,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await H((async()=>{let m=l?`${c}?${l}`:c;try{return await n(m,{headers:i,method:r.method,body:r.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new C("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let m;try{m=await u.text()}catch(g){m=`Failed to read response body: ${g}`}throw new C("ActionFailureError",`Fetch request failed with status ${u.status}: ${m}`)}let d={};u.headers.forEach((m,g)=>{d[g]=m});let p={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{p.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(p.text=await u.text());return p}var jD=5e3;async function Hc({timeout:r=Vr,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,l=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let c=Date.now();i=await Cb(e),a=Date.now();let s=a-c;if(s>1e3&&e.logger.warn({pageAssertDuration:s},"Page assertion took longer than expected"),!i.success)await Z(l,e.signal),l=Math.min(Math.floor(l*1.5),jD);else return i}return i=await Cb(e),i}async function Cb({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let l;if(t){let c=await e.evaluateFunctionInAllFrames(xb,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(s=>s.evaluation):c.some(s=>s.evaluation),l=c.find(s=>s.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:l}=await e.evaluateFunctionInPage(xb,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?gr.CONTAINS:hr.CONTAINS;a=new C("AssertionFailureError",`The page ${c} '${r.value}'.`),o=l}}catch(l){a=new C("AssertionFailureError",`Failed to evaluate page content assertion: ${l instanceof Error?l.message:`${l}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function xb({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 zm=async r=>{let{step:e,resolvedInputs:t}=r.moduleParams,{logger:n,context:o,storage:i,codeEvalTools:a,controller:l}=r.fixtures,c=l.browser,{orgId:s,runId:u}=r.inputs,d=l.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),n.info(Yi({json:{inputs:t,moduleId:e.moduleId},maxJsonStringSize:1e3}),"Set module inputs"));let p,m=!1,g,h;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",E=await er({orgId:s,s:f,context:o,logger:n,localTools:a,signal:d});h={orgId:s,cacheKeys:[E,...Object.entries(t).map(([y,A])=>`${y}:${A}`)]},n.info({original:f,keyParams:h},"Module cache key params");let S=Date.now();for(;Date.now()-S<Ay;){d?.throwIfAborted();let y=await i.getCacheResult(h);if(y){n.info({cacheResult:Qe(y,1e3,!0)},"Got result from module execution cache"),p=zc(e,t,"SUCCESS"),p.message="Used cached module result.",p.data=JSON.parse(y),m=!0;break}else n.info({cacheKey:f,keyParams:h},"No cache result found, continuing with lock acquisition");let A=await i.acquireCacheLock({keyParams:h,clientMetadata:`hostName:${$D()};runId:${u}`},d);if(A.acquired){g=A.keyPrefix,n.info({cacheKeyPrefixIfLockAcquired:g,cacheKey:f,keyParams:h},"Acquired cache lock and proceeding with module execution");break}else n.debug({cacheKeyPrefixIfLockAcquired:g,cacheKey:f,keyParams:h},"Failed to acquire cache lock, retrying...");await Z(2500+Math.random()*1e4,d)}}try{if(!p)p=await WD(r);else if(e.autoAuth){let f=Gl.safeParse(p.data);if(!f.success)throw new C("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);n.debug("Automatically loading auth state after cached module result"),await c.loadAuthState(f.data);let E=!1,S=e.advanced?.cacheInvalidation;if(S&&S.type==="PAGE_CHECK"){let y={type:"CONTENT",value:S.substring},A=await Hc({timeout:Vr,assertion:y,browser:c,logger:n,signal:d,autoExpandIframes:!!c.userBrowserSettings.autoExpandIframes});A.success?n.debug({invalResult:A},"Cached result still valid after page check, continuing..."):(n.info({invalResult:A},"Invalidating cached result due to page check failure"),E=!0)}if(h&&E)return await i.deleteCacheResult(h),zm(r)}}finally{try{g!==void 0&&!m&&p?.status==="SUCCESS"&&await qD({step:e,result:p,browser:l.browser,cacheKeyPrefix:g,logger:n,storage:i})}finally{g!==void 0&&await i.releaseCacheLock(g)}}return p},WD=async r=>{let{step:e,tracer:t}=r.moduleParams,n=zc(e,r.moduleParams.resolvedInputs,"SUCCESS"),o=await t.startSubSteps(),{status:i,results:a}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}});return n.results=a,n.status=i,n.finishedAt=new Date,Zr({asyncTasks:r.work.asyncTasks,nestedResults:a,result:n,logger:r.fixtures.logger}),n};function zc(r,e,t){let n={};return Object.entries(e).forEach(([i,a])=>{n[i]=JSON.stringify(a)}),{type:"MODULE",id:r.id,moduleId:r.moduleId,moduleName:r.name,startedAt:new Date,cacheConfig:r.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:t}}async function _b({orgId:r,step:e,context:t,logger:n,flagStore:o,codeEvalTools:i,signal:a}){let l={};try{for(let c of e.parameters??[]){let s=e.inputs?.[c]??e.defaultParameters?.[c];if(!s){n.warn(`No value or default found for parameter '${c}' that is required by module '${e.name}'`);continue}l[c]=await Zn({orgId:r,code:s,fragment:!0,context:t,logger:n,localTools:i,signal:a})}return l}catch(c){throw a?.throwIfAborted(),new C("UserConfigurationError",`Failed to evaluate module inputs: ${c}`)}}async function qD({step:r,result:e,browser:t,cacheKeyPrefix:n,logger:o,storage:i}){let a=r.cacheConfig?.cacheExpiryMs;(!a||a===cE)&&(a=r.defaultCacheTtl??uE);let l;r.autoAuth?l=JSON.stringify(await t.saveAuthState()):e.data!==void 0?l=JSON.stringify(e.data):l='""',o.debug({cacheKeyPrefix:n,ttlMs:a,truncatedCacheResultJson:Yi({json:l,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:l,keyPrefix:n,ttlMs:a})}async function Zo(r,e,t){return KD(r,e,t)}async function KD(r,e,t){let n=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",l;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(l="Step aborted by user.",a="CANCELLED"):o instanceof C?l=`${o}`:l=`An unexpected error occurred: ${o.message}`,r.type==="RESOLVED_MODULE"){let c=zc(r,{},"FAILED");return c.message=l,c.startedAt=n,c.finishedAt=i,c}return{...Cc(r),startedAt:n,finishedAt:i,status:a,data:null,message:l,results:[]}}}async function aa(r,e){let t=!1;try{return r&&!r.state.failureRecoveryDisabled&&(r.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{r&&t&&(r.state.failureRecoveryDisabled=void 0)}}import{randomUUID as Ib}from"crypto";var Gc=async r=>{let{step:e,tracer:t}=r.presetParams,{logger:n,controller:o,context:i}=r.fixtures,{collectDebugData:a}=r.options,{testMetadata:l}=r.inputs,c=e.command.type,s=n.child({commandType:c,stepId:e.id,commandId:e.command.id}),u=o.browser.url(),d=new Date,p,m=Ib(),g=Ib();if(a)try{if(p=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75}),!o.browser.userBrowserSettings.disableHtmlSnapshots){let y=await o.browser.getRawCondensedHtml();t.attachBeforeHtmlSnapshot({logger:s,snapshotId:m,html:y})}}catch(y){s.debug({err:y},"Failed to take before screenshot, continuing...")}let h,f,E,S=Ul();try{let y=await o.executePresetCommand(S,t,e.command,i,l?.advanced.disableAICaching??!1);y.beforeScreenshotOverride&&(p=y.beforeScreenshotOverride),E=y.afterScreenshotOverride;let A=new Date,R=o.browser.url();f={beforeUrl:u,afterUrl:R,startedAt:d,finishedAt:A,viewport:o.browser.getViewport(),status:y.fail?"FAILED":"SUCCESS",elementInteracted:y.elementInteracted},h={...e,message:y.thoughts??"Successfully executed preset action.",beforeUrl:u,afterUrl:R,finishedAt:A,startedAt:d,status:y.fail?"FAILED":"SUCCESS",data:y.data,results:[f],details:S.details},"assertion"in e.command&&(h.message=y.thoughts||"Assertion passed.")}catch(y){s.error({message:y.message,stack:y.stack},`Failed executing preset step ${bn(e.command)}`);let A=o.browser.url(),R=new Date,w=y instanceof Error?y.message:`${y}`;f={beforeUrl:u,afterUrl:A,startedAt:d,finishedAt:R,viewport:o.browser.getViewport(),status:y instanceof DOMException&&y.name==="AbortError"?"CANCELLED":"FAILED",message:w},h={...e,startedAt:d,finishedAt:R,beforeUrl:u,afterUrl:A,status:y instanceof DOMException&&y.name==="AbortError"?"CANCELLED":"FAILED",message:w,failureReason:y instanceof C?y.reason:void 0,results:[f],details:S.details}}if(a)try{if(E||(E=await o.browser.screenshot({retries:1,quality:75})),!o.browser.userBrowserSettings.disableHtmlSnapshots){let y=await o.browser.getRawCondensedHtml();t.attachAfterHtmlSnapshot({logger:s,snapshotId:g,html:y})}}catch(y){s.debug({err:y},"Failed to store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return f.beforeSnapshot=m,h.beforeSnapshot=m,f.afterSnapshot=g,h.afterSnapshot=g,p&&t.attachBeforeScreenshot({logger:s,snapshotId:m,screenshot:p}),E&&t.attachAfterScreenshot({logger:s,snapshotId:g,screenshot:E}),h};async function Pb({codePath:r,screenshotBuff:e,storage:t,logger:n}){if(e)try{let o=await t.uploadScreenshot(e);return n.info({screenshotUrl:o,codePath:r},"Saved screenshot for debugging"),o}catch(o){n.error({err:o,codePath:r},"Failed to save screenshot for debugging")}}async function tn({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 YD=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function Mb({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(YD.includes(n.type))return;let l=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),s=0;for(;s===0||Date.now()-c<l;){await Z(250),s++;let u=(await t.getOpenPages()).map(p=>p.url),d=t.url();if(u.length!==e.length)for(let p=u.length-1;p>=e.length;p--){let m=u[p];if(Wo(m,o)&&m!==r&&m!==d){o.info({beforePages:e,afterPages:u,beforeUrl:r},"Auto-following new tab after preset action"),await t.switchToPage({type:"INDEX",index:String(p)});break}}}}var Ob="MOMENTIC_RUN_ID",Lb="FINAL_SCREENSHOT_URL";import{cloneDeep as RU}from"lodash-es";async function Nb(r){let{step:e,tracer:t}=r.conditionalParams,{logger:n,controller:o}=r.fixtures,i=new Date,a=Cc(e),l=e.elseSteps,c=!0,s=[],u,d=Ul();for(let f=0;f<e.blocks.length;f++){n.info(`Evaluating condition ${f} in conditional step`);let E=e.blocks[f];try{let S=await Gc({...r,presetParams:{tracer:t,step:E.assertion}});s.push(S),n.info(`Condition ${f} resolved to true, executing the corresponding ${E.steps.length} steps`),c=!1,l=E.steps,u=S}catch(S){n.info({err:S},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(l)c&&n.info("No conditions resolved to true, executing the else block steps");else return n.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...a,status:"SUCCESS",startedAt:i,data:s[s.length-1]?.data,message:s[s.length-1]?.message,results:[],finishedAt:new Date,details:d.details};n.info(`Executing ${l.length} steps in the selected conditional block`);let p=await r.conditionalParams.tracer.startSubSteps(),m=await r.executeStepList({...r,listParams:{steps:l,containerName:"conditional block",tracer:p}}),h={...a,assertionResult:u,...m,startedAt:i,finishedAt:new Date};return Zr({asyncTasks:r.work.asyncTasks,nestedResults:[...s,...m.results],result:h,logger:n}),h}import{randomUUID as Db}from"crypto";var kb=async r=>{let{tracer:e}=r.aiStepParams,{controller:t,logger:n}=r.fixtures;await t.browser.waitForDOMStability();let o=await t.browser.screenshot({}),i=await XD(r);i.finishedAt=new Date,Zr({asyncTasks:r.work.asyncTasks,result:i,nestedResults:i.results,logger:r.fixtures.logger});let a=await t.browser.screenshot({}),l=Db();i.beforeSnapshot=l,e.attachBeforeScreenshot({logger:n,snapshotId:l,screenshot:o});let c=Db();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:n,snapshotId:c,screenshot:a}),i},XD=async r=>{let{step:e,tracer:t}=r.aiStepParams,{controller:n,context:o,logger:i}=r.fixtures,a={...e,startedAt:new Date,beforeTestContext:o.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in e&&e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS"))throw new C("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let c=await t.startSubSteps(),{status:s}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"AI action",results:a.results,tracer:c}});return a.finishedAt=new Date,a.status=s,a}catch(c){i.warn({err:c},"Failed executing saved deprecated AI action steps");let s=n.executeAbortController.signal.aborted;a.message=c instanceof Error?c.message:`${c}`,a.status=s?"CANCELLED":"FAILED"}return a};import{randomUUID as Gm}from"crypto";var Fb=15,JD=7,Ub=async r=>{let{tracer:e}=r.aiStepParams,{logger:t,controller:n}=r.fixtures;await n.browser.waitForDOMStability();let o=await n.browser.screenshot({quality:75}),i=await QD(r);i.finishedAt=new Date,Zr({asyncTasks:r.work.asyncTasks,result:i,nestedResults:i.results,logger:r.fixtures.logger});let a=await n.browser.screenshot({quality:75}),l=Gm();i.beforeSnapshot=l,e.attachBeforeScreenshot({logger:t,snapshotId:l,screenshot:o});let c=Gm();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:t,snapshotId:c,screenshot:a}),i},QD=async r=>{let{step:e,tracer:t}=r.aiStepParams,{testMetadata:n,orgId:o}=r.inputs,{controller:i,context:a,logger:l,codeEvalTools:c}=r.fixtures,{step:s}=r.callbacks,u=`${e.id}-${Date.now()}`,d=l.child({stepId:e.id,langfuseSessionId:u}),p={...e,startedAt:new Date,beforeTestContext:a.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},m=await er({orgId:o,s:e.text,context:a,logger:d,localTools:c});await i.browser.waitForDOMStability({logger:d});let h=`data:image/jpeg;base64,${(await i.browser.screenshot({clearHighlights:!0,retries:2})).toString("base64")}`,f=[],E=0,S=0,y,A;for(;;){if(E>Fb)return p.message=`Exceeded the maximum number of commands allowed per AI step (${Fb})`,p.status="FAILED",p;if(i.executeAbortController.signal.aborted)return p.message="Test execution was cancelled",p.status="CANCELLED",p;s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let R=await i.evaluateAiAction({goal:m,startingScreenshot:E===0?void 0:h,history:f,logger:d,langfuseSessionId:u,lastError:A}),{evaluation:w,reasoning:x,summary:_}=R;d.info(R,"Got AI evaluation");let M=p.results[E-1]?.id;switch(w.type){case"DONE":return p.message=`Our AI evaluator confirmed all tasks are complete: ${x}`,p.status="SUCCESS",M&&s.onDynamicAIActionEvaluatingEvent?.({stepId:M,status:"SUCCESS",message:`${_}
|
|
33
|
-
${x}`}),p;case"RIGHT_TRACK":{y=void 0,
|
|
34
|
-
${w.feedback}`,
|
|
32
|
+
${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 ek}from"lodash-es";async function tr(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:l=Yn,allowUndefined:c=!1}=r,s=/{{(.*?)}}/g,u=t.matchAll(s),d=t;for(let p of u){if(p.length<2)continue;let m=p[1].trim(),g;try{g=await ro({orgId:e,code:m,fragment:!0,context:n,timeoutMs:l,logger:o,retries:a,localTools:r.localTools,signal:i})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(g===void 0&&!c)throw new C("UserConfigurationError",`Template fragment '${m}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let h=typeof g=="string"?g:`${g}`;h=h.replaceAll(/\$/g,"$$$$"),d=d.replace(p[0],h)}return d}async function Yc(r){return Ib(r)}async function Ib({obj:r,bannedKeys:e,allowList:t,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let l in r){if(e.includes(l))continue;let c=!1;if(t)if(t.includes(l))c=!0;else continue;let s=r[l],u=[...o,l];if(typeof s=="string"&&s.includes("{{")){let d=await tr({s,context:n,...a});if(s===d)continue;i.push({path:u,original:s}),r[l]=d}else typeof s=="object"&&s!==null&&!Array.isArray(s)&&await Ib({obj:s,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function Mb(r,e){for(let{path:t,original:n}of e)ek(r,t,n)}import tk from"fetch-retry";var dce=process.env.MAILINATOR_API_KEY,pce=tk(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import{hostname as lk}from"os";import{cloneDeep as Ob}from"lodash-es";async function Lb(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=Nf(e.cache)?e.cache:void 0,a=Ob(i),l=()=>{i&&(a?i.target={...a.target,memory:i.target.memory}:qd(i.target))},c=Date.now(),s=0,u,d=500,p=!1;for(;s<2||Date.now()-c<t;){s++,s>1&&await ee(d,o),o?.throwIfAborted();let{result:m,elementWasFound:g}=await Pb({cacheToUse:i,params:r});if(u=m,p=g,m.success)break;l(),d=Math.min(d*2,1e4)}if(!u)throw new C("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!u.success&&i?.target&&El(i.target)){let m=i?.target?.memory?{target:{id:-1,memory:i.target.memory}}:void 0,{result:g}=await Pb({cacheToUse:m,params:r});u=g,u.success||l()}return u.success&&i?.target&&!p&&qd(i.target),u}async function Pb({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:l}=o;if(t.target&&!Un(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=nk(t.assertion),s,u=!1,d=Ob(r);try{let{elementInteractedDisplayString:p,result:m,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>rk(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:Do(t),targetName:"target"}});return s={success:m.success,data:m.data,err:m.err,elementInteractedDisplayString:p,thoughts:g},u=!0,m.success||(l.warn({aiThoughts:g,elementString:p,err:m.err},"Element check found an element but failed"),s={...m,thoughts:g}),{result:s,elementWasFound:u}}catch(p){if(c)return s={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:s,elementWasFound:u};if(!(p instanceof C)||p.reason!="ActionFailureError")throw p;return s={success:!1,err:p,data:void 0,thoughts:void 0},l.warn({err:p},"Element check did not find an element and failed"),{result:s,elementWasFound:u}}}async function rk(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:Xe(c,500,!0)},!Xc(c,n.value,n.operation,!!n.negated)){let s=n.negated?fr[n.operation]:Sr[n.operation];o=!1,i=new C("AssertionFailureError",`The content ${s} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:Xe(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(s){i=new C("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${s}`),o=!1;break}if(!Xc(c,n.value,n.operation,!!n.negated)){let s=n.negated?fr[n.operation]:Sr[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The attribute ${n.attr} ${s}`):i=new C("AssertionFailureError",`The attribute ${n.attr} ${s} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(s,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(m=>setTimeout(m,250));let p=s.getBoundingClientRect();if(!(p.width===0||p.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},jr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:jr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:jr*1e3});break}case"FOCUSED":{o=await r.evaluate(s=>s===document.activeElement);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?Cm[n.condition]:xm[n.condition];i=new C("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(s=>s.tagName);if(!Xc(c,n.value,n.operation,!!n.negated)){let s=n.negated?fr[n.operation]:Sr[n.operation];o=!1,i=new C("AssertionFailureError",`The element tag name ${s} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((s,u)=>window.getComputedStyle(s).getPropertyValue(u),n.property);if(!Xc(c,n.value,n.operation,!!n.negated)){let s=n.negated?fr[n.operation]:Sr[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The style property ${n.property} ${s}`):i=new C("AssertionFailureError",`The style property ${n.property} ${s} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function Xc(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 nk(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function Nb(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as ok}from"jimp";async function Ls(r,e){let t=await r.screenshot(e),n=await ok.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as Db}from"jimp";import Jm from"jpeg-js";import ik from"pixelmatch";async function kb({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:l}){if(t.target&&!Un(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let c={clearHighlights:!0,hideCaret:!0},s;t.target?.elementDescriptor?s=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async V=>Ls(o,{locator:V.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:s=await Ls(o,c);let u=await l.prepareGoldenScreenshotForComparison(a,t,s);if((s.height!==u.height||s.width!==u.width)&&a.warn({currHeight:s.height,currWidth:s.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(s.height-u.height)>10||Math.abs(s.width-u.width)>10){let X=`${s.width}x${s.height}`,V=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${X}) does not match saved screenshot dimensions (${V}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:s.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await Db.fromBuffer(s.buffer),p={width:s.width,height:s.height},m=await Db.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=p.width*p.height,S=g.width*g.height,E=Math.abs(p.height-g.height),y=Math.abs(p.width-g.width);if(f>S){let X=d.cover({w:g.width,h:g.height});s.buffer=await X.getBuffer("image/jpeg"),h="current",s.width=g.width,s.height=g.height}else if(S>f){let X=m.cover({w:p.width,h:p.height});u.buffer=await X.getBuffer("image/jpeg"),h="saved"}let A={data:Buffer.alloc(s.width*s.height*4),width:s.width,height:s.height},R=t.threshold??.1,x=ik(Jm.decode(u.buffer).data,Jm.decode(s.buffer).data,A.data,s.width,s.height,{threshold:R,diffColorAlt:[0,255,0]})/(s.width*s.height)*100,_=x>R*100,P=`Visual diff of ${x.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${R*100}%.`;if(h&&(P+=` The ${h} screenshot was cropped since it was taller by ${E} pixels and wider by ${y} pixels.`),_)throw new C("ActionFailureError",P);return{fail:_,thoughts:P,beforeScreenshotOverride:s.buffer,afterScreenshotOverride:Jm.encode(A,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var ak=3e4;async function Fb({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??ak/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([m,g])=>m&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([m,g])=>m&&g).forEach(([m,g])=>{a.append(m,g)});let l=a.toString(),c;if(Qi(r.url)&&(c=r.url),t&&Zi(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:l,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await H((async()=>{let m=l?`${c}?${l}`:c;try{return await n(m,{headers:i,method:r.method,body:r.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new C("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let m;try{m=await u.text()}catch(g){m=`Failed to read response body: ${g}`}throw new C("ActionFailureError",`Fetch request failed with status ${u.status}: ${m}`)}let d={};u.headers.forEach((m,g)=>{d[g]=m});let p={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{p.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(p.text=await u.text());return p}var sk=5e3;async function Jc({timeout:r=jr,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,l=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let c=Date.now();i=await Ub(e),a=Date.now();let s=a-c;if(s>1e3&&e.logger.warn({pageAssertDuration:s},"Page assertion took longer than expected"),!i.success)await ee(l,e.signal),l=Math.min(Math.floor(l*1.5),sk);else return i}return i=await Ub(e),i}async function Ub({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let l;if(t){let c=await e.evaluateFunctionInAllFrames(Bb,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(s=>s.evaluation):c.some(s=>s.evaluation),l=c.find(s=>s.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:l}=await e.evaluateFunctionInPage(Bb,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?fr.CONTAINS:Sr.CONTAINS;a=new C("AssertionFailureError",`The page ${c} '${r.value}'.`),o=l}}catch(l){a=new C("AssertionFailureError",`Failed to evaluate page content assertion: ${l instanceof Error?l.message:`${l}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function Bb({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 Qm=async r=>{let{step:e,resolvedInputs:t}=r.moduleParams,{logger:n,context:o,storage:i,codeEvalTools:a,controller:l}=r.fixtures,c=l.browser,{orgId:s,runId:u}=r.inputs,d=l.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),n.info(Ji({json:{inputs:t,moduleId:e.moduleId},maxJsonStringSize:1e3}),"Set module inputs"));let p,m=!1,g,h;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",S=await tr({orgId:s,s:f,context:o,logger:n,localTools:a,signal:d});h={orgId:s,cacheKeys:[S,...Object.entries(t).map(([y,A])=>`${y}:${A}`)]},n.info({original:f,keyParams:h},"Module cache key params");let E=Date.now();for(;Date.now()-E<Dy;){d?.throwIfAborted();let y=await i.getCacheResult(h);if(y){n.info({cacheResult:Xe(y,1e3,!0)},"Got result from module execution cache"),p=Qc(e,t,"SUCCESS"),p.message="Used cached module result.",p.data=JSON.parse(y),m=!0;break}else n.info({cacheKey:f,keyParams:h},"No cache result found, continuing with lock acquisition");let A=await i.acquireCacheLock({keyParams:h,clientMetadata:`hostName:${lk()};runId:${u}`},d);if(A.acquired){g=A.keyPrefix,n.info({cacheKeyPrefixIfLockAcquired:g,cacheKey:f,keyParams:h},"Acquired cache lock and proceeding with module execution");break}else n.debug({cacheKeyPrefixIfLockAcquired:g,cacheKey:f,keyParams:h},"Failed to acquire cache lock, retrying...");await ee(2500+Math.random()*1e4,d)}}try{if(!p)p=await ck(r);else if(e.autoAuth){let f=Yl.safeParse(p.data);if(!f.success)throw new C("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);n.debug("Automatically loading auth state after cached module result"),await c.loadAuthState(f.data);let S=!1,E=e.advanced?.cacheInvalidation;if(E&&E.type==="PAGE_CHECK"){let y={type:"CONTENT",value:E.substring},A=await Jc({timeout:jr,assertion:y,browser:c,logger:n,signal:d,autoExpandIframes:!!c.userBrowserSettings.autoExpandIframes});A.success?n.debug({invalResult:A},"Cached result still valid after page check, continuing..."):(n.info({invalResult:A},"Invalidating cached result due to page check failure"),S=!0)}if(h&&S)return await i.deleteCacheResult(h),Qm(r)}}finally{try{g!==void 0&&!m&&p?.status==="SUCCESS"&&await uk({step:e,result:p,browser:l.browser,cacheKeyPrefix:g,logger:n,storage:i})}finally{g!==void 0&&await i.releaseCacheLock(g)}}return p},ck=async r=>{let{step:e,tracer:t}=r.moduleParams,n=Qc(e,r.moduleParams.resolvedInputs,"SUCCESS"),o=await t.startSubSteps(),{status:i,results:a}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}});return n.results=a,n.status=i,n.finishedAt=new Date,tn({asyncTasks:r.work.asyncTasks,nestedResults:a,result:n,logger:r.fixtures.logger}),n};function Qc(r,e,t){let n={};return Object.entries(e).forEach(([i,a])=>{n[i]=JSON.stringify(a)}),{type:"MODULE",id:r.id,moduleId:r.moduleId,moduleName:r.name,startedAt:new Date,cacheConfig:r.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:t}}async function zb({orgId:r,step:e,context:t,logger:n,codeEvalTools:o,signal:i}){let a={};try{for(let l of e.parameters??[]){let c=e.inputs?.[l]??e.defaultParameters?.[l];if(!c){n.warn(`No value or default found for parameter '${l}' that is required by module '${e.name}'`);continue}a[l]=await ro({orgId:r,code:c,fragment:!0,context:t,logger:n,localTools:o,signal:i})}return a}catch(l){throw i?.throwIfAborted(),new C("UserConfigurationError",`Failed to evaluate module inputs: ${l}`)}}async function uk({step:r,result:e,browser:t,cacheKeyPrefix:n,logger:o,storage:i}){let a=r.cacheConfig?.cacheExpiryMs;(!a||a===TE)&&(a=r.defaultCacheTtl??bE);let l;r.autoAuth?l=JSON.stringify(await t.saveAuthState()):e.data!==void 0?l=JSON.stringify(e.data):l='""',o.debug({cacheKeyPrefix:n,ttlMs:a,truncatedCacheResultJson:Ji({json:l,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:l,keyPrefix:n,ttlMs:a})}async function ti(r,e,t){return dk(r,e,t)}async function dk(r,e,t){let n=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",l;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(l="Step aborted by user.",a="CANCELLED"):o instanceof C?l=`${o}`:l=`An unexpected error occurred: ${o.message}`,r.type==="RESOLVED_MODULE"){let c=Qc(r,{},"FAILED");return c.message=l,c.startedAt=n,c.finishedAt=i,c}return{...Fc(r),startedAt:n,finishedAt:i,status:a,data:null,message:l,results:[]}}}async function ca(r,e){let t=!1;try{return r&&!r.state.failureRecoveryDisabled&&(r.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{r&&t&&(r.state.failureRecoveryDisabled=void 0)}}import{randomUUID as Hb}from"crypto";var Zc=async r=>{let{step:e,tracer:t}=r.presetParams,{logger:n,controller:o,context:i}=r.fixtures,{collectDebugData:a}=r.options,{testMetadata:l}=r.inputs,c=e.command.type,s=n.child({commandType:c,stepId:e.id,commandId:e.command.id}),u=o.browser.url(),d=new Date,p,m=Hb(),g=Hb();if(a)try{if(p=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75}),!o.browser.userBrowserSettings.disableHtmlSnapshots){let y=await o.browser.getRawCondensedHtml();t.attachBeforeHtmlSnapshot({logger:s,snapshotId:m,html:y})}}catch(y){s.debug({err:y},"Failed to take before screenshot, continuing...")}let h,f,S,E=$l();try{let y=await o.executePresetCommand(E,t,e.command,i,l?.advanced.disableAICaching??!1);y.beforeScreenshotOverride&&(p=y.beforeScreenshotOverride),S=y.afterScreenshotOverride;let A=new Date,R=o.browser.url();f={beforeUrl:u,afterUrl:R,startedAt:d,finishedAt:A,viewport:o.browser.getViewport(),status:y.fail?"FAILED":"SUCCESS",elementInteracted:y.elementInteracted},h={...e,message:y.thoughts??"Successfully executed preset action.",beforeUrl:u,afterUrl:R,finishedAt:A,startedAt:d,status:y.fail?"FAILED":"SUCCESS",data:y.data,results:[f],details:E.details},"assertion"in e.command&&(h.message=y.thoughts||"Assertion passed.")}catch(y){s.error({message:y.message,stack:y.stack},`Failed executing preset step ${vn(e.command)}`);let A=o.browser.url(),R=new Date,w=y instanceof Error?y.message:`${y}`;f={beforeUrl:u,afterUrl:A,startedAt:d,finishedAt:R,viewport:o.browser.getViewport(),status:y instanceof DOMException&&y.name==="AbortError"?"CANCELLED":"FAILED",message:w},h={...e,startedAt:d,finishedAt:R,beforeUrl:u,afterUrl:A,status:y instanceof DOMException&&y.name==="AbortError"?"CANCELLED":"FAILED",message:w,failureReason:y instanceof C?y.reason:void 0,results:[f],details:E.details}}if(a)try{if(S||(S=await o.browser.screenshot({retries:1,quality:75})),!o.browser.userBrowserSettings.disableHtmlSnapshots){let y=await o.browser.getRawCondensedHtml();t.attachAfterHtmlSnapshot({logger:s,snapshotId:g,html:y})}}catch(y){s.debug({err:y},"Failed to store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return f.beforeSnapshot=m,h.beforeSnapshot=m,f.afterSnapshot=g,h.afterSnapshot=g,p&&t.attachBeforeScreenshot({logger:s,snapshotId:m,screenshot:p}),S&&t.attachAfterScreenshot({logger:s,snapshotId:g,screenshot:S}),h};import jue,{multistream as Wue}from"pino";import Kue from"pino-pretty";import{PostHog as pk}from"posthog-node";async function Gb(r,e){let t,n=0,o=3,i,a;for(;n<o;)try{let l=await H(r.getAllFlagsAndPayloads(e),{milliseconds:5e3});i=l.featureFlags||{},a=l.featureFlagPayloads||{};break}catch(l){t=l,n++,await new Promise(c=>setTimeout(c,100*n))}if(i&&a)return{flags:i,payloads:a};throw t}var eu=class r extends us{constructor(t,n,o,i){super(o,i);this.client=t;this.orgId=n}static async init(t){let n=new pk("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:i}=await Gb(n,t);return new r(n,t,o,i)}async refresh(){let{flags:t,payloads:n}=await Gb(this.client,this.orgId);this.flags=t,this.payloads=n}};import{randomUUID as mk}from"node:crypto";import{PostHog as gk}from"posthog-node";var tu=class r{bindings;client;options;constructor(e,t={}){this.bindings=e,this.options=t,this.client=new gk("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...t})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new r({...this.bindings,...e},this.options)}track(e,t){if(!US(this.bindings))return console.error(`Cannot track ${e.type} event without required bindings.`,this.bindings),this;let{type:n,...o}=e;return this.client.capture({distinctId:mk(),event:n,timestamp:t?.timestamp,properties:{...this.bindings,...o}}),this}};import Ns from"os";import hk from"v8";var Vb,rn,fk=Ns.platform(),Sk=Ns.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 jb(r){if(En)return;let e=()=>{try{let t=!1,n=yk(),o=Ek();n.freeMemory<1e6&&(t=!0),o&&o?.total>70&&(t=!0);let i=hk.getHeapStatistics(),a=i.used_heap_size,l=i.heap_size_limit;a/l>.9&&(t=!0),t?r.warn({memory:n,cpu:o,heapStats:i},"Critical resource usage metrics detected"):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,2e4),cpuMetadata:Sk,platform:fk}}function yk(){let r=Ns.totalmem(),e=Ns.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function Ek(){let r=Ns.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,!rn)return rn=t,null;let n={user:t.user-rn.user,nice:t.nice-rn.nice,sys:t.sys-rn.sys,idle:t.idle-rn.idle,irq:t.irq-rn.irq,total:t.total-rn.total};return Vb={measurementTime:e,intervalMs:e-rn.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},rn=t,Vb}async function $b({codePath:r,screenshotBuff:e,storage:t,logger:n}){if(e)try{let o=await t.uploadScreenshot(e);return n.info({screenshotUrl:o,codePath:r},"Saved screenshot for debugging"),o}catch(o){n.error({err:o,codePath:r},"Failed to save screenshot for debugging")}}async function nn({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 Tk=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function Wb({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(Tk.includes(n.type))return;let l=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),s=0;for(;s===0||Date.now()-c<l;){await ee(250),s++;let u=(await t.getOpenPages()).map(p=>p.url),d=t.url();if(u.length!==e.length)for(let p=u.length-1;p>=e.length;p--){let m=u[p];if(Yo(m,o)&&m!==r&&m!==d){o.info({beforePages:e,afterPages:u,beforeUrl:r},"Auto-following new tab after preset action"),await t.switchToPage({type:"INDEX",index:String(p)});break}}}}var qb="MOMENTIC_RUN_ID",Kb="FINAL_SCREENSHOT_URL";import{cloneDeep as KU}from"lodash-es";async function Yb(r){let{step:e,tracer:t}=r.conditionalParams,{logger:n,controller:o}=r.fixtures,i=new Date,a=Fc(e),l=e.elseSteps,c=!0,s=[],u,d=$l();for(let f=0;f<e.blocks.length;f++){n.info(`Evaluating condition ${f} in conditional step`);let S=e.blocks[f];try{let E=await Zc({...r,presetParams:{tracer:t,step:S.assertion}});s.push(E),n.info(`Condition ${f} resolved to true, executing the corresponding ${S.steps.length} steps`),c=!1,l=S.steps,u=E}catch(E){n.info({err:E},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(l)c&&n.info("No conditions resolved to true, executing the else block steps");else return n.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...a,status:"SUCCESS",startedAt:i,data:s[s.length-1]?.data,message:s[s.length-1]?.message,results:[],finishedAt:new Date,details:d.details};n.info(`Executing ${l.length} steps in the selected conditional block`);let p=await r.conditionalParams.tracer.startSubSteps(),m=await r.executeStepList({...r,listParams:{steps:l,containerName:"conditional block",tracer:p}}),h={...a,assertionResult:u,...m,startedAt:i,finishedAt:new Date};return tn({asyncTasks:r.work.asyncTasks,nestedResults:[...s,...m.results],result:h,logger:n}),h}import{randomUUID as Xb}from"crypto";var Jb=async r=>{let{tracer:e}=r.aiStepParams,{controller:t,logger:n}=r.fixtures;await t.browser.waitForDOMStability();let o=await t.browser.screenshot({}),i=await bk(r);i.finishedAt=new Date,tn({asyncTasks:r.work.asyncTasks,result:i,nestedResults:i.results,logger:r.fixtures.logger});let a=await t.browser.screenshot({}),l=Xb();i.beforeSnapshot=l,e.attachBeforeScreenshot({logger:n,snapshotId:l,screenshot:o});let c=Xb();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:n,snapshotId:c,screenshot:a}),i},bk=async r=>{let{step:e,tracer:t}=r.aiStepParams,{controller:n,context:o,logger:i}=r.fixtures,a={...e,startedAt:new Date,beforeTestContext:o.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in e&&e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS"))throw new C("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let c=await t.startSubSteps(),{status:s}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"AI action",results:a.results,tracer:c}});return a.finishedAt=new Date,a.status=s,a}catch(c){i.warn({err:c},"Failed executing saved deprecated AI action steps");let s=n.executeAbortController.signal.aborted;a.message=c instanceof Error?c.message:`${c}`,a.status=s?"CANCELLED":"FAILED"}return a};import{randomUUID as Zm}from"crypto";var Qb=15,vk=7,Zb=async r=>{let{tracer:e}=r.aiStepParams,{logger:t,controller:n}=r.fixtures;await n.browser.waitForDOMStability();let o=await n.browser.screenshot({quality:75}),i=await Rk(r);i.finishedAt=new Date,tn({asyncTasks:r.work.asyncTasks,result:i,nestedResults:i.results,logger:r.fixtures.logger});let a=await n.browser.screenshot({quality:75}),l=Zm();i.beforeSnapshot=l,e.attachBeforeScreenshot({logger:t,snapshotId:l,screenshot:o});let c=Zm();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:t,snapshotId:c,screenshot:a}),i},Rk=async r=>{let{step:e,tracer:t}=r.aiStepParams,{testMetadata:n,orgId:o}=r.inputs,{controller:i,context:a,logger:l,codeEvalTools:c}=r.fixtures,{step:s}=r.callbacks,u=`${e.id}-${Date.now()}`,d=l.child({stepId:e.id,langfuseSessionId:u}),p={...e,startedAt:new Date,beforeTestContext:a.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},m=await tr({orgId:o,s:e.text,context:a,logger:d,localTools:c});await i.browser.waitForDOMStability({logger:d});let h=`data:image/jpeg;base64,${(await i.browser.screenshot({clearHighlights:!0,retries:2})).toString("base64")}`,f=[],S=0,E=0,y,A;for(;;){if(S>Qb)return p.message=`Exceeded the maximum number of commands allowed per AI step (${Qb})`,p.status="FAILED",p;if(i.executeAbortController.signal.aborted)return p.message="Test execution was cancelled",p.status="CANCELLED",p;s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let R=await i.evaluateAiAction({goal:m,startingScreenshot:S===0?void 0:h,history:f,logger:d,langfuseSessionId:u,lastError:A}),{evaluation:w,reasoning:x,summary:_}=R;d.info(R,"Got AI evaluation");let P=p.results[S-1]?.id;switch(w.type){case"DONE":return p.message=`Our AI evaluator confirmed all tasks are complete: ${x}`,p.status="SUCCESS",P&&s.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"SUCCESS",message:`${_}
|
|
33
|
+
${x}`}),p;case"RIGHT_TRACK":{y=void 0,S===0?s.onDynamicAIActionEvaluatingEvent?.({stepId:e.id,status:"RUNNING",message:x}):P&&s.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"SUCCESS",message:x});break}case"WRONG_TRACK":{if(y=`${x}
|
|
34
|
+
${w.feedback}`,E++,E>=vk)return p.message=`Our AI agent requires additional information to achieve this goal:
|
|
35
35
|
${x}
|
|
36
|
-
${w.feedback}`,p.status="FAILED",s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:p.message}),p;M&&s.onDynamicAIActionEvaluatingEvent?.({stepId:M,status:"FAILED",message:w.feedback});break}case"IMPOSSIBLE":return p.message=`Our AI evaluator determined this task cannot be achieved: ${x}`,p.status="FAILED",s.onDynamicAIActionEvaluatingEvent?.({stepId:M??e.id,status:"FAILED",message:p.message}),p}let K=setTimeout(()=>{s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);d.info({commandIndex:E,lastActionHint:y},`Generating new sub-command ${E} within AI action`);let $,k;try{({command:$,reasoning:k}=await i.promptToCommand({goal:m,history:f,startingScreenshot:h,disableCache:n?.advanced.disableAICaching??!1,logger:d,actionHint:y,langfuseSessionId:u})),d.info({command:$,reasoning:k},"Got proposed command")}finally{clearTimeout(K)}if($.type==="FAILURE")return clearTimeout(K),p.status="FAILED",p.message=`Our AI agent determined that no supported actions can fulfill the goals: ${k}`,p;let Y={id:Gm(),type:"PRESET_ACTION",command:$},I={substepIndex:E+1,message:k||"Generated new command."};s.onDynamicCommandGenerated?.({...I,step:Y,parentStepId:e.id}),d.info({commandId:$.id},`Executing sub-command ${E} within AI step: ${bn($)}`);let j=await t.startSubSteps(),ne=(await r.executeStepList({...r,options:{...r.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[Y],tracer:j}})).results[0];s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await i.browser.waitForDOMStability({logger:d});let Re=await i.browser.screenshot({clearHighlights:!0,retries:1});p.results.push(ne),f.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${Re.toString("base64")}`,urlAfterCommand:i.browser.url(),serializedCommand:bn($),elementInteracted:ne.results[0]?.elementInteracted,thoughts:k});let He={substepIndex:E,output:{...ne,message:ne.message??"Successfully executed preset action."},step:Y,parentStepId:e.id};if(s.onDynamicCommandExecuted?.(He),await t.finish({output:Il.parse(ne),step:ne,message:ne.message,attempt:1}),ne.status==="FAILED")if(p.status="FAILED",p.message=ne.message,S<3)S++,A=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${ne.message}`;else return p;else if(ne.status==="CANCELLED")return p.status="CANCELLED",p.message=ne.message,p;E++}};import{randomUUID as fU}from"crypto";var Vc=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function ZD(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 jc(r,e){let t=ZD(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var dv="=",Kc=";",eg=",";var pv=8192;var ua={};P_(ua,{getKeyPairs:()=>Ok,parseKeyPairsIntoRecord:()=>Lk,parsePairKeyValue:()=>mv,serializeKeyPairs:()=>Mk});Me();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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function Mk(r){return r.reduce(function(e,t){var n=""+e+(e!==""?eg:"")+t;return n.length>pv?e:n},"")}function Ok(r){return r.getAllEntries().map(function(e){var t=Pk(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Kc+o.metadata.toString()),i})}function mv(r){var e=r.split(Kc);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(dv);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=jm(e.join(Kc))),{key:o,value:i,metadata:a}}}}}function Lk(r){return typeof r!="string"||r.length===0?{}:r.split(eg).map(function(e){return mv(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Me();var Yc;(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"})(Yc||(Yc={}));var Nk=",",Dk=["OTEL_SDK_DISABLED"];function kk(r){return Dk.indexOf(r)>-1}var Fk=["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 Uk(r){return Fk.indexOf(r)>-1}var Bk=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function Hk(r){return Bk.indexOf(r)>-1}var tg=1/0,rg=128,zk=128,Gk=128,ng={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:Ve.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:tg,OTEL_ATTRIBUTE_COUNT_LIMIT:rg,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:tg,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:rg,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:tg,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:rg,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:zk,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:Gk,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Yc.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 Vk(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function jk(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 $k(r,e,t,n){n===void 0&&(n=Nk);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var Wk={ALL:Ve.ALL,VERBOSE:Ve.VERBOSE,DEBUG:Ve.DEBUG,INFO:Ve.INFO,WARN:Ve.WARN,ERROR:Ve.ERROR,NONE:Ve.NONE};function qk(r,e,t){var n=t[r];if(typeof n=="string"){var o=Wk[n.toUpperCase()];o!=null&&(e[r]=o)}}function gv(r){var e={};for(var t in ng){var n=t;switch(n){case"OTEL_LOG_LEVEL":qk(n,e,r);break;default:if(kk(n))Vk(n,e,r);else if(Uk(n))jk(n,e,r);else if(Hk(n))$k(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function wt(){var r=gv(process.env);return Object.assign({},ng,r)}function hv(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Xc(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=hv(r.charCodeAt(n)),i=hv(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var fv="1.25.1";var Kk="deployment.environment";var Yk="process.runtime.name";var Xk="service.name";var Jk="service.instance.id";var Qk="telemetry.sdk.name",Zk="telemetry.sdk.language",e0="telemetry.sdk.version";var Sv=Kk;var yv=Yk;var Jc=Xk;var Ev=Jk;var Ns=Qk,Ds=Zk,ks=e0;var t0="nodejs";var Tv=t0;var da,Qc=(da={},da[Ns]="opentelemetry",da[yv]="node",da[Ds]=Tv,da[ks]=fv,da);var r0=9,n0=6,o0=Math.pow(10,n0),i0=Math.pow(10,r0);function bv(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*o0);return[t,n]}function vv(r){return r[0]*i0+r[1]}function Fs(r){return r[0]*1e6+r[1]/1e3}var ti;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ti||(ti={}));var Rv=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 a0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},s0=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))},Av=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new Rv}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,s0([this._that],a0(n),!1))).then(function(i){return t._deferred.resolve(i)},function(i){return t._deferred.reject(i)})}catch(i){this._deferred.reject(i)}}return this._deferred.promise},r}();var Sr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Sr||(Sr={}));var kt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(kt||(kt={}));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)}}();var mpe=function(r){l0(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function wv(r,e){for(var t=0,n=r.length-1;n-t>1;){var o=Math.trunc((n+t)/2);r[o]<=e?t=o:n=o-1}return r[n]<=e?n:r[t]<=e?t:-1}Me();var yr;(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"})(yr||(yr={}));var Cv=function(){function r(){this.kind=yr.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 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={}));var c0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function u0(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 og=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=u0(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=wv(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 ig=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=yr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new og(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new og(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new og(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:kt.HISTOGRAM,dataPoints:n.map(function(i){var a=c0(i,2),l=a[0],c=a[1],s=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:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();Me();var ag=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},sg=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))},lg=function(){function r(e,t,n,o){e===void 0&&(e=new d0),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var l=a%n;l<0&&(l+=n);for(var c=l;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var d0=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,sg([n,this._counts.length-t],ag(this._counts.slice(t)),!1)),o.splice.apply(o,sg([0,t],ag(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(sg([],ag(this._counts),!1))},r}();var xv=52,p0=2146435072,m0=1048575,cg=1023,Zc=-cg+1,eu=cg,Us=Math.pow(2,-1022);function tu(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&p0)>>20;return n-cg}function ru(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&m0)*Math.pow(2,32);return o+n}function Bs(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function Iv(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var g0=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),eo=function(r){g0(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var Mv=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Us)return this._minNormalLowerBoundaryIndex();var t=tu(e),n=this._rightShift(ru(e)-1,xv);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new eo("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new eo("overflow: "+e+" is > maximum lower boundary: "+n);return Bs(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=Zc>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return eu>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var Ov=function(){function r(e){this._scale=e,this._scaleFactor=Bs(Math.LOG2E,e),this._inverseFactor=Bs(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Us)return this._minNormalLowerBoundaryIndex()-1;if(ru(e)===0){var t=tu(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 eo("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Us;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new eo("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 Zc<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(eu+1<<this._scale)-1},r}();var Lv=-10,Nv=20,h0=Array.from({length:31},function(r,e){return e>10?new Ov(e-10):new Mv(e-10)});function ug(r){if(r>Nv||r<Lv)throw new eo("expected scale >= "+Lv+" && <= "+Nv+", got: "+r);return h0[r+10]}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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},nu=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}(),S0=20,y0=160,dg=2,E0=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=y0),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new lg),u===void 0&&(u=new lg),d===void 0&&(d=ug(S0)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<dg&&(z.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+dg),this._maxSize=dg)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,l=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=Iv(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=ug(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=nu.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=nu.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 nu(0,-1);var o=t-n;return new nu(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var Dv=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=yr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new E0(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:kt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=f0(i,2),l=a[0],c=a[1],s=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:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();var T0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},pg=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=bv(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var kv=function(){function r(){this.kind=yr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new pg(e)},r.prototype.merge=function(e,t){var n=Fs(t.sampleTime)>=Fs(e.sampleTime)?t:e;return new pg(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Fs(t.sampleTime)>=Fs(e.sampleTime)?t:e;return new pg(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:kt.GAUGE,dataPoints:n.map(function(i){var a=T0(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var b0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Hs=function(){function r(e,t,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 mg=function(){function r(e){this.monotonic=e,this.kind=yr.SUM}return r.prototype.createAccumulation=function(e){return new Hs(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Hs(t.startTime,this.monotonic,o,t.reset):new Hs(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 Hs(t.startTime,this.monotonic,o,!0):new Hs(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:kt.SUM,dataPoints:n.map(function(i){var a=b0(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var ri=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)}}(),nn=function(){function r(){}return r.Drop=function(){return jv},r.Sum=function(){return $v},r.LastValue=function(){return Wv},r.Histogram=function(){return qv},r.ExponentialHistogram=function(){return v0},r.Default=function(){return R0},r}();var Fv=function(r){ri(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 Cv,e}(nn);var Uv=function(r){ri(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 mg(!0),e.NON_MONOTONIC_INSTANCE=new mg(!1),e}(nn);var Bv=function(r){ri(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 kv,e}(nn);var Hv=function(r){ri(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 ig([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(nn);var zv=function(r){ri(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(l,c){return l-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new ig(this._boundaries,this._recordMinMax)},e}(nn);var Gv=function(r){ri(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 Dv(this._maxSize,this._recordMinMax)},e}(nn);var Vv=function(r){ri(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 $v;case le.GAUGE:case le.OBSERVABLE_GAUGE:return Wv;case le.HISTOGRAM:return t.advice.explicitBucketBoundaries?new zv(t.advice.explicitBucketBoundaries):qv}return z.warn("Unable to recognize instrument type: "+t.type),jv},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(nn);var jv=new Fv,$v=new Uv,Wv=new Bv,qv=new Hv,v0=new Gv,R0=new Vv;Me();function ou(){return"unknown_service:"+process.argv0}var to=function(){return to=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},to.apply(this,arguments)},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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},C0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},gg=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 z.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[Jc]=ou(),e[Ds]=Qc[Ds],e[Ns]=Qc[Ns],e[ks]=Qc[ks],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&z.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 A0(this,void 0,void 0,function(){return w0(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=to(to({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var l,c=C0(a,2),s=c[0],u=c[1];return to(to(to(to({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var ni;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(ni||(ni={}));Me();var x0=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},_0=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},hg=function(){return Sr.CUMULATIVE},Kv=function(r){switch(r){case le.COUNTER:case le.OBSERVABLE_COUNTER:case le.GAUGE:case le.HISTOGRAM:case le.OBSERVABLE_GAUGE:return Sr.DELTA;case le.UP_DOWN_COUNTER:case le.OBSERVABLE_UP_DOWN_COUNTER:return Sr.CUMULATIVE}},Yv=function(r){switch(r){case le.COUNTER:case le.HISTOGRAM:return Sr.DELTA;case le.GAUGE:case le.UP_DOWN_COUNTER:case le.OBSERVABLE_UP_DOWN_COUNTER:case le.OBSERVABLE_COUNTER:case le.OBSERVABLE_GAUGE:return Sr.CUMULATIVE}};function I0(){var r=wt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?hg:e==="delta"?Kv:e==="lowmemory"?Yv:(z.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."),hg)}function P0(r){return r!=null?r===ni.DELTA?Kv:r===ni.LOWMEMORY?Yv:hg:I0()}function M0(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return nn.Default()}}var Xv=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=M0(t),this._aggregationTemporalitySelector=P0(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return x0(this,void 0,void 0,function(){return _0(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},r.prototype.forceFlush=function(){return Promise.resolve()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r}();Me();Me();var O0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Jv=1e4,Qv=5,Zv=1e3,eR=5e3,tR=1.5;function zs(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=O0(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):z.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function fg(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Sg(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return z.warn("Could not parse export URL: '"+r+"'"),r}}function yg(r){return typeof r=="number"?r<=0?Eg(r,Jv):r:L0()}function L0(){var r,e=Number((r=wt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:wt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Eg(e,Jv):e}function Eg(r,e){return z.warn("Timeout must be greater than 0",r),e}function rR(r){var e=[429,502,503,504];return e.includes(r)}function nR(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 oR=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 Av(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=yg(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:ti.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:ti.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:ti.SUCCESS})}).catch(function(n){t({code:ti.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{z.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 z.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();Me();import*as Tg from"url";import*as au from"http";import*as su from"https";import*as iR from"zlib";import{Readable as D0}from"stream";var ro;(function(r){r.NONE="none",r.GZIP="gzip"})(ro||(ro={}));var N0=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)}}(),pa=function(r){N0(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 iu=function(){return iu=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},iu.apply(this,arguments)};function bg(r,e,t,n,o){var i=r.timeoutMillis,a=new Tg.URL(r.url),l=Number(process.versions.node.split(".")[0]),c,s,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,s.destroyed){var h=new pa("Request Timeout");o(h)}else l>=14?s.destroy():s.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:iu({"Content-Type":t},r.headers),agent:r.agent},m=a.protocol==="http:"?au.request:su.request,g=function(h,f){switch(h===void 0&&(h=Qv),f===void 0&&(f=Zv),s=m(p,function(S){var y="";S.on("data",function(A){return y+=A}),S.on("aborted",function(){if(u){var A=new pa("Request Timeout");o(A)}}),S.on("end",function(){if(u===!1)if(S.statusCode&&S.statusCode<299)z.debug("statusCode: "+S.statusCode,y),n(),clearTimeout(d),clearTimeout(c);else if(S.statusCode&&rR(S.statusCode)&&h>0){var A=void 0;f=tR*f,S.headers["retry-after"]?A=nR(S.headers["retry-after"]):A=Math.round(Math.random()*(eR-f)+f),c=setTimeout(function(){g(h-1,f)},A)}else{var R=new pa(S.statusMessage,S.statusCode,y);o(R),clearTimeout(d),clearTimeout(c)}})}),s.on("error",function(S){if(u){var y=new pa("Request Timeout",S.code);o(y)}else o(S);clearTimeout(d),clearTimeout(c)}),s.on("abort",function(){if(u){var S=new pa("Request Timeout");o(S)}clearTimeout(d),clearTimeout(c)}),r.compression){case ro.GZIP:{s.setHeader("Content-Encoding","gzip");var E=k0(e);E.on("error",o).pipe(iR.createGzip()).on("error",o).pipe(s);break}default:s.end(Buffer.from(e));break}};g()}function k0(r){var e=new D0;return e.push(r),e.push(null),e}function vg(r){if(r.httpAgentOptions&&r.keepAlive===!1){z.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Tg.URL(r.url),t=e.protocol==="http:"?au.Agent:su.Agent;return new t(iu({keepAlive:!0},r.httpAgentOptions))}catch(n){z.error("collector exporter failed to create http agent. err: "+n.message);return}}function Rg(r){if(r)return r;var e=wt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||wt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===ro.GZIP?ro.GZIP:ro.NONE}Me();var F0=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)}}(),lu=function(r){F0(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&&z.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,zs(t.headers),ua.parseKeyPairsIntoRecord(wt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=vg(t),i.compression=Rg(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){z.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,s){var u;bg(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,s)}).then(n,o);this._sendingPromises.push(a);var l=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(l,l)},e.prototype.onShutdown=function(){},e}(oR);function sR(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function U0(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function lR(r){var e=sR(r);return U0(e)}function B0(r){var e=sR(r);return e.toString()}var H0=typeof BigInt<"u"?B0:vv;function aR(r){return r}function cR(r){if(r!==void 0)return Xc(r)}var z0={encodeHrTime:lR,encodeSpanContext:Xc,encodeOptionalSpanContext:cR};function uR(r){var e,t;if(r===void 0)return z0;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?lR:H0,encodeSpanContext:o?aR:Xc,encodeOptionalSpanContext:o?aR:cR}}var G0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function dR(r){return{name:r.name,version:r.version}}function ma(r){return Object.keys(r).map(function(e){return pR(e,r[e])})}function pR(r,e){return{key:r,value:mR(e)}}function mR(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(mR)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=G0(t,2),o=n[0],i=n[1];return pR(o,i)})}}:{}}function gR(r){return{attributes:ma(r.attributes),droppedAttributesCount:0}}Me();function fR(r,e){var t=uR(e);return{resource:gR(r.resource),schemaUrl:void 0,scopeMetrics:V0(r.scopeMetrics,t)}}function V0(r,e){return Array.from(r.map(function(t){return{scope:dR(t.scope),metrics:t.metrics.map(function(n){return j0(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function j0(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=K0(r.aggregationTemporality);switch(r.dataPointType){case kt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:hR(r,e)};break;case kt.GAUGE:t.gauge={dataPoints:hR(r,e)};break;case kt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:W0(r,e)};break;case kt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:q0(r,e)};break}return t}function $0(r,e,t){var n={attributes:ma(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case tr.INT:n.asInt=r.value;break;case tr.DOUBLE:n.asDouble=r.value;break}return n}function hR(r,e){return r.dataPoints.map(function(t){return $0(t,r.descriptor.valueType,e)})}function W0(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ma(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 q0(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ma(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 K0(r){switch(r){case Sr.DELTA:return 1;case Sr.CUMULATIVE:return 2}}function SR(r,e){return{resourceMetrics:r.map(function(t){return fR(t,e)})}}var Ag={serializeRequest:function(r){var e=SR(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 yR="0.52.1";var ER=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)}}(),ga=function(){return ga=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},ga.apply(this,arguments)},TR="v1/metrics",Y0="http://localhost:4318/"+TR,X0={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+yR},J0=function(r){ER(e,r);function e(t){var n=r.call(this,t,Ag,"application/json")||this;return n.headers=ga(ga(ga(ga({},n.headers),X0),ua.parseKeyPairsIntoRecord(wt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),zs(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:wt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Sg(wt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):wt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?fg(wt().OTEL_EXPORTER_OTLP_ENDPOINT,TR):Y0},e}(lu),bR=function(r){ER(e,r);function e(t){return r.call(this,new J0(t),t)||this}return e}(Xv);var ha;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(ha||(ha={}));var on;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(on||(on={}));Me();var Q0=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),vR=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},RR=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},Z0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},eF=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))},tF=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 AR(r){return r!=null}function cu(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function wR(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var wg=function(r){Q0(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function no(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new wg("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function CR(r){return vR(this,void 0,void 0,function(){var e=this;return RR(this,function(t){return[2,Promise.all(r.map(function(n){return vR(e,void 0,void 0,function(){var o,i;return RR(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 xR(r){return r.status==="rejected"}function Cg(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,eF([],Z0(e(n)),!1))}),t}function _R(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=tF(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(l){t={error:l}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function IR(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 PR(r,e){return r.toLowerCase()===e.toLowerCase()}Me();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 xg=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}();Me();var ge;(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"})(ge||(ge={}));function an(r,e,t){var n,o,i,a;return nF(r)||z.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:tr.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function MR(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 OR(r,e){return PR(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var rF=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function nF(r){return r.match(rF)!=null}var oF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function iF(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 uu=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=iF(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=IR(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 du=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Er.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new uu(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new uu(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new uu(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:on.HISTOGRAM,dataPoints:n.map(function(i){var a=oF(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ge.GAUGE||e.type===ge.UP_DOWN_COUNTER||e.type===ge.OBSERVABLE_GAUGE||e.type===ge.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();Me();var _g=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ig=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))},Pg=function(){function r(e,t,n,o){e===void 0&&(e=new aF),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var l=a%n;l<0&&(l+=n);for(var c=l;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var aF=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,Ig([n,this._counts.length-t],_g(this._counts.slice(t)),!1)),o.splice.apply(o,Ig([0,t],_g(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(Ig([],_g(this._counts),!1))},r}();var LR=52,sF=2146435072,lF=1048575,Mg=1023,pu=-Mg+1,mu=Mg,Gs=Math.pow(2,-1022);function gu(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&sF)>>20;return n-Mg}function hu(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&lF)*Math.pow(2,32);return o+n}function Vs(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function DR(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var cF=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),oo=function(r){cF(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var FR=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Gs)return this._minNormalLowerBoundaryIndex();var t=gu(e),n=this._rightShift(hu(e)-1,LR);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new oo("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new oo("overflow: "+e+" is > maximum lower boundary: "+n);return Vs(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=pu>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return mu>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var UR=function(){function r(e){this._scale=e,this._scaleFactor=Vs(Math.LOG2E,e),this._inverseFactor=Vs(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Gs)return this._minNormalLowerBoundaryIndex()-1;if(hu(e)===0){var t=gu(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 oo("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Gs;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new oo("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 pu<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(mu+1<<this._scale)-1},r}();var BR=-10,HR=20,uF=Array.from({length:31},function(r,e){return e>10?new UR(e-10):new FR(e-10)});function Og(r){if(r>HR||r<BR)throw new oo("expected scale >= "+BR+" && <= "+HR+", got: "+r);return uF[r+10]}var dF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},fu=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}(),pF=20,mF=160,Lg=2,zR=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=mF),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new Pg),u===void 0&&(u=new Pg),d===void 0&&(d=Og(pF)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<Lg&&(z.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Lg),this._maxSize=Lg)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,l=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=DR(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Og(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=fu.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=fu.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 fu(0,-1);var o=t-n;return new fu(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var Ng=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Er.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new zR(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:on.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=dF(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ge.GAUGE||e.type===ge.UP_DOWN_COUNTER||e.type===ge.OBSERVABLE_GAUGE||e.type===ge.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();Me();var gF=$m("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function GR(r){return r.setValue(gF,!0)}Me();function VR(){return function(r){z.error(hF(r))}}function hF(r){return typeof r=="string"?r:JSON.stringify(fF(r))}function fF(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 SF=VR();function Su(r){try{SF(r)}catch{}}var jR="1.30.1";var yF="process.runtime.name";var EF="service.name";var TF="telemetry.sdk.name",bF="telemetry.sdk.language",vF="telemetry.sdk.version";var $R=yF;var WR=EF;var js=TF,$s=bF,Ws=vF;var RF="nodejs";var qR=RF;var fa,oi=(fa={},fa[js]="opentelemetry",fa[$R]="node",fa[$s]=qR,fa[Ws]=jR,fa);function qs(r){r.unref()}var PF=9,MF=6,OF=Math.pow(10,MF),She=Math.pow(10,PF);function ii(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*OF);return[t,n]}function Sa(r){return r[0]*1e6+r[1]/1e3}var Ks;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Ks||(Ks={}));Me();function KR(r,e){return new Promise(function(t){ca.with(GR(ca.active()),function(){r.export(e,function(n){t(n)})})})}var YR={_export:KR};var LF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},yu=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=ii(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Dg=function(){function r(){this.kind=Er.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new yu(e)},r.prototype.merge=function(e,t){var n=Sa(t.sampleTime)>=Sa(e.sampleTime)?t:e;return new yu(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Sa(t.sampleTime)>=Sa(e.sampleTime)?t:e;return new yu(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:on.GAUGE,dataPoints:n.map(function(i){var a=LF(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var NF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ya=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Eu=function(){function r(e){this.monotonic=e,this.kind=Er.SUM}return r.prototype.createAccumulation=function(e){return new ya(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new ya(t.startTime,this.monotonic,o,t.reset):new ya(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new ya(t.startTime,this.monotonic,o,!0):new ya(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:on.SUM,dataPoints:n.map(function(i){var a=NF(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var ai=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)}}(),Tr=function(){function r(){}return r.Drop=function(){return rA},r.Sum=function(){return nA},r.LastValue=function(){return oA},r.Histogram=function(){return iA},r.ExponentialHistogram=function(){return DF},r.Default=function(){return kF},r}();var XR=function(r){ai(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 xg,e}(Tr);var JR=function(r){ai(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case ge.COUNTER:case ge.OBSERVABLE_COUNTER:case ge.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Eu(!0),e.NON_MONOTONIC_INSTANCE=new Eu(!1),e}(Tr);var QR=function(r){ai(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 Dg,e}(Tr);var ZR=function(r){ai(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 du([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Tr);var Tu=function(r){ai(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(l,c){return l-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new du(this._boundaries,this._recordMinMax)},e}(Tr);var eA=function(r){ai(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 Ng(this._maxSize,this._recordMinMax)},e}(Tr);var tA=function(r){ai(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case ge.COUNTER:case ge.UP_DOWN_COUNTER:case ge.OBSERVABLE_COUNTER:case ge.OBSERVABLE_UP_DOWN_COUNTER:return nA;case ge.GAUGE:case ge.OBSERVABLE_GAUGE:return oA;case ge.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Tu(t.advice.explicitBucketBoundaries):iA}return z.warn("Unable to recognize instrument type: "+t.type),rA},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Tr);var rA=new XR,nA=new JR,oA=new QR,iA=new ZR,DF=new eA,kF=new tA;var aA=function(r){return Tr.Default()},sA=function(r){return ha.CUMULATIVE};var kg=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Fg=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},lA=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},FF=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))},cA=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:aA,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:sA,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 kg(this,void 0,void 0,function(){var t,n,o,i,a,l;return Fg(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(FF([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],lA(this._metricProducers.map(function(s){return s.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=lA.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Cg(o,function(s){return s.errors})),a=n.resourceMetrics.resource,l=n.resourceMetrics.scopeMetrics.concat(Cg(o,function(s){return s.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:l},errors:i}]}})})},r.prototype.shutdown=function(e){return kg(this,void 0,void 0,function(){return Fg(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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,no(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return kg(this,void 0,void 0,function(){return Fg(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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,no(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Me();var UF=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)}}(),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 l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},vu=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},BF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},HF=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))},Ug=function(r){UF(e,r);function e(t){var n,o,i,a,l=r.call(this,{aggregationSelector:(n=t.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(t.exporter),aggregationTemporalitySelector:(o=t.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(t.exporter),metricProducers:t.metricProducers})||this;if(t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<t.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return l._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,l._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,l._exporter=t.exporter,l}return e.prototype._runOnce=function(){return bu(this,void 0,void 0,function(){var t;return vu(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,no(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof wg?(z.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Su(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return bu(this,void 0,void 0,function(){var o,i,a,l,c,s;return vu(this,function(u){switch(u.label){case 0:return[4,this.collect({timeoutMillis:this._exportTimeout})];case 1:if(o=u.sent(),i=o.resourceMetrics,a=o.errors,a.length>0&&(s=z).error.apply(s,HF(["PeriodicExportingMetricReader: metrics collection errors"],BF(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(t=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(t)];case 3:return u.sent(),[3,5];case 4:return l=u.sent(),z.debug("Error while resolving async portion of resource: ",l),Su(l),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,YR._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Ks.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),qs(this._interval)},e.prototype.onForceFlush=function(){return bu(this,void 0,void 0,function(){return vu(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 bu(this,void 0,void 0,function(){return vu(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}(cA);Me();Me();function Ru(){return"unknown_service:"+process.argv0}var io=function(){return io=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},io.apply(this,arguments)},zF=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},GF=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},VF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Au=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 z.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[WR]=Ru(),e[$s]=oi[$s],e[js]=oi[js],e[Ws]=oi[Ws],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&z.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 zF(this,void 0,void 0,function(){return GF(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=io(io({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var l,c=VF(a,2),s=c[0],u=c[1];return io(io(io(io({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var uA=function(){function r(){this._registeredViews=[]}return r.prototype.addView=function(e){this._registeredViews.push(e)},r.prototype.findViews=function(e,t){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,t)});return o},r.prototype._matchInstrument=function(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)},r.prototype._matchMeter=function(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))},r}();Me();var si=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)}}(),wu=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=ca.active()),typeof e!="number"){z.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===tr.INT&&!Number.isInteger(e)&&(z.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,ii(Date.now()))},r}();var dA=function(r){si(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}(wu);var pA=function(r){si(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){z.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(wu);var mA=function(r){si(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}(wu);var gA=function(r){si(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){z.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(wu);var Cu=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 hA=function(r){si(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Cu);var fA=function(r){si(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Cu);var SA=function(r){si(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Cu);function Ys(r){return r instanceof Cu}var yA=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=an(e,ge.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new mA(o,n)},r.prototype.createHistogram=function(e,t){var n=an(e,ge.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new gA(o,n)},r.prototype.createCounter=function(e,t){var n=an(e,ge.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new pA(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=an(e,ge.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new dA(o,n)},r.prototype.createObservableGauge=function(e,t){var n=an(e,ge.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new fA(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=an(e,ge.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new hA(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=an(e,ge.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new SA(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 xu=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=an(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var jF=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)}}(),EA=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},$F=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 EA(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 EA(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 Nr=function(r){jF(e,r);function e(){return r.call(this,cu)||this}return e}($F);var WF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},_u=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Nr,this._cumulativeMemoStorage=new Nr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=cu(this._overflowAttributes)}return r.prototype.record=function(e,t,n,o){var i=this,a=this._activeCollectionStorage.get(t);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var l=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});l?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(t,a)}a?.record(e)},r.prototype.batchCumulate=function(e,t){var n=this;Array.from(e.entries()).forEach(function(o){var i=WF(o,3),a=i[0],l=i[1],c=i[2],s=n._aggregator.createAccumulation(t);s?.record(l);var u=s;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,s)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,s)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,s,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new Nr,e},r}();var Bg=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.")},TA=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Iu=function(){function r(e,t){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,t.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return r.prototype.buildMetrics=function(e,t,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,l;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),s=c.collectionTime;l=c.aggregationTemporality,l===ha.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,s)}else l=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:l});var u=qF(a);if(u.length!==0)return this._aggregator.toMetricData(t,l,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=Bg(o),a=i.next();!a.done;a=i.next()){var l=a.value,c=this._unreportedAccumulations.get(l);c===void 0&&(c=[],this._unreportedAccumulations.set(l,c)),c.push(e)}}catch(s){t={error:s}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}},r.prototype._getMergedUnreportedAccumulations=function(e){var t,n,o=new Nr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Bg(i),l=a.next();!l.done;l=a.next()){var c=l.value;o=r.merge(o,c,this._aggregator)}}catch(s){t={error:s}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return o},r.merge=function(e,t,n){for(var o=e,i=t.entries(),a=i.next();a.done!==!0;){var l=TA(a.value,3),c=l[0],s=l[1],u=l[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,s);o.set(c,p,u)}else o.set(c,s,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=Bg(e.keys()),l=a.next();!l.done;l=a.next()){var c=TA(l.value,2),s=c[0],u=c[1],d=t.get(s,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function qF(r){return Array.from(r.entries())}var KF=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)}}(),YF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},bA=function(r){KF(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new _u(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Iu(n,i),l}return e.prototype.record=function(t,n){var o=this,i=new Nr;Array.from(t.entries()).forEach(function(a){var l=YF(a,2),c=l[0],s=l[1];i.set(o._attributesProcessor.process(c),s)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(xu);Me();function Hg(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
36
|
+
${w.feedback}`,p.status="FAILED",s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:p.message}),p;P&&s.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"FAILED",message:w.feedback});break}case"IMPOSSIBLE":return p.message=`Our AI evaluator determined this task cannot be achieved: ${x}`,p.status="FAILED",s.onDynamicAIActionEvaluatingEvent?.({stepId:P??e.id,status:"FAILED",message:p.message}),p}let X=setTimeout(()=>{s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);d.info({commandIndex:S,lastActionHint:y},`Generating new sub-command ${S} within AI action`);let V,k;try{({command:V,reasoning:k}=await i.promptToCommand({goal:m,history:f,startingScreenshot:h,disableCache:n?.advanced.disableAICaching??!1,logger:d,actionHint:y,langfuseSessionId:u})),d.info({command:V,reasoning:k},"Got proposed command")}finally{clearTimeout(X)}if(V.type==="FAILURE")return clearTimeout(X),p.status="FAILED",p.message=`Our AI agent determined that no supported actions can fulfill the goals: ${k}`,p;let Q={id:Zm(),type:"PRESET_ACTION",command:V},I={substepIndex:S+1,message:k||"Generated new command."};s.onDynamicCommandGenerated?.({...I,step:Q,parentStepId:e.id}),d.info({commandId:V.id},`Executing sub-command ${S} within AI step: ${vn(V)}`);let re=await t.startSubSteps(),q=(await r.executeStepList({...r,options:{...r.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[Q],tracer:re}})).results[0];s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await i.browser.waitForDOMStability({logger:d});let Qe=await i.browser.screenshot({clearHighlights:!0,retries:1});p.results.push(q),f.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${Qe.toString("base64")}`,urlAfterCommand:i.browser.url(),serializedCommand:vn(V),elementInteracted:q.results[0]?.elementInteracted,thoughts:k});let Ve={substepIndex:S,output:{...q,message:q.message??"Successfully executed preset action."},step:Q,parentStepId:e.id};if(s.onDynamicCommandExecuted?.(Ve),await t.finish({output:kl.parse(q),step:q,message:q.message,attempt:1}),q.status==="FAILED")if(p.status="FAILED",p.message=q.message,E<3)E++,A=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${q.message}`;else return p;else if(q.status==="CANCELLED")return p.status="CANCELLED",p.message=q.message,p;S++}};import{randomUUID as HU}from"crypto";var ru=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function Ak(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 nu(r,e){let t=Ak(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var Cv="=",su=";",dg=",";var xv=8192;var ma={};j_(ma,{getKeyPairs:()=>n0,parseKeyPairsIntoRecord:()=>o0,parsePairKeyValue:()=>_v,serializeKeyPairs:()=>r0});Ie();var t0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function r0(r){return r.reduce(function(e,t){var n=""+e+(e!==""?dg:"")+t;return n.length>xv?e:n},"")}function n0(r){return r.getAllEntries().map(function(e){var t=t0(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=su+o.metadata.toString()),i})}function _v(r){var e=r.split(su);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(Cv);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=tg(e.join(su))),{key:o,value:i,metadata:a}}}}}function o0(r){return typeof r!="string"||r.length===0?{}:r.split(dg).map(function(e){return _v(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Ie();var lu;(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"})(lu||(lu={}));var i0=",",a0=["OTEL_SDK_DISABLED"];function s0(r){return a0.indexOf(r)>-1}var l0=["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 c0(r){return l0.indexOf(r)>-1}var u0=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function d0(r){return u0.indexOf(r)>-1}var pg=1/0,mg=128,p0=128,m0=128,gg={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:Be.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:pg,OTEL_ATTRIBUTE_COUNT_LIMIT:mg,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:pg,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:mg,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:pg,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:mg,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:p0,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:m0,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:lu.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 g0(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function h0(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 f0(r,e,t,n){n===void 0&&(n=i0);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var S0={ALL:Be.ALL,VERBOSE:Be.VERBOSE,DEBUG:Be.DEBUG,INFO:Be.INFO,WARN:Be.WARN,ERROR:Be.ERROR,NONE:Be.NONE};function y0(r,e,t){var n=t[r];if(typeof n=="string"){var o=S0[n.toUpperCase()];o!=null&&(e[r]=o)}}function Iv(r){var e={};for(var t in gg){var n=t;switch(n){case"OTEL_LOG_LEVEL":y0(n,e,r);break;default:if(s0(n))g0(n,e,r);else if(c0(n))h0(n,e,r);else if(d0(n))f0(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function wt(){var r=Iv(process.env);return Object.assign({},gg,r)}function Mv(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function cu(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=Mv(r.charCodeAt(n)),i=Mv(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var Pv="1.25.1";var E0="deployment.environment";var T0="process.runtime.name";var b0="service.name";var v0="service.instance.id";var R0="telemetry.sdk.name",A0="telemetry.sdk.language",w0="telemetry.sdk.version";var Ov=E0;var Lv=T0;var uu=b0;var Nv=v0;var Hs=R0,Gs=A0,Vs=w0;var C0="nodejs";var Dv=C0;var ga,du=(ga={},ga[Hs]="opentelemetry",ga[Lv]="node",ga[Gs]=Dv,ga[Vs]=Pv,ga);var x0=9,_0=6,I0=Math.pow(10,_0),M0=Math.pow(10,x0);function kv(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*I0);return[t,n]}function Fv(r){return r[0]*M0+r[1]}function js(r){return r[0]*1e6+r[1]/1e3}var ni;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ni||(ni={}));var Uv=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 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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},O0=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))},Bv=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new Uv}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,O0([this._that],P0(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 Er;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Er||(Er={}));var kt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(kt||(kt={}));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)}}();var Mge=function(r){L0(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function zv(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}Ie();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 Hv=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}();var ue;(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"})(ue||(ue={}));var N0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function D0(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 hg=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=D0(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=zv(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 fg=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Tr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new hg(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new hg(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new hg(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:kt.HISTOGRAM,dataPoints:n.map(function(i){var a=N0(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ue.GAUGE||e.type===ue.UP_DOWN_COUNTER||e.type===ue.OBSERVABLE_GAUGE||e.type===ue.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();Ie();var Sg=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},yg=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))},Eg=function(){function r(e,t,n,o){e===void 0&&(e=new k0),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var l=a%n;l<0&&(l+=n);for(var c=l;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var k0=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,yg([n,this._counts.length-t],Sg(this._counts.slice(t)),!1)),o.splice.apply(o,yg([0,t],Sg(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(yg([],Sg(this._counts),!1))},r}();var Gv=52,F0=2146435072,U0=1048575,Tg=1023,pu=-Tg+1,mu=Tg,$s=Math.pow(2,-1022);function gu(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&F0)>>20;return n-Tg}function hu(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&U0)*Math.pow(2,32);return o+n}function Ws(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function jv(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var B0=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)}}(),no=function(r){B0(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var Wv=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<$s)return this._minNormalLowerBoundaryIndex();var t=gu(e),n=this._rightShift(hu(e)-1,Gv);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new no("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new no("overflow: "+e+" is > maximum lower boundary: "+n);return Ws(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=pu>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return mu>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var qv=function(){function r(e){this._scale=e,this._scaleFactor=Ws(Math.LOG2E,e),this._inverseFactor=Ws(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=$s)return this._minNormalLowerBoundaryIndex()-1;if(hu(e)===0){var t=gu(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 no("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return $s;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new no("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 pu<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(mu+1<<this._scale)-1},r}();var Kv=-10,Yv=20,z0=Array.from({length:31},function(r,e){return e>10?new qv(e-10):new Wv(e-10)});function bg(r){if(r>Yv||r<Kv)throw new no("expected scale >= "+Kv+" && <= "+Yv+", got: "+r);return z0[r+10]}var H0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},fu=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}(),G0=20,V0=160,vg=2,j0=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=V0),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new Eg),u===void 0&&(u=new Eg),d===void 0&&(d=bg(G0)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<vg&&(z.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+vg),this._maxSize=vg)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,l=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=jv(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=bg(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=fu.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=fu.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 fu(0,-1);var o=t-n;return new fu(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var Xv=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Tr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new j0(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:kt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=H0(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ue.GAUGE||e.type===ue.UP_DOWN_COUNTER||e.type===ue.OBSERVABLE_GAUGE||e.type===ue.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();var $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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Rg=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=kv(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Jv=function(){function r(){this.kind=Tr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Rg(e)},r.prototype.merge=function(e,t){var n=js(t.sampleTime)>=js(e.sampleTime)?t:e;return new Rg(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=js(t.sampleTime)>=js(e.sampleTime)?t:e;return new Rg(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:kt.GAUGE,dataPoints:n.map(function(i){var a=$0(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var W0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},qs=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 Ag=function(){function r(e){this.monotonic=e,this.kind=Tr.SUM}return r.prototype.createAccumulation=function(e){return new qs(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new qs(t.startTime,this.monotonic,o,t.reset):new qs(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 qs(t.startTime,this.monotonic,o,!0):new qs(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:kt.SUM,dataPoints:n.map(function(i){var a=W0(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var oi=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)}}(),an=function(){function r(){}return r.Drop=function(){return iR},r.Sum=function(){return aR},r.LastValue=function(){return sR},r.Histogram=function(){return lR},r.ExponentialHistogram=function(){return q0},r.Default=function(){return K0},r}();var Qv=function(r){oi(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 Hv,e}(an);var Zv=function(r){oi(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case ue.COUNTER:case ue.OBSERVABLE_COUNTER:case ue.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Ag(!0),e.NON_MONOTONIC_INSTANCE=new Ag(!1),e}(an);var eR=function(r){oi(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 Jv,e}(an);var tR=function(r){oi(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 fg([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(an);var rR=function(r){oi(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(l,c){return l-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new fg(this._boundaries,this._recordMinMax)},e}(an);var nR=function(r){oi(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 Xv(this._maxSize,this._recordMinMax)},e}(an);var oR=function(r){oi(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case ue.COUNTER:case ue.UP_DOWN_COUNTER:case ue.OBSERVABLE_COUNTER:case ue.OBSERVABLE_UP_DOWN_COUNTER:return aR;case ue.GAUGE:case ue.OBSERVABLE_GAUGE:return sR;case ue.HISTOGRAM:return t.advice.explicitBucketBoundaries?new rR(t.advice.explicitBucketBoundaries):lR}return z.warn("Unable to recognize instrument type: "+t.type),iR},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(an);var iR=new Qv,aR=new Zv,sR=new eR,lR=new tR,q0=new nR,K0=new oR;Ie();function Su(){return"unknown_service:"+process.argv0}var oo=function(){return oo=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},oo.apply(this,arguments)},Y0=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},X0=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},J0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},wg=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 z.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[uu]=Su(),e[Gs]=du[Gs],e[Hs]=du[Hs],e[Vs]=du[Vs],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&z.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 Y0(this,void 0,void 0,function(){return X0(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=oo(oo({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var l,c=J0(a,2),s=c[0],u=c[1];return oo(oo(oo(oo({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var ii;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(ii||(ii={}));Ie();var Q0=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Z0=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},Cg=function(){return Er.CUMULATIVE},cR=function(r){switch(r){case ue.COUNTER:case ue.OBSERVABLE_COUNTER:case ue.GAUGE:case ue.HISTOGRAM:case ue.OBSERVABLE_GAUGE:return Er.DELTA;case ue.UP_DOWN_COUNTER:case ue.OBSERVABLE_UP_DOWN_COUNTER:return Er.CUMULATIVE}},uR=function(r){switch(r){case ue.COUNTER:case ue.HISTOGRAM:return Er.DELTA;case ue.GAUGE:case ue.UP_DOWN_COUNTER:case ue.OBSERVABLE_UP_DOWN_COUNTER:case ue.OBSERVABLE_COUNTER:case ue.OBSERVABLE_GAUGE:return Er.CUMULATIVE}};function eF(){var r=wt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Cg:e==="delta"?cR:e==="lowmemory"?uR:(z.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."),Cg)}function tF(r){return r!=null?r===ii.DELTA?cR:r===ii.LOWMEMORY?uR:Cg:eF()}function rF(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return an.Default()}}var dR=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=rF(t),this._aggregationTemporalitySelector=tF(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return Q0(this,void 0,void 0,function(){return Z0(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}();Ie();Ie();var nF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},pR=1e4,mR=5,gR=1e3,hR=5e3,fR=1.5;function Ks(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=nF(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):z.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function xg(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function _g(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return z.warn("Could not parse export URL: '"+r+"'"),r}}function Ig(r){return typeof r=="number"?r<=0?Mg(r,pR):r:oF()}function oF(){var r,e=Number((r=wt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:wt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Mg(e,pR):e}function Mg(r,e){return z.warn("Timeout must be greater than 0",r),e}function SR(r){var e=[429,502,503,504];return e.includes(r)}function yR(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 ER=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 Bv(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=Ig(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:ni.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:ni.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:ni.SUCCESS})}).catch(function(n){t({code:ni.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{z.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 z.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();Ie();import*as Pg from"url";import*as Eu from"http";import*as Tu from"https";import*as TR from"zlib";import{Readable as aF}from"stream";var io;(function(r){r.NONE="none",r.GZIP="gzip"})(io||(io={}));var iF=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)}}(),ha=function(r){iF(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 yu=function(){return yu=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},yu.apply(this,arguments)};function Og(r,e,t,n,o){var i=r.timeoutMillis,a=new Pg.URL(r.url),l=Number(process.versions.node.split(".")[0]),c,s,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,s.destroyed){var h=new ha("Request Timeout");o(h)}else l>=14?s.destroy():s.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:yu({"Content-Type":t},r.headers),agent:r.agent},m=a.protocol==="http:"?Eu.request:Tu.request,g=function(h,f){switch(h===void 0&&(h=mR),f===void 0&&(f=gR),s=m(p,function(E){var y="";E.on("data",function(A){return y+=A}),E.on("aborted",function(){if(u){var A=new ha("Request Timeout");o(A)}}),E.on("end",function(){if(u===!1)if(E.statusCode&&E.statusCode<299)z.debug("statusCode: "+E.statusCode,y),n(),clearTimeout(d),clearTimeout(c);else if(E.statusCode&&SR(E.statusCode)&&h>0){var A=void 0;f=fR*f,E.headers["retry-after"]?A=yR(E.headers["retry-after"]):A=Math.round(Math.random()*(hR-f)+f),c=setTimeout(function(){g(h-1,f)},A)}else{var R=new ha(E.statusMessage,E.statusCode,y);o(R),clearTimeout(d),clearTimeout(c)}})}),s.on("error",function(E){if(u){var y=new ha("Request Timeout",E.code);o(y)}else o(E);clearTimeout(d),clearTimeout(c)}),s.on("abort",function(){if(u){var E=new ha("Request Timeout");o(E)}clearTimeout(d),clearTimeout(c)}),r.compression){case io.GZIP:{s.setHeader("Content-Encoding","gzip");var S=sF(e);S.on("error",o).pipe(TR.createGzip()).on("error",o).pipe(s);break}default:s.end(Buffer.from(e));break}};g()}function sF(r){var e=new aF;return e.push(r),e.push(null),e}function Lg(r){if(r.httpAgentOptions&&r.keepAlive===!1){z.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Pg.URL(r.url),t=e.protocol==="http:"?Eu.Agent:Tu.Agent;return new t(yu({keepAlive:!0},r.httpAgentOptions))}catch(n){z.error("collector exporter failed to create http agent. err: "+n.message);return}}function Ng(r){if(r)return r;var e=wt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||wt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===io.GZIP?io.GZIP:io.NONE}Ie();var lF=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)}}(),bu=function(r){lF(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&&z.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Ks(t.headers),ma.parseKeyPairsIntoRecord(wt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=Lg(t),i.compression=Ng(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){z.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,s){var u;Og(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,s)}).then(n,o);this._sendingPromises.push(a);var l=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(l,l)},e.prototype.onShutdown=function(){},e}(ER);function vR(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function cF(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function RR(r){var e=vR(r);return cF(e)}function uF(r){var e=vR(r);return e.toString()}var dF=typeof BigInt<"u"?uF:Fv;function bR(r){return r}function AR(r){if(r!==void 0)return cu(r)}var pF={encodeHrTime:RR,encodeSpanContext:cu,encodeOptionalSpanContext:AR};function wR(r){var e,t;if(r===void 0)return pF;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?RR:dF,encodeSpanContext:o?bR:cu,encodeOptionalSpanContext:o?bR:AR}}var mF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function CR(r){return{name:r.name,version:r.version}}function fa(r){return Object.keys(r).map(function(e){return xR(e,r[e])})}function xR(r,e){return{key:r,value:_R(e)}}function _R(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(_R)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=mF(t,2),o=n[0],i=n[1];return xR(o,i)})}}:{}}function IR(r){return{attributes:fa(r.attributes),droppedAttributesCount:0}}Ie();function PR(r,e){var t=wR(e);return{resource:IR(r.resource),schemaUrl:void 0,scopeMetrics:gF(r.scopeMetrics,t)}}function gF(r,e){return Array.from(r.map(function(t){return{scope:CR(t.scope),metrics:t.metrics.map(function(n){return hF(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function hF(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=EF(r.aggregationTemporality);switch(r.dataPointType){case kt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:MR(r,e)};break;case kt.GAUGE:t.gauge={dataPoints:MR(r,e)};break;case kt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:SF(r,e)};break;case kt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:yF(r,e)};break}return t}function fF(r,e,t){var n={attributes:fa(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case rr.INT:n.asInt=r.value;break;case rr.DOUBLE:n.asDouble=r.value;break}return n}function MR(r,e){return r.dataPoints.map(function(t){return fF(t,r.descriptor.valueType,e)})}function SF(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:fa(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 yF(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:fa(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 EF(r){switch(r){case Er.DELTA:return 1;case Er.CUMULATIVE:return 2}}function OR(r,e){return{resourceMetrics:r.map(function(t){return PR(t,e)})}}var Dg={serializeRequest:function(r){var e=OR(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 LR="0.52.1";var NR=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)}}(),Sa=function(){return Sa=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},Sa.apply(this,arguments)},DR="v1/metrics",TF="http://localhost:4318/"+DR,bF={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+LR},vF=function(r){NR(e,r);function e(t){var n=r.call(this,t,Dg,"application/json")||this;return n.headers=Sa(Sa(Sa(Sa({},n.headers),bF),ma.parseKeyPairsIntoRecord(wt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Ks(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:wt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?_g(wt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):wt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?xg(wt().OTEL_EXPORTER_OTLP_ENDPOINT,DR):TF},e}(bu),kR=function(r){NR(e,r);function e(t){return r.call(this,new vF(t),t)||this}return e}(dR);var ya;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(ya||(ya={}));var sn;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(sn||(sn={}));Ie();var RF=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)}}(),FR=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},UR=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},AF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},wF=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))},CF=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 BR(r){return r!=null}function vu(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function zR(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var kg=function(r){RF(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function ao(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new kg("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function HR(r){return FR(this,void 0,void 0,function(){var e=this;return UR(this,function(t){return[2,Promise.all(r.map(function(n){return FR(e,void 0,void 0,function(){var o,i;return UR(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 GR(r){return r.status==="rejected"}function Fg(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,wF([],AF(e(n)),!1))}),t}function VR(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=CF(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(l){t={error:l}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function jR(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 $R(r,e){return r.toLowerCase()===e.toLowerCase()}Ie();var br;(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"})(br||(br={}));var Ug=function(){function r(){this.kind=br.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}();Ie();var fe;(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"})(fe||(fe={}));function ln(r,e,t){var n,o,i,a;return _F(r)||z.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:rr.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function WR(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 qR(r,e){return $R(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var xF=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function _F(r){return r.match(xF)!=null}var IF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function MF(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 Ru=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=MF(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=jR(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 Au=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=br.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Ru(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new Ru(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new Ru(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:sn.HISTOGRAM,dataPoints:n.map(function(i){var a=IF(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===fe.GAUGE||e.type===fe.UP_DOWN_COUNTER||e.type===fe.OBSERVABLE_GAUGE||e.type===fe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();Ie();var Bg=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},zg=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))},Hg=function(){function r(e,t,n,o){e===void 0&&(e=new PF),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var l=a%n;l<0&&(l+=n);for(var c=l;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var PF=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,zg([n,this._counts.length-t],Bg(this._counts.slice(t)),!1)),o.splice.apply(o,zg([0,t],Bg(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(zg([],Bg(this._counts),!1))},r}();var KR=52,OF=2146435072,LF=1048575,Gg=1023,wu=-Gg+1,Cu=Gg,Ys=Math.pow(2,-1022);function xu(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&OF)>>20;return n-Gg}function _u(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&LF)*Math.pow(2,32);return o+n}function Xs(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function XR(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var NF=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)}}(),so=function(r){NF(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var QR=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ys)return this._minNormalLowerBoundaryIndex();var t=xu(e),n=this._rightShift(_u(e)-1,KR);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new so("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new so("overflow: "+e+" is > maximum lower boundary: "+n);return Xs(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=wu>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Cu>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var ZR=function(){function r(e){this._scale=e,this._scaleFactor=Xs(Math.LOG2E,e),this._inverseFactor=Xs(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ys)return this._minNormalLowerBoundaryIndex()-1;if(_u(e)===0){var t=xu(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 so("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ys;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new so("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 wu<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Cu+1<<this._scale)-1},r}();var eA=-10,tA=20,DF=Array.from({length:31},function(r,e){return e>10?new ZR(e-10):new QR(e-10)});function Vg(r){if(r>tA||r<eA)throw new so("expected scale >= "+eA+" && <= "+tA+", got: "+r);return DF[r+10]}var kF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Iu=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}(),FF=20,UF=160,jg=2,rA=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=UF),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new Hg),u===void 0&&(u=new Hg),d===void 0&&(d=Vg(FF)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<jg&&(z.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+jg),this._maxSize=jg)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,l=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=XR(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Vg(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Iu.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Iu.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 Iu(0,-1);var o=t-n;return new Iu(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var $g=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=br.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new rA(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:sn.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=kF(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===fe.GAUGE||e.type===fe.UP_DOWN_COUNTER||e.type===fe.OBSERVABLE_GAUGE||e.type===fe.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();Ie();var BF=rg("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function nA(r){return r.setValue(BF,!0)}Ie();function oA(){return function(r){z.error(zF(r))}}function zF(r){return typeof r=="string"?r:JSON.stringify(HF(r))}function HF(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 GF=oA();function Mu(r){try{GF(r)}catch{}}var iA="1.30.1";var VF="process.runtime.name";var jF="service.name";var $F="telemetry.sdk.name",WF="telemetry.sdk.language",qF="telemetry.sdk.version";var aA=VF;var sA=jF;var Js=$F,Qs=WF,Zs=qF;var KF="nodejs";var lA=KF;var Ea,ai=(Ea={},Ea[Js]="opentelemetry",Ea[aA]="node",Ea[Qs]=lA,Ea[Zs]=iA,Ea);function el(r){r.unref()}var tU=9,rU=6,nU=Math.pow(10,rU),NSe=Math.pow(10,tU);function si(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*nU);return[t,n]}function Ta(r){return r[0]*1e6+r[1]/1e3}var tl;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(tl||(tl={}));Ie();function cA(r,e){return new Promise(function(t){pa.with(nA(pa.active()),function(){r.export(e,function(n){t(n)})})})}var uA={_export:cA};var oU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Pu=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=si(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Wg=function(){function r(){this.kind=br.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Pu(e)},r.prototype.merge=function(e,t){var n=Ta(t.sampleTime)>=Ta(e.sampleTime)?t:e;return new Pu(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Ta(t.sampleTime)>=Ta(e.sampleTime)?t:e;return new Pu(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:sn.GAUGE,dataPoints:n.map(function(i){var a=oU(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var iU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},ba=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 Ou=function(){function r(e){this.monotonic=e,this.kind=br.SUM}return r.prototype.createAccumulation=function(e){return new ba(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new ba(t.startTime,this.monotonic,o,t.reset):new ba(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 ba(t.startTime,this.monotonic,o,!0):new ba(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:sn.SUM,dataPoints:n.map(function(i){var a=iU(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var li=function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),vr=function(){function r(){}return r.Drop=function(){return SA},r.Sum=function(){return yA},r.LastValue=function(){return EA},r.Histogram=function(){return TA},r.ExponentialHistogram=function(){return aU},r.Default=function(){return sU},r}();var dA=function(r){li(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 Ug,e}(vr);var pA=function(r){li(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case fe.COUNTER:case fe.OBSERVABLE_COUNTER:case fe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Ou(!0),e.NON_MONOTONIC_INSTANCE=new Ou(!1),e}(vr);var mA=function(r){li(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 Wg,e}(vr);var gA=function(r){li(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 Au([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(vr);var Lu=function(r){li(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(l,c){return l-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Au(this._boundaries,this._recordMinMax)},e}(vr);var hA=function(r){li(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 $g(this._maxSize,this._recordMinMax)},e}(vr);var fA=function(r){li(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case fe.COUNTER:case fe.UP_DOWN_COUNTER:case fe.OBSERVABLE_COUNTER:case fe.OBSERVABLE_UP_DOWN_COUNTER:return yA;case fe.GAUGE:case fe.OBSERVABLE_GAUGE:return EA;case fe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Lu(t.advice.explicitBucketBoundaries):TA}return z.warn("Unable to recognize instrument type: "+t.type),SA},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(vr);var SA=new dA,yA=new pA,EA=new mA,TA=new gA,aU=new hA,sU=new fA;var bA=function(r){return vr.Default()},vA=function(r){return ya.CUMULATIVE};var qg=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Kg=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},RA=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},lU=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))},AA=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:bA,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:vA,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 qg(this,void 0,void 0,function(){var t,n,o,i,a,l;return Kg(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(lU([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],RA(this._metricProducers.map(function(s){return s.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=RA.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Fg(o,function(s){return s.errors})),a=n.resourceMetrics.resource,l=n.resourceMetrics.scopeMetrics.concat(Fg(o,function(s){return s.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:l},errors:i}]}})})},r.prototype.shutdown=function(e){return qg(this,void 0,void 0,function(){return Kg(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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,ao(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return qg(this,void 0,void 0,function(){return Kg(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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,ao(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Ie();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)}}(),Nu=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},dU=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))},Yg=function(r){cU(e,r);function e(t){var n,o,i,a,l=r.call(this,{aggregationSelector:(n=t.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(t.exporter),aggregationTemporalitySelector:(o=t.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(t.exporter),metricProducers:t.metricProducers})||this;if(t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<t.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return l._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,l._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,l._exporter=t.exporter,l}return e.prototype._runOnce=function(){return Nu(this,void 0,void 0,function(){var t;return Du(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,ao(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof kg?(z.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Mu(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return Nu(this,void 0,void 0,function(){var o,i,a,l,c,s;return Du(this,function(u){switch(u.label){case 0:return[4,this.collect({timeoutMillis:this._exportTimeout})];case 1:if(o=u.sent(),i=o.resourceMetrics,a=o.errors,a.length>0&&(s=z).error.apply(s,dU(["PeriodicExportingMetricReader: metrics collection errors"],uU(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(t=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(t)];case 3:return u.sent(),[3,5];case 4:return l=u.sent(),z.debug("Error while resolving async portion of resource: ",l),Mu(l),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,uA._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==tl.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),el(this._interval)},e.prototype.onForceFlush=function(){return Nu(this,void 0,void 0,function(){return Du(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 Nu(this,void 0,void 0,function(){return Du(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}(AA);Ie();Ie();function ku(){return"unknown_service:"+process.argv0}var lo=function(){return lo=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},lo.apply(this,arguments)},pU=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},mU=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},gU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Fu=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 z.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[sA]=ku(),e[Qs]=ai[Qs],e[Js]=ai[Js],e[Zs]=ai[Zs],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&z.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 pU(this,void 0,void 0,function(){return mU(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=lo(lo({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var l,c=gU(a,2),s=c[0],u=c[1];return lo(lo(lo(lo({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var wA=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}();Ie();var ci=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)}}(),Uu=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=pa.active()),typeof e!="number"){z.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===rr.INT&&!Number.isInteger(e)&&(z.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,si(Date.now()))},r}();var CA=function(r){ci(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}(Uu);var xA=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){z.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Uu);var _A=function(r){ci(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}(Uu);var IA=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){z.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Uu);var Bu=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 MA=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Bu);var PA=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Bu);var OA=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Bu);function rl(r){return r instanceof Bu}var LA=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=ln(e,fe.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new _A(o,n)},r.prototype.createHistogram=function(e,t){var n=ln(e,fe.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new IA(o,n)},r.prototype.createCounter=function(e,t){var n=ln(e,fe.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new xA(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=ln(e,fe.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new CA(o,n)},r.prototype.createObservableGauge=function(e,t){var n=ln(e,fe.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new PA(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=ln(e,fe.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new MA(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=ln(e,fe.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new OA(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 zu=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=ln(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var hU=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)}}(),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:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},fU=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 NA(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 NA(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 Dr=function(r){hU(e,r);function e(){return r.call(this,vu)||this}return e}(fU);var 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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Hu=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Dr,this._cumulativeMemoStorage=new Dr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=vu(this._overflowAttributes)}return r.prototype.record=function(e,t,n,o){var i=this,a=this._activeCollectionStorage.get(t);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var l=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});l?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(t,a)}a?.record(e)},r.prototype.batchCumulate=function(e,t){var n=this;Array.from(e.entries()).forEach(function(o){var i=SU(o,3),a=i[0],l=i[1],c=i[2],s=n._aggregator.createAccumulation(t);s?.record(l);var u=s;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,s)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,s)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,s,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new Dr,e},r}();var Xg=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.")},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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Gu=function(){function r(e,t){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,t.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return r.prototype.buildMetrics=function(e,t,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,l;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),s=c.collectionTime;l=c.aggregationTemporality,l===ya.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,s)}else l=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:l});var u=yU(a);if(u.length!==0)return this._aggregator.toMetricData(t,l,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=Xg(o),a=i.next();!a.done;a=i.next()){var l=a.value,c=this._unreportedAccumulations.get(l);c===void 0&&(c=[],this._unreportedAccumulations.set(l,c)),c.push(e)}}catch(s){t={error:s}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}},r.prototype._getMergedUnreportedAccumulations=function(e){var t,n,o=new Dr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Xg(i),l=a.next();!l.done;l=a.next()){var c=l.value;o=r.merge(o,c,this._aggregator)}}catch(s){t={error:s}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return o},r.merge=function(e,t,n){for(var o=e,i=t.entries(),a=i.next();a.done!==!0;){var l=DA(a.value,3),c=l[0],s=l[1],u=l[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,s);o.set(c,p,u)}else o.set(c,s,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=Xg(e.keys()),l=a.next();!l.done;l=a.next()){var c=DA(l.value,2),s=c[0],u=c[1],d=t.get(s,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function yU(r){return Array.from(r.entries())}var EU=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)}}(),TU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},kA=function(r){EU(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new Hu(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Gu(n,i),l}return e.prototype.record=function(t,n){var o=this,i=new Dr;Array.from(t.entries()).forEach(function(a){var l=TU(a,2),c=l[0],s=l[1];i.set(o._attributesProcessor.process(c),s)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(zu);Ie();function Jg(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
37
37
|
`),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
|
|
38
38
|
`),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
|
|
39
39
|
`),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
|
|
40
|
-
`),t}function
|
|
40
|
+
`),t}function bU(r,e){return" - use valueType '"+r.valueType+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function vU(r,e){return" - use unit '"+r.unit+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function RU(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 AU(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+`'
|
|
41
41
|
- OR - create a new view with the name `+r.name+" and description '"+r.description+"' and InstrumentSelector "+n+`
|
|
42
|
-
- OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function
|
|
42
|
+
- OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function Qg(r,e){return r.valueType!==e.valueType?bU(r,e):r.unit!==e.unit?vU(r,e):r.type!==e.type?RU(r,e):r.description!==e.description?AU(r,e):""}var Zg=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.")},FA=function(){function r(){this._sharedRegistry=new Map,this._perCollectorRegistry=new Map}return r.create=function(){return new r},r.prototype.getStorages=function(e){var t,n,o,i,a=[];try{for(var l=Zg(this._sharedRegistry.values()),c=l.next();!c.done;c=l.next()){var s=c.value;a=a.concat(s)}}catch(m){t={error:m}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}var u=this._perCollectorRegistry.get(e);if(u!=null)try{for(var d=Zg(u.values()),p=d.next();!p.done;p=d.next()){var s=p.value;a=a.concat(s)}}catch(m){o={error:m}}finally{try{p&&!p.done&&(i=d.return)&&i.call(d)}finally{if(o)throw o.error}}return a},r.prototype.register=function(e){this._registerStorage(e,this._sharedRegistry)},r.prototype.registerForCollector=function(e,t){var n=this._perCollectorRegistry.get(e);n==null&&(n=new Map,this._perCollectorRegistry.set(e,n)),this._registerStorage(t,n)},r.prototype.findOrUpdateCompatibleStorage=function(e){var t=this._sharedRegistry.get(e.name);return t===void 0?null:this._findOrUpdateCompatibleStorage(e,t)},r.prototype.findOrUpdateCompatibleCollectorStorage=function(e,t){var n=this._perCollectorRegistry.get(e);if(n===void 0)return null;var o=n.get(t.name);return o===void 0?null:this._findOrUpdateCompatibleStorage(t,o)},r.prototype._registerStorage=function(e,t){var n=e.getInstrumentDescriptor(),o=t.get(n.name);if(o===void 0){t.set(n.name,[e]);return}o.push(e)},r.prototype._findOrUpdateCompatibleStorage=function(e,t){var n,o,i=null;try{for(var a=Zg(t),l=a.next();!l.done;l=a.next()){var c=l.value,s=c.getInstrumentDescriptor();qR(s,e)?(s.description!==e.description&&(e.description.length>s.description.length&&c.updateDescription(e.description),z.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.
|
|
43
43
|
`,`Details:
|
|
44
|
-
`,
|
|
45
|
-
To resolve the conflict:`,
|
|
44
|
+
`,Jg(s,e),`The longer description will be used.
|
|
45
|
+
To resolve the conflict:`,Qg(s,e))),i=c):z.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
|
|
46
46
|
`,`Details:
|
|
47
|
-
`,
|
|
48
|
-
`,zg(s,e))}}catch(u){n={error:u}}finally{try{l&&!l.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var RA=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}();Me();Me();var AA=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Nr}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){z.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===tr.INT&&!Number.isInteger(e)&&(z.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 wA=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!Ys(e)){var o=this._buffer.get(e);if(o==null&&(o=new Nr,this._buffer.set(e,o)),typeof t!="number"){z.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===tr.INT&&!Number.isInteger(t)&&(z.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 Vg=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},jg=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},CA=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},xA=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))},_A=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(Ys));if(n.size===0){z.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(Ys)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return Vg(this,void 0,void 0,function(){var n,o,i,a;return jg(this,function(l){switch(l.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,CR(xA(xA([],CA(n),!1),CA(o),!1))];case 1:return i=l.sent(),a=i.filter(xR).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 Vg(n,void 0,void 0,function(){var l,c;return jg(this,function(s){switch(s.label){case 0:return l=new AA(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(l)),t!=null&&(c=no(c,t)),[4,c];case 1:return s.sent(),a._metricStorages.forEach(function(u){u.record(l._buffer,e)}),[2]}})})})},r.prototype._observeBatchCallbacks=function(e,t){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return Vg(n,void 0,void 0,function(){var l,c;return jg(this,function(s){switch(s.label){case 0:return l=new wA,c=Promise.resolve(i(l)),t!=null&&(c=no(c,t)),[4,c];case 1:return s.sent(),a.forEach(function(u){var d=l._buffer.get(u);d!=null&&u._metricStorages.forEach(function(p){p.record(d,e)})}),[2]}})})})},r.prototype._findCallback=function(e,t){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===t})},r.prototype._findBatchCallback=function(e,t){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&_R(n.instruments,t)})},r}();var eU=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)}}(),IA=function(r){eU(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new _u(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Iu(n,i),l}return e.prototype.record=function(t,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(t,n,o,i)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(xu);var PA=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)}}(),Ea=function(){function r(){}return r.Noop=function(){return rU},r}();var tU=function(r){PA(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(Ea);var MA=function(r){PA(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}(Ea);var rU=new tU;var nU=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},oU=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},iU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},OA=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new vA,this.observableRegistry=new _A,this.meter=new yA(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,IA);return t.length===1?t[0]:new RA(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,bA);return t},r.prototype.collect=function(e,t,n){return nU(this,void 0,void 0,function(){var o,i,a;return oU(this,function(l){switch(l.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=l.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,t)}).filter(AR),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},r.prototype._registerMetricStorage=function(e,t){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(c){var s=MR(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(s);if(u!=null)return u;var d=c.aggregation.createAggregator(s),p=new t(s,d,c.attributesProcessor,n._meterProviderSharedState.metricCollectors,c.aggregationCardinalityLimit);return n.metricStorageRegistry.register(p),p});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),l=a.map(function(c){var s=iU(c,2),u=s[0],d=s[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var m=d.createAggregator(e),g=u.selectCardinalityLimit(e.type),h=new t(e,m,Ea.Noop(),[u],g);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(l)}return i},r}();var aU=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.")},LA=function(){function r(e){this.resource=e,this.viewRegistry=new uA,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=wR(e),n=this.meterSharedStates.get(t);return n==null&&(n=new OA(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=aU(this.metricCollectors),a=i.next();!a.done;a=i.next()){var l=a.value;o.push([l,l.selectAggregation(e)])}}catch(c){t={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return o},r}();var Pu=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Mu=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},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(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},lU=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))},NA=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return Pu(this,void 0,void 0,function(){var t,n,o,i,a=this;return Mu(this,function(l){switch(l.label){case 0:return t=ii(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return Pu(a,void 0,void 0,function(){var s;return Mu(this,function(u){switch(u.label){case 0:return[4,c.collect(this,t,e)];case 1:return s=u.sent(),s?.scopeMetrics!=null&&n.push(s.scopeMetrics),s?.errors!=null&&o.push.apply(o,lU([],sU(s.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return l.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return Pu(this,void 0,void 0,function(){return Mu(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 Pu(this,void 0,void 0,function(){return Mu(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 DA=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},kA=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},FA=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 cU(r,e){var t=e??Au.empty();return r?Au.default().merge(t):t}var $g=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new LA(cU((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var l=FA(e.views),c=l.next();!c.done;c=l.next()){var s=c.value;this._sharedState.viewRegistry.addView(s)}}catch(m){t={error:m}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=FA(e.readers),d=u.next();!d.done;d=u.next()){var p=d.value;this.addMetricReader(p)}}catch(m){o={error:m}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(o)throw o.error}}}return r.prototype.getMeter=function(e,t,n){return t===void 0&&(t=""),n===void 0&&(n={}),this._shutdown?(z.warn("A shutdown MeterProvider cannot provide a Meter"),Xm()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new NA(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return DA(this,void 0,void 0,function(){return kA(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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 DA(this,void 0,void 0,function(){return kA(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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 uU=/[\^$\\.+?()[\]{}|]/g,Ou=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(uU,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var Ta=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 UA=function(){function r(e){var t;this._nameFilter=new Ou((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new Ta(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 BA=function(){function r(e){this._nameFilter=new Ta(e?.name),this._versionFilter=new Ta(e?.version),this._schemaUrlFilter=new Ta(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 dU(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var Wg=function(){function r(e){var t;if(dU(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Ou.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 MA(e.attributeKeys):this.attributesProcessor=Ea.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:Tr.Default(),this.instrumentSelector=new UA({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new BA({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var JSe=process.env.APP||"unknown";Me();import{v4 as pU}from"uuid";function mU(){return new bR({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:ni.DELTA})}var gU=[new Wg({instrumentName:"test_operation_duration_ms",instrumentType:ge.HISTOGRAM,aggregation:new Tu([100,500,1e3,5e3,1e4,2e4])})],Lu=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 gg({[Jc]:e.serviceName,[Sv]:t,[Ev]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:pU()}),o=mU(),i=new Ug({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new $g({resource:n,readers:[i],views:gU}),qc.setGlobalMeterProvider(this.provider),this.meter=qc.getMeter("momentic-serverless")}increment(e,t,n){try{let o=jc(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=jc(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 rr=new Vc;function HA(r){r.disabled||(rr=new Lu(r))}var SU=3;async function GA(r){let{logger:e}=r.fixtures,{results:t}=r.failureRecoveryParams,n=t[t.length-1],o=EU(r.work,n);if(o)return e.info({failedResult:n,isNotEligible:o},"Skipping failure recovery because of ineligible failure"),{type:"NOT_ELIGIBLE",message:`The failed step is not eligible for failure recovery: ${o}`};r.work.state.failureRecoveryAttempts=(r.work.state.failureRecoveryAttempts??0)+1;try{return await yU(r)}catch(i){return e.warn({err:i},"Error during failure recovery attempt, continuing..."),null}}async function yU(r){let{fixtures:e,work:t,failureRecoveryParams:n}=r,{controller:o,logger:i}=e,{testMetadata:a}=r.inputs,{results:l,failedStep:c,nextSteps:s,tracer:u}=n;if(!l.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(t.asyncTasks??[]);let d=o.browser.url(),p=`data:image/jpeg;base64,${(await o.browser.screenshot({})).toString("base64")}`,m=(await o.browser.getBrowserState({})).serialize(),{results:g}=await Ki(i,u,l,{numStepsWithScreenshots:8,addIndices:!0,includeBeforeScreenshots:!1}),h=s.map(_=>Jn(_)),f=a?.description?.trim(),E=a?.advanced?.failureRecoveryInstructions?.trim(),{scenario:S,thoughts:y,instructions:A}=await o.getFailureRecoveryPlan({currentUrl:d,currentScreenshot:p,failedResults:g,currentPageState:m,nextStepsSerialized:h,testDescription:f||void 0,customInstructions:E||void 0});if(S!=="RECOVERABLE")return i.info({scenario:S,thoughts:y,instructions:A},"Failure recovery is not applicable"),{type:"NOT_ELIGIBLE",message:`Momentic's failure recovery agent determined that this failure is not eligible for recovery: ${y}`};if(!A)throw new Error("Momentic's failure recovery agent did not provide any instructions for recovery");let R={id:fU(),type:"AI_ACTION_DYNAMIC",text:A},w=await aa(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures},listParams:{steps:[R,c],containerName:"AI-recovered step list",tracer:u}})),x=w.results[0];if(x&&x.type==="AI_ACTION_DYNAMIC")if(pc({results:w.results,onPresetAction:_=>{_.aiSuggested=!0},onSimpleStepContainer:_=>{_.aiSuggested=!0}}),w.status==="SUCCESS"){let _=`The following steps were automatically executed by the failure recovery agent. Analysis: ${y}`;return x.message=_,rr.increment("test_event",1,["name:failure_recovery_success",`orgId:${r.inputs.orgId}`]),i.info({thoughts:y},"Failure recovery succeeded"),{type:"ATTEMPTED",status:"SUCCESS",result:w,message:_}}else{let _=`The following steps were unsuccessfully attempted by the failure recovery agent. Analysis: ${y}`;return x.message=_,i.info({thoughts:y,aiActionResult:x},"Failure recovery failed"),{type:"ATTEMPTED",status:"FAILED",result:w,message:_}}return null}function EU(r,e){if(!e)return"There is no failed result";if(e.type!=="PRESET_ACTION")return"The failed step is not a preset action";let t=e.message;return t?t.includes("AbortError:")?"The user aborted the test":Zf.some(n=>t.includes(n))?"The failed step is an irrecoverable configuration error":(r.state.failureRecoveryAttempts??0)>SU?"Too many failure recovery attempts":"":"There is no error message available on the failed step"}import{randomUUID as Nu}from"crypto";import TU from"fast-json-patch";import{cloneDeep as bU}from"lodash-es";async function VA(r){let e=r.failedResults,t=[],{sectionParams:n,fixtures:o,work:i,startingUrl:a,startingContextSnapshot:l,tracer:c}=r,{step:s}=n,{controller:u,logger:d}=o,p=s?.autohealingConfig,m=p?.restartBehavior??{type:"GO_TO_SECTION_START"},g=p?.attempts??1;for(let h=0;h<g;h++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let f=bU(s.steps);await Promise.allSettled(i.asyncTasks??[]);let{results:E}=await Ki(d,c,e.results,{numStepsWithScreenshots:4}),S=await u.runSectionAutohealing({results:E,errorMessage:e.terminalResult?.message,goal:s.description});f=TU.applyPatch(f,S.patches).newDocument;let y=qt.fromSnapshot({snapshot:l,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await vU({logger:d,controller:u,tracer:c,context:y,restartConfig:m,startingUrl:a});let A=await aa(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures,context:y},listParams:{steps:f,containerName:"auto-healed step list",tracer:c}}));if(t.push(A.results),A.status==="SUCCESS")return{successfulHealing:{proposedStep:{...s,steps:f},listResult:A,context:y},healingAttempts:t};e=A}return{healingAttempts:t}}async function vU({logger:r,controller:e,tracer:t,restartConfig:n,context:o,startingUrl:i}){switch(n.type){case"NAVIGATE_URL":{let a={id:Nu(),type:"PRESET_ACTION",command:{id:Nu(),type:"NAVIGATE",url:n.url}},l=await t.startStep({logger:r,step:a,attempt:1});await e.executePresetCommand(null,l,a.command,o,!1);break}case"GO_TO_SECTION_START":{let a={id:Nu(),type:"PRESET_ACTION",command:{id:Nu(),type:"NAVIGATE",url:i}},l=await t.startStep({logger:r,step:a,attempt:1});await e.executePresetCommand(null,l,a.command,o,!1);break}}}function jA(r,e){switch(r||(r="ON_FAILURE"),r){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&_f(e.command.type))}}async function $A(r){let{step:e,tracer:t}=r.sectionParams,{logger:n,controller:o,context:i}=r.fixtures,a=new Date,l=o.browser.url(),c=i.toObjectCopy(),s=await t.startSubSteps(),u=async()=>r.executeStepList({...r,listParams:{steps:e.steps,containerName:"section step list",tracer:s}}),d=e.autohealingConfig?await aa(r.work,u):await u(),p,m;if(d.status==="FAILED"&&e.autohealingConfig&&!r.work.state.autoHealingDisabled&&jA(e.autohealingConfig.trigger,d.terminalResult)){let h=await t.startSubSteps(),f=await VA({...r,startingContextSnapshot:c,startingUrl:l,failedResults:d,tracer:h});f.successfulHealing&&(p=f.successfulHealing.proposedStep,d=f.successfulHealing.listResult,r.fixtures.context=f.successfulHealing.context),m=f.healingAttempts}let g={...e,...d,startedAt:a,finishedAt:new Date,proposedStep:p,healingAttempts:m};return Zr({asyncTasks:r.work.asyncTasks,nestedResults:d.results,result:g,logger:n}),g}var AU=60*60*1e3;async function Dr(r){let{results:e=[],containerName:t,steps:n,tracer:o}=r.listParams,{logger:i}=r.fixtures,a=o.getParentStepIdChain(),{fromStep:l,toStep:c}=r.inputs,s=r.work,u="SUCCESS",d,p=0;for(p;p<n.length;p++){let m=n[p];if(m.skipped)continue;if(s.fastForwardingToStep&&l){let y=JSON.stringify(a);if(m.id===l.fromStepId&&y===JSON.stringify(l.parentStepIdChain))s.fastForwardingToStep=!1;else if(!HE(m,a,l.fromStepId,l.parentStepIdChain))continue}let g=Jn(m),h=0,f=1,E=Date.now();"retries"in m&&m.retries&&m.retries>0&&(f+=m.retries);let S;for(;h<f&&Date.now()-E<AU;){h++,i.info({step:m,currentAttempt:h},`Executing step ${p+1}/${n.length} in ${t}: ${g}`);let y=Date.now(),{stepResult:A,status:R,failureRecoveryResults:w,shouldStopExecuting:x}=await wU({attempt:h,params:r,step:m,i:p,steps:n,results:e,currentParentIdChain:a,work:s,fromStep:l,toStep:c,lastRetry:h===f});if(R==="FAILED"&&h<f){S=[...S??[],A],Date.now()-y<1e3&&await Z(1e3-(Date.now()-y));continue}else e.push(A),S&&(A.previousAttempts=S);if(w&&e.push(...w),x)return u=R,d=A,{status:u,results:e,terminalResult:d};break}}return{status:u,results:e,terminalResult:d}}async function wU({attempt:r,params:e,step:t,i:n,steps:o,results:i,currentParentIdChain:a,work:l,fromStep:c,toStep:s,lastRetry:u}){let{tracer:d}=e.listParams,{logger:p,context:m,controller:g,codeEvalTools:h,usageTracker:f}=e.fixtures,{orgId:E}=e.inputs,S=new Date,y=await d.startStep({logger:p,step:t,attempt:r}),A=RU(t),R=m.toRedactedDisplayCopy(),w=g.browser.url(),x=g.executeAbortController.signal;f.trackStepExecution(t);let _,M;switch(t.type){case"PRESET_ACTION":{_="Preset action",M=await Zo(t,async()=>await Gc({...e,presetParams:{tracer:y,step:t}}),x);break}case"AI_ACTION":{_="AI action",M=await Zo(t,()=>kb({...e,aiStepParams:{step:t,tracer:y},executeStepList:Dr}),x);break}case"AI_ACTION_DYNAMIC":{_="AI action",M=await Zo(t,()=>Ub({...e,aiStepParams:{step:t,tracer:y},executeStepList:Dr}),x);break}case"RESOLVED_MODULE":{_=`Module (${t.name})`,M=await Zo(t,async()=>{let I=await _b({orgId:E,step:t,context:m,logger:p,flagStore:g.flagStore,codeEvalTools:h,signal:x});return zm({...e,executeStepList:Dr,moduleParams:{step:t,resolvedInputs:I,tracer:y}})},x);break}case"CONDITIONAL":{_="Conditional step",M=await Zo(t,()=>Nb({...e,conditionalParams:{step:t,tracer:y},executeStepList:Dr}),x);break}case"SECTION":{_="Section",M=await Zo(t,()=>$A({...e,sectionParams:{step:t,tracer:y},executeStepList:Dr}),x);break}default:return(j=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}M.beforeUrl=M.beforeUrl??w,M.beforeTestContext=R,t.envKey&&m.setVariable(t.envKey,M.data);let K=g.browser.url();m.setCurrentUrl(K),M.afterUrl=M.afterUrl??K,M.afterTestContext=m.toRedactedDisplayCopy(),await CU({startedAt:S,stepTypeName:_,result:M,callbacks:e.callbacks,globalWorkRef:e.work,tracer:y,attempt:r});let $,k;if(u&&M.status==="FAILED"&&!l.state.failureRecoveryDisabled&&c?.fromStepId===void 0&&s?.toStepId===void 0){let I=await GA({...e,executeStepList:Dr,failureRecoveryParams:{failedStep:A,nextSteps:o.slice(n+1),results:i.concat(M),tracer:d}});I&&(I.type==="ATTEMPTED"?($=I.result.results,k=I.status):I.type==="NOT_ELIGIBLE"&&(M.message=M.message?`${M.message} ${I.message}`:I.message),M.type==="PRESET_ACTION"&&(M.failureRecoveryStatus={type:I.type,message:I.message}))}return l.fastForwardingToStep&&c&&(c.fromStepId===t.id&&JSON.stringify(a)===JSON.stringify(c.parentStepIdChain)&&(l.fastForwardingToStep=!1),t.type==="RESOLVED_MODULE"&&pm(a,c.parentStepIdChain)&&(l.fastForwardingToStep=!1)),M.status!=="SUCCESS"&&k!=="SUCCESS"||g.closed?{shouldStopExecuting:!0,status:M.status,stepResult:M,failureRecoveryResults:$}:s&&t.id===s.toStepId&&JSON.stringify(a)===JSON.stringify(s.parentStepIdChain)?(g.setClosed(),{shouldStopExecuting:!0,status:"SUCCESS",stepResult:M,failureRecoveryResults:$}):{shouldStopExecuting:!1,status:"SUCCESS",stepResult:M,failureRecoveryResults:$}}async function CU({stepTypeName:r,result:e,tracer:t,attempt:n}){let o=r.toLowerCase(),i=r.charAt(0).toUpperCase()+r.slice(1),a="";switch(e.status){case"SUCCESS":a=e.message??`${i} executed successfully.`;break;case"FAILED":a=e.message??`${i} failed.`;break;case"CANCELLED":a=e.message??`${i} cancelled.`;break;default:throw new Error(`Unexpected ${o} status: ${e.status}`)}await t.finish({step:e,message:a,output:Il.parse(e),attempt:n})}import{randomUUID as WA}from"crypto";async function qA({browser:r,signal:e}){let t=new Date;try{return await r.navigate({url:r.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(n){let o={id:WA(),type:"PRESET_ACTION",status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:n.message,startedAt:t,finishedAt:new Date,results:[],command:{id:WA(),type:"NAVIGATE",url:r.baseUrl}};return{status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:o}}}var Du=async r=>{let{orgId:e,runId:t,testMetadata:n,steps:o,beforeSteps:i,afterSteps:a}=r.inputs;r.fixtures.logger=r.fixtures.logger.child({orgId:e,runId:t,testId:n?.id});let{logger:l,controller:c}=r.fixtures,{onTestComplete:s,onTestSuccess:u,onTestFailure:d}=r.callbacks.test,p=db(l);if(r.options.reinitializeBrowser){let g=await qA({browser:c.browser,signal:c.executeAbortController.signal});if(g.status!=="PASSED")return await s?.(),clearInterval(p?.interval),g}let m;try{return l.info({platform:p?.platform,cpuMetadata:p?.cpuMetadata,labels:n?.labels,orgSettings:wy.parse(r.inputs.orgSettings)},`Starting run for Momentic test '${n?.name??"Unnamed test"}'`),m=await _U(r),m}finally{l.info({status:m?.status,labels:n?.labels},"Momentic test final result"),clearInterval(p?.interval),await s?.(),m?.status==="PASSED"?await u?.({steps:o,beforeSteps:i,afterSteps:a}):m?.status==="FAILED"&&await d?.({steps:o,beforeSteps:i,afterSteps:a})}};function xU({beforeStatus:r,mainStatus:e,afterStatus:t}){return r==="FAILED"?"FAILED":r==="CANCELLED"?"CANCELLED":t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":"PASSED"}var _U=async r=>{let{tracer:e}=r.testParams,{fromStep:t,toStep:n,steps:o,beforeSteps:i,afterSteps:a}=r.inputs,{logger:l,controller:c,context:s,storage:u}=r.fixtures,{collectDebugData:d,disableHealing:p}=r.options;s.setCurrentUrl(c.browser.url());let m="test",g=o,h=[],f=p||t!==void 0||n!==void 0||void 0,E={results:h,state:{autoHealingDisabled:f,failureRecoveryDisabled:f,failureRecoveryAttempts:0},asyncTasks:[]},S=!1;t?.fromStepId&&t.fromStepId===n?.toStepId?(m="filtered step",E.fastForwardingToStep=!0):t?.fromStepId?(m="partial steps list from step",E.fastForwardingToStep=!0):n?m="partial steps list until step":(m="entire test",S=!0);let y,A,R;if(S&&i&&i.length>0){let k=await KA(i,"beforeSteps",r);y=k.status,A=k.results,R=k.terminalResult?{...k.terminalResult,failureReason:"SetupFailureError"}:void 0}let w,x;if(y===void 0||y==="PASSED"){l.info({fromStep:t,toStep:n},`Starting execution of ${m}`);let k=await e.startMainStepList(),Y=await Dr({...r,work:E,listParams:{steps:g,containerName:m,results:h,tracer:k}});w=Y.status,x=Y.terminalResult}let _,M,K;if(S&&a&&a.length>0){let k=await KA(a,"afterSteps",r);_=k.status,M=k.results,K=k.terminalResult?{...k.terminalResult,failureReason:"TeardownFailureError"}:void 0}let $=xU({beforeStatus:y,mainStatus:w,afterStatus:_});if(d&&IU({tracer:e,work:E,controller:c,storage:u,context:s,logger:l,status:$}),await Promise.allSettled(E.asyncTasks),E.asyncTasks.push(Promise.resolve(r.callbacks.test.onSaveFinalRunResults?.({results:h,beforeResults:A,afterResults:M}))),$==="FAILED"){let k=y==="FAILED"?R:void 0,Y=_==="FAILED"?K:void 0;return{status:"FAILED",results:h,beforeResults:A,afterResults:M,failedStepResult:k??x??Y}}else if($==="CANCELLED")return{status:"CANCELLED",results:h,beforeResults:A,afterResults:M};return{status:"PASSED",failureRecoveryDetails:E.state.failureRecoveryAttempts?{attempts:E.state.failureRecoveryAttempts}:void 0,results:h,beforeResults:A,afterResults:M}};async function KA(r,e,t){let n=t.fixtures.logger,o=e==="beforeSteps"?await t.testParams.tracer.startBeforeStepList():await t.testParams.tracer.startAfterStepList();n.info(`Starting step execution for ${e}`);let i={results:[],asyncTasks:[],state:{}},a={...t.callbacks,test:{...t.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0}},{status:l,results:c,terminalResult:s}=await Dr({...t,work:i,callbacks:a,listParams:{steps:r,containerName:e,tracer:o}});await Promise.allSettled(i.asyncTasks);let u;return l==="SUCCESS"?u="PASSED":l==="CANCELLED"?u="CANCELLED":u="FAILED",{status:u,results:c,terminalResult:s}}function IU({tracer:r,work:e,controller:t,storage:n,logger:o,context:i,status:a}){let l=t.browser.retrieveAndClearDebugData(),c=qE(l.logsPerPage),s=Np(l.harPages||{},l.harEntries||{});r.attachConsoleLogs({logger:o,logs:c}),r.attachNetworkLogs({logger:o,logs:s}),e.asyncTasks.push((async()=>{try{let u=await t.browser.screenshot({quality:75}),d=await Pb({codePath:"test-complete-final",storage:n,screenshotBuff:u,logger:o}),p=await H(t.browser.html(),{milliseconds:2e3});i.setVariable(Lb,d),a!=="PASSED"&&a!=="SUCCESS"&&(o.debug({finalPageHtml:p},"Final page state HTML"),o.debug({finalScreenshotUrl:d},"Uploaded final screenshot URL"))}catch{}})())}async function ku({settings:r,customHeaders:e,envVariables:t,envName:n,testName:o,baseUrl:i,logger:a,localTools:l,orgId:c}){let s=Ol.parse(r);e&&(s.extraHeaders={...s.extraHeaders,...e});let u=new qt({baseUrl:i,envName:n,testName:o,variablesFromEnvironment:t,currentUrl:i});await Uc({obj:s,context:u,bannedKeys:[],allowList:nS,localTools:l,logger:a,orgId:c});try{return Ol.parse(s)}catch(d){throw new C("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${d.message}`)}}import{cloneDeep as qH}from"lodash-es";var YA={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
|
|
47
|
+
`,Jg(s,e),`To resolve the conflict:
|
|
48
|
+
`,Qg(s,e))}}catch(u){n={error:u}}finally{try{l&&!l.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var UA=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}();Ie();Ie();var BA=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Dr}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){z.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===rr.INT&&!Number.isInteger(e)&&(z.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 zA=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!rl(e)){var o=this._buffer.get(e);if(o==null&&(o=new Dr,this._buffer.set(e,o)),typeof t!="number"){z.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===rr.INT&&!Number.isInteger(t)&&(z.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 eh=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},th=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},HA=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},GA=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))},VA=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(rl));if(n.size===0){z.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(rl)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return eh(this,void 0,void 0,function(){var n,o,i,a;return th(this,function(l){switch(l.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,HR(GA(GA([],HA(n),!1),HA(o),!1))];case 1:return i=l.sent(),a=i.filter(GR).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 eh(n,void 0,void 0,function(){var l,c;return th(this,function(s){switch(s.label){case 0:return l=new BA(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(l)),t!=null&&(c=ao(c,t)),[4,c];case 1:return s.sent(),a._metricStorages.forEach(function(u){u.record(l._buffer,e)}),[2]}})})})},r.prototype._observeBatchCallbacks=function(e,t){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return eh(n,void 0,void 0,function(){var l,c;return th(this,function(s){switch(s.label){case 0:return l=new zA,c=Promise.resolve(i(l)),t!=null&&(c=ao(c,t)),[4,c];case 1:return s.sent(),a.forEach(function(u){var d=l._buffer.get(u);d!=null&&u._metricStorages.forEach(function(p){p.record(d,e)})}),[2]}})})})},r.prototype._findCallback=function(e,t){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===t})},r.prototype._findBatchCallback=function(e,t){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&VR(n.instruments,t)})},r}();var wU=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)}}(),jA=function(r){wU(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new Hu(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Gu(n,i),l}return e.prototype.record=function(t,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(t,n,o,i)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(zu);var $A=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)}}(),va=function(){function r(){}return r.Noop=function(){return xU},r}();var CU=function(r){$A(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(va);var WA=function(r){$A(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}(va);var xU=new CU;var _U=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},IU=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},MU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},qA=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new FA,this.observableRegistry=new VA,this.meter=new LA(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,jA);return t.length===1?t[0]:new UA(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,kA);return t},r.prototype.collect=function(e,t,n){return _U(this,void 0,void 0,function(){var o,i,a;return IU(this,function(l){switch(l.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=l.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,t)}).filter(BR),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},r.prototype._registerMetricStorage=function(e,t){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(c){var s=WR(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(s);if(u!=null)return u;var d=c.aggregation.createAggregator(s),p=new t(s,d,c.attributesProcessor,n._meterProviderSharedState.metricCollectors,c.aggregationCardinalityLimit);return n.metricStorageRegistry.register(p),p});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),l=a.map(function(c){var s=MU(c,2),u=s[0],d=s[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var m=d.createAggregator(e),g=u.selectCardinalityLimit(e.type),h=new t(e,m,va.Noop(),[u],g);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(l)}return i},r}();var PU=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(){function r(e){this.resource=e,this.viewRegistry=new wA,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=zR(e),n=this.meterSharedStates.get(t);return n==null&&(n=new qA(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=PU(this.metricCollectors),a=i.next();!a.done;a=i.next()){var l=a.value;o.push([l,l.selectAggregation(e)])}}catch(c){t={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return o},r}();var Vu=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},ju=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},OU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},LU=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))},YA=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return Vu(this,void 0,void 0,function(){var t,n,o,i,a=this;return ju(this,function(l){switch(l.label){case 0:return t=si(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return Vu(a,void 0,void 0,function(){var s;return ju(this,function(u){switch(u.label){case 0:return[4,c.collect(this,t,e)];case 1:return s=u.sent(),s?.scopeMetrics!=null&&n.push(s.scopeMetrics),s?.errors!=null&&o.push.apply(o,LU([],OU(s.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return l.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return Vu(this,void 0,void 0,function(){return ju(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 Vu(this,void 0,void 0,function(){return ju(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 XA=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},JA=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},QA=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 NU(r,e){var t=e??Fu.empty();return r?Fu.default().merge(t):t}var rh=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new KA(NU((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var l=QA(e.views),c=l.next();!c.done;c=l.next()){var s=c.value;this._sharedState.viewRegistry.addView(s)}}catch(m){t={error:m}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=QA(e.readers),d=u.next();!d.done;d=u.next()){var p=d.value;this.addMetricReader(p)}}catch(m){o={error:m}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(o)throw o.error}}}return r.prototype.getMeter=function(e,t,n){return t===void 0&&(t=""),n===void 0&&(n={}),this._shutdown?(z.warn("A shutdown MeterProvider cannot provide a Meter"),sg()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new YA(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return XA(this,void 0,void 0,function(){return JA(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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 XA(this,void 0,void 0,function(){return JA(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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 DU=/[\^$\\.+?()[\]{}|]/g,$u=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(DU,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var Ra=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 ZA=function(){function r(e){var t;this._nameFilter=new $u((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new Ra(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 ew=function(){function r(e){this._nameFilter=new Ra(e?.name),this._versionFilter=new Ra(e?.version),this._schemaUrlFilter=new Ra(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 kU(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var nh=function(){function r(e){var t;if(kU(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||$u.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 WA(e.attributeKeys):this.attributesProcessor=va.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:vr.Default(),this.instrumentSelector=new ZA({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new ew({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var gTe=process.env.APP||"unknown";Ie();import{v4 as FU}from"uuid";function UU(){return new kR({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:ii.DELTA})}var BU=[new nh({instrumentName:"test_operation_duration_ms",instrumentType:fe.HISTOGRAM,aggregation:new Lu([100,500,1e3,5e3,1e4,2e4])})],Wu=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 wg({[uu]:e.serviceName,[Ov]:t,[Nv]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:FU()}),o=UU(),i=new Yg({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new rh({resource:n,readers:[i],views:BU}),au.setGlobalMeterProvider(this.provider),this.meter=au.getMeter("momentic-serverless")}increment(e,t,n){try{let o=nu(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=nu(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 nr=new ru;function tw(r){r.disabled||(nr=new Wu(r))}var GU=3;async function nw(r){let{logger:e}=r.fixtures,{results:t}=r.failureRecoveryParams,n=t[t.length-1],o=jU(r.work,n);if(o)return e.info({failedResult:n,isNotEligible:o},"Skipping failure recovery because of ineligible failure"),{type:"NOT_ELIGIBLE",message:`The failed step is not eligible for failure recovery: ${o}`};e.info({failedResult:n},"Attempting failure recovery"),r.work.state.failureRecoveryAttempts=(r.work.state.failureRecoveryAttempts??0)+1;try{return await VU(r)}catch(i){return e.warn({err:i},"Error during failure recovery attempt, continuing..."),null}}async function VU(r){let{fixtures:e,work:t,failureRecoveryParams:n}=r,{controller:o,logger:i}=e,{testMetadata:a}=r.inputs,{results:l,failedStep:c,nextSteps:s,tracer:u}=n;if(!l.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(t.asyncTasks??[]);let d=o.browser.url(),p=`data:image/jpeg;base64,${(await o.browser.screenshot({})).toString("base64")}`,m=(await o.browser.getBrowserState({})).serialize(),{results:g}=await Xi(i,u,l,{numStepsWithScreenshots:8,addIndices:!0,includeBeforeScreenshots:!1}),h=s.map(_=>eo(_)),f=a?.description?.trim(),S=a?.advanced?.failureRecoveryInstructions?.trim(),{scenario:E,thoughts:y,instructions:A}=await o.getFailureRecoveryPlan({currentUrl:d,currentScreenshot:p,failedResults:g,currentPageState:m,nextStepsSerialized:h,testDescription:f||void 0,customInstructions:S||void 0});if(E!=="RECOVERABLE")return i.info({scenario:E,thoughts:y,instructions:A},"Failure recovery is not applicable"),{type:"NOT_ELIGIBLE",message:`Momentic's failure recovery agent determined that this failure is not eligible for recovery: ${y}`};if(!A)throw new Error("Momentic's failure recovery agent did not provide any instructions for recovery");let R={id:HU(),type:"AI_ACTION_DYNAMIC",text:A},w=await ca(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures},listParams:{steps:[R,c],containerName:"AI-recovered step list",tracer:u}})),x=w.results[0];if(x&&x.type==="AI_ACTION_DYNAMIC")if(vc({results:w.results,onPresetAction:_=>{_.aiSuggested=!0},onSimpleStepContainer:_=>{_.aiSuggested=!0}}),w.status==="SUCCESS"){let _=`The following steps were automatically executed by the failure recovery agent. Analysis: ${y}`;return x.message=_,nr.increment("test_event",1,["name:failure_recovery_success",`orgId:${r.inputs.orgId}`]),i.info({thoughts:y},"Failure recovery succeeded"),{type:"ATTEMPTED",status:"SUCCESS",result:w,message:_}}else{let _=`The following steps were unsuccessfully attempted by the failure recovery agent. Analysis: ${y}`;return x.message=_,i.info({thoughts:y,aiActionResult:x},"Failure recovery failed"),{type:"ATTEMPTED",status:"FAILED",result:w,message:_}}return null}function jU(r,e){if(!e)return"There is no failed result";if(e.type!=="PRESET_ACTION")return"The failed step is not a preset action";let t=e.message;return t?t.includes("AbortError:")?"The user aborted the test":cS.some(n=>t.includes(n))?"The failed step is an irrecoverable configuration error":(r.state.failureRecoveryAttempts??0)>GU?"Too many failure recovery attempts":"":"There is no error message available on the failed step"}import{randomUUID as qu}from"crypto";import $U from"fast-json-patch";import{cloneDeep as WU}from"lodash-es";async function ow(r){let e=r.failedResults,t=[],{sectionParams:n,fixtures:o,work:i,startingUrl:a,startingContextSnapshot:l,tracer:c}=r,{step:s}=n,{controller:u,logger:d}=o,p=s?.autohealingConfig,m=p?.restartBehavior??{type:"GO_TO_SECTION_START"},g=p?.attempts??1;for(let h=0;h<g;h++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let f=WU(s.steps);await Promise.allSettled(i.asyncTasks??[]);let{results:S}=await Xi(d,c,e.results,{numStepsWithScreenshots:4}),E=await u.runSectionAutohealing({results:S,errorMessage:e.terminalResult?.message,goal:s.description});f=$U.applyPatch(f,E.patches).newDocument;let y=qt.fromSnapshot({snapshot:l,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await qU({logger:d,controller:u,tracer:c,context:y,restartConfig:m,startingUrl:a});let A=await ca(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures,context:y},listParams:{steps:f,containerName:"auto-healed step list",tracer:c}}));if(t.push(A.results),A.status==="SUCCESS")return{successfulHealing:{proposedStep:{...s,steps:f},listResult:A,context:y},healingAttempts:t};e=A}return{healingAttempts:t}}async function qU({logger:r,controller:e,tracer:t,restartConfig:n,context:o,startingUrl:i}){switch(n.type){case"NAVIGATE_URL":{let a={id:qu(),type:"PRESET_ACTION",command:{id:qu(),type:"NAVIGATE",url:n.url}},l=await t.startStep({logger:r,step:a,attempt:1});await e.executePresetCommand(null,l,a.command,o,!1);break}case"GO_TO_SECTION_START":{let a={id:qu(),type:"PRESET_ACTION",command:{id:qu(),type:"NAVIGATE",url:i}},l=await t.startStep({logger:r,step:a,attempt:1});await e.executePresetCommand(null,l,a.command,o,!1);break}}}function iw(r,e){switch(r||(r="ON_FAILURE"),r){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&Uf(e.command.type))}}async function aw(r){let{step:e,tracer:t}=r.sectionParams,{logger:n,controller:o,context:i}=r.fixtures,a=new Date,l=o.browser.url(),c=i.toObjectCopy(),s=await t.startSubSteps(),u=async()=>r.executeStepList({...r,listParams:{steps:e.steps,containerName:"section step list",tracer:s}}),d=e.autohealingConfig?await ca(r.work,u):await u(),p,m;if(d.status==="FAILED"&&e.autohealingConfig&&!r.work.state.autoHealingDisabled&&iw(e.autohealingConfig.trigger,d.terminalResult)){let h=await t.startSubSteps(),f=await ow({...r,startingContextSnapshot:c,startingUrl:l,failedResults:d,tracer:h});f.successfulHealing&&(p=f.successfulHealing.proposedStep,d=f.successfulHealing.listResult,r.fixtures.context=f.successfulHealing.context),m=f.healingAttempts}let g={...e,...d,startedAt:a,finishedAt:new Date,proposedStep:p,healingAttempts:m};return tn({asyncTasks:r.work.asyncTasks,nestedResults:d.results,result:g,logger:n}),g}var YU=60*60*1e3;async function kr(r){let{results:e=[],containerName:t,steps:n,tracer:o}=r.listParams,{logger:i}=r.fixtures,a=o.getParentStepIdChain(),{fromStep:l,toStep:c}=r.inputs,s=r.work,u="SUCCESS",d,p=0;for(p;p<n.length;p++){let m=n[p];if(m.skipped)continue;if(s.fastForwardingToStep&&l){let y=JSON.stringify(a);if(m.id===l.fromStepId&&y===JSON.stringify(l.parentStepIdChain))s.fastForwardingToStep=!1;else if(!JE(m,a,l.fromStepId,l.parentStepIdChain))continue}let g=eo(m),h=0,f=1,S=Date.now();"retries"in m&&m.retries&&m.retries>0&&(f+=m.retries);let E;for(;h<f&&Date.now()-S<YU;){h++,i.info({step:m,currentAttempt:h},`Executing step ${p+1}/${n.length} in ${t}: ${g}`);let y=Date.now(),{stepResult:A,status:R,failureRecoveryResults:w,shouldStopExecuting:x}=await XU({attempt:h,params:r,step:m,i:p,steps:n,results:e,currentParentIdChain:a,work:s,fromStep:l,toStep:c,lastRetry:h===f});if(R==="FAILED"&&h<f){E=[...E??[],A],Date.now()-y<1e3&&await ee(1e3-(Date.now()-y));continue}else e.push(A),E&&(A.previousAttempts=E);if(w&&e.push(...w),x)return u=R,d=A,{status:u,results:e,terminalResult:d};break}}return{status:u,results:e,terminalResult:d}}async function XU({attempt:r,params:e,step:t,i:n,steps:o,results:i,currentParentIdChain:a,work:l,fromStep:c,toStep:s,lastRetry:u}){let{tracer:d}=e.listParams,{logger:p,context:m,controller:g,codeEvalTools:h,usageTracker:f}=e.fixtures,{orgId:S}=e.inputs,E=new Date,y=await d.startStep({logger:p,step:t,attempt:r}),A=KU(t),R=m.toRedactedDisplayCopy(),w=g.browser.url(),x=g.executeAbortController.signal;f.trackStepExecution(t);let _,P;switch(t.type){case"PRESET_ACTION":{_="Preset action",P=await ti(t,async()=>await Zc({...e,presetParams:{tracer:y,step:t}}),x);break}case"AI_ACTION":{_="AI action",P=await ti(t,()=>Jb({...e,aiStepParams:{step:t,tracer:y},executeStepList:kr}),x);break}case"AI_ACTION_DYNAMIC":{_="AI action",P=await ti(t,()=>Zb({...e,aiStepParams:{step:t,tracer:y},executeStepList:kr}),x);break}case"RESOLVED_MODULE":{_=`Module (${t.name})`,P=await ti(t,async()=>{let I=await zb({orgId:S,step:t,context:m,logger:p,codeEvalTools:h,signal:x});return Qm({...e,executeStepList:kr,moduleParams:{step:t,resolvedInputs:I,tracer:y}})},x);break}case"CONDITIONAL":{_="Conditional step",P=await ti(t,()=>Yb({...e,conditionalParams:{step:t,tracer:y},executeStepList:kr}),x);break}case"SECTION":{_="Section",P=await ti(t,()=>aw({...e,sectionParams:{step:t,tracer:y},executeStepList:kr}),x);break}default:return(re=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}P.beforeUrl=P.beforeUrl??w,P.beforeTestContext=R,t.envKey&&m.setVariable(t.envKey,P.data);let X=g.browser.url();m.setCurrentUrl(X),P.afterUrl=P.afterUrl??X,P.afterTestContext=m.toRedactedDisplayCopy(),await JU({startedAt:E,stepTypeName:_,result:P,callbacks:e.callbacks,globalWorkRef:e.work,tracer:y,attempt:r});let V,k;if(u&&P.status==="FAILED"&&!l.state.failureRecoveryDisabled&&c?.fromStepId===void 0&&s?.toStepId===void 0){let I=await nw({...e,executeStepList:kr,failureRecoveryParams:{failedStep:A,nextSteps:o.slice(n+1),results:i.concat(P),tracer:d}});I&&(I.type==="ATTEMPTED"?(V=I.result.results,k=I.status):I.type==="NOT_ELIGIBLE"&&(P.message=P.message?`${P.message} ${I.message}`:I.message),P.type==="PRESET_ACTION"&&(P.failureRecoveryStatus={type:I.type,message:I.message}))}return l.fastForwardingToStep&&c&&(c.fromStepId===t.id&&JSON.stringify(a)===JSON.stringify(c.parentStepIdChain)&&(l.fastForwardingToStep=!1),t.type==="RESOLVED_MODULE"&&Am(a,c.parentStepIdChain)&&(l.fastForwardingToStep=!1)),P.status!=="SUCCESS"&&k!=="SUCCESS"||g.closed?{shouldStopExecuting:!0,status:P.status,stepResult:P,failureRecoveryResults:V}:s&&t.id===s.toStepId&&JSON.stringify(a)===JSON.stringify(s.parentStepIdChain)?(g.setClosed(),{shouldStopExecuting:!0,status:"SUCCESS",stepResult:P,failureRecoveryResults:V}):{shouldStopExecuting:!1,status:"SUCCESS",stepResult:P,failureRecoveryResults:V}}async function JU({stepTypeName:r,result:e,tracer:t,attempt:n}){let o=r.toLowerCase(),i=r.charAt(0).toUpperCase()+r.slice(1),a="";switch(e.status){case"SUCCESS":a=e.message??`${i} executed successfully.`;break;case"FAILED":a=e.message??`${i} failed.`;break;case"CANCELLED":a=e.message??`${i} cancelled.`;break;default:throw new Error(`Unexpected ${o} status: ${e.status}`)}await t.finish({step:e,message:a,output:kl.parse(e),attempt:n})}import{randomUUID as sw}from"crypto";async function lw({browser:r,signal:e}){let t=new Date;try{return await r.navigate({url:r.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(n){let o={id:sw(),type:"PRESET_ACTION",status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:n.message,startedAt:t,finishedAt:new Date,results:[],command:{id:sw(),type:"NAVIGATE",url:r.baseUrl}};return{status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:o}}}var Ku=async r=>{let{orgId:e,runId:t,testMetadata:n,steps:o,beforeSteps:i,afterSteps:a}=r.inputs;r.fixtures.logger=r.fixtures.logger.child({orgId:e,runId:t,testId:n?.id});let{logger:l,controller:c}=r.fixtures,{onTestComplete:s,onTestSuccess:u,onTestFailure:d}=r.callbacks.test,p=jb(l);if(r.options.reinitializeBrowser){let g=await lw({browser:c.browser,signal:c.executeAbortController.signal});if(g.status!=="PASSED")return await s?.(),clearInterval(p?.interval),g}let m;try{return l.info({platform:p?.platform,cpuMetadata:p?.cpuMetadata,labels:n?.labels,orgSettings:ky.parse(r.inputs.orgSettings)},`Starting run for Momentic test '${n?.name??"Unnamed test"}'`),m=await ZU(r),m}finally{l.info({status:m?.status,labels:n?.labels,steps:o,beforeSteps:i,afterSteps:a},"Momentic test final result"),clearInterval(p?.interval),await s?.(),m?.status==="PASSED"?await u?.({steps:o,beforeSteps:i,afterSteps:a}):m?.status==="FAILED"&&await d?.({steps:o,beforeSteps:i,afterSteps:a})}};function QU({beforeStatus:r,mainStatus:e,afterStatus:t}){return r==="FAILED"?"FAILED":r==="CANCELLED"?"CANCELLED":t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":"PASSED"}var ZU=async r=>{let{tracer:e}=r.testParams,{fromStep:t,toStep:n,steps:o,beforeSteps:i,afterSteps:a}=r.inputs,{logger:l,controller:c,context:s,storage:u}=r.fixtures,{collectDebugData:d,disableHealing:p}=r.options;s.setCurrentUrl(c.browser.url());let m="test",g=o,h=[],f=p||t!==void 0||n!==void 0||void 0,S={results:h,state:{autoHealingDisabled:f,failureRecoveryDisabled:f,failureRecoveryAttempts:0},asyncTasks:[]},E=!1;t?.fromStepId&&t.fromStepId===n?.toStepId?(m="filtered step",S.fastForwardingToStep=!0):t?.fromStepId?(m="partial steps list from step",S.fastForwardingToStep=!0):n?m="partial steps list until step":(m="entire test",E=!0);let y,A,R;if(E&&i&&i.length>0){let k=await cw(i,"beforeSteps",r);y=k.status,A=k.results,R=k.terminalResult?{...k.terminalResult,failureReason:"SetupFailureError"}:void 0}let w,x;if(y===void 0||y==="PASSED"){l.info({fromStep:t,toStep:n},`Starting execution of ${m}`);let k=await e.startMainStepList(),Q=await kr({...r,work:S,listParams:{steps:g,containerName:m,results:h,tracer:k}});w=Q.status,x=Q.terminalResult}let _,P,X;if(E&&a&&a.length>0){let k=await cw(a,"afterSteps",r);_=k.status,P=k.results,X=k.terminalResult?{...k.terminalResult,failureReason:"TeardownFailureError"}:void 0}let V=QU({beforeStatus:y,mainStatus:w,afterStatus:_});if(d&&eB({tracer:e,work:S,controller:c,storage:u,context:s,logger:l,status:V}),await Promise.allSettled(S.asyncTasks),S.asyncTasks.push(Promise.resolve(r.callbacks.test.onSaveFinalRunResults?.({results:h,beforeResults:A,afterResults:P}))),V==="FAILED"){let k=y==="FAILED"?R:void 0,Q=_==="FAILED"?X:void 0;return{status:"FAILED",results:h,beforeResults:A,afterResults:P,failedStepResult:k??x??Q}}else if(V==="CANCELLED")return{status:"CANCELLED",results:h,beforeResults:A,afterResults:P};return{status:"PASSED",failureRecoveryDetails:S.state.failureRecoveryAttempts?{attempts:S.state.failureRecoveryAttempts}:void 0,results:h,beforeResults:A,afterResults:P}};async function cw(r,e,t){let n=t.fixtures.logger,o=e==="beforeSteps"?await t.testParams.tracer.startBeforeStepList():await t.testParams.tracer.startAfterStepList();n.info(`Starting step execution for ${e}`);let i={results:[],asyncTasks:[],state:{}},a={...t.callbacks,test:{...t.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0}},{status:l,results:c,terminalResult:s}=await kr({...t,work:i,callbacks:a,listParams:{steps:r,containerName:e,tracer:o}});await Promise.allSettled(i.asyncTasks);let u;return l==="SUCCESS"?u="PASSED":l==="CANCELLED"?u="CANCELLED":u="FAILED",{status:u,results:c,terminalResult:s}}function eB({tracer:r,work:e,controller:t,storage:n,logger:o,context:i,status:a}){let l=t.browser,c=l.retrieveAndClearDebugData(),s=nT(c.logsPerPage),u=jp(c.harPages||{},c.harEntries||{});r.attachConsoleLogs({logger:o,logs:s}),r.attachNetworkLogs({logger:o,logs:u}),a!=="PASSED"&&a!=="SUCCESS"&&(r.attachBrowserCrashDump({crashReportDirFetcher:()=>l.browserCrashDumpDir,logger:o}),e.asyncTasks.push((async()=>{try{let d=await l.screenshot({quality:75}),p=await $b({codePath:"test-complete-final",storage:n,screenshotBuff:d,logger:o}),m=await H(l.html(),{milliseconds:2e3});i.setVariable(Kb,p),o.debug({finalPageHtml:m},"Final page state HTML"),o.debug({finalScreenshotUrl:p},"Uploaded final screenshot URL")}catch{}})()))}async function Yu({settings:r,customHeaders:e,envVariables:t,envName:n,testName:o,baseUrl:i,logger:a,localTools:l,orgId:c}){let s=Bl.parse(r);e&&(s.extraHeaders={...s.extraHeaders,...e});let u=new qt({baseUrl:i,envName:n,testName:o,variablesFromEnvironment:t,currentUrl:i});await Yc({obj:s,context:u,bannedKeys:[],allowList:mS,localTools:l,logger:a,orgId:c});try{return Bl.parse(s)}catch(d){throw new C("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${d.message}`)}}import{cloneDeep as SH}from"lodash-es";var uw={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
|
|
49
49
|
var momenticConstants = {
|
|
50
50
|
bannedClassSubstrings: [
|
|
51
51
|
"relative",
|
|
@@ -1480,9 +1480,6 @@ function addAddIdsScript() {
|
|
|
1480
1480
|
customWindow.nextAvailableMomenticId ?? 0,
|
|
1481
1481
|
currentId
|
|
1482
1482
|
);
|
|
1483
|
-
if (!customWindow.idMaintainer) {
|
|
1484
|
-
customWindow.addIdMaintainer?.();
|
|
1485
|
-
}
|
|
1486
1483
|
return currentId;
|
|
1487
1484
|
};
|
|
1488
1485
|
}
|
|
@@ -1505,83 +1502,6 @@ function addGetNextElementScript() {
|
|
|
1505
1502
|
return null;
|
|
1506
1503
|
};
|
|
1507
1504
|
}
|
|
1508
|
-
function addIdMaintainerScript() {
|
|
1509
|
-
const customWindow = window;
|
|
1510
|
-
if (customWindow.addIdMaintainer || customWindow.idMaintainer) {
|
|
1511
|
-
return;
|
|
1512
|
-
}
|
|
1513
|
-
const callback = (mutationList) => {
|
|
1514
|
-
if (!customWindow.addIdsToElement || !customWindow.nextAvailableMomenticId) {
|
|
1515
|
-
return;
|
|
1516
|
-
}
|
|
1517
|
-
for (const mutation of mutationList) {
|
|
1518
|
-
if (mutation.type === "childList" && mutation.addedNodes.length > 0) {
|
|
1519
|
-
for (const nodeRef of mutation.addedNodes) {
|
|
1520
|
-
if (nodeRef.nodeType !== Node.ELEMENT_NODE) {
|
|
1521
|
-
continue;
|
|
1522
|
-
}
|
|
1523
|
-
const node = nodeRef;
|
|
1524
|
-
if (node.getAttribute("data-momentic-id")) {
|
|
1525
|
-
continue;
|
|
1526
|
-
}
|
|
1527
|
-
const nodeBefore = node.previousElementSibling ?? node.parentElement;
|
|
1528
|
-
if (!nodeBefore) {
|
|
1529
|
-
continue;
|
|
1530
|
-
}
|
|
1531
|
-
const nodeAfter = customWindow.getNextElement?.(node);
|
|
1532
|
-
if (!nodeAfter) {
|
|
1533
|
-
continue;
|
|
1534
|
-
}
|
|
1535
|
-
const beforeId = nodeBefore.getAttribute("data-momentic-id");
|
|
1536
|
-
const afterId = nodeAfter.getAttribute("data-momentic-id");
|
|
1537
|
-
if (beforeId === null || afterId === null) {
|
|
1538
|
-
continue;
|
|
1539
|
-
}
|
|
1540
|
-
const beforeIdNum = parseInt(beforeId);
|
|
1541
|
-
const afterIdNum = parseInt(afterId);
|
|
1542
|
-
if (beforeIdNum >= afterIdNum - 1) {
|
|
1543
|
-
continue;
|
|
1544
|
-
}
|
|
1545
|
-
customWindow.addIdsToElement?.(node, beforeIdNum + 1, afterIdNum);
|
|
1546
|
-
}
|
|
1547
|
-
} else if (mutation.type === "attributes") {
|
|
1548
|
-
const target = mutation.target;
|
|
1549
|
-
if (target.nodeType !== Node.ELEMENT_NODE) {
|
|
1550
|
-
continue;
|
|
1551
|
-
}
|
|
1552
|
-
const ele = target;
|
|
1553
|
-
try {
|
|
1554
|
-
const oldId = parseInt(mutation.oldValue ?? "");
|
|
1555
|
-
const newAttr = ele.getAttribute("data-momentic-id");
|
|
1556
|
-
if (!newAttr) {
|
|
1557
|
-
ele.setAttribute("data-momentic-id", \`\${oldId}\`);
|
|
1558
|
-
ele.setAttribute("aria-keyshortcuts", \`\${oldId}\`);
|
|
1559
|
-
}
|
|
1560
|
-
} catch (err) {
|
|
1561
|
-
console.error(\`[MOMENTIC] Failed to update ID in maintainer: \${err}\`);
|
|
1562
|
-
}
|
|
1563
|
-
}
|
|
1564
|
-
}
|
|
1565
|
-
};
|
|
1566
|
-
customWindow.addIdMaintainer = () => {
|
|
1567
|
-
if (customWindow.idMaintainer) {
|
|
1568
|
-
return;
|
|
1569
|
-
}
|
|
1570
|
-
try {
|
|
1571
|
-
const observer = new MutationObserver(callback);
|
|
1572
|
-
customWindow.idMaintainer = observer;
|
|
1573
|
-
observer.observe(document.body, {
|
|
1574
|
-
attributeFilter: ["data-momentic-id"],
|
|
1575
|
-
attributeOldValue: true
|
|
1576
|
-
});
|
|
1577
|
-
} catch (_err) {
|
|
1578
|
-
window.setTimeout(() => {
|
|
1579
|
-
customWindow.addIdMaintainer?.();
|
|
1580
|
-
}, 1e3);
|
|
1581
|
-
return;
|
|
1582
|
-
}
|
|
1583
|
-
};
|
|
1584
|
-
}
|
|
1585
1505
|
|
|
1586
1506
|
// src/html/element-location.ts
|
|
1587
1507
|
function addFindElementInBodyOrShadowDomScript() {
|
|
@@ -3316,6 +3236,36 @@ function addMPathScripts() {
|
|
|
3316
3236
|
customWindow.getMPathSelector = getMPathSelector;
|
|
3317
3237
|
}
|
|
3318
3238
|
|
|
3239
|
+
// src/html/performance-observer.ts
|
|
3240
|
+
function addPerformanceObserver() {
|
|
3241
|
+
const customWindow = window;
|
|
3242
|
+
if (customWindow.performanceObserver) {
|
|
3243
|
+
return;
|
|
3244
|
+
}
|
|
3245
|
+
const obs = new PerformanceObserver((list) => {
|
|
3246
|
+
for (const e of list.getEntriesByType("longtask")) {
|
|
3247
|
+
try {
|
|
3248
|
+
console.warn("[MOMENTIC] Long-running task detected", {
|
|
3249
|
+
start: e.startTime.toFixed(1),
|
|
3250
|
+
dur: e.duration.toFixed(1),
|
|
3251
|
+
// https://developer.mozilla.org/en-US/docs/Web/API/PerformanceLongTaskTiming/attribution
|
|
3252
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3253
|
+
attribution: e.attribution?.map((a) => ({
|
|
3254
|
+
name: a.name,
|
|
3255
|
+
entryType: a.entryType,
|
|
3256
|
+
containerType: a.containerType,
|
|
3257
|
+
containerSrc: a.containerSrc,
|
|
3258
|
+
scriptUrl: a.containerSrc || a.name
|
|
3259
|
+
}))
|
|
3260
|
+
});
|
|
3261
|
+
} catch (err) {
|
|
3262
|
+
console.error(\`[MOMENTIC] Failed to log long task: \${err}\`);
|
|
3263
|
+
}
|
|
3264
|
+
}
|
|
3265
|
+
});
|
|
3266
|
+
obs.observe({ entryTypes: ["longtask"] });
|
|
3267
|
+
}
|
|
3268
|
+
|
|
3319
3269
|
// src/html/recording-listeners.ts
|
|
3320
3270
|
function addResolveRecordingTarget() {
|
|
3321
3271
|
const customWindow = window;
|
|
@@ -3983,10 +3933,10 @@ function addTargetRedirectionScript() {
|
|
|
3983
3933
|
|
|
3984
3934
|
// src/html/registration.ts
|
|
3985
3935
|
function registerAllMomenticListeners() {
|
|
3936
|
+
addPerformanceObserver();
|
|
3986
3937
|
addMd5Hash();
|
|
3987
3938
|
addAddIdsScript();
|
|
3988
3939
|
addGetNextElementScript();
|
|
3989
|
-
addIdMaintainerScript();
|
|
3990
3940
|
addMPathScripts();
|
|
3991
3941
|
addIndexDbScripts();
|
|
3992
3942
|
addMomenticConstantsToWindow();
|
|
@@ -4009,34 +3959,34 @@ function registerAllMomenticListeners() {
|
|
|
4009
3959
|
|
|
4010
3960
|
// src/html/index.ts
|
|
4011
3961
|
registerAllMomenticListeners();
|
|
4012
|
-
`};var
|
|
3962
|
+
`};var Rr={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-qa","data-aria-hidden","data-hidden","data-automation-id","data-overlay","data-content-editable-leaf","data-wf-icon","data-tns","data-sticky-stack-name","data-popup-origin","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-labelledby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],stronglyIdentifyingAttributes:["aria-label","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-row-index","data-col-index","for","aria-modal"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"],bannedAiRequiredCacheAttributes:["id","data-momentic-id","href","name","x","y","width","height","data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],ineligibleElementAttribute:"momentic-ineligible"};var dw="BoundingBoxMovedError",pw="ZeroOpacityError",Xu="visual_actions",_n="data-momentic-id";function mw(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(`
|
|
4013
3963
|
`,o);a>0&&a<n&&(o=a);let l=i,c=0;for(;c<1e3&&l>n&&r[l]!==`
|
|
4014
3964
|
`;)c++,l--;return l>n&&r[l]===`
|
|
4015
|
-
`&&(i=l),r.slice(o,i)}function kr(r){let e=typeof r=="string"?r:r.toString();return`[${xn}="${e}"]`}import{execSync as lH}from"child_process";import{randomUUID as Eh}from"crypto";import{diff as Th}from"deep-object-diff";import{existsSync as qu,mkdirSync as cH,readFileSync as uH,writeFileSync as dH}from"fs";import{Jimp as nC}from"jimp";import pH from"js-beautify";import{cloneDeep as Ra}from"lodash-es";import mH from"mime";import{homedir as vh,hostname as gH,platform as hH}from"os";import{basename as fH,extname as SH,join as Aa,resolve as yH}from"path";import{chromium as iC,devices as EH}from"playwright";import{addExtra as TH}from"playwright-extra";import bH from"puppeteer-extra-plugin-recaptcha";import{v4 as vH}from"uuid";import{rmSync as Tw}from"fs";import{basename as oB,join as iB}from"path";import{errors as aB}from"playwright-core";var ZA=new Set(["about:blank","chrome-error://chromewebdata/"]);var qg=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],Kg=1e4,Xs=500;import{mkdirSync as MU,rmSync as ew,statSync as OU}from"fs";import*as Qg from"node:fs";import LU from"nodejs-file-downloader";import{tmpdir as NU}from"os";import ao,{basename as DU,dirname as kU}from"path";var Zg="file://",Jg=ao.join(NU(),"momentic","downloads"),Xg=1e4,FU=50*1024*1024;async function tw(r){let{uri:e}=r;if(e.startsWith(Zg))return BU(r);if(e.startsWith("http"))return zU(r);if(by)return HU(r);throw new C("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function UU(r,e){let t=ao.join(Jg,r,e.slice(Zg.length)),n=ao.join(Jg,r),o=t.startsWith(n);if(!Qg.existsSync(t)||!o)throw new C("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function BU({uri:r,orgId:e}){let t=UU(e,r);return{filePath:t,cleanup:()=>{ew(kU(t),{recursive:!0,force:!0})}}}async function HU({uri:r}){let e=ao.resolve(r);if(!Qg.existsSync(e))throw new C("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 zU({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=DU(n.href),i=th(o),a=ao.extname(i);if(ay.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let l=eh(t),c=new LU({url:r,fileName:i,directory:l,maxAttempts:2,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:Xg}),{downloadStatus:s,filePath:u}=await H(c.download(),{milliseconds:Xg,message:`Download timed out after ${Xg}ms`});if(s!=="COMPLETE")throw new Error(`Download ended in non-success status: ${s}`);if(!u)throw new Error("File path of successfully downloaded file was empty");let p=OU(u).size;if(p>FU)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:p,filePath:u,fileName:i},"Downloaded file to disk");let m;return{filePath:u,cleanup:()=>{clearTimeout(m),m=setTimeout(()=>ew(l,{recursive:!0,force:!0}),10*60*1e3)}}}function rw(r,e){return`${Zg}${r}/${e}`}function eh(r){let e=Math.random().toString(36).substring(4),t=ao.join(Jg,r,e);return MU(t,{recursive:!0}),t}function th(r){let e=ao.extname(r),t=ao.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function _n(r,e){try{return await r.evaluate(n=>window.serializeElementOnlyWithText?.(n,{truncateToLength:500}),void 0,{timeout:1e3})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}async function nw(r,e){let t=r.evaluate(async()=>{let i=window,a={};try{let l=await indexedDB.databases();for(let c of l){if(!c.name)continue;let s=await i.exportIdbToObject?.(c.name,c.version);s&&(a[c.name]=s)}return[a,void 0]}catch(l){return[void 0,l.message]}}),[n,o]=await H(t,{milliseconds:3e3});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function ow(r,e,t){if(e){t.debug("Importing indexedDB data");try{let n=r.evaluate(async o=>{let i=window;for(let[a,l]of Object.entries(o))await i.importObjectToIdb?.(a,l)},e);await H(n,{milliseconds:3e3})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function iw(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 H(t,{milliseconds:3e3})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function aw(r,e,t,n,o){try{await GU(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function GU(r,e,t,n){let o=n.text();o.length>Xs&&(o=o.slice(0,Xs)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let l=await a.jsonValue(),c=JSON.stringify(l);c.length>Xs?i.push(c.slice(0,Xs)+"...(TRUNCATED)"):(typeof l!="object"||Object.keys(l).length>0)&&i.push(l)}catch{}rh(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function rh(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>Kg&&(i[t]=i[t].slice(Math.floor(Kg/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 vr({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await Ss({promiseGenerator:r,signal:n,codePath:e,logger:o}),l=Date.now();return t[e]=l-i,a}import VU from"truncate-json";var jU="[redacted due to size]",sw=5e3,$U=5e3;async function cw(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 nh(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([l,c])=>({name:l,value:c})),i={...await dw(e),url:n.toString(),method:e.method(),queryString:o,postData:await qU(e)};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:pw(t).timings}}async function uw(r,e,t){await t.finished();let n={};try{n=await JU(t)}catch{}let o={...await dw(t),status:t.status(),statusText:t.statusText(),content:n,redirectURL:t.headers().location,_mocked:!1};r.response=o;let i;try{i=await e.sizes(),r.request.bodySize=i.requestBodySize,r.request.headersSize=i.requestHeadersSize}catch{}r.response&&i&&(r.response.bodySize=i.responseBodySize,r.response.headersSize=i.responseHeadersSize,r.response.content.size=i.responseBodySize);let a=e.timing();r.startedDateTime=new Date(a.startTime).toISOString();let{timings:l,total:c}=pw(a);r.time=c,r.timings=l}function Js(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function lw(r){try{return new Date(r).toISOString()}catch{return}}function WU(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=sn(i),e.value=sn(a);continue}i==="Domain"&&(e.domain=sn(a)),i==="Expires"&&(e.expires=lw(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=lw(Date.now()+ +a*1e3)),i==="Path"&&(e.path=sn(a)),i==="Secure"&&(e.secure=!0)}return e}async function dw(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(WU)??[];return{headers:Object.entries(e).map(([n,o])=>({name:sn(n),value:sn(o)})),cookies:t}}async function qU(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:sn(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:sn(i),value:a?sn(a):void 0})}return n}var KU=["text"],YU=["json","xml","html","javascript"];function XU(r){let[e,t]=r.split("/");return e?KU.includes(e)?!0:t?!!YU.some(n=>t?.includes(n)):!1:!1}async function JU(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&&XU(t)&&(n.text=sn(await r.text())),n}function sn(r){try{let e=JSON.parse(r),{jsonString:t}=VU(r,$U);return t}catch{return r.length>sw?r.slice(0,sw)+jU:r}}function li(r){return r<0?0:r}function pw(r){return{timings:{blocked:li(r.domainLookupStart),dns:li(r.domainLookupEnd-r.domainLookupStart),connect:li(r.connectEnd-r.connectStart),send:li(r.responseStart-r.requestStart),wait:0,receive:li(r.responseEnd-r.responseStart),ssl:li(r.connectEnd-r.secureConnectionStart)},total:li(r.responseEnd)}}function mw(){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 dt({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await H(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 oh(){return window.lastCursorPos}import{errors as QU}from"playwright-core";async function ci({func:r,action:e,logger:t,callbacks:n,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),l;for(;Date.now()-a<o;)try{return await r(i)}catch(c){if(c instanceof QU.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),l=await ZU(c,i.locator,n,t);else throw c}throw l instanceof C?l:new C("ActionFailureError",`Failed to interact with targeted element. Error: ${l.message}`,{errOptions:{cause:l}})}async function ZU(r,e,t,n){return r.message.includes("attempt #")?eB(r,e,t,n):tB(r)}async function eB(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(`
|
|
4016
|
-
`,";").replace(/\s+/g," ");let a="",l=await
|
|
4017
|
-
${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let s=await e.boundingBox({timeout:3e3});s?s.height===0?c="The element you attempted to interact with has zero height.":s.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new C("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 C("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 tB(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 C("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}async function gw(r){try{return await rB(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function rB({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:1e3}),o=await _n(r,e),i=await r.boundingBox({timeout:1e3});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5||n!=="input")return;if(t)try{let c=r.page().locator(`label[for=${JSON.stringify(t)}]`);return await c.waitFor({state:"visible",timeout:1e3}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let s=window,u=c.parentElement;if(!u)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.getBoundingClientRect(),p=u.getBoundingClientRect();if(p.width===0||p.height===0)return{type:"error",error:"Parent element has no width or height"};let m={x:Math.min(Math.max(1,d.left-p.left),p.width-1),y:Math.min(Math.max(1,d.top-p.top),p.height-1)},g=s._MOMENTIC_FEATURE_FLAGS?.[Fu],h=c.getAttribute(xn),f=!g&&h?kr(h):s.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:m,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:1e3});if(a.type==="error")throw new Error(a.error);let l=r.page().locator(a.selector);return await l.waitFor({state:"visible",timeout:1e3}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:l,relativePoint:a.relativePoint}}var fw=["date","datetime-local","month","time","week"],hw={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 Sw(r){try{await H(nB(r),{milliseconds:3e3})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function nB({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await dt({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!hw[i])return;hw[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 Xt}from"zod";var yw=Xt.object({doubleClick:Xt.boolean().optional(),rightClick:Xt.boolean().optional(),force:Xt.boolean().optional(),waitForDownload:Xt.boolean().optional(),delayMs:Xt.number().optional(),downloadTimeoutMs:Xt.number().optional(),relativePosition:Xt.object({x:Xt.number(),y:Xt.number()}).optional()}),lbe=Xt.object({repeat:Xt.number().optional(),convertMeta:Xt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Xt.number().optional()});async function Uu({locator:r,callbacks:e,logger:t,timeoutMs:n=1e3}){try{await ih(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let m=window.getComputedStyle(d,null).getPropertyValue("display");if(m==="none"||m==="contents")return!1;let g=d.getBoundingClientRect();return!(!g.height||!g.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let l=0;for(;!a.momenticIsEligible(i)&&l<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,l++}let c=i.style.getPropertyValue("outline"),s=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,s),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await H(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 ih(r,e=1e3){let t=await r.state.getRoot();await dt({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 ah(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return ci({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>bw({...r,targetingResult:t,useVisualClick:e})})}async function sB(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await lB(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 lB(r,e){let{logger:t,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(r.message.includes("label")&&r.message.includes("for=")&&r.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:1e3});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:1e3}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),bw({...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 cB(r){let{browserCallbacks:e,logger:t,targetingResult:n,position:o,options:i}=r,a=await e.state.getRoot(),l=a&&a!==n.locator.page()&&"frameElement"in a?await a.frameElement():null,c;try{c=l?await $o({promiseGenerator:async()=>l.boundingBox(),timeoutMs:3e3,logger:t}):null}catch(g){throw new C("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${g.message}`)}finally{await l?.dispose()}let s=Date.now(),{clickX:u,clickY:d,reason:p}=await pB({frameCoordinates:c,logger:t,targetingResult:n,position:o,options:i}),m=yw.safeParse(i);t.info({frameCoordinates:c,position:o,options:m.success?m.data:void 0,clickLocation:{clickX:u,clickY:d,reason:p},duration:Date.now()-s},"Visual click")}async function uB(r){let{actionSource:e,targetingResult:t,options:n,logger:o}=r,i=r.targetingResult.locator,a=n?.relativePosition??r.position;if(e==="click"&&!a){let c=await gw({locator:i,logger:o});c&&(i=c.locator,a=c.relativePoint??a)}let l=n?.force||t.hints?.force||!1;try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l}):await i.click({button:n?.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l})}catch(c){let s=c;if(gB(s))o.warn({err:s},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:s},"Error clicking on locator, attempting to recover..."),sB(s,{...r,targetingResult:{...i,locator:i}})}}async function bw(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,l;e?.waitForDownload&&(l=(async()=>{let c=e.downloadTimeoutMs??3e4;try{return await a.locator.page().waitForEvent("download",{timeout:c})}catch(s){return s instanceof aB.TimeoutError?new C("ActionFailureError",`Download did not complete in ${c}ms`):new C("ActionFailureError",`Download failed: ${s.message}`)}})());try{await Uu({locator:a.locator,callbacks:n,logger:t,timeoutMs:1e3})}catch(c){t.warn({err:c},"Error highlighting locator in click, continuing...")}if(i?await cB(r):await uB(r),e?.waitForDownload)if(l){if(!o?.createIsolatedFolder)throw new C("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let c=await H(l,{milliseconds:e.downloadTimeoutMs??3e4});if(c instanceof Error)throw c;return{downloadedFile:await mB(c,o.createIsolatedFolder,t)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function dB(r,e){if(e.hints?.clickableXY){let i=(r?.x??0)+e.hints.clickableXY.x,a=(r?.y??0)+e.hints.clickableXY.y;return[{x:i,y:a},"targeting hint"]}let t=await e.locator.boundingBox({timeout:3e3});if(!t)throw new C("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 pB({frameCoordinates:r,logger:e,options:t,targetingResult:n,position:o}){let i,a,l;if(o){let d=await n.locator.boundingBox({timeout:3e3});i=(r?.x??0)+(d?.x??0)+o.x,a=(r?.y??0)+(d?.y??0)+o.y,l="predefined position"}else{let[d,p]=await dB(r,n);i=d.x,a=d.y,l=p}let c=n.locator.page(),s=t?.rightClick?"right":"left",u=t?.delayMs??25;return t?.doubleClick?await c.mouse.dblclick(i,a,{button:s,delay:u}):await c.mouse.click(i,a,{button:s,delay:u}),{clickX:i,clickY:a,reason:l}}async function mB(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=th(r.suggestedFilename()),i=e();await r.saveAs(iB(i,o)),Tw(n,{force:!0}),setTimeout(()=>{Tw(i,{recursive:!0,force:!0})},5*60*1e3);let a=rw(oB(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function gB(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as hB}from"os";var fB={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 SB(){let r=hB();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function vw(r){return JSON.stringify(r.split("+").sort())}function Bu(r){let e=SB(),t=vw(r);for(let n of Object.values(fB))if(Object.values(n).some(o=>vw(o)===t))return n[e];return process.platform==="darwin"?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function sh({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:l,logger:c}){if(!t&&!o)return;let s=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await dt({root:r,fn:([d,p,m,g])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*m,window.scrollY+(p??window.innerHeight)*g),arg:[t,o,s,u],waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"scrolling page"});else{let d=e.viewportSize()||Pt,p=await dt({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing page height"}),[m,g,h]=await dt({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let E=f.getBoundingClientRect();return[f.scrollTop,E.x,E.y]},arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*s,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<2e3;){a?.throwIfAborted();let E=await H(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[S,y,A]=await H(e.evaluate(()=>{let R=document.activeElement;if(!R)return[void 0,void 0,void 0];let w=R.getBoundingClientRect();return[R.scrollTop,w.x,w.y]}),{milliseconds:1e3});if(E===p&&S===m&&y===g&&A===h)break;p=E,m=S,g=y,h=A,await Z(500)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function lh(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 Z(500)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as CB}from"crypto";import{cloneDeep as uh}from"lodash-es";function so(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as yB}from"crypto";var EB="v1";function Hu(r,e){if(r.tagName.toLowerCase()==="svg"&&!bB(r))try{let t=Rw(r,e),n=TB(JSON.stringify(t));return{version:EB,json:t,hash:n}}catch{return}}function TB(r){return yB("md5").update(r).digest("hex")}function Rw(r,e){let t=r.tagName.toLowerCase(),n=vB(r);if(t==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:t,props:n,children:[]};for(let i of r.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let l=Rw(a,e);l&&o.children.push(l)}}return o}function bB(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function vB(r){let e={},t=r.attributes;for(let n of Object.keys(t))br.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var ui={r:147,g:196,b:125,a:.55},ww={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:ui,paddingColor:ui,borderColor:ui,marginColor:ui,eventTargetColor:ui,shapeColor:ui,shapeMarginColor:ui,showInfo:!0,showAccessibilityInfo:!0};function Cw({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},l={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:l};return i.forEach((s,u)=>{let d=RB({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:l,logger:n});c.roots.push(d)}),c}function RB({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:l}){let c=r[o],s=c.layout,u={};s.nodeIndex.forEach((x,_)=>{u[x]=_});let d=s.styles,p=s.bounds??[],m=c.nodes,g=m.contentDocumentIndex??{index:[],value:[]},h=m.backendNodeId??[],f=m.attributes??[],E=m.parentIndex??[],S=m.nodeName??[],y=m.nodeType??[],A=m.pseudoType??{index:[],value:[]},R=m.inputChecked??{index:[]},w=e[c.frameId];for(let x=0;x<h.length;x++){let _=h[x],M=y[x],K=f[x]??[],$=E[x]!==void 0&&E[x]>=0?E[x]:void 0,k=$!==void 0?h[$]:void 0,Y=k!==void 0?a[k]:void 0,I=A.index.indexOf(x),j=I!==-1?e[A.value[I]]:void 0,ce=u[x],ne;ce?ne=p[ce]??[]:ne=[];let Re=S[x]!==void 0?e[S[x]]?.toLowerCase():void 0;if(!Re){l.warn({backendNodeId:_,frameId:w,frameIndex:o,nodeBounds:ne},"DOM node has no tag name");continue}let He={backendNodeId:_,psuedoType:j,nodeType:M,frameIndex:o,parentFrameId:w,ownedFrameId:void 0,bounds:{x:ne[0]??null,y:ne[1]??null,width:ne[2]??null,height:ne[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:k??null,tagName:Re,parent:Y??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};Y&&Y.childrenBackendIds.push(_);let Ar=g.index.indexOf(x);if(Ar!==-1){let oe=g.value[Ar];i[oe]=He;let xe=r[oe]?.frameId;He.ownedFrameId=xe!==void 0?e[xe]:void 0}for(let oe of Object.keys(He.bounds)){let xe=oe;He.bounds[xe]!==null&&(He.bounds[xe]/=n)}let tt=ce!==void 0?d[ce]??[]:[];for(let oe=0;oe<tt.length&&!(oe>=t.length);oe++){let xe=tt[oe];if(xe===void 0||isNaN(xe))continue;let ze=e[xe];if(ze===void 0)continue;let wr=t[oe];He.computedStyles[wr]=ze}for(let oe=0;oe<K.length;oe+=2){let xe=K[oe],ze=K[oe+1];if(!xe||!ze)continue;let wr=e[xe],Si=e[ze];!wr||!Si||(He.attributes[wr]=Si)}R.index.includes(x)&&(He.attributes.checked="true"),a[He.backendNodeId]=He}return a[h[0]]}function ch(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=`${ch(t,e)}${a}`}return r.mPathSelector=n,n}function Aw(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var AB=["html","#document","#document-fragment"];function xw({node:r,domGraph:e}){let t=[],n=r,o=Aw(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=Aw(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++,AB.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,s=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],p=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${s})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&s++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function _w(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 Iw(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:2e3}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:2e3})).attributes,i=so(o,xn);if(!i)throw new Error(`Could not find attribute ${xn} for object ${e}`);return i}function Pw(r){let e=[];for(let t=0;t<r.domGraph.roots.length;t++){let n=r.domGraph.roots[t],o=wB({root:n,domGraph:r.domGraph,existingHashes:r.existingHashes,flagStore:r.flagStore,logger:r.logger});e=e.concat(o)}return e}function wB(r){let{root:e,domGraph:t,existingHashes:n}=r,o=[],i=[e];for(;i.length;){let a=i.pop();if(a.nodeType===1&&a.tagName.toLowerCase()==="svg"){let l=Hu(a,t);l&&!n[l.hash]&&o.push(l)}for(let l of a.childrenBackendIds){let c=t.backendIdToNode[l];c&&i.push(c)}}return o}var xB=["focusable","keyshortcuts","controls","live","relevant","orientation"],_B=["selected","readonly","modal","required","invalid"],IB=["id","name","role","content"],Mw=["absolute","fixed","sticky"],PB=["i"],MB=["path"],OB=["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"],Nw=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],Dw=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],LB=["menulistpopup","statictext","inlinetextbox"],NB=80,Ow=100,kw=50,mh=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],DB=["cite"],kB={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"]},FB={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},Lw={indentLevel:0},dh=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<kw?t:""),this.role=this.role||(e.domNode.attributes.role??""),zB(this.properties,e.domNode,e.importantProperties)}VB(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&&MB.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>Dw.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>zw(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>Gw(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),l=i[1]?.trim();if(a===void 0||l===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===l||l==="*")}))return!0}if(this.domNode&&PB.includes(this.domNode.tagName)||OB.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||br.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>Hw(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=Lw){let t=Object.assign({},Lw,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:l,condensedMode:c}=t,s=uh(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(R=>!R.superseded&&R.type==="contents")&&this.children.length>0&&(m="");let h=this.nameSources?.find(R=>!R.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let R=h.attributeValue?.relatedNodes??[];R.length===1&&R[0].text&&R[0].text===m&&(m="")}let f=mh.includes(this.role)||DB.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${m}
|
|
4018
|
-
`;let
|
|
4019
|
-
`;else{let R="";for(let x of this.children)R+=x.serialize({...e,indentLevel:n+2,neighbors:0});let w=R.trim();w.length<=
|
|
4020
|
-
`)?
|
|
4021
|
-
`:
|
|
3965
|
+
`&&(i=l),r.slice(o,i)}function Fr(r){let e=typeof r=="string"?r:r.toString();return`[${_n}="${e}"]`}import{execSync as Oz}from"child_process";import{randomUUID as Ph}from"crypto";import{diff as Oh}from"deep-object-diff";import{existsSync as mi,mkdirSync as Lz,readFileSync as Nz,readdirSync as Dz,rmSync as kz,statSync as SC,writeFileSync as Fz}from"fs";import{Jimp as yC}from"jimp";import Uz from"js-beautify";import{cloneDeep as Ca}from"lodash-es";import Bz from"mime";import{homedir as xa,platform as id}from"os";import{basename as zz,extname as Hz,join as pn,resolve as Gz}from"path";import{chromium as TC,devices as Vz}from"playwright";import{addExtra as jz}from"playwright-extra";import $z from"puppeteer-extra-plugin-recaptcha";import{v4 as Wz}from"uuid";import{rmSync as Dw}from"fs";import{basename as IB,join as MB}from"path";import{errors as PB}from"playwright-core";var gw=new Set(["about:blank","chrome-error://chromewebdata/"]);var oh=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],ih=1e4,nl=500;import{mkdirSync as rB,rmSync as hw,statSync as nB}from"fs";import*as ch from"node:fs";import oB from"nodejs-file-downloader";import{tmpdir as iB}from"os";import co,{basename as aB,dirname as sB}from"path";var uh="file://",lh=co.join(iB(),"momentic","downloads"),sh=1e4,lB=50*1024*1024;async function fw(r){let{uri:e}=r;if(e.startsWith(uh))return uB(r);if(e.startsWith("http"))return pB(r);if(Oy)return dB(r);throw new C("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function cB(r,e){let t=co.join(lh,r,e.slice(uh.length)),n=co.join(lh,r),o=t.startsWith(n);if(!ch.existsSync(t)||!o)throw new C("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function uB({uri:r,orgId:e}){let t=cB(e,r);return{filePath:t,cleanup:()=>{hw(sB(t),{recursive:!0,force:!0})}}}async function dB({uri:r}){let e=co.resolve(r);if(!ch.existsSync(e))throw new C("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 pB({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=aB(n.href),i=ph(o),a=co.extname(i);if(Sy.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let l=dh(t),c=new oB({url:r,fileName:i,directory:l,maxAttempts:2,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:sh}),{downloadStatus:s,filePath:u}=await H(c.download(),{milliseconds:sh,message:`Download timed out after ${sh}ms`});if(s!=="COMPLETE")throw new Error(`Download ended in non-success status: ${s}`);if(!u)throw new Error("File path of successfully downloaded file was empty");let p=nB(u).size;if(p>lB)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:p,filePath:u,fileName:i},"Downloaded file to disk");let m;return{filePath:u,cleanup:()=>{clearTimeout(m),m=setTimeout(()=>hw(l,{recursive:!0,force:!0}),10*60*1e3)}}}function Sw(r,e){return`${uh}${r}/${e}`}function dh(r){let e=Math.random().toString(36).substring(4),t=co.join(lh,r,e);return rB(t,{recursive:!0}),t}function ph(r){let e=co.extname(r),t=co.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function In(r,e){try{return await r.evaluate(n=>window.serializeElementOnlyWithText?.(n,{truncateToLength:500}),void 0,{timeout:1e3})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}async function yw(r,e){let t=r.evaluate(async()=>{let i=window,a={};try{let l=await indexedDB.databases();for(let c of l){if(!c.name)continue;let s=await i.exportIdbToObject?.(c.name,c.version);s&&(a[c.name]=s)}return[a,void 0]}catch(l){return[void 0,l.message]}}),[n,o]=await H(t,{milliseconds:3e3});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function Ew(r,e,t){if(e){t.debug("Importing indexedDB data");try{let n=r.evaluate(async o=>{let i=window;for(let[a,l]of Object.entries(o))await i.importObjectToIdb?.(a,l)},e);await H(n,{milliseconds:3e3})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function Tw(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 H(t,{milliseconds:3e3})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function bw(r,e,t,n,o){try{await mB(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function mB(r,e,t,n){let o=n.text();o.length>nl&&(o=o.slice(0,nl)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let l=await a.jsonValue(),c=JSON.stringify(l);c.length>nl?i.push(c.slice(0,nl)+"...(TRUNCATED)"):(typeof l!="object"||Object.keys(l).length>0)&&i.push(l)}catch{}mh(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function mh(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>ih&&(i[t]=i[t].slice(Math.floor(ih/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 Ar({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await Rs({promiseGenerator:r,signal:n,codePath:e,logger:o}),l=Date.now();return t[e]=l-i,a}import gB from"truncate-json";var hB="[redacted due to size]",vw=5e3,fB=5e3;async function Aw(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 gh(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([l,c])=>({name:l,value:c})),i={...await Cw(e),url:n.toString(),method:e.method(),queryString:o,postData:await yB(e)};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:xw(t).timings}}async function ww(r,e,t){await t.finished();let n={};try{n=await vB(t)}catch{}let o={...await Cw(t),status:t.status(),statusText:t.statusText(),content:n,redirectURL:t.headers().location,_mocked:!1};r.response=o;let i;try{i=await e.sizes(),r.request.bodySize=i.requestBodySize,r.request.headersSize=i.requestHeadersSize}catch{}r.response&&i&&(r.response.bodySize=i.responseBodySize,r.response.headersSize=i.responseHeadersSize,r.response.content.size=i.responseBodySize);let a=e.timing();r.startedDateTime=new Date(a.startTime).toISOString();let{timings:l,total:c}=xw(a);r.time=c,r.timings=l}function ol(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function Rw(r){try{return new Date(r).toISOString()}catch{return}}function SB(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=cn(i),e.value=cn(a);continue}i==="Domain"&&(e.domain=cn(a)),i==="Expires"&&(e.expires=Rw(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=Rw(Date.now()+ +a*1e3)),i==="Path"&&(e.path=cn(a)),i==="Secure"&&(e.secure=!0)}return e}async function Cw(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(SB)??[];return{headers:Object.entries(e).map(([n,o])=>({name:cn(n),value:cn(o)})),cookies:t}}async function yB(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:cn(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:cn(i),value:a?cn(a):void 0})}return n}var EB=["text"],TB=["json","xml","html","javascript"];function bB(r){let[e,t]=r.split("/");return e?EB.includes(e)?!0:t?!!TB.some(n=>t?.includes(n)):!1:!1}async function vB(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&&bB(t)&&(n.text=cn(await r.text())),n}function cn(r){try{let e=JSON.parse(r),{jsonString:t}=gB(r,fB);return t}catch{return r.length>vw?r.slice(0,vw)+hB:r}}function ui(r){return r<0?0:r}function xw(r){return{timings:{blocked:ui(r.domainLookupStart),dns:ui(r.domainLookupEnd-r.domainLookupStart),connect:ui(r.connectEnd-r.connectStart),send:ui(r.responseStart-r.requestStart),wait:0,receive:ui(r.responseEnd-r.responseStart),ssl:ui(r.connectEnd-r.secureConnectionStart)},total:ui(r.responseEnd)}}function _w(){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 ut({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await H(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 hh(){return window.lastCursorPos}import{errors as RB}from"playwright-core";async function di({func:r,action:e,logger:t,callbacks:n,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),l;for(;Date.now()-a<o;)try{return await r(i)}catch(c){if(c instanceof RB.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),l=await AB(c,i.locator,n,t);else throw c}throw l instanceof C?l:new C("ActionFailureError",`Failed to interact with targeted element. Error: ${l.message}`,{errOptions:{cause:l}})}async function AB(r,e,t,n){return r.message.includes("attempt #")?wB(r,e,t,n):CB(r)}async function wB(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(`
|
|
3966
|
+
`,";").replace(/\s+/g," ");let a="",l=await In(e,n);if(l&&(a=`Target element HTML: ${Xe(l,100,!0)}`),i.includes("element is not enabled"))return new C("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}});if(i.includes("intercepts pointer events")){let c="",s=i.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(s){let u=(await t.state.getRoot()).locator(Fr(s)),d=await In(u,n);d&&(c=`Covering element HTML: ${Xe(d,100,!0)}`)}return new C("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}
|
|
3967
|
+
${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let s=await e.boundingBox({timeout:3e3});s?s.height===0?c="The element you attempted to interact with has zero height.":s.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new C("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 C("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 CB(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 C("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}async function Iw(r){try{return await xB(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function xB({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:1e3}),o=await In(r,e),i=await r.boundingBox({timeout:1e3});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5||n!=="input")return;if(t)try{let c=r.page().locator(`label[for=${JSON.stringify(t)}]`);return await c.waitFor({state:"visible",timeout:1e3}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let s=window,u=c.parentElement;if(!u)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.getBoundingClientRect(),p=u.getBoundingClientRect();if(p.width===0||p.height===0)return{type:"error",error:"Parent element has no width or height"};let m={x:Math.min(Math.max(1,d.left-p.left),p.width-1),y:Math.min(Math.max(1,d.top-p.top),p.height-1)},g=s._MOMENTIC_FEATURE_FLAGS?.[Xu],h=c.getAttribute(_n),f=!g&&h?Fr(h):s.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:m,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:1e3});if(a.type==="error")throw new Error(a.error);let l=r.page().locator(a.selector);return await l.waitFor({state:"visible",timeout:1e3}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:l,relativePoint:a.relativePoint}}var Pw=["date","datetime-local","month","time","week"],Mw={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 Ow(r){try{await H(_B(r),{milliseconds:3e3})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function _B({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await ut({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!Mw[i])return;Mw[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 Jt}from"zod";var Lw=Jt.object({doubleClick:Jt.boolean().optional(),rightClick:Jt.boolean().optional(),force:Jt.boolean().optional(),waitForDownload:Jt.boolean().optional(),delayMs:Jt.number().optional(),downloadTimeoutMs:Jt.number().optional(),relativePosition:Jt.object({x:Jt.number(),y:Jt.number()}).optional()}),wRe=Jt.object({repeat:Jt.number().optional(),convertMeta:Jt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Jt.number().optional()});async function Ju({locator:r,callbacks:e,logger:t,timeoutMs:n=1e3}){try{await fh(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let m=window.getComputedStyle(d,null).getPropertyValue("display");if(m==="none"||m==="contents")return!1;let g=d.getBoundingClientRect();return!(!g.height||!g.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let l=0;for(;!a.momenticIsEligible(i)&&l<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,l++}let c=i.style.getPropertyValue("outline"),s=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,s),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await H(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 fh(r,e=1e3){let t=await r.state.getRoot();await ut({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 Sh(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return di({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>kw({...r,targetingResult:t,useVisualClick:e})})}async function OB(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await LB(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 LB(r,e){let{logger:t,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(r.message.includes("label")&&r.message.includes("for=")&&r.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:1e3});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:1e3}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),kw({...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 NB(r){let{browserCallbacks:e,logger:t,targetingResult:n,position:o,options:i}=r,a=await e.state.getRoot(),l=a&&a!==n.locator.page()&&"frameElement"in a?await a.frameElement():null,c;try{c=l?await Ko({promiseGenerator:async()=>l.boundingBox(),timeoutMs:3e3,logger:t}):null}catch(g){throw new C("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${g.message}`)}finally{await l?.dispose()}let s=Date.now(),{clickX:u,clickY:d,reason:p}=await FB({frameCoordinates:c,logger:t,targetingResult:n,position:o,options:i}),m=Lw.safeParse(i);t.info({frameCoordinates:c,position:o,options:m.success?m.data:void 0,clickLocation:{clickX:u,clickY:d,reason:p},duration:Date.now()-s},"Visual click")}async function DB(r){let{actionSource:e,targetingResult:t,options:n,logger:o}=r,i=r.targetingResult.locator,a=n?.relativePosition??r.position;if(e==="click"&&!a){let c=await Iw({locator:i,logger:o});c&&(i=c.locator,a=c.relativePoint??a)}let l=n?.force||t.hints?.force||!1;try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l}):await i.click({button:n?.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l})}catch(c){let s=c;if(BB(s))o.warn({err:s},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:s},"Error clicking on locator, attempting to recover..."),OB(s,{...r,targetingResult:{...i,locator:i}})}}async function kw(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,l;e?.waitForDownload&&(l=(async()=>{let c=e.downloadTimeoutMs??3e4;try{return await a.locator.page().waitForEvent("download",{timeout:c})}catch(s){return s instanceof PB.TimeoutError?new C("ActionFailureError",`Download did not complete in ${c}ms`):new C("ActionFailureError",`Download failed: ${s.message}`)}})());try{await Ju({locator:a.locator,callbacks:n,logger:t,timeoutMs:1e3})}catch(c){t.warn({err:c},"Error highlighting locator in click, continuing...")}if(i?await NB(r):await DB(r),e?.waitForDownload)if(l){if(!o?.createIsolatedFolder)throw new C("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let c=await H(l,{milliseconds:e.downloadTimeoutMs??3e4});if(c instanceof Error)throw c;return{downloadedFile:await UB(c,o.createIsolatedFolder,t)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function kB(r,e){if(e.hints?.clickableXY){let i=(r?.x??0)+e.hints.clickableXY.x,a=(r?.y??0)+e.hints.clickableXY.y;return[{x:i,y:a},"targeting hint"]}let t=await e.locator.boundingBox({timeout:3e3});if(!t)throw new C("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 FB({frameCoordinates:r,logger:e,options:t,targetingResult:n,position:o}){let i,a,l;if(o){let d=await n.locator.boundingBox({timeout:3e3});i=(r?.x??0)+(d?.x??0)+o.x,a=(r?.y??0)+(d?.y??0)+o.y,l="predefined position"}else{let[d,p]=await kB(r,n);i=d.x,a=d.y,l=p}let c=n.locator.page(),s=t?.rightClick?"right":"left",u=t?.delayMs??25;return t?.doubleClick?await c.mouse.dblclick(i,a,{button:s,delay:u}):await c.mouse.click(i,a,{button:s,delay:u}),{clickX:i,clickY:a,reason:l}}async function UB(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=ph(r.suggestedFilename()),i=e();await r.saveAs(MB(i,o)),Dw(n,{force:!0}),setTimeout(()=>{Dw(i,{recursive:!0,force:!0})},5*60*1e3);let a=Sw(IB(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function BB(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as zB}from"os";var HB={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 GB(){let r=zB();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function Fw(r){return JSON.stringify(r.split("+").sort())}function Qu(r){let e=GB(),t=Fw(r);for(let n of Object.values(HB))if(Object.values(n).some(o=>Fw(o)===t))return n[e];return process.platform==="darwin"?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function yh({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:l,logger:c}){if(!t&&!o)return;let s=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await ut({root:r,fn:([d,p,m,g])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*m,window.scrollY+(p??window.innerHeight)*g),arg:[t,o,s,u],waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"scrolling page"});else{let d=e.viewportSize()||Mt,p=await ut({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing page height"}),[m,g,h]=await ut({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let S=f.getBoundingClientRect();return[f.scrollTop,S.x,S.y]},arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*s,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<2e3;){a?.throwIfAborted();let S=await H(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[E,y,A]=await H(e.evaluate(()=>{let R=document.activeElement;if(!R)return[void 0,void 0,void 0];let w=R.getBoundingClientRect();return[R.scrollTop,w.x,w.y]}),{milliseconds:1e3});if(S===p&&E===m&&y===g&&A===h)break;p=S,m=E,g=y,h=A,await ee(500)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function Eh(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(500)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as XB}from"crypto";import{cloneDeep as vh}from"lodash-es";function uo(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as VB}from"crypto";var jB="v1";function Th(r,e){if(r.tagName.toLowerCase()==="svg"&&!WB(r))try{let t=Uw(r,e),n=$B(JSON.stringify(t));return{version:jB,json:t,hash:n}}catch{return}}function $B(r){return VB("md5").update(r).digest("hex")}function Uw(r,e){let t=r.tagName.toLowerCase(),n=qB(r);if(t==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:t,props:n,children:[]};for(let i of r.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let l=Uw(a,e);l&&o.children.push(l)}}return o}function WB(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function qB(r){let e={},t=r.attributes;for(let n of Object.keys(t))Rr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var pi={r:147,g:196,b:125,a:.55},zw={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:pi,paddingColor:pi,borderColor:pi,marginColor:pi,eventTargetColor:pi,shapeColor:pi,shapeMarginColor:pi,showInfo:!0,showAccessibilityInfo:!0};function Hw({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},l={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:l};return i.forEach((s,u)=>{let d=KB({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:l,logger:n});c.roots.push(d)}),c}function KB({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:l}){let c=r[o],s=c.layout,u={};s.nodeIndex.forEach((x,_)=>{u[x]=_});let d=s.styles,p=s.bounds??[],m=c.nodes,g=m.contentDocumentIndex??{index:[],value:[]},h=m.backendNodeId??[],f=m.attributes??[],S=m.parentIndex??[],E=m.nodeName??[],y=m.nodeType??[],A=m.pseudoType??{index:[],value:[]},R=m.inputChecked??{index:[]},w=e[c.frameId];for(let x=0;x<h.length;x++){let _=h[x],P=y[x],X=f[x]??[],V=S[x]!==void 0&&S[x]>=0?S[x]:void 0,k=V!==void 0?h[V]:void 0,Q=k!==void 0?a[k]:void 0,I=A.index.indexOf(x),re=I!==-1?e[A.value[I]]:void 0,me=u[x],q;me?q=p[me]??[]:q=[];let Qe=E[x]!==void 0?e[E[x]]?.toLowerCase():void 0;if(!Qe){l.warn({backendNodeId:_,frameId:w,frameIndex:o,nodeBounds:q},"DOM node has no tag name");continue}let Ve={backendNodeId:_,psuedoType:re,nodeType:P,frameIndex:o,parentFrameId:w,ownedFrameId:void 0,bounds:{x:q[0]??null,y:q[1]??null,width:q[2]??null,height:q[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:k??null,tagName:Qe,parent:Q??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};Q&&Q.childrenBackendIds.push(_);let gt=g.index.indexOf(x);if(gt!==-1){let K=g.value[gt];i[K]=Ve;let Ee=r[K]?.frameId;Ve.ownedFrameId=Ee!==void 0?e[Ee]:void 0}for(let K of Object.keys(Ve.bounds)){let Ee=K;Ve.bounds[Ee]!==null&&(Ve.bounds[Ee]/=n)}let bt=me!==void 0?d[me]??[]:[];for(let K=0;K<bt.length&&!(K>=t.length);K++){let Ee=bt[K];if(Ee===void 0||isNaN(Ee))continue;let sr=e[Ee];if(sr===void 0)continue;let Ln=t[K];Ve.computedStyles[Ln]=sr}for(let K=0;K<X.length;K+=2){let Ee=X[K],sr=X[K+1];if(!Ee||!sr)continue;let Ln=e[Ee],Nn=e[sr];!Ln||!Nn||(Ve.attributes[Ln]=Nn)}R.index.includes(x)&&(Ve.attributes.checked="true"),a[Ve.backendNodeId]=Ve}return a[h[0]]}function bh(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=`${bh(t,e)}${a}`}return r.mPathSelector=n,n}function Bw(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var YB=["html","#document","#document-fragment"];function Gw({node:r,domGraph:e}){let t=[],n=r,o=Bw(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=Bw(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++,YB.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,s=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],p=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${s})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&s++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function Vw(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 jw(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:2e3}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:2e3})).attributes,i=uo(o,_n);if(!i)throw new Error(`Could not find attribute ${_n} for object ${e}`);return i}var JB=["focusable","keyshortcuts","controls","live","relevant","orientation"],QB=["selected","readonly","modal","required","invalid"],ZB=["id","name","role","content"],$w=["absolute","fixed","sticky"],ez=["i"],tz=["path"],rz=["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"],Kw=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],Yw=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],nz=["menulistpopup","statictext","inlinetextbox"],oz=80,Ww=100,Xw=50,wh=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],iz=["cite"],az={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"]},sz={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},qw={indentLevel:0},Rh=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<Xw?t:""),this.role=this.role||(e.domNode.attributes.role??""),dz(this.properties,e.domNode,e.importantProperties)}mz(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&&tz.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>Yw.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>tC(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>rC(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),l=i[1]?.trim();if(a===void 0||l===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===l||l==="*")}))return!0}if(this.domNode&&ez.includes(this.domNode.tagName)||rz.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||Rr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>eC(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=qw){let t=Object.assign({},qw,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:l,condensedMode:c}=t,s=vh(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(R=>!R.superseded&&R.type==="contents")&&this.children.length>0&&(m="");let h=this.nameSources?.find(R=>!R.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let R=h.attributeValue?.relatedNodes??[];R.length===1&&R[0].text&&R[0].text===m&&(m="")}let f=wh.includes(this.role)||iz.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${m}
|
|
3968
|
+
`;let S=`${u}<${p}`;!a&&!f&&(S+=` id="${this.id}"`);let E=l??!1;if((s.multiline||s.contenteditable)&&this.children.length>0&&(E=!0),d&&d!=="generic"&&d!==p&&!(az[d]??[]).includes(p)&&(S+=` role=${JSON.stringify(d)}`),m&&(S+=` name=${JSON.stringify(m)}`),this.content&&!E&&(S+=` content=${JSON.stringify(this.content)}`),this.flagNotActionableNodes&&this.tagName!=="#document"&&this.isNotActionable()&&(S+=` ${Rr.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let R=this.domNode.bounds,w=Math.round(R.x??0),x=Math.round(R.y??0),_=Math.round((R.x??0)+(R.width??0)),P=Math.round((R.y??0)+(R.height??0));S+=` bounds=[${w} ${x} ${_} ${P}]`}let y=Date.now();if(Object.keys(s).length>0&&!i){if(Date.now()-y>1e3)throw new Error(`Serialization for the HTML element with tag ${p} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(s).forEach(([R,w])=>{if(!JB.includes(R)){{if(QB.includes(R)&&(!w||w==="false"))return;if(R==="value"&&E&&(s.type==="text"||this.role==="textbox"))return;if(R==="level"&&`${w}`=="1")return;if(R==="url"&&s.src&&p==="img")return;if(R==="url"&&s.href&&p==="a")return;if(R==="editable"&&w==="plaintext")return;if(R==="type"&&w===p)return;if(c&&!sz[R])return}typeof w=="string"?S+=` ${R}="${Xe(w,Ww,!0)}"`:typeof w=="boolean"?w?S+=` ${R}`:S+=` ${R}={false}`:typeof w<"u"&&(S+=` ${R}={${Xe(JSON.stringify(w),Ww,!0)}}`)}})}if(p==="::before"||p==="::after"){let R="";for(let w of this.children)R+=w.serialize({...e,indentLevel:n,neighbors:0});return R}let A=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||A)S+=` />
|
|
3969
|
+
`;else{let R="";for(let x of this.children)R+=x.serialize({...e,indentLevel:n+2,neighbors:0});let w=R.trim();w.length<=oz&&!w.includes(`
|
|
3970
|
+
`)?S+=`>${w}</${p}>
|
|
3971
|
+
`:S+=`>
|
|
4022
3972
|
${R}${u}</${p}>
|
|
4023
3973
|
`}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let R=this.parent.children.findIndex(_=>_.id===this.id),w=R>0?this.parent.children[R-1]?.serialize({...e,neighbors:0}):"",x=R<this.parent.children.length-1?this.parent.children[R+1]?.serialize({...e,neighbors:0}):"";return`${w||""}
|
|
4024
|
-
${
|
|
4025
|
-
${x||""}`}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:uh(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=uh(this.properties),e}},ph=class r{constructor(e,t,n,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingSummaries(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n={},o={},i={},a=c=>{let s=c.shallowClone();if(e[c.id])return s.properties["data-momentic-summary"]=e[c.id],n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s;let u=[];for(let d of c.children){let p=a(d);p&&(u.push(p),p.parent=s)}return s.children=u,n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s},l=a(t);return new r(l,n,o,i)}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let l=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),s=i.children,u=!1,d=[];for(let p of s){let m=n(p,l||u);m&&(d.push(m),m.parent=c,u=!0)}if(c.children=d,l||u)return c;if(mh.includes(i.role)&&a)return c}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}pruneToSerializedCharLimit(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n=t.shallowClone(),o=()=>n.serialize().length,i=(a,l)=>{l.children=[];for(let c of a.children){let s=c.shallowClone();if(s.parent=l,l.children.push(s),o()>e){l.children.pop();break}if(i(c,s),o()>e){for(;s.children.length>0&&o()>e;)s.children.pop();if(o()>e){l.children.pop();break}}}};for(i(t,n);n.children.length>0&&o()>e;)n.children.pop();return new r(n,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function UB(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 BB(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?(ec({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?(ec({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 Fw({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:l,showZeroOpacityElements:c,filterByViewport:s,viewportDetails:u,useMPaths:d,importantProperties:p,cdpClient:m,logger:g,callId:h}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let f=(I,j={})=>{},E=r.backendDOMNodeId,S=LB.includes(r.role?.value?.toLowerCase()??"");if(!S&&E===void 0)return f("Filtering out node since it doesn't exist in the DOM"),[];let y=E?i.backendIdToNode[E]:void 0;if(!S&&!y)try{let I=await H(m.send({method:"DOM.describeNode",params:{backendNodeId:E}}),{milliseconds:750,fallback:()=>{g.debug("Timeout getting node from CDP while processing a11y tree")}});if(I&&I.node.nodeName.toLowerCase()==="slot"&&I.node.distributedNodes?.length)g.debug({redirectedDomNode:y,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:I},"Redirecting node to assigned slot");else return f("Filtering out node since it doesn't exist in the DOM",{cdpResult:I}),[]}catch(I){return f("Filtering out node since it doesn't exist in the DOM",{err:I}),[]}if(y&&e&&s&&u&&r.backendDOMNodeId&&!BB(y,u,g,h))return y.momenticIgnored=!0,[];if(y&&y.computedStyles.display==="none")return y.momenticIgnored=!0,[];if(y&&y.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&y.tagName.toLowerCase()!=="input")return y.momenticIgnored=!0,[];if(c===!1)return y.momenticIgnored=!0,[]}let A=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",R=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",w=new dh({domNode:y,id:parseInt(r.nodeId),role:r.role?.value||"",name:A,nameSources:r.name?.sources,content:R,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(I=>Nw.includes(I.name)||Dw.includes(I.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+UB(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:l}),x=n,_=a[t],M=t;if(y?.tagName.toLowerCase()==="iframe"&&y.ownedFrameId){let I=n.childFrames.find(ne=>ne.frameId===y.ownedFrameId),j=o[I?.frameId??""]?.root,ce=a[I?.frameId??""];if(I&&j&&ce){r.childIds&&r.childIds.length>0&&g.debug("Replacing existing node's children with children from the iframe");let ne=j;r.childIds=ne.childIds,x=I,_=ce,M=I.frameId}}let K=y?.childrenBackendIds?.length??0,$=(r.childIds??[]).filter(I=>!!_.get(parseInt(I))).length;if(K>$){let I=r.childIds?.map(ce=>_.get(parseInt(ce))).filter(Boolean).map(ce=>ce?.backendDOMNodeId).filter(ce=>ce!==void 0)??[],j=0;for(let ce of y?.childrenBackendIds??[]){if(I.includes(ce)){j=(r.childIds?.findIndex(tt=>_.get(parseInt(tt))?.backendDOMNodeId===ce)??0)+1;continue}let ne=i.backendIdToNode[ce];if(!ne||ne?.tagName.toLowerCase()!=="svg")continue;let Re=Math.floor(-1*Math.random()*1e7),He={nodeId:Re.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:ce,frameId:M,role:{type:"string",value:"graphics-symbol"}};_.set(Re,He),r.childIds||(r.childIds=[]),r.childIds.splice(j,0,Re.toString()),j++}}if(r.childIds?.length===1&&y){let I=_.get(parseInt(r.childIds[0])),j=I?.role?.value,ce=y.childrenBackendIds;if(I&&j==="StaticText"&&ce.length===1){let ne=i.backendIdToNode[ce[0]];if(ne?.tagName?.toLowerCase()==="span"){let Re=Math.floor(-1*Math.random()*1e7).toString(),He={nodeId:Re,parentId:r.nodeId,ignored:!1,backendDOMNodeId:ne.backendNodeId,frameId:M,childIds:[I.nodeId]};I.parentId=Re,_.set(parseInt(Re),He),r.childIds=[Re]}}}for(let I of r.childIds??[]){if(!I)continue;let j=_.get(parseInt(I));if(!j)continue;let ce=await Fw({node:j,parent:w,domGraph:i,axGraph:o,frameId:M,frameContext:x,inputNodeMap:a,cdpClient:m,logger:g,callId:h,filterByViewport:s,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:l});ce.length&&(w.children=w.children.concat(ce))}if(w.role==="StaticText"&&(w.children=[]),w.children.length===1&&w.children[0].role==="StaticText"){let I=w.name,j=w.children[0]?.name;(I===j||!j)&&(w.children=[])}let k=[];for(let I=w.children.length-1;I>=0;I--){let j=w.children[I];if(j.role!=="StaticText"){k.push(j);continue}if(I===0||w.children[I-1].role!=="StaticText"){k.push(j);continue}w.children[I-1].name+=j.name}if(w.children=k.reverse(),!w.isInteresting(p)&&r.parentId)return y&&(y.momenticIgnored=!0),w.children;for(let I of w.children)I.parent=w;return GB(w),y&&d&&ch(y,i),[w]}function Uw({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:l,iconKnowledgeBase:c,startId:s=1}){r.id=s,s+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:mh.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(l[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let p=Hu(d,i),m=p?c[p.hash]:void 0,g=m?m.description:void 0;m&&(r.properties["data-momentic-description"]=g)}for(let p of r.children)s=Uw({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s,useMPaths:a,domGraph:i,selectorToNodeMap:l,iconKnowledgeBase:c});return s}async function Bw({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:l,importantProperties:c,viewportDetails:s,useMPaths:u,frameContext:d,iconKnowledgeBase:p}){let m=t??"root",g=r[m]?.root;if(!g)throw new Error("A11y tree has no root");let h=CB(),f=w=>{let x=w.allNodes.filter(M=>!M.ignoredReasons?.find($=>Nw.includes($.name))),_=new Map;return x.forEach(M=>{_.set(parseInt(M.nodeId),M)}),_},E={};Object.entries(r).forEach(([w,x])=>{E[w]=f(x)});let S=await Fw({node:g,domGraph:e,parent:null,inputNodeMap:E,axGraph:r,frameId:m,frameContext:d,cdpClient:o,logger:n,callId:h,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:s,useMPaths:u,flagNotActionableNodes:l});if(S.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(S)}`);if(S.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let y={},A={},R={};return Uw({node:S[0],a11yIdNodeMap:y,dataMomenticIdMap:A,selectorToNodeMap:R,domGraph:e,logger:n,callId:h,useMPaths:u,iconKnowledgeBase:p}),new ph(S[0],y,A,R)}function HB(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<kw&&!br.bannedClassSubstrings.some(l=>a.includes(l))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(Hw(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 zB(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,l])=>{let c=r[a]||a.startsWith("aria")||IB.includes(a);if((br.relevantElementAttributes.includes(a)||zw(a,t))&&!c){let u=HB(a,l,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&Mw.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of Mw)if(e.attributes.style.includes(`position: ${a}`)){n=a;break}}n&&o.push(`position: ${n}`);let i;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(i="opacity: 0"),i&&o.push(i);for(let a of t?.styles??[]){let l=a.split(":"),c=l[0]?.trim(),s=l[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&s!==void 0&&u!==void 0&&(s==="*"||u===s)){let d=e.computedStyles[c],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(r.style=o.join("; "))}function GB(r){let e=r.properties.class;if(typeof e=="string"&&e.includes("cm-content")){r.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){r.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),r.children.length>0&&(r.children[r.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(r.tagName==="table"){let i=[],a=r.children.find(c=>c.tagName==="thead");if(a){let c=a.children.find(s=>s.tagName==="tr");if(c){let s=c.children.filter(u=>u.tagName==="th");s.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(Qe(u.name,100,!1))}),i?.length!==s.length&&(i=void 0)}}let l=0;for(let c of r.children)if(c.tagName==="tbody")for(let s=0;s<c.children.length;s++){let u=c.children[s];if(u.tagName!=="tr")continue;if(s===0&&!i?.length){let m=u.children.filter(g=>g.tagName==="th");if(m.length){if(i=m.map(g=>Qe(g.name,100,!1)),i.length===m.length)continue;i=void 0}}l+=1,u.properties["row-index"]||(u.properties["row-index"]=l);let d=u.children.filter(m=>m.tagName==="td"||m.tagName==="th"),p=d.length===i?.length;d.forEach((m,g)=>{m.tagName!=="th"&&(m.properties["col-index"]||(m.properties["col-index"]=g+1),p&&(m.properties.col||(m.properties.col=i[g])))})}}}function VB(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function Hw(r,e){if(e&&Gw(r,e))return!0;if(br.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(br.alwaysInterestingClassNames.includes(r))return!0;for(let t of br.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function zw(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 Gw(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 zu=class r{constructor(e,t,n,o,i){this.session=e;this.logger=t;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:t,pageGetter:n,defaultTimeoutMs:o}){let i=t(),a=n(),l,c;for(let u=0;u<2;u++)try{l=await H(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new C("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await Z(500),c=d}if(!l)throw c;let s=new r(l,e,t,n,o);try{await H(s.registerHandlers(l),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw s.cdpFullyDead=!0,new C("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return s}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(t){this.logger.warn({err:t},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(t)}`)}),e.on("Page.navigatedWithinDocument",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(t)}`)}),e.on("Page.lifecycleEvent",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(t)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await H(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new C("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 H(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 H(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new C("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 H(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 H(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 ba="<empty>";function jB(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 jw(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||jB(r.url)}async function $B(r,e){let t=await r.send({timeout:3e3,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:3e3,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function va({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:3e3,method:"Page.getFrameTree",params:{}}),r.send({timeout:3e3,method:"DOM.getDocument",params:{depth:0}})]),s=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(jw(d.frame))return null;try{return await $w({cdpClient:r,rawFrameTree:d,indices:[p],parent:n,warnings:o,logger:t})}catch(m){return o.push(`Failed to get child frame: ${m}`),null}}),u=await Promise.all(s);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function $w({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,l=await $B(r,a),c=l.attributes??[],s=null,u=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=so(c,g);h&&(u.push(`${g}=${JSON.stringify(h)}`),g==="src"&&(s=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:s,childFrames:[],parent:n,domNode:l},m=(e.childFrames??[]).map(async(g,h)=>{if(jw(g.frame))return null;try{return await $w({cdpClient:r,rawFrameTree:g,indices:[...t,h],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(m)).filter(g=>g!==null),d}async function WB(r){try{return await r.owner().count()===1}catch{return!1}}async function qB(r){try{return await r.count()===1}catch{return!1}}async function ln(r,e){let t=[],n=r;for(;n.parent.type==="frame";)t.push(n.parent),n=n.parent;t.reverse();let o=e,i=[];for(let s of t){let u=!1;for(let d of[...s.locationData.attributeSelectors,ba]){let p=o.frameLocator(d===ba?"iframe":`iframe[${d}]`);if(await WB(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new C("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${s.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let s of[...r.locationData.attributeSelectors,ba]){let u=o.locator(s===ba?"iframe":`iframe[${s}]`);if(await qB(u)){a=u,i.push(s);break}}if(!a)throw new C("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${r.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let l=await a.evaluateHandle(s=>s,{timeout:1e3}),c=await l.asElement().contentFrame();if(!c)throw new C("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await l.dispose(),{frame:c,mPathSelectorTokens:i}}function Vw(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 Ww({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let l=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===ba?l=l.length===1?l[0].childFrames:[]:l=l.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],s=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(s===ba?c=l:c=l.filter(u=>u.locationData.attributeSelectors.includes(s)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await ln(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with mpath ${t.mPathSelectorTokens.join(" > ")}`)}if(t.frameSrcRegex){let l=new RegExp(t.frameSrcRegex),c=Vw(o,s=>!!s.src&&l.test(s.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await ln(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with src regex ${t.frameSrcRegex}`),t.frameSrcRegex=void 0}if(t.frameUrlRegex){let l=new RegExp(t.frameUrlRegex),c=Vw(o,s=>!!s.url&&l.test(s.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await ln(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with url regex ${t.frameUrlRegex}`),t.frameUrlRegex=void 0}let a=o;for(let l=0;l<t.indices.length-1;l++)a=a[t.indices[l]]?.childFrames??[];if(n=a[t.indices[t.indices.length-1]],n)return i.push(`Found unique frame with indices ${t.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await ln(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new $r("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function Gu(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function gh(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function qw(r){let e=gh(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let l=a.shift();l.src&&o.push(l.src),l.url&&i.push(l.url),a.push(...l.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function Kw(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 Yw({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await KB({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 KB({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await $o({promiseGenerator:async()=>r.evaluate(async i=>{let a=i.scrollTop;i.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(c=>setTimeout(c,250));let l=Date.now();for(;Date.now()-l<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(s=>setTimeout(s,250))}}),timeoutMs:2e3,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}function Xw(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:l}of r)(!l||l.matches({url:n.url(),method:n.method()}))&&(o[i]=a);await t.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as XB}from"crypto";function Jw(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function Qw(r){let{route:e,mock:t,entry:n,debugData:o,requestId:i,requestRecorders:a,logger:l}=r,c={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(m=>[m.name,m.value]),body:n.request.postData?.text}},s;if(t.fetchOriginalResponse){let m=await e.fetch();s={body:await m.text(),options:{status:m.status(),statusText:m.statusText(),headers:Object.entries(await m.headers())}}}let u=await YB(t,c,s),d={};u.headers.forEach((m,g)=>{d[g]=m});let p={body:await u.text(),contentType:u.headers.get("content-type")||"text/plain",headers:d,status:u.status};await e.fulfill(p);try{n.response={status:p.status,statusText:u.statusText,headers:Object.entries(p.headers).map(([m,g])=>({name:m,value:g})),cookies:[],content:{mimeType:p.contentType,text:p.body},_mocked:!0},Js(o,n,i);for(let m of Object.values(a))m.onRequestComplete(i,n)}catch(m){m.message.includes("has been closed")||l.warn({err:m},"Failed to add response to HAR")}}async function YB(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 hh(r){try{await JB(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function JB(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:l}=r,c=XB(),s=await nh(e,n);try{Js(o,s,c);for(let d of Object.values(a))d.onRequestStart(c,s)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=Jw(n,l);u?await Qw({logger:i,route:t,mock:u,entry:s,debugData:o,requestId:c,requestRecorders:a}):await QB({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:s,requestId:c})}async function QB({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let l=await e.response();if(!l||!i)return;await uw(i,e,l),Js(t,i,a);for(let c of Object.values(o))c.onRequestComplete(a,i)}catch(l){l.message.includes("has been closed")||n.warn({err:l},"Failed to add response to HAR")}}async function ZB(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 eH(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 Vu(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 fh(r){let e=r.request(),t=r.status(),n=r.headers(),o=await eH(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await ZB(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var lo=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:xc(t,this.requestMatcher.urlMatcher)}};function ju(r){let e=new URL(r.request().url());return/^127\./.test(e.hostname)||/^192\.168\./.test(e.hostname)||/^10\./.test(e.hostname)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e.hostname)||e.hostname==="localhost"?r.abort():r.fallback()}async function Zw({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:l,properties:c}=r.target;if(l){i.error({error:l,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let s=n.parentFrame()?n.url():void 0,d=n.page().frames().map(g=>g.url());i.debug({frameUrl:s,...r},"Passive click event captured on element");let p,m;if(s)try{let g=await n.frameElement();p=await H(g?.boundingBox(),{milliseconds:3e3})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:s});if(h.urlRegex)m={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(g){i.warn({err:g},"Failed to construct iframe details for recorded action, using hardcoded URL only"),m={type:"url",url:s}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:m,frameBoundingBox:p})}catch(g){i.error({err:g},"Failed to transform passive click action")}})()}import{randomUUID as cn}from"crypto";import tH from"js-beautify";var rH=["Dead"],$u=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:t,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onStepRecorded(l,c)},onActionReceived:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onActionReceived?.(l,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:cn(),type:"PRESET_ACTION",command:mn(e)}}),this.nextStepOffset++,t}async recordElementAction(e){let{type:t,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,l=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=l,s;switch(e.frameConfig?e.frameBoundingBox?s={x:e.frameBoundingBox.x+n.properties.boundingBox.x,y:e.frameBoundingBox.y+n.properties.boundingBox.y,width:n.properties.boundingBox.width,height:n.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):s=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let h=mn(i);a={id:cn(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}}}};break}case"SELECT":{i="SELECT_OPTION";let h=mn(i);a={id:cn(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:c},cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=mn(i);a={id:cn(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:Pe(this.logger),boundingBox:s}}}};break}default:throw new Error(`Unknown action type: ${t}`)}let u;e.offset===void 0?(u=this.nextStepOffset,this.nextStepOffset++):u=e.offset,this.callbacks.onActionReceived?.(a,u);let d=e.target.browserState;try{d=tH.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=QA(d,"data-momentic-interacted",4e4)}catch{}let p;try{p=(await this.generator.getReverseMappedDescription({target:d,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:n.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...Pe(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=l}let m=this.recordedSteps.get(u)?.step??a,g=m?.command;g&&"target"in g&&g.target?(g.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...m,command:g},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(rH.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=mn("TYPE");i={id:cn(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=mn("PRESS");i={id:cn(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,l=this.nextStepOffset-1,c=this.recordedSteps.get(l),s=c?.step,u=s?.command;if(n){if(u?.type===i.command.type){let d=u.value,p=i.command.value;i={id:cn(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},a=l}else if(u?.type==="CLICK"&&i.command.type==="TYPE")s.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=l;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:cn(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=l}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let t=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_DOWN"&&l.deltaY?(i+=l.deltaY,c=a):l?.type==="SCROLL_UP"&&l.deltaY?(i-=l.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_DOWN":"SCROLL_UP",u=mn(s);u.deltaY=Math.abs(i);let d={id:cn(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_RIGHT"&&l.deltaX?(i+=l.deltaX,c=a):l?.type==="SCROLL_LEFT"&&l.deltaX?(i-=l.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=mn(s);u.deltaX=Math.abs(i);let d={id:cn(),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 Sh}from"zod";var CRe=Sh.object({type:Sh.literal("url"),url:Sh.string()});var Wu=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:l,enricher:c,iconKnowledgeBase:s,userBrowserSettings:u}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=l,this.enricher=c,this.iconKnowledgeBase=s,this.userBrowserSettings=u,this.userBrowserSettings.importantStyles)for(let d of this.userBrowserSettings.importantStyles){let p=d.split(":");if(p.length!==2){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}let m=p[0]?.trim(),g=p[1]?.trim();if(m===void 0||g===void 0){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(m)||this.computedStylesToFetch.push(m)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userBrowserSettings.autoExpandIframes)return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),n=gh(e),{frame:o,mPathSelectorTokens:i}=await ln(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 va({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await Ww({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(Gu(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:Gu(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await Yw({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await va({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[H(n.evaluate(e,t),{milliseconds:2e3})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),s=c.url;s==="about:blank"||s.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(ln(c,n).then(({frame:u})=>H(u.evaluate(e,t),{milliseconds:2e3})).catch(u=>(this.logger.warn({err:u,frameUrl:c.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(i)).filter(c=>c!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),t=await va({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(t.childFrames),o=[];for(;n.length>0;){let i=n.shift();n.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:t,logger:n}){return this.getDOMTree({devicePixelRatio:e??1,signal:t,logger:n??this.logger})}async getA11yTree(e){let t={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),a,l,c=null;if(this.frameConfig?.type==="url"){if(a=await vr({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new C("ActionFailureError","Got null frame details despite active frame config");l=a.handle,c=l.frameId}else this.userBrowserSettings.autoExpandIframes?(l=await vr({fn:()=>va({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(l={type:"root",page:i,childFrames:[]},c=null);await vr({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:l.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let s=await vr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await vr({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:l.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await vr({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:s,startingFrameId:c,frameContext:l,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(p=>p>750)&&n.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=s,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:En,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=xw({node:o,domGraph:this.domGraph});return _w(e,i)}else return this.getLocatorFromBackendId(t,n.backendNodeId)}async getLocatorFromBackendId(e,t){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:t},timeout:2e3});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await Iw(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(kr(o))}getNodeUsingMPathSelector(e){let t=this.selectorToNodeMap[e];if(t)return t;let n=e.split(" > "),o="";for(let i=n.length-1;i>=0;i--){let a=n.slice(i).join(" > ");if(this.selectorToNodeMap[a]){o=a;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:t=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,l,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await va({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),a=await this.getMatchingFrameByUrlWithCdp(i,e),n.info({frameId:a.handle.frameId,url:a.handle.url,src:a.handle.src,locationData:a.handle.locationData},`Found matching frame using ${a.matchType}`);break}catch(s){if(l=s,s instanceof C&&s.reason==="UserInfrastructureError")throw s;c%3===0&&this.logger.warn({attempt:c,err:s},"Failed to resolve active frame, retrying..."),await Z(500,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:Gu(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw l}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let l=i.shift(),c=l.domNode;i.push(...l.childFrames);let s=so(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!s&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[s,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:l,matchType:"regex",...await ln(l,o)});break}}else if(n.trim()===d.trim()){a.push({handle:l,matchType:"url",...await ln(l,o)});break}}}if(a.length===1){let l=a[0];return this.userBrowserSettings.autoExpandIframes||(l.handle.childFrames=[]),l}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new C("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:l,showZeroOpacityElements:c,flagNotActionableNodes:s}){let u=await Bw({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:s,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userBrowserSettings.importantAttributes,classes:this.userBrowserSettings.importantClasses,styles:this.userBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:l,useMPaths:this.userBrowserSettings.visualActions});if(!u||!u.root)throw new Error("Accessibility tree appears empty");return{tree:u}}async addMomenticIds({rootPage:e,childFrames:t,frameFilter:n,logger:o}){if(this.userBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),l=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let s=async()=>{try{let{frame:u}=await ln(c,e);i=await this.addMomenticIdsHelper(u,i)}catch(u){c.url!=="about:blank"&&o.warn({err:u},"Error adding momentic IDs to child frame, continuing...")}};l.push(s())}await Promise.all(l)}async addMomenticIdsHelper(e,t){if(this.userBrowserSettings.visualActions)return t;let n=this.logger;return await dt({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:2e3,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(i){n.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??t}getPageDomain(e){try{let t=new URL(e);if(!t.hostname)return null;let n=t.hostname.split("."),o=n.length>2?n.slice(-2).join("."):t.hostname;return`${t.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:t,handle:n}){try{let{shouldUnroll:o,reason:i}=await this.decideChildFrameUnrollEligibilityHelper({domNode:n.domNode});return{shouldUnroll:o,reason:i}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let i=`Got error when determining whether to filter frame ${n.frameId} with url ${n.url}, allowing it to be fetched: ${o}`;return t?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let t=e.attributes??[];if(so(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=so(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:3e3,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:3e3,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let a of i.computedStyle){if(a.name==="display"&&a.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(a.name==="visibility"&&a.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(a.name==="opacity"&&a.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:t,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let l=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(m){i.warn({err:m},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,s;for(let m=0;m<3;m++)try{s=await vr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,signal:a,logger:i});break}catch(g){c=g,i.warn({err:g},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!s)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=s,!this.userBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),p=[];for(;d.length>0;){let m=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:m,warnings:l});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;l.push(`Got error when determining whether to filter frame ${m.frameId} with url ${m.url}, allowing it to be fetched: ${h}`)}d.push(...m.childFrames);let g=async()=>{try{let h=await vr({fn:()=>this.getRawA11yTreeForFrame({frameId:m.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${m.frameId}`,logObject:o,signal:a,logger:i});u[m.frameId]=h}catch(h){i.warn({err:h,url:m.url,src:m.src},`Error getting raw a11y tree for child frame ${m.frameId}, continuing...`)}};p.push(g())}return await Promise.all(p),l.length>0&&this.logger.warn({warnings:l},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await vr({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes;else{let a=(await vr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:2e3}),codePath:"cdp-get-root-ax-node",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).node.backendDOMNodeId;o=(await vr({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:t,logger:n}){let o,i=0,a;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:this.computedStylesToFetch},timeout:3e3}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(l){await Z(500,t),i++,a=l}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new C("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 Cw({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=qw(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 yh(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var bh=Aa(vh(),"momentic","chromium"),RH=Aa(vh(),"video"),Ku=process.env.TWO_CAPTCHA_KEY,aC=TH(iC);aC.use(bH({provider:{id:"2captcha",token:Ku},visualFeedback:!0}));var Rr=class r{static USER_AGENT=EH["Desktop Chrome"].userAgent;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;lastIconKnowledgeBaseUpdateTime=0;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;flagStore;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,flagStore:t,enricher:n,browser:o,context:i,page:a,baseUrl:l,logger:c,userBrowserSettings:s,viewport:u,properties:d,clientCallbacks:p,iconKnowledgeBase:m}){if(EE(s),this.storage=e,this.flagStore=t,this.enricher=n,this.browser=o,this.context=i,this.page=a,this.baseUrl=l,this.logger=c,this.userControlledBrowserSettings=s,this.viewport=u,this.properties=d,this.clientCallbacks=p,d.recordVideo){let g=this.page.video();g&&this.videos.push(g)}this.iconKnowledgeBase=m}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={[Fu]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:YA.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})];t&&await this.page.reload();let i=l=>this.handleNewPageEvent(l);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)});let a=Promise.all(o);await Promise.all([a]),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&hH()==="darwin"&&lH("system_profiler SPDisplaysDataType").toString().includes("Retina")?(T.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 zu.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new Wu({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let t=e.sessionId,n=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=n,this.clientCallbacks?.onScreencastFrame?.(n,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:t}})}catch{}})()})}))}static async init({baseUrl:e,logger:t,storage:n,flagStore:o,enricher:i,userBrowserSettings:a,contextArgs:l,recordVideo:c,iconKnowledgeBase:s,callbacks:u}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let d;switch(a.browserType){case"Google Chrome":d="chrome";break;case"Chrome for Testing":d=void 0;break;case"Chromium":d="chromium";break;default:d="chromium";break}let p={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:d},m={...l??{},geolocation:l?.geolocation||Gn,locale:l?.locale||Hn,timezoneId:l?.timezoneId||zn,colorScheme:l?.colorScheme,httpCredentials:a.basicAuthorization?{username:a.basicAuthorization.username??"",password:a.basicAuthorization.password??""}:void 0,javaScriptEnabled:a.disableJavaScript?!1:void 0,ignoreHTTPSErrors:a.ignoreHttpsErrors??!1,userAgent:a.userAgent??r.USER_AGENT,viewport:l?.viewport??Pt},g=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"],h=null,f,E,S={systemDevicePixelRatio:l?.deviceScaleFactor,recordVideo:c,isNewHeadless:!1};(d==="chrome"||d==="chromium")&&(S.isNewHeadless=!0,p.headless&&g.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&g.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),a.disableGpu&&g.push("--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-audio-input","--disable-audio-output");let y=a.localChromeExtensionPaths?.map(R=>R.startsWith("~")?Aa(vh(),R.slice(1)):R);if(y?.length){if(d===void 0)throw new C("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let _ of y){let M=Aa(_,"manifest.json");if(!qu(M))throw new C("UserConfigurationError",`Chrome extension path ${M} does not exist.`)}if(yn)throw new C("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let R=Aa(bh,`momentic-session-${Date.now()}`);if(!qu(R))try{cH(R,{recursive:!0})}catch(_){throw new C("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${bh} folder: ${_}`)}let w=[...g],x=y.map(_=>yH(_)).join(",");w.push(`--disable-extensions-except=${x}`),m?.deviceScaleFactor&&w.push(`--force-device-scale-factor=${m.deviceScaleFactor}`,`--device-scale-factor=${m.deviceScaleFactor}`),m.viewport&&w.push(`--window-size=${m.viewport.width},${m.viewport.height}`),f=await iC.launchPersistentContext(Aa(bh,`momentic-session-${Date.now()}`),{...p,...m,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:w,baseURL:e}),t.debug({sharedContextOptions:m,sharedBrowserOptions:p,userBrowserSettings:a,chromeArgs:w,flags:o.getAllFlags(),properties:S,baseUrl:e},"Browser initialization context args (persistent)"),E=f.pages()[0]}else{h=await aC.launch({...p,args:g});let R={...m,baseURL:e,recordVideo:c?{dir:RH}:void 0};f=await h.newContext(R),t.debug({contextArgs:R,sharedBrowserOptions:p,chromeArgs:g,userBrowserSettings:a,flags:o.getAllFlags(),properties:S,baseUrl:e},"Browser initialization context args (standard)"),E=await f.newPage()}yn&&await f.route("**",ju);let A=new r({browser:h,context:f,page:E,baseUrl:e,logger:t,storage:n,flagStore:o,enricher:i,userBrowserSettings:a,viewport:m.viewport||Pt,properties:S,clientCallbacks:u,iconKnowledgeBase:s});return await A.initialize({grantPermissions:!0,runInitScripts:!1}),A}static async fromExistingContext({context:e,storage:t,flagStore:n,enricher:o,userBrowserSettings:i,logger:a}){let l=e.pages()[0];if(!l)throw new Error("No page found in existing context");let c=l.viewportSize(),s=l?.url(),u=new r({browser:e.browser(),context:e,page:l,baseUrl:s,logger:a,storage:t,flagStore:n,enricher:o,userBrowserSettings:i,viewport:c,properties:{isNewHeadless:!0},clientCallbacks:void 0,iconKnowledgeBase:null});return await u.initialize({grantPermissions:!1,runInitScripts:!0}),u}async handleAvailableTabsChangeHelper(){try{let e=await lh(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=Eh(),o=`${e}-${n}`,i=Date.now(),a=!1,l=async()=>{try{await H(t(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(c){c.name!=="AbortError"&&this.logger.error({err:c,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],a=!0}};this.pageLoadPromises[o]=l().catch(()=>{}),a&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let t=async()=>{if(this.closed)return;this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let n=this.context.pages();for(let o=n.length-1;o>=0;o--){let i=n[o];if(!(!i||i.isClosed()||!Wo(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=Eh(),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=>{aw(e,o,this.debugData,a,this.logger)});let i=async()=>{await cw(t,this.debugData,e),await e.route("**/*",async(a,l)=>{await hh({pageId:t,route:a,request:l,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",Xw(this.customHeaders,this.logger)),yn&&await e.route("**/*",ju),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){if(!this.flagStore.isBooleanFlagEnabled("icon_knowledge_base")||this.page.isClosed()||this.page.mainFrame()!==e||!this.iconKnowledgeBase||!this.clientCallbacks?.onSvgsCollected||Date.now()-this.lastIconKnowledgeBaseUpdateTime<5e3)return;this.lastIconKnowledgeBaseUpdateTime=Date.now();let t=await this.stateManager.getDomGraph({devicePixelRatio:this.devicePixelRatio}),n=Pw({domGraph:t,flagStore:this.flagStore,logger:this.logger,existingHashes:this.iconKnowledgeBase});if(n.forEach(l=>{this.iconKnowledgeBase[l.hash]=l}),!n.length)return;let o=Pe(this.logger),i={pageUrl:e.url(),firstSeenTime:Date.now(),hostname:gH()};for(let l of["runId","testId"])o[l]&&(i[l]=o[l]);let a={metadata:i,newSvgs:n};this.clientCallbacks.onSvgsCollected(a)}handleFrameNavigationEvent(e){let t=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${t.slice(0,50)}-${n}`;if(!t||t==="about:blank"||!Wo(t)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let i=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o,signal:this.abortSignal}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(l){this.logger.warn({err:l},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(a){a.name!=="AbortError"&&this.logger.warn({err:a},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>i())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let n={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(n[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let i=window;i._MOMENTIC_ICON_KNOWLEDGE_BASE=o},n)}catch(t){this.logger.warn({err:t},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await H(ih(this.getBrowserCallbacks()),{milliseconds:1e3})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,t,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<8e3;){a++,n?.throwIfAborted();try{if(await dt({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:1e3,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(l){if(i++,i>=3){t.warn({err:l},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await Z(500),a%2===0&&t.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),dt({root:e,fn:()=>{let t=window;if(!t?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return t.getFullHtmlTree()},arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,t=[],n=new Map;document.querySelectorAll("input,textarea,[contenteditable]").forEach(o=>{n.set(o,{value:o.style.getPropertyValue("caret-color"),priority:o.style.getPropertyPriority("caret-color")}),o.style.setProperty("caret-color","transparent","important")}),t.push(()=>{for(let[o,i]of n)o.style.setProperty("caret-color",i.value,i.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of t)o();delete e._MOMENTIC_SCREENSHOT_CLEANUP}},void 0,"stabilizing page for screenshot")}catch(e){(!(e instanceof Error)||!e.message.includes("Execution context was destroyed"))&&this.logger.warn({err:e},"Failed to stabilize page before screenshot, continuing...")}}async removeScreenshotStabilization(){try{await this.evaluateFunctionInPage(()=>{window._MOMENTIC_SCREENSHOT_CLEANUP?.()},void 0,"removing screenshot stabilization")}catch{}}async screenshot(e){let{retries:t=1,stabilizeBeforeScreenshot:n=!1}=e,o=this.page.url();n&&await this.stabilizePageForScreenshot();let i=Date.now();try{await this.fixViewportForNewHeadless();let a=await this.screenshotHelper({...e,retries:t});if(a.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(a.length===0)throw new Error("Got empty screenshot");return a}catch(a){if(t<=0||a.message.includes("has been closed"))throw a;return this.logger.warn({err:a,pageUrl:o},"Failed taking screenshot, retrying..."),await Z(250),this.screenshot({...e,retries:t-1})}finally{Date.now()-i>1e3&&this.logger.warn({pageUrl:o,duration:Date.now()-i},"Screenshot took longer than expected"),n&&await this.removeScreenshotStabilization()}}async screenshotHelper({locator:e,quality:t,saveToDiskPath:n,timeout:o,respectActiveFrame:i,clearHighlights:a=!1}){a&&await this.clearHighlights(),i&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let l=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:o??2e3}),c=Buffer.from(l.data,"base64"),s=await nC.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(s.bitmap.width!==u||s.bitmap.height!==d)&&(c=await s.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&dH(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:3e3});if(!p)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:m,y:g,width:h,height:f}=p;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");m=Math.floor(m),g=Math.floor(g),h=Math.floor(h),f=Math.floor(f);try{let E=await nC.fromBuffer(c),S=E.bitmap.width,y=E.bitmap.height;m=Math.max(0,Math.min(m,S-1)),g=Math.max(0,Math.min(g,y-1)),h=Math.max(1,Math.min(h,S-m)),f=Math.max(1,Math.min(f,y-g)),c=await E.crop({x:m,y:g,w:h,h:f}).getBuffer("image/jpeg")}catch(E){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${g}) with size (${h}, ${f}): ${E}`)}finally{"dispose"in e&&await e?.dispose()}return c}getViewport(){return this.viewport?this.viewport:this.page.viewportSize()}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){NT(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();t||(await this.waitForPageLoad(),await this.waitForDOMStability());let i=!1,a;for(let c=0;c<3;c++)try{await this.page.goto(e,{timeout:n,waitUntil:"domcontentloaded"}),i=!0;break}catch(s){if(a=s,this.abortSignal?.throwIfAborted(),this.logger.warn({err:s},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await Z(500),a.message.includes("Timeout")&&a.message.includes("exceeded")||a.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:1e3})}if(!i)throw new C("UserInfrastructureError",a?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let l=this.url();if(ZA.has(l))throw new C("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 dt({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;return n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n}:void 0},arg:void 0,timeout:1e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(t){this.logger.warn({err:t},"Failed to get active element");return}}async directTypeHelper(e,t={},n=!1){let o=await this.getActivePageOrFrame();await Sw({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 Z(250),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}t.clearContent&&(t.forceClearContent||i?.tag==="input"||i?.tag==="textarea"?(process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25)):this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:t.delay??wf}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:2e3})}catch(t){this.logger.warn({err:t},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async n=>{let o=n.scrollTop;n.scrollIntoView(),await new Promise(a=>setTimeout(a,250));let i=Date.now();for(;Date.now()-i<1e3;){let a=n.scrollTop;if(a===o)break;o=a,await new Promise(l=>setTimeout(l,250))}},void 0,{timeout:2e3})}catch(n){this.logger.warn({err:n},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:t}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(t.locator),!0}catch(t){return this.logger.debug({err:t,id:e},"Failed to highlight target"),!1}}async highlight(e){return Uu({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let t=new URL(e).origin;if(t==="null")return;this.originsVisited.add(t)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;t.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(t),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:1e3}),this.originsVisited.delete(o);let t=this.context.pages().indexOf(this.page),n=[...this.context.pages()];for(let o=0;o<n.length;o++){let i=n[o];if(i.isClosed())continue;let a=i.url();try{this.originsVisited.delete(new URL(a).origin)}catch{}await iw(i,this.logger),o!==t&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${a}`),await i.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let t=[];for(let i of e.cookies??[]){let a=await this.setCookie(i);t=t.concat(a)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:1e3});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:1e3,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(l){this.logger.warn({err:l,origin:i},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${n} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await ow(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 nw(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 C("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return lh(this.context,e)}saveA11yDetailsToCache(e,t){t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,delete t.serializedForm,delete t.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:t,locator:n,forceSaveNewCssSelectors:o,startingBoundingBox:i,allowNotActionableNodesOverride:a,logger:l=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let c=await this.fetchHtmlAttributes({locator:n,logger:l,startingBoundingBox:i,allowNotActionableNodesOverride:a}),s=!1;for(let u of["generatedSelectors","serializedHtml","nodeOnlySerializedHtml","hybridSelector"]){let d=c?.[u];if(d&&!t[u]){s=!0;break}if(d&&JSON.stringify(d)!==JSON.stringify(t[u])){s=!0;break}}c&&(o||s)&&(t.generatedSelectors=c.generatedSelectors,t.serializedHtml=c.serializedHtml,t.nodeOnlySerializedHtml=c.nodeOnlySerializedHtml,t.hybridSelector=c.hybridSelector)}catch(c){if(c instanceof Wr)throw c;l.warn({err:c},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:l,boundingBox:i})}catch(c){l.debug({err:c},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!qg.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:3e3})),!o||!o.width||!o.height)return n.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:i=0,y:a=0,width:l=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-l)<1&&Math.abs(e.boundingBox.height-c)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-a)<1)return{scrollPerformed:!0};e.boundingBox=o;let s=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(s),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({locator:e,requirements:t}){let n={};if(t?.boundingBox){let o=await e.boundingBox({timeout:3e3});if(!o||!o.width||!o.height)throw new C("ActionFailureError","Element does not have a bounding box as required");n.boundingBox=o??void 0}if(t?.text){let o=await e.innerText({timeout:3e3});n.text=o?.trim()}if(t?.attributes&&t.attributes.length>0){let o={};for(let i of t.attributes){let a=i.trim().toLowerCase();if(!(!a||br.bannedAiRequiredCacheAttributes.includes(a)))try{let l=await e.getAttribute(a,{timeout:3e3});l!==null&&(o[i]=l)}catch(l){this.logger.warn({err:l,attr:i},"Failed to fetch required attribute, continuing...")}}n.attributes=o}return n}async getAdditionalElementDetails({mainLocator:e,additionalElement:t,root:n,logger:o}){let i=this.stateManager.a11yIdToNodeMap[t.id];if(!i)return;let a=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:n,node:i});if(e.contentFrame!==a.contentFrame)return;let l=await this.fetchHtmlAttributes({locator:a,logger:o});if(!l?.generatedSelectors||l.generatedSelectors.length===0)return;let c={selectors:l.generatedSelectors};return t.requirements&&(c.requirements=await this.getElementRequiredValues({locator:a,requirements:t.requirements})),c}async getAdditionalElementsDetails({mainElementId:e,mainLocator:t,additionalElements:n,root:o,logger:i}){let a=new Set,l=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let s=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!s)continue;l.push(s)}catch(s){this.logger.warn({err:s,additionalElement:c},"Failed to fetch additional element details, continuing...")}return l}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:l}){t&&(o.requirements=await this.getElementRequiredValues({locator:i,requirements:t})),n&&(o.additionalElements=await this.getAdditionalElementsDetails({mainElementId:e,mainLocator:i,additionalElements:n,root:a,logger:l}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:l}){if(e<0)throw new C("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new C("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let s=this.stateManager.frameConfig,u,d,p,m;if(this.userBrowserSettings.autoExpandIframes&&!s&&c.parentFrame){let S=c.parentFrame,{cache:y,config:A}=await this.stateManager.getAutoFrameDetailsFromHandle(S);d=y,p=A,u=A.frame,m="auto iframe"}else c.parentFrame&&s?(p=s,u=await this.getActivePageOrFrame(),m="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),m="should not be possible");let g=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:u,node:c}),h={id:e,inputDescription:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:Pe(i),frameCache:d},f,E=!1;o||(p&&(i.info({frameConfigSource:m,frameConfig:Kw(p)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),E=!0),await this.updateCacheWithNewNodeDetails({node:c,target:h,locator:g,logger:i,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:l,target:h,root:u,locator:g,logger:i}));try{return{resolution:{locator:g,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:h,frameConfig:p,frameConfigSource:m}}finally{E&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,t,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowNotActionableNodesOverride:l}=n;if(t.frameCache&&this.userBrowserSettings.autoExpandIframes){let m,g=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),g=!0;break}catch(f){m=f,await Z(500,a)}if(!g)throw m}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let s=Date.now(),u=0,d=0,p;for(;Date.now()-s<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let m=u===2||Date.now()-s>this.smartWaitingTimeout-2e3&&u%2===0;try{p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,logger:m?i:En,allowNotActionableNodesOverride:l,signal:a});break}catch(g){if(g instanceof ns)break;if(g instanceof Wr){if(d++,d>2)throw i.error({err:g},"Got multiple cache disqualification errors, giving up"),g;i.warn({err:g},"Got cache disqualification error, waiting and retrying resolution"),await Z(500,a)}a?.throwIfAborted(),m&&i.info({err:g},`Could not resolve target using primary cache only (x${u})`),await Z(500,a)}}return p||(p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:l}),t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=Pe(i),i.info({decisions:p.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:p?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),p}async resolveTargetHelper({root:e,target:t,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){let l=Ra(t),c=[],s=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),u;if(t.generatedSelectors||t.hybridSelector){let d;try{d=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a})}catch(p){u=p,p instanceof $r&&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:Ra(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw u;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let d=await this.resolveTargetWithSecondaryMethods({root:e,tree:s,target:t,decisions:c,logger:o,signal:i,allowNotActionableNodesOverride:a});if(d)return d}throw new $r(`Could not find any relevant node given target: ${JSON.stringify(l)}`,c)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o}){if(!t.nodeOnlySerializedHtml)throw new ns("Insufficient data to resolve target using primary methods (missing node HTML)");let i=this.userControlledBrowserSettings.hybridSelectorMode,a={ldistThreshold:.05,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements},{css:l,hybrid:c}=await dt({fn:S=>window.evaluatePrimaryCaches(S),arg:{cssParams:{selectors:t.generatedSelectors??[],cachedElementSerialized:t.nodeOnlySerializedHtml,opts:a},hybridParams:i&&t.hybridSelector?{nodes:t.hybridSelector,cachedElementSerialized:t.nodeOnlySerializedHtml,opts:a}:void 0},root:e,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),s,u,d=[];if(i==="prefer"&&c?.result){s=c.result;let S={type:"HYBRID_SELECTOR",matched:!0,logs:c.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};d.push(S),u="HYBRID_SELECTOR"}else if(l?.result){s=l.result;let S=`${s.workingSelectors.length} CSS selectors matched the following element: ${s.serializedElement}`,y=s.workingSelectors.slice(0,5);d.push({type:"CSS_SELECTOR",matched:!0,logs:l.logs,reason:S,selectors:y}),n.debug({reason:S,workingSelectors:y},"Resolved with CSS selectors"),u="CSS_SELECTOR"}else throw d.push({type:"CSS_SELECTOR",matched:!1,reason:l.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:l.logs}),c&&d.push({type:"HYBRID_SELECTOR",matched:!1,reason:c.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:c.logs}),new $r("Cache evaluation failed",d);let p,m,g,h=!1;if(this.userBrowserSettings.visualActions){let S=s.mPath;if(!S)throw new Error("Found element did not have an mPath despite using visual actions");let y=S.join(" > ");p=e.locator(y),m=this.stateManager.getNodeUsingMPathSelector(y)}else if(s.dataMomenticId!==void 0)g=parseInt(s.dataMomenticId),m=this.stateManager.dataMomenticIdToNodeMap[g],"workingSelectors"in s?(p=e.locator(s.workingSelectors[0]),h=s.workingSelectors.length<5):p=e.locator(kr(g));else throw new C("InternalWebAgentError","Received an element resolution result with no identifying attributes");i&&t.hybridSelector&&(c?.logs.length===1?n.warn({hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution rejected, continuing..."):c?.result?l?.result&&c?.result&&c.result.serializedElement!==l.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(l.result.mPath)!==JSON.stringify(c.result.mPath)?n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):l.result.dataMomenticId!==c.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let f=Ra(t);await this.updateCacheWithNewNodeDetails({node:m,target:t,locator:p,logger:n,startingBoundingBox:s.boundingBox,forceSaveNewCssSelectors:h,allowNotActionableNodesOverride:o});let E=Th(f,t);return E&&Object.keys(E).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=Pe(n),t.cacheResolutionUpdateSource=u,n.debug({diffs:E},"Updated cache")),{a11yNode:m,displayString:s.serializedElement,locator:p,decisions:d}}async resolveHardcodedCssSelector(e){let{ctx:t,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,l=await this.getActivePageOrFrame(),c=Date.now(),s=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),s++;let p=l.locator(n),m;try{return await p.waitFor({state:"attached",timeout:1e3}),m=await _n(p,o)??"",d.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${n} matched an element on the page.`}),t?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:d,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:p,displayString:m,decisions:d}}catch(g){let h=g.message;u=new C("ActionFailureError",`CSS selector '${n}' failed to resolve after ${s} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await Z(500,i)}}throw u}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:t,y:n,width:o,height:i}=e.target.boundingBox,a=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!a)return;let l=await a.locator.boundingBox({timeout:3e3});if(!l){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:s,width:u,height:d}=l;if(Math.abs(u-o)>10||Math.abs(d-i)>10){this.logger.debug({newW:u,oldW:o,newH:d,oldH:i,proposedNode:a.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(!t||!n||!c||!s){this.logger.debug({oldX:t,oldY:n,newX:c,newY:s,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-t)>100||Math.abs(s-n)>100){this.logger.debug({newX:c,newY:s,oldX:t,oldY:n,proposedNode:a.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return a}async resolveTargetWithSecondaryMethodsHelper({root:e,target:t,decisions:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<10){let s="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:s})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let s=await dt({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:2e3,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(.05*t.nodeOnlySerializedHtml.length);if(s&&s.closestDistance&&s.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${s.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:s.closestDistance,closestElement:s.closestNodeSerialized})}else{if(s?.error)throw new Error(s.error);if(s?.dataMomenticId||s?.mPathSelector){let d=s.dataMomenticId?parseInt(s.dataMomenticId):void 0,p,m;if(d)p=this.stateManager.dataMomenticIdToNodeMap[d],m=e.locator(kr(d));else if(s.mPathSelector)p=this.stateManager.getNodeUsingMPathSelector(s.mPathSelector),m=e.locator(s.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let g=s.closestNodeSerialized??await _n(m,o)??"unknown element";o.warn({result:s,originalTarget:t,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=Ra(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:m,logger:o,startingBoundingBox:s.boundingBox,allowNotActionableNodesOverride:a,forceSaveNewCssSelectors:!0});let f=Th(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=Pe(o),t.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:s},"Updated cache after l-dist resolution")),n.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${u} string comparison distance of the saved element.`,logs:s.logs,distance:s.closestDistance,closestElement:g,savedElement:t.nodeOnlySerializedHtml}),{locator:m,a11yNode:p,displayString:g,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(s)}`)}}catch(s){o.info({err:s},"Failed to find closest HTML node using levenshtein distance"),n.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${s}`})}let l=t.screenshotUrl,c=t.role??"";if(l&&qg.includes(c))try{let s=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:l,signal:i,allowNotActionableNodesOverride:a});return{...s,decisions:[...n,...s.decisions],pageState:void 0}}catch(s){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${s}`,elementImageUrl:l}),o.warn({err:s},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({root:e,screenshotUrl:t,oldTarget:n,signal:o,allowNotActionableNodesOverride:i}){let a;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let l=await this.screenshot({retries:0}),s=await(await fetch(t)).arrayBuffer(),u=vH(),d=await this.enricher.runTemplateMatching({id:u,searchImageBase64String:Buffer.from(s).toString("base64"),pageImageBase64String:l.toString("base64")},{signal:o}),{target:p,locator:m}=await this.getTargetFromPositionPercentages({percentX:d.x,percentY:d.y,allowNotActionableNodesOverride:i}),g=p.boundingBox?.width,h=p.boundingBox?.height;if(!g||!h)throw a="Rejecting target from screenshot due to no bounding box",new Error(a);let f=p.id,E=this.stateManager.a11yIdToNodeMap[f],S=Ra(n);await this.updateCacheWithNewNodeDetails({target:n,node:E,locator:m,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:i});let y=Th(S,n);return y&&Object.keys(y).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=Pe(this.logger),n.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:u,diffs:y,templateMatch:d},"Updated cache after template matching resolution")),{locator:m,a11yNode:E,displayString:p.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:t}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:1e3})??"",i=fw.some(a=>a===o.toLowerCase());return await ah({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 ah({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:t},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,l=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),l=this.url(),xc(l,t,n)){a=!0;break}await Z(500,this.abortSignal)}if(!a)throw new C("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${yc(t)} in ${o}ms.
|
|
4026
|
-
Current tab: ${l}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(c){this.logger.warn({err:c},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,t,n={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:3e3});if(!o)throw new C("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,l=n.steps??5;await this.page.mouse.move(i,a,{steps:l}),await Z(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o){o&&await this.hover({locator:o});let i=await(await this.getActivePageOrFrame()).evaluate(oh);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 Z(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await ci({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:3e3});if(!n)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(n.x+n.width/2,n.y+n.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await ci({func:t=>t.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let t=await this.getActivePageOrFrame();await dt({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurring the active element"});return}await this.highlight(e.locator),await ci({func:t=>t.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,t,n=!1){await this.highlight(e.locator),await ci({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 C("UserConfigurationError",`Page index ${t.index} is not a number`)}await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?Number(t.index):void 0},{force:n,timeout:3e3})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=Bu(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=Bu(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of yh(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=Bu(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of yh(e))await this.page.keyboard.up(n)}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let n=0,o=2;for(;n<o;){n++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});break}catch(i){this.logger.warn({err:i,attempt:n},`Failed to reload page${n<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"}),await this.waitForDOMStability()}async getBrowserState(e){let{maxAttempts:t=2,logger:n=this.logger,skipWaitForPageLoad:o,allowNotActionableNodesOverride:i}=e,a=e.abortSignal??this.abortSignal,l=!i,c=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:a});let s=0,u;for(;s<t;){s++;try{return await H(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:a,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:c,flagNotActionableNodes:l}),{milliseconds:this.pageLoadTimeout*s,signal:a,message:"Getting browser state took too long"})}catch(d){if(a?.throwIfAborted(),u=d instanceof Error?d.message:`${d}`,s>=t)throw d;n.warn({err:d,url:this.url()},"Error getting a11y tree, retrying...")}}throw new C("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${u}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await dt({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:t,lowerBound:t+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:n=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=p=>{i.value=Date.now()},l=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",l);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let s=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",s);let u=()=>a("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",u);let d=()=>a("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",d);try{await this.waitForDOMStabilityHelper(i,t,n,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",l),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",s),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),l,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},s=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await Z(250,this.abortSignal),l)try{let d=await this.screenshot(c);if(!d.equals(l)){l=d,s=!1;continue}s=!0}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{l=await this.screenshot(c)}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<250)){i=!0;break}}i||t.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:s}},"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,t){let{x:n,y:o}=e;this.logger.debug({x:n,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(n,o,{button:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,t,n){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await Z(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,t,n,o){await this.hoverUsingVisualCoordinates(o);let i=await(await this.getActivePageOrFrame()).evaluate(oh);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 Z(250),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),n=await H(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&n===1&&(n=2);let o=t.documents[0],i=o.layout,a=o.nodes,l=a.nodeName||[],c=a.backendNodeId||[],s=i.nodeIndex,u=i.bounds,d=-1;for(let S=0;S<l.length;S++)if(c[S]===e){d=s.indexOf(S);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[p=0,m=0,g=0,h=0]=u[d];p/=n,m/=n,g/=n,h/=n;let f=p+g/2,E=m+h/2;return{centerX:f,centerY:E}}async scrollVertical(e){return sh({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 sh({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async createRawCDPSession(e){let t=await H(this.context.newCDPSession(this.page),{milliseconds:e??this.pageLoadTimeout,fallback:()=>{throw this.logger.error(`Timed out creating new CDP session for ${this.page.url()}`),new C("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${this.page.url()})`)}});return this.logger.info(`Created new CDP session for ${this.page.url()}`),t}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,t){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let n=!0,o,i=Date.now();for(;n||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){n=!1;try{await this.switchToPageHelper(e,t);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await Z(500)}}throw o}async switchToPageHelper(e,t){let n=this.context.pages().map((i,a)=>({page:i,url:i.url(),index:a})),o;if(e.type==="INDEX"){let i=Number(e.index);if(isNaN(i))throw new C("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)}.
|
|
4027
|
-
Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!Wo(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=zl(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let n;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,t],`setting local storage key ${e}`);return}catch(i){n=i}if(n)throw n}async solveCaptcha(){await this.getBrowserState({allowNotActionableNodesOverride:!0});let e;for(let l of Object.values(this.stateManager.a11yIdToNodeMap))if(l.role==="image"&&l.name.toLowerCase().includes("captcha")){if(!l.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,l.backendNodeId);break}if(!e){let l=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!l.captchas||!l.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:Ku,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let l=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},l),new Error(l)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<6e4;){await Z(2500);let l=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:Ku,taskId:o})});if(!l.ok){let s=`Captcha solution API returned error response: ${l.statusText}`;throw this.logger.error({text:await l.text()},s),new Error(s)}let c=await l.json();if(c.errorId){let s=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(s),new Error(s)}if(c.status==="ready"){a=c.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&Zw({event:t,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async startRecordingCrons(e){if(e.aborted)return;let t,n=(await this.getOpenPages()).map(l=>l.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let l;try{l=(await this.getOpenPages()).map(s=>s.url),o=0}catch(s){this.logger.debug({err:s},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let c=this.url();for(let s=l.length-1;s>=n.length;s--){let u=l[s];Wo(u,this.logger)&&u!==c&&this.logger.info({lastActivePages:n,currentUrl:c,newOpenPages:l},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(s)});break}n=l};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(l){this.logger.error({err:l},"Error while checking pages during recording")}finally{i=!1}}},500),e.addEventListener("abort",async()=>{clearInterval(t)})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(o=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!0,i._MOMENTIC_CLICK_RECORD_ACTIVE=o},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page),e.addEventListener("abort",async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let o=window;o._MOMENTIC_RECORDING_ACTIVE=!1,o._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:1e3})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await $o({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let l=a;if(l.name==="AbortError")throw new C("UserInfrastructureError",`The page with URL ${Qe(i,50)} did not load within the configured timeout (${o}ms): ${l}`);if(!l.message.includes("detached"))throw l}try{await $o({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 pH.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 dt({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new C("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}registerDialogHandler(e){let t=async n=>{try{e==="ACCEPT"?await n.accept():await n.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",t)}async evaluateFunctionInAllFrames(e,t){return this.stateManager.executeFunctionInAllFrames(e,t)}async evaluateFunctionInPage(e,t,n,o=2e3){let i=await this.getActivePageOrFrame();return dt({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=$n}){let i=mw(),a={code:e,fragment:t,context:n},{result:l}=await H(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new C("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return l}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new C("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:l}=await this.getViewportOffsetDetails(e),c=Math.round(a),s=Math.round(l),u=Math.ceil(o*t),d=Math.ceil(i*n),p=u+s,m=d+c;return this.getDomNodeFromPixelPosition(p,m)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:ww,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:1e3,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:1e3})}catch{}}async getTargetFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e);return this.getTargetFromBackendNodeId({root:t,backendNodeId:n.backendNodeId,allowNotActionableNodesOverride:e.allowNotActionableNodesOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:t,allowNotActionableNodesOverride:n}){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[xn],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let l=e.locator(kr(a)),c;o.bounds.x!==null&&o.bounds.y!==null&&(c={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let s=await this.fetchHtmlAttributes({locator:l,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...s};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:l}}async performTargetRedirection(e,t,n){try{return await this.scrollIntoViewIfNeeded(e),await H(this.performTargetRedirectionHelper(e,t,n),{milliseconds:3e3})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,n){let o=Date.now(),i=await _n(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:3e3})??void 0),!n){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:a,y:l,width:c,height:s}=n,u=this.getViewport();if(a<0||l<0||!u||a+c>u.width||l+s>u.height){t.info("Skipping locator redirection because the element is outside the viewport");return}let d=await this.getActivePageOrFrame(),{dataMomenticId:p,mPathSelector:m,error:g,serializedElement:h,point:f,force:E,logs:S}=await e.evaluate(A=>{let R=window;if(!R.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return R.performTargetRedirection(A)},void 0,{timeout:1e3}),y=Date.now()-o;if(g){t.warn({error:g,serializedElement:h,duration:y,force:E,logs:S},"Got error from target redirection with bounding box");return}else{if(p)return t.info({newDataMomenticId:p,serializedElement:h,duration:y,force:E,logs:S},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(kr(p)),hints:{clickableXY:f,force:E}};if(m)return t.info({newMPathSelector:m,serializedElement:h,duration:y,force:E,logs:S},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(m),hints:{clickableXY:f,force:E}};if(f)return t.info({point:f,serializedElement:h,duration:y,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:y,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,l=await e.evaluate((c,s)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,s):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:2e3});if("error"in l&&l.error)throw l.error.startsWith(XA)?new Kl(l.error):l.error.startsWith(JA)?new Yl(l.error):new Error(l.error);return l.warnings.length&&t.warn(l,"Got warnings while generating HTML attributes for target"),l.attributes}async moveMouseFromPositionPercentages(e,t){let n=this.getViewport();if(!n)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(n.width*e),i=Math.ceil(n.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:i,button:"left",clickCount:0}}),{x:o,y:i}}async clickMouseFromPositionPercentages(e,t,n){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*t),a=Math.ceil(o.height*n);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:i,y:a,button:"left",clickCount:e==="down"?1:0},timeout:1e3})}async scrollFromPositionPercentages(e,t,n,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),l=Math.ceil(i.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:l,x:n,y:o}}),{deltaX:a,deltaY:l}}canSolveCaptchas(){return!!Ku}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,rh(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!qu(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()||fH(e),o=uH(e),i=SH(e),a=Hp[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!qu(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:mH.getType(e)||"application/octet-stream"},{timeout:8e3})}catch(s){this.logger.error({err:s},"Error handling file chooser"),this.logToUserConsole(this.page,"error",s.message)}});let l=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:s,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=s;let p=atob(s),m=new Array(p.length);for(let h=0;h<p.length;h++)m[h]=p.charCodeAt(h);let g=new Uint8Array(m);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([g],{type:u})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([g]);return new File([h],d.momenticFileName,{type:u})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},d.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new d.MomenticFile])},{fileName:n,base64Data:l,mimeType:a},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let t={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},t}async copy(e){try{await this.evaluateFunctionInPage(t=>navigator.clipboard.writeText(t),e,"copying text to clipboard")}catch(t){if(t instanceof Error&&t.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard");return}throw t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(t=>{let n=t.request();return e.matches({url:n.url(),method:n.method()})})}registerRequestRecorder(e,t,n){this.requestRecorders[e]={onRequestStart:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestStart(o,i)},onRequestComplete:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestComplete(o,i)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,t,n){this.customHeaders.push({key:e.toLowerCase(),value:t,matcher:n})}registerMock(e,t,n,o){let i=e??Eh();return this.mocks[i]={matcher:t,generateResponse:n,fetchOriginalResponse:o},i}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get userBrowserSettings(){return Ra(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}};import zH from"fetch-cookie";import{cloneDeep as EC}from"lodash-es";import{CookieJar as GH}from"tough-cookie";async function co(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(),tree:t}}var di=3.1783027;function AH(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 In(r){return Math.ceil(Rh(r)/di)}function Rh(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
|
|
4028
|
-
`,""),t=t.replaceAll(" ","");let n=
|
|
3974
|
+
${S}
|
|
3975
|
+
${x||""}`}return S}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:vh(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=vh(this.properties),e}},Ah=class r{constructor(e,t,n,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingSummaries(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n={},o={},i={},a=c=>{let s=c.shallowClone();if(e[c.id])return s.properties["data-momentic-summary"]=e[c.id],n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s;let u=[];for(let d of c.children){let p=a(d);p&&(u.push(p),p.parent=s)}return s.children=u,n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s},l=a(t);return new r(l,n,o,i)}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let l=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),s=i.children,u=!1,d=[];for(let p of s){let m=n(p,l||u);m&&(d.push(m),m.parent=c,u=!0)}if(c.children=d,l||u)return c;if(wh.includes(i.role)&&a)return c}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}pruneToSerializedCharLimit(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n=t.shallowClone(),o=()=>n.serialize().length,i=(a,l)=>{l.children=[];for(let c of a.children){let s=c.shallowClone();if(s.parent=l,l.children.push(s),o()>e){l.children.pop();break}if(i(c,s),o()>e){for(;s.children.length>0&&o()>e;)s.children.pop();if(o()>e){l.children.pop();break}}}};for(i(t,n);n.children.length>0&&o()>e;)n.children.pop();return new r(n,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function lz(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 cz(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?(uc({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?(uc({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 Jw({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:l,showZeroOpacityElements:c,filterByViewport:s,viewportDetails:u,useMPaths:d,importantProperties:p,cdpClient:m,logger:g,callId:h}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let f=(I,re={})=>{},S=r.backendDOMNodeId,E=nz.includes(r.role?.value?.toLowerCase()??"");if(!E&&S===void 0)return f("Filtering out node since it doesn't exist in the DOM"),[];let y=S?i.backendIdToNode[S]:void 0;if(!E&&!y)try{let I=await H(m.send({method:"DOM.describeNode",params:{backendNodeId:S}}),{milliseconds:750,fallback:()=>{g.debug("Timeout getting node from CDP while processing a11y tree")}});if(I&&I.node.nodeName.toLowerCase()==="slot"&&I.node.distributedNodes?.length)g.debug({redirectedDomNode:y,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:I},"Redirecting node to assigned slot");else return f("Filtering out node since it doesn't exist in the DOM",{cdpResult:I}),[]}catch(I){return f("Filtering out node since it doesn't exist in the DOM",{err:I}),[]}if(y&&e&&s&&u&&r.backendDOMNodeId&&!cz(y,u,g,h))return y.momenticIgnored=!0,[];if(y&&y.computedStyles.display==="none")return y.momenticIgnored=!0,[];if(y&&y.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&y.tagName.toLowerCase()!=="input")return y.momenticIgnored=!0,[];if(c===!1)return y.momenticIgnored=!0,[]}let A=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",R=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",w=new Rh({domNode:y,id:parseInt(r.nodeId),role:r.role?.value||"",name:A,nameSources:r.name?.sources,content:R,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(I=>Kw.includes(I.name)||Yw.includes(I.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+lz(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:l}),x=n,_=a[t],P=t;if(y?.tagName.toLowerCase()==="iframe"&&y.ownedFrameId){let I=n.childFrames.find(q=>q.frameId===y.ownedFrameId),re=o[I?.frameId??""]?.root,me=a[I?.frameId??""];if(I&&re&&me){r.childIds&&r.childIds.length>0&&g.debug("Replacing existing node's children with children from the iframe");let q=re;r.childIds=q.childIds,x=I,_=me,P=I.frameId}}let X=y?.childrenBackendIds?.length??0,V=(r.childIds??[]).filter(I=>!!_.get(parseInt(I))).length;if(X>V){let I=r.childIds?.map(me=>_.get(parseInt(me))).filter(Boolean).map(me=>me?.backendDOMNodeId).filter(me=>me!==void 0)??[],re=0;for(let me of y?.childrenBackendIds??[]){if(I.includes(me)){re=(r.childIds?.findIndex(bt=>_.get(parseInt(bt))?.backendDOMNodeId===me)??0)+1;continue}let q=i.backendIdToNode[me];if(!q||q?.tagName.toLowerCase()!=="svg")continue;let Qe=Math.floor(-1*Math.random()*1e7),Ve={nodeId:Qe.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:me,frameId:P,role:{type:"string",value:"graphics-symbol"}};_.set(Qe,Ve),r.childIds||(r.childIds=[]),r.childIds.splice(re,0,Qe.toString()),re++}}if(r.childIds?.length===1&&y){let I=_.get(parseInt(r.childIds[0])),re=I?.role?.value,me=y.childrenBackendIds;if(I&&re==="StaticText"&&me.length===1){let q=i.backendIdToNode[me[0]];if(q?.tagName?.toLowerCase()==="span"){let Qe=Math.floor(-1*Math.random()*1e7).toString(),Ve={nodeId:Qe,parentId:r.nodeId,ignored:!1,backendDOMNodeId:q.backendNodeId,frameId:P,childIds:[I.nodeId]};I.parentId=Qe,_.set(parseInt(Qe),Ve),r.childIds=[Qe]}}}for(let I of r.childIds??[]){if(!I)continue;let re=_.get(parseInt(I));if(!re)continue;let me=await Jw({node:re,parent:w,domGraph:i,axGraph:o,frameId:P,frameContext:x,inputNodeMap:a,cdpClient:m,logger:g,callId:h,filterByViewport:s,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:l});me.length&&(w.children=w.children.concat(me))}if(w.role==="StaticText"&&(w.children=[]),w.children.length===1&&w.children[0].role==="StaticText"){let I=w.name,re=w.children[0]?.name;(I===re||!re)&&(w.children=[])}let k=[];for(let I=w.children.length-1;I>=0;I--){let re=w.children[I];if(re.role!=="StaticText"){k.push(re);continue}if(I===0||w.children[I-1].role!=="StaticText"){k.push(re);continue}w.children[I-1].name+=re.name}if(w.children=k.reverse(),!w.isInteresting(p)&&r.parentId)return y&&(y.momenticIgnored=!0),w.children;for(let I of w.children)I.parent=w;return pz(w),y&&d&&bh(y,i),[w]}function Qw({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:l,iconKnowledgeBase:c,startId:s=1}){r.id=s,s+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:wh.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(l[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let p=Th(d,i),m=p?c[p.hash]:void 0,g=m?m.description:void 0;m&&(r.properties["data-momentic-description"]=g)}for(let p of r.children)s=Qw({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s,useMPaths:a,domGraph:i,selectorToNodeMap:l,iconKnowledgeBase:c});return s}async function Zw({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:l,importantProperties:c,viewportDetails:s,useMPaths:u,frameContext:d,iconKnowledgeBase:p}){let m=t??"root",g=r[m]?.root;if(!g)throw new Error("A11y tree has no root");let h=XB(),f=w=>{let x=w.allNodes.filter(P=>!P.ignoredReasons?.find(V=>Kw.includes(V.name))),_=new Map;return x.forEach(P=>{_.set(parseInt(P.nodeId),P)}),_},S={};Object.entries(r).forEach(([w,x])=>{S[w]=f(x)});let E=await Jw({node:g,domGraph:e,parent:null,inputNodeMap:S,axGraph:r,frameId:m,frameContext:d,cdpClient:o,logger:n,callId:h,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:s,useMPaths:u,flagNotActionableNodes:l});if(E.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(E)}`);if(E.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let y={},A={},R={};return Qw({node:E[0],a11yIdNodeMap:y,dataMomenticIdMap:A,selectorToNodeMap:R,domGraph:e,logger:n,callId:h,useMPaths:u,iconKnowledgeBase:p}),new Ah(E[0],y,A,R)}function uz(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<Xw&&!Rr.bannedClassSubstrings.some(l=>a.includes(l))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(eC(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 dz(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,l])=>{let c=r[a]||a.startsWith("aria")||ZB.includes(a);if((Rr.relevantElementAttributes.includes(a)||tC(a,t))&&!c){let u=uz(a,l,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&$w.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of $w)if(e.attributes.style.includes(`position: ${a}`)){n=a;break}}n&&o.push(`position: ${n}`);let i;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(i="opacity: 0"),i&&o.push(i);for(let a of t?.styles??[]){let l=a.split(":"),c=l[0]?.trim(),s=l[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&s!==void 0&&u!==void 0&&(s==="*"||u===s)){let d=e.computedStyles[c],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(r.style=o.join("; "))}function pz(r){let e=r.properties.class;if(typeof e=="string"&&e.includes("cm-content")){r.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){r.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),r.children.length>0&&(r.children[r.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(r.tagName==="table"){let i=[],a=r.children.find(c=>c.tagName==="thead");if(a){let c=a.children.find(s=>s.tagName==="tr");if(c){let s=c.children.filter(u=>u.tagName==="th");s.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(Xe(u.name,100,!1))}),i?.length!==s.length&&(i=void 0)}}let l=0;for(let c of r.children)if(c.tagName==="tbody")for(let s=0;s<c.children.length;s++){let u=c.children[s];if(u.tagName!=="tr")continue;if(s===0&&!i?.length){let m=u.children.filter(g=>g.tagName==="th");if(m.length){if(i=m.map(g=>Xe(g.name,100,!1)),i.length===m.length)continue;i=void 0}}l+=1,u.properties["row-index"]||(u.properties["row-index"]=l);let d=u.children.filter(m=>m.tagName==="td"||m.tagName==="th"),p=d.length===i?.length;d.forEach((m,g)=>{m.tagName!=="th"&&(m.properties["col-index"]||(m.properties["col-index"]=g+1),p&&(m.properties.col||(m.properties.col=i[g])))})}}}function mz(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function eC(r,e){if(e&&rC(r,e))return!0;if(Rr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(Rr.alwaysInterestingClassNames.includes(r))return!0;for(let t of Rr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function tC(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 rC(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 Zu=class r{constructor(e,t,n,o,i){this.session=e;this.logger=t;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:t,pageGetter:n,defaultTimeoutMs:o}){let i=t(),a=n(),l,c;for(let u=0;u<2;u++)try{l=await H(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new C("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await ee(500),c=d}if(!l)throw c;let s=new r(l,e,t,n,o);try{await H(s.registerHandlers(l),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw s.cdpFullyDead=!0,new C("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return s}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(t){this.logger.warn({err:t},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(t)}`)}),e.on("Page.navigatedWithinDocument",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(t)}`)}),e.on("Page.lifecycleEvent",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(t)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await H(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new C("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 H(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 H(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new C("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 H(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 H(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 Aa="<empty>";function gz(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 oC(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||gz(r.url)}async function hz(r,e){let t=await r.send({timeout:3e3,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:3e3,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function wa({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:3e3,method:"Page.getFrameTree",params:{}}),r.send({timeout:3e3,method:"DOM.getDocument",params:{depth:0}})]),s=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(oC(d.frame))return null;try{return await iC({cdpClient:r,rawFrameTree:d,indices:[p],parent:n,warnings:o,logger:t})}catch(m){return o.push(`Failed to get child frame: ${m}`),null}}),u=await Promise.all(s);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function iC({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,l=await hz(r,a),c=l.attributes??[],s=null,u=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=uo(c,g);h&&(u.push(`${g}=${JSON.stringify(h)}`),g==="src"&&(s=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:s,childFrames:[],parent:n,domNode:l},m=(e.childFrames??[]).map(async(g,h)=>{if(oC(g.frame))return null;try{return await iC({cdpClient:r,rawFrameTree:g,indices:[...t,h],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(m)).filter(g=>g!==null),d}async function fz(r){try{return await r.owner().count()===1}catch{return!1}}async function Sz(r){try{return await r.count()===1}catch{return!1}}async function un(r,e){let t=[],n=r;for(;n.parent.type==="frame";)t.push(n.parent),n=n.parent;t.reverse();let o=e,i=[];for(let s of t){let u=!1;for(let d of[...s.locationData.attributeSelectors,Aa]){let p=o.frameLocator(d===Aa?"iframe":`iframe[${d}]`);if(await fz(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new C("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${s.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let s of[...r.locationData.attributeSelectors,Aa]){let u=o.locator(s===Aa?"iframe":`iframe[${s}]`);if(await Sz(u)){a=u,i.push(s);break}}if(!a)throw new C("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${r.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let l=await a.evaluateHandle(s=>s,{timeout:1e3}),c=await l.asElement().contentFrame();if(!c)throw new C("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await l.dispose(),{frame:c,mPathSelectorTokens:i}}function nC(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 aC({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let l=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===Aa?l=l.length===1?l[0].childFrames:[]:l=l.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],s=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(s===Aa?c=l:c=l.filter(u=>u.locationData.attributeSelectors.includes(s)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await un(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with mpath ${t.mPathSelectorTokens.join(" > ")}`)}if(t.frameSrcRegex){let l=new RegExp(t.frameSrcRegex),c=nC(o,s=>!!s.src&&l.test(s.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await un(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with src regex ${t.frameSrcRegex}`),t.frameSrcRegex=void 0}if(t.frameUrlRegex){let l=new RegExp(t.frameUrlRegex),c=nC(o,s=>!!s.url&&l.test(s.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await un(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with url regex ${t.frameUrlRegex}`),t.frameUrlRegex=void 0}let a=o;for(let l=0;l<t.indices.length-1;l++)a=a[t.indices[l]]?.childFrames??[];if(n=a[t.indices[t.indices.length-1]],n)return i.push(`Found unique frame with indices ${t.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await un(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new qr("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function ed(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function Ch(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function sC(r){let e=Ch(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let l=a.shift();l.src&&o.push(l.src),l.url&&i.push(l.url),a.push(...l.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function lC(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 cC({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await yz({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 yz({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await Ko({promiseGenerator:async()=>r.evaluate(async i=>{let a=i.scrollTop;i.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(c=>setTimeout(c,250));let l=Date.now();for(;Date.now()-l<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(s=>setTimeout(s,250))}}),timeoutMs:2e3,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}function uC(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:l}of r)(!l||l.matches({url:n.url(),method:n.method()}))&&(o[i]=a);await t.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as Tz}from"crypto";function dC(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function pC(r){let{route:e,mock:t,entry:n,debugData:o,requestId:i,requestRecorders:a,logger:l}=r,c={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(m=>[m.name,m.value]),body:n.request.postData?.text}},s;if(t.fetchOriginalResponse){let m=await e.fetch();s={body:await m.text(),options:{status:m.status(),statusText:m.statusText(),headers:Object.entries(await m.headers())}}}let u=await Ez(t,c,s),d={};u.headers.forEach((m,g)=>{d[g]=m});let p={body:await u.text(),contentType:u.headers.get("content-type")||"text/plain",headers:d,status:u.status};await e.fulfill(p);try{n.response={status:p.status,statusText:u.statusText,headers:Object.entries(p.headers).map(([m,g])=>({name:m,value:g})),cookies:[],content:{mimeType:p.contentType,text:p.body},_mocked:!0},ol(o,n,i);for(let m of Object.values(a))m.onRequestComplete(i,n)}catch(m){m.message.includes("has been closed")||l.warn({err:m},"Failed to add response to HAR")}}async function Ez(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 xh(r){try{await bz(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function bz(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:l}=r,c=Tz(),s=await gh(e,n);try{ol(o,s,c);for(let d of Object.values(a))d.onRequestStart(c,s)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=dC(n,l);u?await pC({logger:i,route:t,mock:u,entry:s,debugData:o,requestId:c,requestRecorders:a}):await vz({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:s,requestId:c})}async function vz({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let l=await e.response();if(!l||!i)return;await ww(i,e,l),ol(t,i,a);for(let c of Object.values(o))c.onRequestComplete(a,i)}catch(l){l.message.includes("has been closed")||n.warn({err:l},"Failed to add response to HAR")}}async function Rz(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 Az(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 td(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 _h(r){let e=r.request(),t=r.status(),n=r.headers(),o=await Az(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await Rz(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var po=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:Uc(t,this.requestMatcher.urlMatcher)}};function rd(r){let e=new URL(r.request().url());return/^127\./.test(e.hostname)||/^192\.168\./.test(e.hostname)||/^10\./.test(e.hostname)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e.hostname)||e.hostname==="localhost"?r.abort():r.fallback()}async function mC({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:l,properties:c}=r.target;if(l){i.error({error:l,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let s=n.parentFrame()?n.url():void 0,d=n.page().frames().map(g=>g.url());i.debug({frameUrl:s,...r},"Passive click event captured on element");let p,m;if(s)try{let g=await n.frameElement();p=await H(g?.boundingBox(),{milliseconds:3e3})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:s});if(h.urlRegex)m={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(g){i.warn({err:g},"Failed to construct iframe details for recorded action, using hardcoded URL only"),m={type:"url",url:s}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:m,frameBoundingBox:p})}catch(g){i.error({err:g},"Failed to transform passive click action")}})()}import{randomUUID as dn}from"crypto";import wz from"js-beautify";var Cz=["Dead"],nd=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:t,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onStepRecorded(l,c)},onActionReceived:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onActionReceived?.(l,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:dn(),type:"PRESET_ACTION",command:fn(e)}}),this.nextStepOffset++,t}async recordElementAction(e){let{type:t,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,l=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=l,s;switch(e.frameConfig?e.frameBoundingBox?s={x:e.frameBoundingBox.x+n.properties.boundingBox.x,y:e.frameBoundingBox.y+n.properties.boundingBox.y,width:n.properties.boundingBox.width,height:n.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):s=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let h=fn(i);a={id:dn(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}}}};break}case"SELECT":{i="SELECT_OPTION";let h=fn(i);a={id:dn(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:c},cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=fn(i);a={id:dn(),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:Ne(this.logger),boundingBox:s}}}};break}default:throw new Error(`Unknown action type: ${t}`)}let u;e.offset===void 0?(u=this.nextStepOffset,this.nextStepOffset++):u=e.offset,this.callbacks.onActionReceived?.(a,u);let d=e.target.browserState;try{d=wz.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=mw(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,...Ne(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=l}let m=this.recordedSteps.get(u)?.step??a,g=m?.command;g&&"target"in g&&g.target?(g.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...m,command:g},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(Cz.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=fn("TYPE");i={id:dn(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=fn("PRESS");i={id:dn(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,l=this.nextStepOffset-1,c=this.recordedSteps.get(l),s=c?.step,u=s?.command;if(n){if(u?.type===i.command.type){let d=u.value,p=i.command.value;i={id:dn(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},a=l}else if(u?.type==="CLICK"&&i.command.type==="TYPE")s.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=l;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:dn(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=l}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let t=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_DOWN"&&l.deltaY?(i+=l.deltaY,c=a):l?.type==="SCROLL_UP"&&l.deltaY?(i-=l.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_DOWN":"SCROLL_UP",u=fn(s);u.deltaY=Math.abs(i);let d={id:dn(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_RIGHT"&&l.deltaX?(i+=l.deltaX,c=a):l?.type==="SCROLL_LEFT"&&l.deltaX?(i-=l.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=fn(s);u.deltaX=Math.abs(i);let d={id:dn(),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 Ih}from"zod";var Vwe=Ih.object({type:Ih.literal("url"),url:Ih.string()});var od=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:l,enricher:c,iconKnowledgeBase:s,userBrowserSettings:u}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=l,this.enricher=c,this.iconKnowledgeBase=s,this.userBrowserSettings=u,this.userBrowserSettings.importantStyles)for(let d of this.userBrowserSettings.importantStyles){let p=d.split(":");if(p.length!==2){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}let m=p[0]?.trim(),g=p[1]?.trim();if(m===void 0||g===void 0){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(m)||this.computedStylesToFetch.push(m)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userBrowserSettings.autoExpandIframes)return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),n=Ch(e),{frame:o,mPathSelectorTokens:i}=await un(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 wa({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await aC({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(ed(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:ed(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await cC({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await wa({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[H(n.evaluate(e,t),{milliseconds:2e3})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),s=c.url;s==="about:blank"||s.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(un(c,n).then(({frame:u})=>H(u.evaluate(e,t),{milliseconds:2e3})).catch(u=>(this.logger.warn({err:u,frameUrl:c.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(i)).filter(c=>c!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),t=await wa({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(t.childFrames),o=[];for(;n.length>0;){let i=n.shift();n.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:t,logger:n}){return this.getDOMTree({devicePixelRatio:e??1,signal:t,logger:n??this.logger})}async getA11yTree(e){let t={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),a,l,c=null;if(this.frameConfig?.type==="url"){if(a=await Ar({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new C("ActionFailureError","Got null frame details despite active frame config");l=a.handle,c=l.frameId}else this.userBrowserSettings.autoExpandIframes?(l=await Ar({fn:()=>wa({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(l={type:"root",page:i,childFrames:[]},c=null);await Ar({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:l.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let s=await Ar({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await Ar({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:l.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await Ar({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:s,startingFrameId:c,frameContext:l,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(p=>p>750)&&n.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=s,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:Tn,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=Gw({node:o,domGraph:this.domGraph});return Vw(e,i)}else return this.getLocatorFromBackendId(t,n.backendNodeId)}async getLocatorFromBackendId(e,t){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:t},timeout:2e3});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await jw(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(Fr(o))}getNodeUsingMPathSelector(e){let t=this.selectorToNodeMap[e];if(t)return t;let n=e.split(" > "),o="";for(let i=n.length-1;i>=0;i--){let a=n.slice(i).join(" > ");if(this.selectorToNodeMap[a]){o=a;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:t=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,l,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await wa({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),a=await this.getMatchingFrameByUrlWithCdp(i,e),n.info({frameId:a.handle.frameId,url:a.handle.url,src:a.handle.src,locationData:a.handle.locationData},`Found matching frame using ${a.matchType}`);break}catch(s){if(l=s,s instanceof C&&s.reason==="UserInfrastructureError")throw s;c%3===0&&this.logger.warn({attempt:c,err:s},"Failed to resolve active frame, retrying..."),await ee(500,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:ed(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw l}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let l=i.shift(),c=l.domNode;i.push(...l.childFrames);let s=uo(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!s&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[s,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:l,matchType:"regex",...await un(l,o)});break}}else if(n.trim()===d.trim()){a.push({handle:l,matchType:"url",...await un(l,o)});break}}}if(a.length===1){let l=a[0];return this.userBrowserSettings.autoExpandIframes||(l.handle.childFrames=[]),l}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new C("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:l,showZeroOpacityElements:c,flagNotActionableNodes:s}){let u=await Zw({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:s,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userBrowserSettings.importantAttributes,classes:this.userBrowserSettings.importantClasses,styles:this.userBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:l,useMPaths:this.userBrowserSettings.visualActions});if(!u||!u.root)throw new Error("Accessibility tree appears empty");return{tree:u}}async addMomenticIds({rootPage:e,childFrames:t,frameFilter:n,logger:o}){if(this.userBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),l=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let s=async()=>{try{let{frame:u}=await un(c,e);i=await this.addMomenticIdsHelper(u,i)}catch(u){c.url!=="about:blank"&&o.warn({err:u},"Error adding momentic IDs to child frame, continuing...")}};l.push(s())}await Promise.all(l)}async addMomenticIdsHelper(e,t){if(this.userBrowserSettings.visualActions)return t;let n=this.logger;return await ut({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:2e3,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(i){n.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??t}getPageDomain(e){try{let t=new URL(e);if(!t.hostname)return null;let n=t.hostname.split("."),o=n.length>2?n.slice(-2).join("."):t.hostname;return`${t.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:t,handle:n}){try{let{shouldUnroll:o,reason:i}=await this.decideChildFrameUnrollEligibilityHelper({domNode:n.domNode});return{shouldUnroll:o,reason:i}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let i=`Got error when determining whether to filter frame ${n.frameId} with url ${n.url}, allowing it to be fetched: ${o}`;return t?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let t=e.attributes??[];if(uo(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=uo(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:3e3,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:3e3,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let a of i.computedStyle){if(a.name==="display"&&a.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(a.name==="visibility"&&a.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(a.name==="opacity"&&a.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:t,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let l=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(m){i.warn({err:m},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,s;for(let m=0;m<3;m++)try{s=await Ar({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,signal:a,logger:i});break}catch(g){c=g,i.warn({err:g},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!s)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=s,!this.userBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),p=[];for(;d.length>0;){let m=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:m,warnings:l});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;l.push(`Got error when determining whether to filter frame ${m.frameId} with url ${m.url}, allowing it to be fetched: ${h}`)}d.push(...m.childFrames);let g=async()=>{try{let h=await Ar({fn:()=>this.getRawA11yTreeForFrame({frameId:m.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${m.frameId}`,logObject:o,signal:a,logger:i});u[m.frameId]=h}catch(h){i.warn({err:h,url:m.url,src:m.src},`Error getting raw a11y tree for child frame ${m.frameId}, continuing...`)}};p.push(g())}return await Promise.all(p),l.length>0&&this.logger.warn({warnings:l},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await Ar({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes;else{let a=(await Ar({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:2e3}),codePath:"cdp-get-root-ax-node",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).node.backendDOMNodeId;o=(await Ar({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:t,logger:n}){let o,i=0,a;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:this.computedStylesToFetch},timeout:3e3}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(l){await ee(500,t),i++,a=l}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new C("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 Hw({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=sC(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 Mh(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var Lh=pn(xa(),"momentic","chromium"),qz=pn(xa(),"video"),ad=process.env.TWO_CAPTCHA_KEY,bC=jz(TC);bC.use($z({provider:{id:"2captcha",token:ad},visualFeedback:!0}));var wr=class r{static USER_AGENT=Vz["Desktop Chrome"].userAgent;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;lastIconKnowledgeBaseUpdateTime=0;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,enricher:t,browser:n,context:o,page:i,baseUrl:a,logger:l,userBrowserSettings:c,viewport:s,properties:u,clientCallbacks:d,iconKnowledgeBase:p}){if(ME(c),this.storage=e,this.enricher=t,this.browser=n,this.context=o,this.page=i,this.baseUrl=a,this.logger=l,this.userControlledBrowserSettings=c,this.viewport=s,this.properties=u,this.clientCallbacks=d,u.recordVideo){let m=this.page.video();m&&this.videos.push(m)}this.iconKnowledgeBase=p}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let n={[Xu]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:uw.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})];t&&await this.page.reload();let i=l=>this.handleNewPageEvent(l);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)});let a=Promise.all(o);await Promise.all([a]),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&id()==="darwin"&&Oz("system_profiler SPDisplaysDataType").toString().includes("Retina")?(T.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 Zu.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new od({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let t=e.sessionId,n=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=n,this.clientCallbacks?.onScreencastFrame?.(n,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:t}})}catch{}})()})}))}static async init({baseUrl:e,logger:t,storage:n,enricher:o,userBrowserSettings:i,contextArgs:a,recordVideo:l,iconKnowledgeBase:c,callbacks:s}){r.clearCrashReportsDirs(),process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let u;switch(i.browserType){case"Google Chrome":u="chrome";break;case"Chrome for Testing":u=void 0;break;case"Chromium":u="chromium";break;default:u="chromium";break}let d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:u},p={...a??{},geolocation:a?.geolocation||$n,locale:a?.locale||Vn,timezoneId:a?.timezoneId||jn,colorScheme:a?.colorScheme,httpCredentials:i.basicAuthorization?{username:i.basicAuthorization.username??"",password:i.basicAuthorization.password??""}:void 0,javaScriptEnabled:i.disableJavaScript?!1:void 0,ignoreHTTPSErrors:i.ignoreHttpsErrors??!1,userAgent:i.userAgent??r.USER_AGENT,viewport:a?.viewport??Mt},m=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream","--enable-logging=stderr","--log-level=2","--enable-crashpad","--crash-on-hang-threads"];process.env.MOMENTIC_CHROME_EXTRA_ARGS&&m.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let g=null,h,f,S={systemDevicePixelRatio:a?.deviceScaleFactor,recordVideo:l,isNewHeadless:!1};(u==="chrome"||u==="chromium")&&(S.isNewHeadless=!0,d.headless&&m.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&m.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),i.disableGpu&&m.push("--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-audio-input","--disable-audio-output");let E=i.localChromeExtensionPaths?.map(A=>A.startsWith("~")?pn(xa(),A.slice(1)):A);if(E?.length){if(u===void 0)throw new C("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let x of E){let _=pn(x,"manifest.json");if(!mi(_))throw new C("UserConfigurationError",`Chrome extension path ${_} does not exist.`)}if(En)throw new C("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let A=pn(Lh,`momentic-session-${Date.now()}`);if(!mi(A))try{Lz(A,{recursive:!0})}catch(x){throw new C("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${Lh} folder: ${x}`)}let R=[...m],w=E.map(x=>Gz(x)).join(",");R.push(`--disable-extensions-except=${w}`),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}`),h=await TC.launchPersistentContext(pn(Lh,`momentic-session-${Date.now()}`),{...d,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:R,baseURL:e}),t.info({sharedContextOptions:p,sharedBrowserOptions:d,userBrowserSettings:i,chromeArgs:R,properties:S,baseUrl:e},"Browser initialization context args (persistent)"),f=h.pages()[0]}else{g=await bC.launch({...d,args:m});let A={...p,baseURL:e,recordVideo:l?{dir:qz}:void 0};h=await g.newContext(A),t.info({contextArgs:A,sharedBrowserOptions:d,chromeArgs:m,userBrowserSettings:i,properties:S,baseUrl:e},"Browser initialization context args (standard)"),f=await h.newPage()}En&&await h.route("**",rd);let y=new r({browser:g,context:h,page:f,baseUrl:e,logger:t,storage:n,enricher:o,userBrowserSettings:i,viewport:p.viewport||Mt,properties:S,clientCallbacks:s,iconKnowledgeBase:c});return await y.initialize({grantPermissions:!0,runInitScripts:!1}),y}static async fromExistingContext({context:e,storage:t,enricher:n,userBrowserSettings:o,logger:i}){let a=e.pages()[0];if(!a)throw new Error("No page found in existing context");let l=a.viewportSize(),c=a?.url(),s=new r({browser:e.browser(),context:e,page:a,baseUrl:c,logger:i,storage:t,enricher:n,userBrowserSettings:o,viewport:l,properties:{isNewHeadless:!0},clientCallbacks:void 0,iconKnowledgeBase:null});return await s.initialize({grantPermissions:!1,runInitScripts:!0}),s}async handleAvailableTabsChangeHelper(){try{let e=await Eh(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=Ph(),o=`${e}-${n}`,i=Date.now(),a=!1,l=async()=>{try{await H(t(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(c){c.name!=="AbortError"&&this.logger.error({err:c,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],a=!0}};this.pageLoadPromises[o]=l().catch(()=>{}),a&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let t=async()=>{if(this.closed)return;this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let n=this.context.pages();for(let o=n.length-1;o>=0;o--){let i=n[o];if(!(!i||i.isClosed()||!Yo(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=Ph(),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=>{bw(e,o,this.debugData,a,this.logger)});let i=async()=>{await Aw(t,this.debugData,e),await e.route("**/*",async(a,l)=>{await xh({pageId:t,route:a,request:l,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",uC(this.customHeaders,this.logger)),En&&await e.route("**/*",rd),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"||!Yo(t)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let i=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o,signal:this.abortSignal}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(l){this.logger.warn({err:l},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(a){a.name!=="AbortError"&&this.logger.warn({err:a,url:t,codePath:o},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>i())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let n={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(n[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let i=window;i._MOMENTIC_ICON_KNOWLEDGE_BASE=o},n)}catch(t){this.logger.warn({err:t},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await H(fh(this.getBrowserCallbacks()),{milliseconds:1e3})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,t,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<8e3;){a++,n?.throwIfAborted();try{if(await ut({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:1e3,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(l){if(i++,i>=3){t.warn({err:l},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await ee(500),a%2===0&&t.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),ut({root:e,fn:()=>{let t=window;if(!t?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return t.getFullHtmlTree()},arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,t=[],n=new Map;document.querySelectorAll("input,textarea,[contenteditable]").forEach(o=>{n.set(o,{value:o.style.getPropertyValue("caret-color"),priority:o.style.getPropertyPriority("caret-color")}),o.style.setProperty("caret-color","transparent","important")}),t.push(()=>{for(let[o,i]of n)o.style.setProperty("caret-color",i.value,i.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of t)o();delete e._MOMENTIC_SCREENSHOT_CLEANUP}},void 0,"stabilizing page for screenshot")}catch(e){(!(e instanceof Error)||!e.message.includes("Execution context was destroyed"))&&this.logger.warn({err:e},"Failed to stabilize page before screenshot, continuing...")}}async removeScreenshotStabilization(){try{await this.evaluateFunctionInPage(()=>{window._MOMENTIC_SCREENSHOT_CLEANUP?.()},void 0,"removing screenshot stabilization")}catch{}}async screenshot(e){let{retries:t=1,stabilizeBeforeScreenshot:n=!1}=e,o=this.page.url();n&&await this.stabilizePageForScreenshot();let i=Date.now();try{await this.fixViewportForNewHeadless();let a=await this.screenshotHelper({...e,retries:t});if(a.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(a.length===0)throw new Error("Got empty screenshot");return a}catch(a){if(t<=0||a.message.includes("has been closed"))throw a;return this.logger.warn({err:a,pageUrl:o},"Failed taking screenshot, retrying..."),await ee(250),this.screenshot({...e,retries:t-1})}finally{Date.now()-i>1e3&&this.logger.warn({pageUrl:o,duration:Date.now()-i},"Screenshot took longer than expected"),n&&await this.removeScreenshotStabilization()}}async screenshotHelper({locator:e,quality:t,saveToDiskPath:n,timeout:o,respectActiveFrame:i,clearHighlights:a=!1}){a&&await this.clearHighlights(),i&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let l=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:o??2e3}),c=Buffer.from(l.data,"base64"),s=await yC.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(s.bitmap.width!==u||s.bitmap.height!==d)&&(c=await s.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&Fz(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:3e3});if(!p)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:m,y:g,width:h,height:f}=p;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");m=Math.floor(m),g=Math.floor(g),h=Math.floor(h),f=Math.floor(f);try{let S=await yC.fromBuffer(c),E=S.bitmap.width,y=S.bitmap.height;m=Math.max(0,Math.min(m,E-1)),g=Math.max(0,Math.min(g,y-1)),h=Math.max(1,Math.min(h,E-m)),f=Math.max(1,Math.min(f,y-g)),c=await S.crop({x:m,y:g,w:h,h:f}).getBuffer("image/jpeg")}catch(S){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${g}) with size (${h}, ${f}): ${S}`)}finally{"dispose"in e&&await e?.dispose()}return c}getViewport(){return this.viewport?this.viewport:this.page.viewportSize()}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){WT(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();t||(await this.waitForPageLoad(),await this.waitForDOMStability());let i=!1,a;for(let c=0;c<3;c++)try{await this.page.goto(e,{timeout:n,waitUntil:"domcontentloaded"}),i=!0;break}catch(s){if(a=s,this.abortSignal?.throwIfAborted(),this.logger.warn({err:s},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await ee(500),a.message.includes("Timeout")&&a.message.includes("exceeded")||a.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:1e3})}if(!i)throw new C("UserInfrastructureError",a?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let l=this.url();if(gw.has(l))throw new C("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 ut({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;return n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n}:void 0},arg:void 0,timeout:1e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(t){this.logger.warn({err:t},"Failed to get active element");return}}async directTypeHelper(e,t={},n=!1){let o=await this.getActivePageOrFrame();await Ow({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(250),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}t.clearContent&&(t.forceClearContent||i?.tag==="input"||i?.tag==="textarea"?(process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25)):this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:t.delay??Df}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:2e3})}catch(t){this.logger.warn({err:t},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async n=>{let o=n.scrollTop;n.scrollIntoView(),await new Promise(a=>setTimeout(a,250));let i=Date.now();for(;Date.now()-i<1e3;){let a=n.scrollTop;if(a===o)break;o=a,await new Promise(l=>setTimeout(l,250))}},void 0,{timeout:2e3})}catch(n){this.logger.warn({err:n},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:t}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(t.locator),!0}catch(t){return this.logger.debug({err:t,id:e},"Failed to highlight target"),!1}}async highlight(e){return Ju({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let t=new URL(e).origin;if(t==="null")return;this.originsVisited.add(t)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;t.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(t),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:1e3}),this.originsVisited.delete(o);let t=this.context.pages().indexOf(this.page),n=[...this.context.pages()];for(let o=0;o<n.length;o++){let i=n[o];if(i.isClosed())continue;let a=i.url();try{this.originsVisited.delete(new URL(a).origin)}catch{}await Tw(i,this.logger),o!==t&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${a}`),await i.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let t=[];for(let i of e.cookies??[]){let a=await this.setCookie(i);t=t.concat(a)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:1e3});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:1e3,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(l){this.logger.warn({err:l,origin:i},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${n} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await Ew(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 yw(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 C("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return Eh(this.context,e)}saveA11yDetailsToCache(e,t){t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,delete t.serializedForm,delete t.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:t,locator:n,forceSaveNewCssSelectors:o,startingBoundingBox:i,allowNotActionableNodesOverride:a,logger:l=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let c=await this.fetchHtmlAttributes({locator:n,logger:l,startingBoundingBox:i,allowNotActionableNodesOverride:a}),s=!1;for(let u of["generatedSelectors","serializedHtml","nodeOnlySerializedHtml","hybridSelector"]){let d=c?.[u];if(d&&!t[u]){s=!0;break}if(d&&JSON.stringify(d)!==JSON.stringify(t[u])){s=!0;break}}c&&(o||s)&&(t.generatedSelectors=c.generatedSelectors,t.serializedHtml=c.serializedHtml,t.nodeOnlySerializedHtml=c.nodeOnlySerializedHtml,t.hybridSelector=c.hybridSelector)}catch(c){if(c instanceof Kr)throw c;l.warn({err:c},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:l,boundingBox:i})}catch(c){l.debug({err:c},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!oh.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:3e3})),!o||!o.width||!o.height)return n.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:i=0,y:a=0,width:l=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-l)<1&&Math.abs(e.boundingBox.height-c)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-a)<1)return{scrollPerformed:!0};e.boundingBox=o;let s=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(s),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({locator:e,requirements:t}){let n={};if(t?.boundingBox){let o=await e.boundingBox({timeout:3e3});if(!o||!o.width||!o.height)throw new C("ActionFailureError","Element does not have a bounding box as required");n.boundingBox=o??void 0}if(t?.text){let o=await e.innerText({timeout:3e3});n.text=o?.trim()}if(t?.attributes&&t.attributes.length>0){let o={};for(let i of t.attributes){let a=i.trim().toLowerCase();if(!(!a||Rr.bannedAiRequiredCacheAttributes.includes(a)))try{let l=await e.getAttribute(a,{timeout:3e3});l!==null&&(o[i]=l)}catch(l){this.logger.warn({err:l,attr:i},"Failed to fetch required attribute, continuing...")}}n.attributes=o}return n}async getAdditionalElementDetails({mainLocator:e,additionalElement:t,root:n,logger:o}){let i=this.stateManager.a11yIdToNodeMap[t.id];if(!i)return;let a=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:n,node:i});if(e.contentFrame!==a.contentFrame)return;let l=await this.fetchHtmlAttributes({locator:a,logger:o});if(!l?.generatedSelectors||l.generatedSelectors.length===0)return;let c={selectors:l.generatedSelectors};return t.requirements&&(c.requirements=await this.getElementRequiredValues({locator:a,requirements:t.requirements})),c}async getAdditionalElementsDetails({mainElementId:e,mainLocator:t,additionalElements:n,root:o,logger:i}){let a=new Set,l=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let s=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!s)continue;l.push(s)}catch(s){this.logger.warn({err:s,additionalElement:c},"Failed to fetch additional element details, continuing...")}return l}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:l}){t&&(o.requirements=await this.getElementRequiredValues({locator:i,requirements:t})),n&&(o.additionalElements=await this.getAdditionalElementsDetails({mainElementId:e,mainLocator:i,additionalElements:n,root:a,logger:l}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:l}){if(e<0)throw new C("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new C("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let s=this.stateManager.frameConfig,u,d,p,m;if(this.userBrowserSettings.autoExpandIframes&&!s&&c.parentFrame){let E=c.parentFrame,{cache:y,config:A}=await this.stateManager.getAutoFrameDetailsFromHandle(E);d=y,p=A,u=A.frame,m="auto iframe"}else c.parentFrame&&s?(p=s,u=await this.getActivePageOrFrame(),m="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),m="should not be possible");let g=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:u,node:c}),h={id:e,inputDescription:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:Ne(i),frameCache:d},f,S=!1;o||(p&&(i.info({frameConfigSource:m,frameConfig:lC(p)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),S=!0),await this.updateCacheWithNewNodeDetails({node:c,target:h,locator:g,logger:i,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:l,target:h,root:u,locator:g,logger:i}));try{return{resolution:{locator:g,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:h,frameConfig:p,frameConfigSource:m}}finally{S&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,t,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowNotActionableNodesOverride:l}=n;if(t.frameCache&&this.userBrowserSettings.autoExpandIframes){let m,g=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),g=!0;break}catch(f){m=f,await ee(500,a)}if(!g)throw m}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let s=Date.now(),u=0,d=0,p;for(;Date.now()-s<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let m=u===2||Date.now()-s>this.smartWaitingTimeout-2e3&&u%2===0;try{p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,logger:m?i:Tn,allowNotActionableNodesOverride:l,signal:a});break}catch(g){if(g instanceof cs)break;if(g instanceof Kr){if(d++,d>2)throw i.error({err:g},"Got multiple cache disqualification errors, giving up"),g;i.warn({err:g},"Got cache disqualification error, waiting and retrying resolution"),await ee(500,a)}a?.throwIfAborted(),m&&i.info({err:g},`Could not resolve target using primary cache only (x${u})`),await ee(500,a)}}return p||(p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:l}),t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=Ne(i),i.info({decisions:p.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:p?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),p}async resolveTargetHelper({root:e,target:t,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){let l=Ca(t),c=[],s=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),u;if(t.generatedSelectors||t.hybridSelector){let d;try{d=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a})}catch(p){u=p,p instanceof qr&&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:Ca(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw u;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let d=await this.resolveTargetWithSecondaryMethods({root:e,tree:s,target:t,decisions:c,logger:o,signal:i,allowNotActionableNodesOverride:a});if(d)return d}throw new qr(`Could not find any relevant node given target: ${JSON.stringify(l)}`,c)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o}){if(!t.nodeOnlySerializedHtml)throw new cs("Insufficient data to resolve target using primary methods (missing node HTML)");let i=this.userControlledBrowserSettings.hybridSelectorMode,a={ldistThreshold:.05,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements},{css:l,hybrid:c}=await ut({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:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),s,u,d=[];if(i==="prefer"&&c?.result){s=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(l?.result){s=l.result;let E=`${s.workingSelectors.length} CSS selectors matched the following element: ${s.serializedElement}`,y=s.workingSelectors.slice(0,5);d.push({type:"CSS_SELECTOR",matched:!0,logs:l.logs,reason:E,selectors:y}),n.debug({reason:E,workingSelectors:y},"Resolved with CSS selectors"),u="CSS_SELECTOR"}else throw d.push({type:"CSS_SELECTOR",matched:!1,reason:l.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:l.logs}),c&&d.push({type:"HYBRID_SELECTOR",matched:!1,reason:c.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:c.logs}),new qr("Cache evaluation failed",d);let p,m,g,h=!1;if(this.userBrowserSettings.visualActions){let E=s.mPath;if(!E)throw new Error("Found element did not have an mPath despite using visual actions");let y=E.join(" > ");p=e.locator(y),m=this.stateManager.getNodeUsingMPathSelector(y)}else if(s.dataMomenticId!==void 0)g=parseInt(s.dataMomenticId),m=this.stateManager.dataMomenticIdToNodeMap[g],"workingSelectors"in s?(p=e.locator(s.workingSelectors[0]),h=s.workingSelectors.length<5):p=e.locator(Fr(g));else throw new C("InternalWebAgentError","Received an element resolution result with no identifying attributes");i&&t.hybridSelector&&(c?.logs.length===1?n.warn({hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution rejected, continuing..."):c?.result?l?.result&&c?.result&&c.result.serializedElement!==l.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(l.result.mPath)!==JSON.stringify(c.result.mPath)?n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):l.result.dataMomenticId!==c.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let f=Ca(t);await this.updateCacheWithNewNodeDetails({node:m,target:t,locator:p,logger:n,startingBoundingBox:s.boundingBox,forceSaveNewCssSelectors:h,allowNotActionableNodesOverride:o});let S=Oh(f,t);return S&&Object.keys(S).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=Ne(n),t.cacheResolutionUpdateSource=u,n.debug({diffs:S},"Updated cache")),{a11yNode:m,displayString:s.serializedElement,locator:p,decisions:d}}async resolveHardcodedCssSelector(e){let{ctx:t,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,l=await this.getActivePageOrFrame(),c=Date.now(),s=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),s++;let p=l.locator(n),m;try{return await p.waitFor({state:"attached",timeout:1e3}),m=await In(p,o)??"",d.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${n} matched an element on the page.`}),t?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:d,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:p,displayString:m,decisions:d}}catch(g){let h=g.message;u=new C("ActionFailureError",`CSS selector '${n}' failed to resolve after ${s} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await ee(500,i)}}throw u}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:t,y:n,width:o,height:i}=e.target.boundingBox,a=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!a)return;let l=await a.locator.boundingBox({timeout:3e3});if(!l){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:s,width:u,height:d}=l;if(Math.abs(u-o)>10||Math.abs(d-i)>10){this.logger.debug({newW:u,oldW:o,newH:d,oldH:i,proposedNode:a.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(!t||!n||!c||!s){this.logger.debug({oldX:t,oldY:n,newX:c,newY:s,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-t)>100||Math.abs(s-n)>100){this.logger.debug({newX:c,newY:s,oldX:t,oldY:n,proposedNode:a.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return a}async resolveTargetWithSecondaryMethodsHelper({root:e,target:t,decisions:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<10){let s="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:s})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let s=await ut({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:2e3,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(.05*t.nodeOnlySerializedHtml.length);if(s&&s.closestDistance&&s.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${s.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:s.closestDistance,closestElement:s.closestNodeSerialized})}else{if(s?.error)throw new Error(s.error);if(s?.dataMomenticId||s?.mPathSelector){let d=s.dataMomenticId?parseInt(s.dataMomenticId):void 0,p,m;if(d)p=this.stateManager.dataMomenticIdToNodeMap[d],m=e.locator(Fr(d));else if(s.mPathSelector)p=this.stateManager.getNodeUsingMPathSelector(s.mPathSelector),m=e.locator(s.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let g=s.closestNodeSerialized??await In(m,o)??"unknown element";o.warn({result:s,originalTarget:t,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=Ca(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:m,logger:o,startingBoundingBox:s.boundingBox,allowNotActionableNodesOverride:a,forceSaveNewCssSelectors:!0});let f=Oh(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=Ne(o),t.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:s},"Updated cache after l-dist resolution")),n.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${u} string comparison distance of the saved element.`,logs:s.logs,distance:s.closestDistance,closestElement:g,savedElement:t.nodeOnlySerializedHtml}),{locator:m,a11yNode:p,displayString:g,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(s)}`)}}catch(s){o.info({err:s},"Failed to find closest HTML node using levenshtein distance"),n.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${s}`})}let l=t.screenshotUrl,c=t.role??"";if(l&&oh.includes(c))try{let s=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:l,signal:i,allowNotActionableNodesOverride:a});return{...s,decisions:[...n,...s.decisions],pageState:void 0}}catch(s){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${s}`,elementImageUrl:l}),o.warn({err:s},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({root:e,screenshotUrl:t,oldTarget:n,signal:o,allowNotActionableNodesOverride:i}){let a;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let l=await this.screenshot({retries:0}),s=await(await fetch(t)).arrayBuffer(),u=Wz(),d=await this.enricher.runTemplateMatching({id:u,searchImageBase64String:Buffer.from(s).toString("base64"),pageImageBase64String:l.toString("base64")},{signal:o}),{target:p,locator:m}=await this.getTargetFromPositionPercentages({percentX:d.x,percentY:d.y,allowNotActionableNodesOverride:i}),g=p.boundingBox?.width,h=p.boundingBox?.height;if(!g||!h)throw a="Rejecting target from screenshot due to no bounding box",new Error(a);let f=p.id,S=this.stateManager.a11yIdToNodeMap[f],E=Ca(n);await this.updateCacheWithNewNodeDetails({target:n,node:S,locator:m,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:i});let y=Oh(E,n);return y&&Object.keys(y).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=Ne(this.logger),n.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:u,diffs:y,templateMatch:d},"Updated cache after template matching resolution")),{locator:m,a11yNode:S,displayString:p.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:t}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:1e3})??"",i=Pw.some(a=>a===o.toLowerCase());return await Sh({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 Sh({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:t},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,l=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),l=this.url(),Uc(l,t,n)){a=!0;break}await ee(500,this.abortSignal)}if(!a)throw new C("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${xc(t)} in ${o}ms.
|
|
3976
|
+
Current tab: ${l}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(c){this.logger.warn({err:c},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,t,n={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:3e3});if(!o)throw new C("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,l=n.steps??5;await this.page.mouse.move(i,a,{steps:l}),await ee(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o){o&&await this.hover({locator:o});let i=await(await this.getActivePageOrFrame()).evaluate(hh);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(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await di({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:3e3});if(!n)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(n.x+n.width/2,n.y+n.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await di({func:t=>t.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let t=await this.getActivePageOrFrame();await ut({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurring the active element"});return}await this.highlight(e.locator),await di({func:t=>t.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,t,n=!1){await this.highlight(e.locator),await di({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 C("UserConfigurationError",`Page index ${t.index} is not a number`)}await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?Number(t.index):void 0},{force:n,timeout:3e3})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=Qu(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=Qu(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Mh(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=Qu(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Mh(e))await this.page.keyboard.up(n)}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let n=0,o=2;for(;n<o;){n++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});break}catch(i){this.logger.warn({err:i,attempt:n},`Failed to reload page${n<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"}),await this.waitForDOMStability()}async getBrowserState(e){let{maxAttempts:t=2,logger:n=this.logger,skipWaitForPageLoad:o,allowNotActionableNodesOverride:i}=e,a=e.abortSignal??this.abortSignal,l=!i,c=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:a});let s=0,u;for(;s<t;){s++;try{return await H(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:a,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:c,flagNotActionableNodes:l}),{milliseconds:this.pageLoadTimeout*s,signal:a,message:"Getting browser state took too long"})}catch(d){if(a?.throwIfAborted(),u=d instanceof Error?d.message:`${d}`,s>=t)throw d;n.warn({err:d,url:this.url()},"Error getting a11y tree, retrying...")}}throw new C("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${u}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await ut({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:t,lowerBound:t+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:n=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=p=>{i.value=Date.now()},l=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",l);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let s=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",s);let u=()=>a("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",u);let d=()=>a("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",d);try{await this.waitForDOMStabilityHelper(i,t,n,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",l),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",s),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),l,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},s=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await ee(250,this.abortSignal),l)try{let d=await this.screenshot(c);if(!d.equals(l)){l=d,s=!1;continue}s=!0}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{l=await this.screenshot(c)}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<250)){i=!0;break}}i||t.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:s}},"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,t){let{x:n,y:o}=e;this.logger.debug({x:n,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(n,o,{button:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,t,n){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await ee(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,t,n,o){await this.hoverUsingVisualCoordinates(o);let i=await(await this.getActivePageOrFrame()).evaluate(hh);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(250),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),n=await H(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&n===1&&(n=2);let o=t.documents[0],i=o.layout,a=o.nodes,l=a.nodeName||[],c=a.backendNodeId||[],s=i.nodeIndex,u=i.bounds,d=-1;for(let E=0;E<l.length;E++)if(c[E]===e){d=s.indexOf(E);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[p=0,m=0,g=0,h=0]=u[d];p/=n,m/=n,g/=n,h/=n;let f=p+g/2,S=m+h/2;return{centerX:f,centerY:S}}async scrollVertical(e){return yh({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 yh({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(500)}}throw o}async switchToPageHelper(e,t){let n=this.context.pages().map((i,a)=>({page:i,url:i.url(),index:a})),o;if(e.type==="INDEX"){let i=Number(e.index);if(isNaN(i))throw new C("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)}.
|
|
3977
|
+
Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!Yo(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=Kl(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let n;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,t],`setting local storage key ${e}`);return}catch(i){n=i}if(n)throw n}async solveCaptcha(){await this.getBrowserState({allowNotActionableNodesOverride:!0});let e;for(let l of Object.values(this.stateManager.a11yIdToNodeMap))if(l.role==="image"&&l.name.toLowerCase().includes("captcha")){if(!l.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,l.backendNodeId);break}if(!e){let l=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!l.captchas||!l.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:ad,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let l=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},l),new Error(l)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<6e4;){await ee(2500);let l=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:ad,taskId:o})});if(!l.ok){let s=`Captcha solution API returned error response: ${l.statusText}`;throw this.logger.error({text:await l.text()},s),new Error(s)}let c=await l.json();if(c.errorId){let s=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(s),new Error(s)}if(c.status==="ready"){a=c.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&mC({event:t,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async startRecordingCrons(e){if(e.aborted)return;let t,n=(await this.getOpenPages()).map(l=>l.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let l;try{l=(await this.getOpenPages()).map(s=>s.url),o=0}catch(s){this.logger.debug({err:s},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let c=this.url();for(let s=l.length-1;s>=n.length;s--){let u=l[s];Yo(u,this.logger)&&u!==c&&this.logger.info({lastActivePages:n,currentUrl:c,newOpenPages:l},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(s)});break}n=l};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(l){this.logger.error({err:l},"Error while checking pages during recording")}finally{i=!1}}},500),e.addEventListener("abort",async()=>{clearInterval(t)})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(o=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!0,i._MOMENTIC_CLICK_RECORD_ACTIVE=o},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page),e.addEventListener("abort",async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let o=window;o._MOMENTIC_RECORDING_ACTIVE=!1,o._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:1e3})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await Ko({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let l=a;if(l.name==="AbortError")throw new C("UserInfrastructureError",`The page with URL ${Xe(i,50)} did not load within the configured timeout (${o}ms): ${l}`);if(!l.message.includes("detached"))throw l}try{await Ko({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 Uz.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 ut({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new C("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}registerDialogHandler(e){let t=async n=>{try{e==="ACCEPT"?await n.accept():await n.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",t)}async evaluateFunctionInAllFrames(e,t){return this.stateManager.executeFunctionInAllFrames(e,t)}async evaluateFunctionInPage(e,t,n,o=2e3){let i=await this.getActivePageOrFrame();return ut({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=Yn}){let i=_w(),a={code:e,fragment:t,context:n},{result:l}=await H(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new C("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return l}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new C("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:l}=await this.getViewportOffsetDetails(e),c=Math.round(a),s=Math.round(l),u=Math.ceil(o*t),d=Math.ceil(i*n),p=u+s,m=d+c;return this.getDomNodeFromPixelPosition(p,m)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:zw,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:1e3,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:1e3})}catch{}}async getTargetFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e);return this.getTargetFromBackendNodeId({root:t,backendNodeId:n.backendNodeId,allowNotActionableNodesOverride:e.allowNotActionableNodesOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:t,allowNotActionableNodesOverride:n}){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[_n],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let l=e.locator(Fr(a)),c;o.bounds.x!==null&&o.bounds.y!==null&&(c={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let s=await this.fetchHtmlAttributes({locator:l,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...s};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:l}}async performTargetRedirection(e,t,n){try{return await this.scrollIntoViewIfNeeded(e),await H(this.performTargetRedirectionHelper(e,t,n),{milliseconds:3e3})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,n){let o=Date.now(),i=await In(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:3e3})??void 0),!n){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:a,y:l,width:c,height:s}=n,u=this.getViewport();if(a<0||l<0||!u||a+c>u.width||l+s>u.height){t.info("Skipping locator redirection because the element is outside the viewport");return}let d=await this.getActivePageOrFrame(),{dataMomenticId:p,mPathSelector:m,error:g,serializedElement:h,point:f,force:S,logs:E}=await e.evaluate(A=>{let R=window;if(!R.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return R.performTargetRedirection(A)},void 0,{timeout:1e3}),y=Date.now()-o;if(g){t.warn({error:g,serializedElement:h,duration:y,force:S,logs:E},"Got error from target redirection with bounding box");return}else{if(p)return t.info({newDataMomenticId:p,serializedElement:h,duration:y,force:S,logs:E},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(Fr(p)),hints:{clickableXY:f,force:S}};if(m)return t.info({newMPathSelector:m,serializedElement:h,duration:y,force:S,logs:E},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(m),hints:{clickableXY:f,force:S}};if(f)return t.info({point:f,serializedElement:h,duration:y,force:S,logs:E},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:S}};if(S)return t.info({serializedElement:h,duration:y,force:S,logs:E},"Forcing click on original element"),{locator:e,hints:{force:S}}}}async fetchHtmlAttributes({locator:e,logger:t=this.logger,startingBoundingBox:n,allowNotActionableNodesOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,l=await e.evaluate((c,s)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,s):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:2e3});if("error"in l&&l.error)throw l.error.startsWith(dw)?new oc(l.error):l.error.startsWith(pw)?new ic(l.error):new Error(l.error);return l.warnings.length&&t.warn(l,"Got warnings while generating HTML attributes for target"),l.attributes}async moveMouseFromPositionPercentages(e,t){let n=this.getViewport();if(!n)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(n.width*e),i=Math.ceil(n.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:i,button:"left",clickCount:0}}),{x:o,y:i}}async clickMouseFromPositionPercentages(e,t,n){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*t),a=Math.ceil(o.height*n);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:i,y:a,button:"left",clickCount:e==="down"?1:0},timeout:1e3})}async scrollFromPositionPercentages(e,t,n,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),l=Math.ceil(i.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:l,x:n,y:o}}),{deltaX:a,deltaY:l}}canSolveCaptchas(){return!!ad}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,mh(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!mi(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()||zz(e),o=Nz(e),i=Hz(e),a=Jp[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!mi(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:Bz.getType(e)||"application/octet-stream"},{timeout:8e3})}catch(s){this.logger.error({err:s},"Error handling file chooser"),this.logToUserConsole(this.page,"error",s.message)}});let l=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:s,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=s;let p=atob(s),m=new Array(p.length);for(let h=0;h<p.length;h++)m[h]=p.charCodeAt(h);let g=new Uint8Array(m);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([g],{type:u})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([g]);return new File([h],d.momenticFileName,{type:u})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},d.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new d.MomenticFile])},{fileName:n,base64Data:l,mimeType:a},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let t={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},t}async copy(e){try{await this.evaluateFunctionInPage(t=>navigator.clipboard.writeText(t),e,"copying text to clipboard")}catch(t){if(t instanceof Error&&t.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard");return}throw t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(t=>{let n=t.request();return e.matches({url:n.url(),method:n.method()})})}registerRequestRecorder(e,t,n){this.requestRecorders[e]={onRequestStart:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestStart(o,i)},onRequestComplete:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestComplete(o,i)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,t,n){this.customHeaders.push({key:e.toLowerCase(),value:t,matcher:n})}registerMock(e,t,n,o){let i=e??Ph();return this.mocks[i]={matcher:t,generateResponse:n,fetchOriginalResponse:o},i}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}static getPossibleCrashReportsDirs(){let e=[];if(id()==="linux"){let t=xa();["chromium","google-chrome","chrome-canary"].forEach(n=>{e.push(pn(t,".config",n,"Crash Reports"))})}else if(id()==="darwin"){let t=xa();["Chromium","Google","Chrome for Testing"].forEach(n=>{e.push(pn(t,"Library","Application Support",n,"Crashpad"))})}else if(id()==="win32"){let t=xa();["Chromium","Google","Google Chrome Canary"].forEach(n=>{e.push(pn(t,"AppData","Local",n,"User Data","CrashPad","reports"))})}return e}static clearCrashReportsDirs(){try{r.getPossibleCrashReportsDirs().forEach(t=>{mi(t)&&kz(t,{recursive:!0,force:!0})})}catch{}}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get userBrowserSettings(){return Ca(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=r.getPossibleCrashReportsDirs();for(let t of e)if(!(!mi(t)||!SC(t).isDirectory()||!["new","pending","completed"].some(o=>{let i=pn(t,o);return mi(i)&&SC(i).isDirectory()&&Dz(i).length>0})))return t}};import dH from"fetch-cookie";import{cloneDeep as NC}from"lodash-es";import{CookieJar as pH}from"tough-cookie";async function mo(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(),tree:t}}var gi=3.1783027;function Kz(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 Mn(r){return Math.ceil(Nh(r)/gi)}function Nh(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
|
|
3978
|
+
`,""),t=t.replaceAll(" ","");let n=Kz(t);return t.length-n+gi*n}if(typeof r>"u")return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=Nh(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*gi:e+=85*gi:e+=Nh(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 RC={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},AC={minChunkTokenCount:5e3,acceptableChunkTokenCount:15e3,maxChunkTokenCount:5e4,maxLineLength:500},vC=/<(\S+) id="(\d+)".*?>/g,Yz=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,wC=["h1","h2","section","footer","nav","aside","form","label","dialog"],Xz=[...wC,"span","div","h3"],Jz=["table","select","form","ul","ol","menu","pre","code","dialog"],Qz=["table","form","dialog","nav","section","ul","select"];function sd(r){return Zz(r)}function Zz({serializedTree:r,options:e,logger:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=e,l=[],c=r.split(`
|
|
4029
3979
|
`),s=0,u=[],d=0,p=[],m=[],g=!1;for(;s<c.length;){g&&(l.push({ids:p,content:u.join(`
|
|
4030
|
-
`),tokenLength:d}),u=[],d=0,p=m.length?[m[m.length-1].id]:[],g=!1);let h=c[s],f=
|
|
4031
|
-
`),tokenLength:d}),l.forEach((h,f)=>{t.debug({chunk:h},`Chunk for page filtering (index ${f+1}/${l.length})`)}),{chunks:l}}var
|
|
4032
|
-
${r}`;case"ELEMENT_CHECK":return`${
|
|
4033
|
-
${r}`;default:return r}}var UH=15;async function Ju({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=UH}){if(!r.assertion.trim())throw new C("ActionFailureError","Assertion command is missing the assertion content");let{browser:l}=n,c=r.timeout?r.timeout*1e3:l.smartWaitingTimeout,s=LT(c),u=0,d=Date.now(),p,m,g;try{await tn({action:()=>l.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:l,logger:t})}catch(f){t.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;u<a&&(!h||h-d<c);){n.abortSignal.throwIfAborted(),u!==0&&await Z(s,n.abortSignal),h=Date.now();try{if(p=await tn({action:async()=>{let E=await fC(l,t,n.abortSignal);return m&&m.serializedTree===E.serializedTree&&m.screenshotBuff.equals(E.screenshotBuff)?p:(m=E,SC({command:r,state:E,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:t,source:o}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l}),p?.updatedMemory&&gc(r,p.updatedMemory,t),p?.success)break;throw p?.thoughts?new C("AssertionFailureError",p.thoughts):new C("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`),t.info({err:f},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!p?.success)try{p=await tn({action:async()=>SC({command:r,state:await fC(l,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l})}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new C("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:l.url()}}async function fC(r,e,t){let[n,o]=await Promise.all([co(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function SC({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:l,source:c,logger:s}){let{browser:u,generator:d,abortSignal:p}=t,m={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),S=u.url(),y=r.contextChoice??"MULTIMODAL",A=g;y!=="VISION_ONLY"&&(A=await pi({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:s,orgId:t.orgId}}),A!==g&&(m.ragUsed=!0),m.pageState=A);let R={goal:r.assertion,url:S,memory:o?r.cache?.memory:void 0,browserState:A,screenshot:E,contextChoice:y,source:c},x=await(y==="VISION_ONLY"?(_,M)=>d.getVisualAssertionResult(_,M):(_,M)=>d.getAssertionResult(_,M))(R,{useConsensus:n,attemptNumber:l,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:s,loggerTags:Pe(s)});return(x.result||i)&&x.relevantElements&&(m.relevantElementsSerialized=x.relevantElements.map(_=>u.getSerializedFormFromA11yId(_)).filter(_=>!!_),await BH(x.relevantElements,u,s)),{success:x.result,thoughts:x.thoughts,afterScreenshotOverride:f,updatedMemory:o?x.updatedMemory:void 0}}async function BH(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 H(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var HH=3e4;async function yC({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??HH/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let l;if(Xi(r.url)&&(l=r.url),t&&Ji(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);let s=await H((async()=>{try{return await n(l,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables?JSON.parse(r.variables):void 0}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!s)throw new C("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!s.ok){let d,p=await s.text();try{d=JSON.parse(p)}catch{throw new C("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new C("ActionFailureError",`GraphQL request failed with status ${s.status}: ${d.errors[0].message}`):new C("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}let u={};return s.headers.forEach((d,p)=>{u[p]=d}),{status:s.status,headers:u,json:await s.json()}}var uo=class{flagStore;orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,flagStore:o,storage:i,orgId:a,localCodeEvalTools:l,uploadedFileStorage:c,visualDiffScreenshotStorage:s,options:u}){this.orgId=a,this.options=u,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=i,this.uploadedFileStorage=c,this.visualDiffScreenshotStorage=s,this.localCodeEvalTools=l,this.generator=t,this.logger=n,this.flagStore=o}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:l=this.logger}){let[c,s]=await Promise.all([co(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:l}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${s.toString("base64")}`,d=await pi({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:l,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...Pe(l)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:l}){let c=this.browser.url(),[s,u]=await Promise.all([co(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 pi({type:"ai-action",description:e,screenshot:d,serializedTree:s.serializedTree,tree:s.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),m={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...Pe(a)},langfuseSessionId:l})}catch(g){throw new C("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return co(this.browser,e)}async locateElement(e){return await wh({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return tn({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,flagStore:this.flagStore,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:l,options:c,retriesWithAI:s=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],m=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(m)}try{let d=await l(...u.map(g=>g.result)),p=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",m=u.map((g,h)=>g.thoughts?`${p(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:m}}catch(d){if(this.throwIfClosed(),s>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:l,options:c,retriesWithAI:s-1});throw new C("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 tn({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&&kp(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(Up(i)||Fp(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Bp(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Wr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof C?n:new C("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:l}=o;if(t.type!=="description")throw new C("ActionFailureError","Cannot use selector with non-description target");let c,s=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){s=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:l,logger:a});return{result:await n({locator:d.locator}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;c=d,a.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-s<500&&await Z(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:l,command:c}=e,{disableCache:s,useSelector:u,targetName:d,targetHealingInProgress:p,source:m}=l,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=l.retriesWithAI??1,E=!1,S=EC(e.cache);if((!S||s)&&!Fd(o))throw new C("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);s&&(g.info("Cache explicitly disabled for this step"),E=!0,S=void 0),S&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&S.targetSource==="HEURISTIC_HEALED"&&(E=!0,S=void 0),S?.inputDescription&&!hC(o.elementDescriptor,S.inputDescription)&&(g.warn({old:S.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,S=void 0);let y=R=>!!R&&pl(R),A=!0;if(!y(S)){A=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:l.memory,useMemory:h},"Prompting AI for an updated element location"),E&&await Z(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let R;try{R=await wh({description:o.elementDescriptor,disableCache:!!l.disableCache,iframeUrl:l.iframeUrl,source:m,useMemory:h,memory:h?l.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(_){if(_ instanceof Hi&&_.updatedLocatorMemory){let M={id:-1,...i,memory:_.updatedLocatorMemory};zo({cmd:c,key:d,newTarget:M,logger:g})}throw new C("ActionFailureError",_.message)}R.frameConfig&&this.browser.setActiveFrameConfig(R.frameConfig);let w=l.disableGlobalLocatorRedirect?{locator:R.resolution.locator}:await this.attemptLocatorRedirect(R.resolution.locator,g),x=await a(w);return zo({cmd:c,key:d,newTarget:R.target,logger:g}),p&&(n.recordTargetAutoHeal({healType:"AI"}),R.target.targetSource="AI_HEALED",R.target.targetUpdateTime=new Date().toUTCString(),R.target.targetUpdateLoggerTags=Pe(g)),{result:x,elementInteractedDisplayString:R.resolution.displayString,thoughts:R.thoughts}}try{let R=await this.browser.resolveTarget(t,S,{allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect)&&await this.browser.scrollIntoViewIfNeeded(R.locator);let w=l.disableGlobalLocatorRedirect?{locator:R.locator}:await this.attemptLocatorRedirect(R.locator,g),x=await a(w);if(rr.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`]),zo({cmd:c,key:d,newTarget:S,logger:g}),A){let _=R.decisions.filter(M=>M.matched);if(_.length!==1)g.warn({decisions:R.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let M=_[0].type;n.recordTargetAutoHeal({healType:M})}}return{result:x,elementInteractedDisplayString:R.displayString}}catch(R){this.throwIfClosed(),rr.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`]);let w=!1;if((R instanceof Wr||kp(R)||Up(R)||Bp(R)||oy(R)||Fp(R))&&(w=!0),R instanceof C&&!w)throw g.error({err:R},"Failed to execute action with cached target (fatal)"),R;if(f>0&&o){g.info({err:R},"Failed to execute action with cached target, retrying with AI");let x;return S.memory&&ml(S.memory)&&(x=S.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...l,memory:x,retriesWithAI:f,targetHealingInProgress:!0}})}throw new C("ActionFailureError",R.message,{errOptions:{cause:R}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return xs(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await Z(this.options.slowMoMs);let a=await this.browser.getOpenPages(),l=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(s){throw this.throwIfClosed(),new C("ActionFailureError",`Failed to substitute template strings in command: ${s.message}`,{errOptions:{cause:s}})}try{let s=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&xf(n)?await this.browser.waitForDOMStability({timeout:2e3}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:1e3}),this.options?.autoFollowNewTabs&&await Mb({beforeUrl:l,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),s}catch(s){throw s.name!=="AbortError"&&this.logger.error({err:s},"Error thrown in action controller"),s}finally{Eb(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>eh(e)}}async resolveCommandTemplateStrings(e,t){return Uc({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,n,o,i){i=i||"disableCache"in n&&!!n.disableCache;let a=this.logger.child({commandId:n.id});switch(n.type){case"SUCCESS":let l=n.condition;return l?.assertion.trim()?Ju({command:l,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!n.assertion.trim())throw new C("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new C("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Ju({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=yE(n.schema);if(f)throw new C("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:g,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:Pe(a)});if(f.result==="NOT_FOUND")throw new C("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("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 C("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 C("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:f}}):f}}case"NAVIGATE":if(!Xi(n.url)&&!Ji(n.url,this.browser.baseUrl))throw new C("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let g,h;if(n.target&&Gr(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:S,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:A=>this.browser.hover(A),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});g=S,h=y}let f=this.browser.getViewport()?.height??Pt.height,E=this.browser.getViewport()?.width??Pt.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??E));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??E);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new C("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new C("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let s=n.delay*1e3;await Z(s,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Gr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:y=>this.browser.click(y,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),S={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:E,data:f};return _c(g,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(Gr(n.fromTarget)&&Gr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Gr(n.fromTarget)||Gr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,E)=>this.browser.dragAndDrop(f.locator,E.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(g)||isNaN(h))throw new C("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Gr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let E,S,y;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:A,result:R,thoughts:w}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async x=>x.locator,options:{disableCache:i,targetName:"target",...n}});E=R,S=A,y=w}return await this.browser.mouseDrag(g,h,f,E,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:S,thoughts:y}}case"SELECT_OPTION":{if(!Dn(n.target))throw new Error("Select with x/y is not supported yet");let g=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:g},cache:n.cache?.target,action:S=>this.browser.selectOption(S,h,n.force),options:{...n,targetName:"target",disableCache:i,source:Oo(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let g={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,g);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let g;try{n.environment==="BROWSER"?(g=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:g},"Executed JavaScript in browser")):g=await Zn({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 C("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new C("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(n.target&&Gr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let g=this.browser.url(),h,f,E=EC(n.target);if(E){let{elementInteractedDisplayString:y,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:R=>this.browser.typeIntoTarget(n.value,R,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!0,source:Oo(n)}});h=y,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 _c(g,S.urlAfterCommand)&&(S.succeedImmediately=!0,S.succeedImmediatelyReason="URL changed"),S}case"HOVER":{if(Gr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!Dn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(n.target&&!Dn(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return _c(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let g=new GH,h=zH(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await wb({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:NS(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await yC({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return Ab({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,g=await tw({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!g)throw new C("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!n.storageState.trim())g=void 0;else if(g=await Zn({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new C("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=Gl.optional().parse(g)}catch(f){throw new C("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??Vr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(vb(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 Ju({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&&gc(n,E.cache?.memory.traces,a)}}let f=await bb({command:n,tracer:t,timeoutMs:g,targetingWrapper:E=>this.wrapElementTargetingCommand(E),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let g=await tn({action:async()=>Hc({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new lo(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await fh(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[n.key];if(!g)throw new C("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await H(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new lo(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Vu(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Vu(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new C("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return n.requestMatcher&&(g=new lo(n.requestMatcher)),this.browser.setHeader(n.name,n.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new lo(n.requestMatcher),async(h,f)=>{let E=await Zn({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=qS.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(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:Pe(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:t,isClickToRecord:n}){this.recordAbortController=t;let o=new $u({signal:t.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,n),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Pe(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Pe(this.logger)})}};import{cloneDeep as VH}from"lodash-es";var jH={showOverlay:!1},Qu=class{sessions=new Map;sessionCountByIp=new Map;latestSessionId;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:t,cleanup:n,clientIp:o,sessionId:i,socket:a}){return this.sessions.set(i,{controller:e,context:t,cleanup:n,clientIp:o,browserBehavior:VH(jH),socket:a}),this.latestSessionId=i,i}removeSession(e,t){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:i}=o;try{i.setClosed(),await i.browser.cleanup()}catch(a){t.error({err:a},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(a){t.error({err:a},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}getLatestSession(){if(this.latestSessionId)return this.getSession(this.latestSessionId)}};function TC(r,e,t,n){let o=Date.now(),i=Date.now(),a,l,c,s,u=!1,d=async(h,f)=>{if(!h.closed&&!h.isInPageLoad)try{let E=c;c=void 0;let S=h.url(),y=f.toEditorDisplayCopy();JSON.stringify(y)===JSON.stringify(a)&&S===s&&o>i||(r.emit("browserState",{logsPerPage:E?.logsPerPage,harPages:E?.harPages,harEntries:E?.harEntries,viewport:h.getViewport(),url:S,iframeSrcUrls:l??[],context:y,isInPageLoad:h.isInPageLoad}),o=Date.now()),s=S,a=y}catch(E){if(!r.connected)return;let S=E instanceof Error?E.message:`${E}`;if(S.includes("Frame was detached")||S.includes("Not attached to an active page")||S.includes("browser has been closed")||S.includes("UserInfrastructureError"))return;t.error({err:E,sessionId:e},"Error grabbing browser state")}},p=setInterval(()=>{let h=n.getSession(e),f=h?.controller?.browser;if(!f||f.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(p);return}d(f,h.context)},1e3),m=(h,f)=>!!(JSON.stringify(h)!==JSON.stringify(l)||f.logsPerPage.some(E=>E.length>0)||f.harPages&&Object.keys(f.harPages).length>0||f.harEntries&&Object.keys(f.harEntries).length>0),g=setInterval(async()=>{let f=n.getSession(e)?.controller?.browser;if(!f||f.closed){clearInterval(g);return}else if(u)return;u=!0;try{let E=await f.getAllFrameUrls(),S=f.retrieveAndClearDebugData();m(E,S)&&(l=E,c=S,i=Date.now())}catch(E){t.warn({err:E},"Failed to fetch extended details")}finally{u=!1}},2500);return{timers:[p,g]}}var $H=4;async function bC({socket:r,logger:e,storageFactory:t,uploadedFileStorage:n,visualDiffScreenshotStorage:o,devicePixelRatio:i,generatorFactory:a,enricherFactory:l,authorization:c,flagStoreFactory:s,settingsFactory:u,getOrgId:d,branchGetter:p,globalE2eStateManager:m}){let g=r.id,h=r.handshake.query.testId;if(!h)throw new Error("Socket connection request is missing testId");let f=await d({type:"e2e",testId:h}),E=await p?.();e=e.child({testId:h,orgId:f,sessionId:g,branch:E});let S=await a(f,e),y=await l(f,e),A=await s(f),R=await u(f,e),w=await t(f),{testMetadata:x,baseUrl:_,envName:M,browserConfig:K,aiSettings:$,environmentVariables:k,localCodeEvalTools:Y}=await mi({testId:h,orgId:f,logger:e,storage:w,authorization:c,flagStore:A,settings:R}),I=m.getSession(g);if(I)return e.info("Associating connection with existing session (likely reconnect)"),await I.controller.browser.clearAllCdpHighlights(),{type:"e2e",sessionId:g,orgId:f,testId:h};let j=r.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:j,event:"connect",args:r.handshake.query},"Websocket event (connect)"),j&&m.getCurrentConnectionsByIp(j)>=$H)throw e.error({clientIp:j,sessions:m.getCurrentSessionsByIp(),...r.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close duplicate tabs and try again later.");m.reserveCapacityByIp(j);try{await WH({socket:r,baseUrl:_,envName:M,testMetadata:x,orgId:f,sessionId:g,logger:e,environmentVariables:k,clientIp:j,devicePixelRatio:i,storage:w,uploadedFileStorage:n,visualDiffScreenshotStorage:o,localCodeEvalTools:Y,generator:S,enricher:y,browserConfig:K,aiSettings:$,flagStore:A,globalE2eStateManager:m})}catch(ce){throw e.warn({err:ce},"Error setting up socket session, possibly due to client closing the connection"),m.releaseCapacityByIp(j),ce}return{type:"e2e",sessionId:g,testId:h,orgId:f}}async function WH({socket:r,baseUrl:e,envName:t,devicePixelRatio:n,testMetadata:o,orgId:i,sessionId:a,logger:l,storage:c,uploadedFileStorage:s,visualDiffScreenshotStorage:u,localCodeEvalTools:d,generator:p,environmentVariables:m,browserConfig:g,aiSettings:h,clientIp:f,enricher:E,flagStore:S,globalE2eStateManager:y}){let A={viewport:o.advanced?.viewport??Pt,locale:o.advanced?.locale??Hn,timezoneId:o.advanced?.timezone??zn,geolocation:o.advanced?.geolocation??Gn,colorScheme:o.advanced?.colorScheme};n&&(A.deviceScaleFactor=n);let R=o.id,w=await ku({settings:g,orgId:i,baseUrl:e,envName:t,testName:o.name,localTools:d,envVariables:m,logger:l,customHeaders:void 0});l=l.child({orgId:i,sessionId:a,testId:R});let x=S.isBooleanFlagEnabled("icon_knowledge_base")?await c.fetchIconKnowledgeBase(l):null,_=await Rr.init({baseUrl:e,userBrowserSettings:w,enricher:E,storage:c,flagStore:S,logger:l,contextArgs:A,iconKnowledgeBase:x,callbacks:{onTabsChange:(Y,I)=>{r.emit("tabs",{tabs:Y,activeTab:I})},onScreencastFrame:(Y,I)=>{let j=r;yn&&(j=r.compress(!0)),j.emit("screenshot",{buffer:Y},()=>{I()})},onSvgsCollected:Y=>{r.emit("newIconDetected",{numIcons:Y.newSvgs.length}),c.saveNewIcons(Y,l)}}});await _.navigate({url:e,initialNavigation:!0});let M=new uo({browser:_,generator:p,logger:l,flagStore:S,orgId:i,options:{scratchPadId:void 0,slowMoMs:w.slowMoMs,autoFollowNewTabs:w.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering??S.isBooleanFlagEnabled("rag_v2")},storage:c,localCodeEvalTools:d,uploadedFileStorage:s,visualDiffScreenshotStorage:u}),K=TC(r,a,l,y),$=async()=>{K.timers.forEach(Y=>clearInterval(Y))},k=new qt({baseUrl:e,testName:o.name,currentUrl:M.browser.url(),variablesFromEnvironment:m,envName:t});if(!r.connected)throw await _.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");r.emit("session",{url:e,userAgent:Rr.USER_AGENT,viewport:M.browser.getViewport(),sessionId:a}),y.registerSession({controller:M,context:k,sessionId:a,cleanup:$,clientIp:f,socket:r})}async function mi({testId:r,orgId:e,logger:t,storage:n,authorization:o,settings:i}){let a=await n.fetchTestMetadata(r,t);if(!a)throw new Error(`Test metadata could not found for test ${r}`);let l;o?.type==="API_KEY"&&(l=new Xr({httpClient:new At({...o,logger:t}),fakerSeed:void 0}));let c=a.envs?.find(h=>h.default),s;c&&(s=await n.fetchEnvironment(c.name,t));let u=s&&"browser"in s?s.browser:void 0,d={...i.browser,...u,...a.advanced},p=a.baseUrl||s?.variables?.[ht];if(!p)throw new Error("Base URL is empty in both test options and the configured environment");let m={...s?.variables};await Promise.all((a.parameters??[]).map(async h=>{let f=await er({orgId:e,s:h.defaultValue,context:qt.dummyContext(a.name,s?.name,m),logger:t,localTools:l});m[h.name]=f}));let g={...i.ai,...a.advanced};return{localCodeEvalTools:l,baseUrl:p,envName:s?.name,testName:a.name,browserConfig:d,environmentVariables:m,testMetadata:a,aiSettings:g}}var Ch=class{parentTracer=null;socket;step;orgId;constructor({step:e,socket:t,parentTracer:n,orgId:o}){this.socket=t,this.parentTracer=n,this.step=e,this.orgId=o}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}async finish(e){switch(e.step.status){case"SUCCESS":this.socket.emit("success",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"FAILED":this.socket.emit("failure",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"CANCELLED":this.socket.emit("cancelled",{...e,parentStepIdChain:this.getParentStepIdChain()});return}}async startSubSteps(){return new po({parentStep:this.step,socket:this.socket,parentTracer:this,orgId:this.orgId})}},po=class{stepFrequenciesByType={};parentTracer;parentStep;socket;orgId;recordStepStat(e){e.type!=="PRESET_ACTION"?this.stepFrequenciesByType[e.type]=(this.stepFrequenciesByType[e.type]||0)+1:this.stepFrequenciesByType[e.command.type]=(this.stepFrequenciesByType[e.command.type]||0)+1}sendFinalizedStepStats(){for(let[e,t]of Object.entries(this.stepFrequenciesByType))rr.increment("test_step_execution",t,[`type:${e}`,`orgId:${this.orgId}`])}constructor({parentStep:e,socket:t,parentTracer:n,orgId:o}){this.parentTracer=n,this.parentStep=e,this.socket=t,this.orgId=o}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.recordStepStat(e.step),this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:this.getParentStepIdChain(),attempt:e.attempt}),new Ch({step:e.step,parentTracer:this,socket:this.socket,orgId:this.orgId})}async finish(){this.sendFinalizedStepStats()}},Zu=class{constructor(e,t,n,o,i){this.socket=e;this.storage=t;this.orgId=n;this.testId=o;this.stepsBeforeRun=i}children=[];async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}attachConsoleLogs(){}attachNetworkLogs(){}async finish(){this.socket.emit("finished"),await Promise.all(this.children.map(e=>e.finish()))}async startBeforeStepList(){let e=new po({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startMainStepList(){let e=new po({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startAfterStepList(){let e=new po({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}};var xh={currentlyExecutingRequests:{}},KH=r=>async(e,t)=>{let{testId:n,orgId:o}=r.metadata,i=await r.flagStoreFactory(o),a=await r.settingsFactory(o,r.logger),l=await r.storageFactory(o),c,s=await mi({testId:n,orgId:o,logger:r.logger,storage:l,authorization:r.authorization,flagStore:i,settings:a}),u=`${n}|${s.baseUrl}`;try{let d=xh.currentlyExecutingRequests[u]??0;xh.currentlyExecutingRequests[u]=d+1,c=await YH({...r,...e,...s,done:t})}finally{r.logger.info({result:c,sessionId:r.metadata.sessionId},"Test execution complete"),xh.currentlyExecutingRequests[u]--}},YH=async({socket:r,steps:e,baseUrl:t,testMetadata:n,reInitialize:o,toStep:i,fromStep:a,storageFactory:l,aiSettings:c,browserConfig:s,metadata:u,logger:d,envName:p,testName:m,environmentVariables:g,localCodeEvalTools:h,done:f,cacheStorageFactory:E,globalE2eStateManager:S})=>{let{testId:y,sessionId:A,orgId:R}=u,w=A,x=S.getSession(A);if(!x)throw new Error("No active session found");let{controller:_,context:M}=x;_.setOpen(),d=d.child({testId:y,orgId:R,sessionId:A,runId:w}),d.info({steps:e.map(oe=>`${oe.type}${"command"in oe?` - ${oe.command.type}`:""}`),toStep:i,fromStep:a,reInitialize:o,envName:p,testName:m,baseUrl:t,context:M,flags:_.flagStore.getAllFlags()},"Socket execution parameters");let K=g??{},$=async()=>{o&&(await _.browser.reset({newUrl:t}),M.reset({baseUrl:t,currentUrl:_.browser.url(),variablesFromEnvironment:K,envName:p,testName:m}))},k=await l(R),Y=await E(R),I=async()=>{try{await Y.resolveStepCacheEntries({schemaVersion:n.schemaVersion,testId:y,stepLists:{steps:e},logger:d})}catch(oe){d.error({err:oe},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await Ss({promiseGenerator:async()=>Promise.all([$(),I()]),signal:_.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),_.setOpen()}catch(oe){if(r.emit("finished"),oe.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${oe}`)}let j=qH(e),ce={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},ne={orgId:R,runId:w,testMetadata:n,steps:e,fromStep:a,toStep:i,orgSettings:{ai:c,browser:s}},Re={controller:_,context:M,storage:k,codeEvalTools:h,usageTracker:new Di,logger:d},He={test:{},step:{onDynamicAIActionStatusUpdateEvent:oe=>{r.emit("dynamicCommandStatusUpdate",oe)},onDynamicAIActionEvaluatingEvent:oe=>{r.emit("dynamicCommandEvaluating",oe)},onDynamicCommandGenerated:oe=>{r.emit("dynamicCommandGenerated",oe)},onDynamicCommandExecuted:oe=>{r.emit("dynamicCommandExecuted",oe)}}},Ar=new Zu(r,k,R,y,j),tt=await Du({fixtures:Re,options:ce,callbacks:He,inputs:ne,testParams:{tracer:Ar}});return tt?.status==="PASSED"?await hc({logger:d,cacheStorage:Y,orgId:R,testId:y,originalSteps:{steps:j},updatedSteps:{steps:e}}):tt?.status==="FAILED"&&await fc({logger:d,cacheStorage:Y,orgId:R,testId:y,originalSteps:{steps:j},updatedSteps:{steps:e}}),await Ar.finish(),f?.(tt),tt.status};var vC={event:"execute",createHandler:KH};import{cloneDeep as XH}from"lodash-es";var JH=r=>async({command:e},t)=>{let{logger:n,generatorFactory:o,metadata:i}=r,a=XH(e),l=tT(a);if(l.category!=="NO_DESCRIPTION_PROVIDED"){if(l.category!=="NONE"){t?.({result:l});return}"cache"in a&&(a.cache=void 0);try{let s=await(await o(i.orgId,n)).getLintStepResult({command:a},{logger:n});t?.({result:s})}catch(c){n.error({event:"lint",err:c},"Failed to lint step"),t?.({result:void 0})}}},RC={event:"lintStep",createHandler:JH};var QH=({metadata:r,logger:e,storageFactory:t,globalE2eStateManager:n})=>{let{sessionId:o,orgId:i}=r;return async(a,l)=>{let{description:c,command:s,testMetadata:u,returnScreenshot:d}=a;e.info({params:a},`Locate handler called - ${c}`);let p=n.getSession(o);if(!p)throw new Error("No active session found");let{controller:m,context:g}=p;m.setOpen();let h=await t(i),f=Fo.parse(u.advanced??{}),E={},S;if(c){if("useSelector"in s&&s.useSelector)try{let y=await m.locateElementWithSelector(c,"iframeUrl"in s?s.iframeUrl:void 0);S=y.resolution.locator,E={target:y.target,thoughts:y.thoughts}}catch(y){e.warn({err:y},"Failed resolving target with selector"),l({err:`Failed locating element: ${y.message}`,decisions:y instanceof $r?y.decisions:void 0});return}else try{let y=await m.locateElement({description:c,disableCache:f.disableAICaching??!1,skipWait:!0,testContext:g,source:Oo(s),iframeUrl:"iframeUrl"in s?s.iframeUrl:void 0,memory:"cache"in s&&s.cache&&"target"in s.cache&&ml(s.cache.target.memory)?s.cache.target.memory:void 0,logger:e});E={target:y.target,thoughts:y.thoughts},S=y.resolution.locator}catch(y){(async()=>{try{let A=await m.browser.getCondensedHtml({skipWait:!0});e.warn({err:y,html:A.slice(0,1e5)},"Failed locating element with AI")}catch(A){e.warn({err:A},"Failed grabbing HTML after trying to locate element with AI")}})(),l({err:`${y.message}`});return}if(s.type==="SELECT_OPTION"&&S)try{E.options=await m.browser.getSelectOptions(S)}catch(y){e.warn({err:y},"Failed getting select options"),l({err:`Failed getting select options: ${y.message}`});return}e.info({result:E},"Locate handler result")}if(d)try{let{buffer:y,width:A,height:R}=await m.screenshotWithDimensions({clearHighlights:!0,locator:S}),w=await h.uploadScreenshot(y);E.screenshot={data:w,width:A,height:R},e.info({width:A,height:R},"Captured screenshot during locate")}catch(y){e.error({err:y},"Error capturing screenshot during locate"),l({err:`Error taking screenshot: ${y.message}`});return}if(l({result:E}),S)try{await Promise.all([m.browser.scrollIntoViewIfNeeded(S),m.browser.highlight(S)])}catch(y){e.warn({err:y},"Error highlighting element, continuing...")}}},AC={event:"locate",createHandler:QH};var ZH=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({event:o,percentX:i,percentY:a})=>{let l=t.getSession(n);if(!l)throw new Error("No active session found");let c=l.controller.browser;if(c.closed||c.getActivePage().isClosed()){e.warn("Ignoring mouse move because the browser is closed");return}try{await c.clickMouseFromPositionPercentages(o,i,a)}catch(s){e.error({err:s},"Error performing click during cloud recording in control mode")}}},wC={event:"mouseClickEvent",createHandler:ZH};var ez=({metadata:r,generatorFactory:e,logger:t,socket:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:l}=r;return async({stepId:c,parentStepIdChain:s,attribute:u})=>{let d=o.getSession(i);if(!d)throw new Error("No active session found");let{controller:p}=d,m=await e(a,t);p.setOpen(),d.browserBehavior.showOverlay=!0;let g=new AbortController;g.signal.addEventListener("abort",async()=>{try{d.browserBehavior.showOverlay=!1,await p.stopRecordMode()}catch(E){t.warn({err:E},"Failed to stop record mode in target click socket handler")}});let h=!1,f=(E,S)=>{S.type!=="PRESET_ACTION"||S.command.type!=="CLICK"||(n.emit("targetRecordingUpdate",{type:E,stepId:c,parentStepIdChain:s,command:S.command,attribute:u}),g.abort(),h=!0)};setTimeout(()=>{h||(g.abort(),n.emit("targetRecordingUpdate",{type:"error",err:"Timed out waiting for click event",stepId:c,parentStepIdChain:s,attribute:u}))},1e4),await p.startRecordMode({params:{generator:m,logger:t,testId:l,orgId:a,callbacks:{onActionReceived:E=>f("clickReceived",E),onStepRecorded:E=>f("descriptionGenerated",E)}},abortController:g,isClickToRecord:!0}),n.emit("targetRecordingUpdate",{type:"listenersInitialized",stepId:c,parentStepIdChain:s,attribute:u})}},CC={event:"recordTargetClick",createHandler:ez};var tz=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({key:o})=>{let i=t.getSession(n);if(!i)throw new Error("No active session found");if(o==="Dead")return;let{controller:a}=i;if(a.browser.closed||a.browser.getActivePage().isClosed()){e.debug({sessionId:n},"Browser is closed, ignoring keyboard press socket event");return}try{a.setOpen(),await a.browser.keyDown(o,{})}catch(l){if(l.message.includes("has been closed")){e.debug({sessionId:n,err:l},"Browser is closed, ignoring key down socket event error");return}throw l}}},xC={event:"keyDownEvent",createHandler:tz};var rz=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({key:o})=>{let i=t.getSession(n);if(!i)throw new Error("No active session found");if(o==="Dead")return;let{controller:a}=i;if(a.browser.closed||a.browser.getActivePage().isClosed()){e.debug({sessionId:n},"Browser is closed, ignoring keyboard press socket event");return}try{a.setOpen(),await a.browser.keyUp(o,{})}catch(l){if(l.message.includes("has been closed")){e.debug({sessionId:n,err:l},"Browser is closed, ignoring key up socket event error");return}throw l}}},_C={event:"keyUpEvent",createHandler:rz};var nz=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r,o,i=0,a=(s,u)=>{let d=async()=>{o=void 0};clearTimeout(o),o=setTimeout(d,Math.min(1e3,250*(i+1)))},l,c=0;return async s=>{let u=t.getSession(n);if(!u)throw new Error("No active session found");let{controller:d,browserBehavior:p}=u,m=d.browser;if(m.closed||m.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}if(s.event==="scroll"){let g=await m.scrollFromPositionPercentages(s.percentX,s.percentY,l?.x??0,l?.y??0),h=u.browserBehavior.recordingState?.transformer;h&&g&&h.recordScroll(g);return}p.showOverlay&&a(m,s);try{let g=await m.moveMouseFromPositionPercentages(s.percentX,s.percentY);c=0,l=g}catch(g){c++,c%5===0&&e.warn({err:g,mouseErrors:c},"Error in socket mouse move handler")}}},IC={event:"mouseMoveEvent",createHandler:nz};var oz=({metadata:r,generatorFactory:e,socket:t,logger:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:l}=r;return async({stepId:c})=>{let s=o.getSession(i);if(!s)throw new Error("No active session found");let{controller:u,browserBehavior:d}=s,p=await e(a,n);n.info("Starting cloud recording");let m=new AbortController,g=await u.startRecordMode({params:{generator:p,logger:n,testId:l,orgId:a,callbacks:{onActionReceived:(h,f)=>{t.emit("stepRecorded",{stepId:c,step:h,offset:f})},onStepRecorded:(h,f)=>{t.emit("stepRecorded",{stepId:c,step:h,offset:f})}}},abortController:m,isClickToRecord:!1});d.recordingState={transformer:g}}},PC={event:"recordingStart",createHandler:oz};var iz=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async()=>{let o=t.getSession(n);if(!o)throw new Error("No active session found");e.info("Stopping cloud recording"),await o.controller.stopRecordMode(),o.browserBehavior.recordingState=void 0,o.browserBehavior.showOverlay=!1}},MC={event:"recordingStop",createHandler:iz};var az=({socket:r,metadata:e,logger:t,storageFactory:n,authorization:o,flagStoreFactory:i,settingsFactory:a,globalE2eStateManager:l})=>async(c,s)=>{let{testId:u,sessionId:d,orgId:p}=e;t.info({testId:u,sessionId:d},"Refresh event received");let m=await i(p),g=await a(p,t),h=await n(p),{baseUrl:f}=await mi({testId:u,orgId:p,logger:t,storage:h,authorization:o,flagStore:m,settings:g}),E=l.getSession(d);if(!E){r.emit("error",{message:"No session to refresh"});return}let{controller:S}=E;S.setOpen(),await S.browser.refresh();let y=S.browser.getViewport();t.info({baseUrl:f,viewport:y},`Session refreshed for test ${u} at ${f}`),s()},OC={event:"refresh",createHandler:az};var sz=({socket:r,metadata:e,logger:t,storageFactory:n,authorization:o,flagStoreFactory:i,settingsFactory:a,globalE2eStateManager:l})=>async()=>{let{testId:c,sessionId:s,orgId:u}=e;t.info({testId:c,sessionId:s},"Reset event received");let d=await i(u),p=await a(u,t),m=await n(u),{baseUrl:g,envName:h,testName:f,environmentVariables:E}=await mi({testId:c,orgId:u,logger:t,storage:m,authorization:o,flagStore:d,settings:p}),S=l.getSession(s);if(!S){r.emit("error",{message:"No session to reset"});return}let{controller:y,context:A}=S;await y.browser.reset({newUrl:g});let R=y.browser.baseUrl;A.reset({baseUrl:R,currentUrl:y.browser.url(),variablesFromEnvironment:E,envName:h,testName:f});let w=y.browser.getViewport(),x=Rr.USER_AGENT;t.info({baseUrl:g,viewport:w},`Session reset for test ${c} at ${R}`),r.emit("session",{url:R,userAgent:x,viewport:w,sessionId:s})},LC={event:"reset",createHandler:sz};var lz=({metadata:r,globalE2eStateManager:e})=>{let{sessionId:t}=r;return async({url:n})=>{let o=e.getSession(t);if(!o)throw new Error("No active session found");await o.controller.browser.switchToPage({type:"SUBSTRING",substring:n})}},NC={event:"switchTab",createHandler:lz};async function DC(r){return bC(r)}var kC=[cb,vC,AC,LC,OC,ab,NC,RC,CC,PC,MC,IC,wC,xC,_C,lb,sb];var FC=r=>{let{logger:e}=r,t=new cz(r.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0});return t.on("connection",async n=>{let o;try{e.info({event:"connection",transport:n.conn.transport.name},"Websocket connection established"),o=await DC({...r,socket:n,logger:e}),e=e.child(o)}catch(i){e.error({event:"connection",type:"websocket",err:i},"Failed to setup connection"),n.emit("error",{message:i instanceof Error?i.message:`${i}`}),n.disconnect(!0);return}kC.forEach(i=>uz(i,{...r,socket:n,metadata:o,logger:e}))}),t},uz=(r,e)=>{let t=r.createHandler(e),n=(...o)=>{["mouseMoveEvent","keyDownEvent","keyUpEvent","mouseClickEvent","lintStep"].includes(r.event)||e.logger.debug({...e.metadata,event:r.event},`Websocket event (${r.event})`);let i=a=>{e.logger.error({event:r.event,type:"websocket",err:a instanceof Error?a:new Error(`${a}`)},"Unhandled exception in socket handler"),e.socket.emit("error",{message:a instanceof Error?a.message:`${a}`})};try{let a=t.apply(void 0,o);a&&typeof a.catch=="function"&&a.catch(i)}catch(a){i(a)}};e.socket.on(r.event,n)};import{Router as hz}from"express";import{Router as pz}from"express";import el from"fs";import Zs from"path";import{v4 as mz}from"uuid";import gz from"yaml";import{hostname as dz}from"os";var _h="2.17.9",st=oc({app:"desktop-server",hostname:dz(),disableConsoleLogs:!0}).child({cliVersion:_h});var wa=pz();async function Ih(r){return(await Lc(r,st)).map(n=>{let o=r.modules[n.moduleId];if(!o){T.warn(`Found a dangling module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}wa.get("/",fe(async(r,e)=>{let t=te(),n=q(t),o=await Ih(n);e.status(200).json(o)}));wa.post("/",fe(async(r,e)=>{let t;try{t=my.parse(r.body)}catch(l){e.status(400).json({error:`Invalid request body: ${l}`});return}try{Vn(t.name)}catch(l){e.status(400).json({error:`Invalid module name: ${l}`});return}let n=te(),o=q(n).modules;if(Object.values(o).find(l=>l.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let i=Zs.join(n.rootDir,t.folderPath??"");if(!el.existsSync(i)||!el.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let a=await Oc({...t,folder:i,project:n});e.status(201).json(a)}));wa.get("/:moduleId",fe(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=q(te()),n=t.modules[r.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await fr(n,t,T);e.json(o)}catch(o){e.status(400).json({err:o})}}));wa.post("/:moduleId/duplicate",fe(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=py.parse(r.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}try{Vn(t.name)}catch(h){e.status(400).json({error:h.message});return}let n=te(),o=q(n),i=o.modules[r.params.moduleId];if(!i){e.status(404).json({error:"Module not found."});return}if(Object.values(o.modules).find(h=>h.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let a=await fr(i,o,T),l=Zs.join(n.rootDir,Zs.dirname(i.relativePath));if(!el.existsSync(l)||!el.statSync(l).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${l}' does not exist.`});return}let c=_e(t.name),s=Zs.join(l,`${c}.module.yaml`),u=mz(),{stepsToSave:d}=await Ge({stepLists:{steps:a.steps},createNewCacheIds:!0,cacheCreationParams:{orgId:yt()}}),p={fileType:Se.MODULE,schemaVersion:ue,moduleId:u,name:t.name,description:"",enabled:!0,steps:d.steps,parameters:a.parameters,defaultParameters:a.defaultParameters,parameterEnums:a.parameterEnums,defaultCacheKey:a.defaultCacheKey,defaultCacheTtl:a.defaultCacheTtl,defaultCacheAllInvocations:a.defaultCacheAllInvocations,autoAuth:a.autoAuth,advanced:a.advanced},m=gz.stringify(p);el.writeFileSync(s,m,"utf-8");let g={relativeFilePath:Zs.relative(n.rootDir,s)};e.status(201).json(g)}));wa.patch("/:moduleId/metadata",fe(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=gy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=te(),o=q(n);zT({moduleId:r.params.moduleId,content:t,momenticFiles:o,logger:T,project:n}),e.status(201).json({message:"ok"})}));var UC=wa;var BC=hz();BC.get("/",fe(async(r,e)=>{let t=te(),n=q(t),o=new Set;n?.tests&&Object.values(n.tests).forEach(s=>{s.labels?.forEach(u=>o.add(u))});let i=Array.from(o).sort(),a=Object.values(n.tests),l=await Ih(n),c={labels:i,tests:a,modules:l};e.status(200).json(c)}));var HC=BC;import{Router as fz}from"express";var Ph=fz();Ph.get("/",fe((r,e)=>{let t=Nc(te(),st);e.status(200).json(t)}));Ph.get("/names",fe((r,e)=>{let n=te().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var zC=Ph;import{Router as Sz}from"express";var GC=Sz();GC.get("/",fe((r,e)=>{e.status(200).json({userId:ea(),orgId:yt()})}));var VC=GC;import{StreamableHTTPServerTransport as a1}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as s1}from"@modelcontextprotocol/sdk/types.js";import{randomUUID as l1}from"crypto";import{Router as c1}from"express";import{McpServer as o1}from"@modelcontextprotocol/sdk/server/mcp.js";import{SSEServerTransport as i1}from"@modelcontextprotocol/sdk/server/sse.js";import{tool as yz}from"ai";import{z as Ez}from"zod";var ed=r=>({builder:(t,n)=>yz({description:r.schema.description,inputSchema:Ez.object(r.schema.inputSchema),execute:async o=>{t.logger.info({input:o},`Executing tool ${r.schema.name}`);try{await r.handle(t,o,n,void 0)}catch(a){n.addError(String(a))}let i=await n.serialize();return i.isError?t.logger.error({toolName:r.schema.name,input:o,err:i.content.map(a=>a.text).join(`
|
|
4034
|
-
`)},"Tool execution resulted in error"):t.logger.info({toolName:r.schema.name,input:o},"Tool execution completed"),i}}),tool:r});var
|
|
3980
|
+
`),tokenLength:d}),u=[],d=0,p=m.length?[m[m.length-1].id]:[],g=!1);let h=c[s],f=Mn(h);d+=f,h.length>a&&(h=h.slice(0,a));let y=Array.from(h.matchAll(vC)).map(I=>I&&I.length>=3?{tagName:I[1],id:I[2]}:void 0).filter(I=>!!I),R=Array.from(h.matchAll(Yz)).map(I=>I&&(I[2]||I[4])).filter(I=>!!I);R.reverse();let w=h.replace(/ id="[0-9]+"/g,"");u.push(w);for(let I of y)p.push(I.id),m.push(I);for(let I of R){let re=m[m.length-1];re&&re.tagName===I&&m.pop()}let x=m.some(I=>Jz.includes(I.tagName)),_=c[s+1]??"",P=Mn(_),V=Array.from(_.matchAll(vC)).map(I=>I&&I.length>2?I[1]:void 0).filter(I=>!!I),k=V.some(I=>wC.includes(I)),Q=V.some(I=>Xz.includes(I));d+P>=i&&(g=!0),d>=n&&(k&&!x||R.some(I=>Qz.includes(I)))&&(g=!0),d>=o&&Q&&!x&&(g=!0),s++}return u.length&&l.push({ids:p,content:u.join(`
|
|
3981
|
+
`),tokenLength:d}),l.forEach((h,f)=>{t.debug({chunk:h},`Chunk for page filtering (index ${f+1}/${l.length})`)}),{chunks:l}}var eH=9e5,ld=3e5,tH=5e3;async function hi(r){let{options:e,fixtures:t,screenshot:n}=r,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:l,signal:c}=t,s=r.tree,u=r.serializedTree,d=Mn(u);if(d>eH)try{let p=sd({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});s=await nH({...r,tokenLimit:ld-1e4,chunks:p.chunks}),u=s.serialize();let m=Mn(u);i.info({oldTokens:d,newTokens:m},"Filtered page using keywords"),d=m}catch(p){i.warn({err:p},"Error filtering page using keyword matching, using naive truncation"),s=s.pruneToSerializedCharLimit(ld*gi),u=s.serialize(),i.info("Filtered page using naive truncation")}if(d>ld)try{if(o){let p=sd({serializedTree:u,options:AC,logger:i});s=await H(rH({...r,chunks:p.chunks}),{milliseconds:12e3}),u=s.serialize();let m=Mn(u);i.info({oldTokens:d,newTokens:m},"Filtered page using AI chunk ranking"),d=m}else{let p=sd({serializedTree:u,options:RC,logger:i});s=await H(oH({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=s.serialize();let m=Mn(u);i.info({oldTokens:d,newTokens:m},"Filtered page using RAG"),d=m}}catch(p){i.warn({err:p},"Error filtering page using RAG/AI, using naive truncation"),s=s.pruneToSerializedCharLimit(ld*gi),u=s.serialize(),i.info("Filtered page using naive truncation")}if(o&&d>tH&&r.type==="locator"&&(l==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||l==="org_01HMJTX4GT1KG94KZRCT8MZ6YB"))try{let p=await a.getPageSummary({browserContext:u,currentStep:r.description,screenshot:n,type:r.type},{logger:i,loggerTags:Ne(i),abortSignal:c});i.info(p,"Got AI summaries");let m=new Set;for(let h of p.relevantSections){let f=Math.min(h.startId,h.endId),S=Math.max(h.startId,h.endId);for(let E=f;E<=S;E++)m.add(E.toString())}s=s.pruneUsingRelevantIds(m),u=s.serialize();let g=Mn(u);i.info({newTokens:g,oldTokens:d},"Filtered page using AI summary"),d=g}catch(p){i.warn({err:p},"Error filtering page using AI summary, continuing...")}return u}async function rH({type:r,chunks:e,description:t,fixtures:n,tree:o}){let{generator:i,signal:a,logger:l}=n,c=await i.rankChunksWithAi({chunks:e,description:t,type:r,softTokenLimit:4e4,hardTokenLimit:8e4},{abortSignal:a,logger:l,loggerTags:Ne(l)}),s=[];return e.forEach((d,p)=>{c.indices.includes(p)&&(s=s.concat(d.ids))}),o.pruneUsingRelevantIds(new Set(s))}async function nH(r){let{description:e,fixtures:t,tree:n}=r,{generator:o,logger:i,signal:a}=t;if(!e.trim())throw new Error("Empty description passed to page filtering");let l=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:Ne(i),abortSignal:a});i.info({keywordsResult:l},"Got keywords for page filtering");for(let c of l.keywords){let s=r.chunks.filter(m=>m.content.toLowerCase().includes(c.toLowerCase()));if(!s.length||s.reduce((m,g)=>m+g.tokenLength,0)>r.tokenLimit&&s.length>1)continue;let d=s.flatMap(m=>m.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function oH(r){let{description:e,fixtures:t,chunkResult:n,tokenLimit:o,tree:i}=r,{generator:a,logger:l,signal:c}=t,s=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:l,loggerTags:Ne(l)});if(s.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(s.ids.map(d=>`${d}`)))}async function kh(r,e){if(!r.description)throw new C("UserConfigurationError","Cannot locate element with empty description");return nn({action:async()=>iH(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function iH(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:l,aiPageFiltering:c,logger:s,allowNotActionableNodesOverride:u}=r,{ctx:d,orgId:p,browser:m,localCodeEvalTools:g,generator:h,abortSignal:f}=e,S=r.description,E=r.useMemory&&!t;n&&(S=await tr({orgId:p,s:S,context:n,localTools:g,signal:f,logger:s})),a&&(S=sH(S,a));let{serializedTree:y,tree:A}=await mo(m,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:s}),R,w=Date.now(),x;for(;!R&&Date.now()-w<3e3;){f.throwIfAborted();try{R=await m.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(q){x=q}}if(!R)throw new C("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${x?.message}`);let _=y,P=!1,V=`data:image/jpeg;base64,${R.toString("base64")}`;_=await hi({type:"locator",description:S,screenshot:V,serializedTree:y,options:{aiPageFiltering:c},tree:A,fixtures:{generator:h,signal:f,logger:s,orgId:p}}),_!==y&&(P=!0);let k=await h.getElementLocation({browserState:_,goal:S,screenshot:V,source:a,memory:E?l:void 0},{disableCache:t,abortSignal:f,loggerTags:Ne(s),useMemory:E});s.debug({usedRag:P,result:k},"Got locator result");let Q=k.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:Q,pageState:_,ragUsed:P,thoughts:k.thoughts}),!Q)throw new Gi(`Could not find any relevant element: ${k.thoughts}`,k.updatedMemory?{type:"GCS_TRACES",traces:k.updatedMemory}:void 0);let{resolution:I,target:re,frameConfig:me}=await m.createTargetFromA11yId({id:k.id,requirements:k.requirements,additionalElements:k.additionalElements,description:S,targetSource:"AI",logger:s});if(I.a11yNode?.properties?.hidden&&I.a11yNode?.properties?.hidden!=="false")throw new C("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: ${I.displayString}`);return E&&(k.updatedMemory?re.memory={type:"GCS_TRACES",traces:k.updatedMemory}:l&&(re.memory=l)),{thoughts:k.thoughts,target:re,resolution:I,frameConfig:me,screenshot:V}}var aH=["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:"],CC="<select> element:",xC="text input or contenteditable element:",_C="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:",IC="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:",Dh=[CC,xC,_C,IC,...aH];function MC(r,e){if(r===e)return!0;for(let t of Dh){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Dh.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Dh.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function sH(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${CC} ${r}`;case"TYPE":return`${xC} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${_C}
|
|
3982
|
+
${r}`;case"ELEMENT_CHECK":return`${IC}
|
|
3983
|
+
${r}`;default:return r}}var lH=15;async function cd({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=lH}){if(!r.assertion.trim())throw new C("ActionFailureError","Assertion command is missing the assertion content");let{browser:l}=n,c=r.timeout?r.timeout*1e3:l.smartWaitingTimeout,s=$T(c),u=0,d=Date.now(),p,m,g;try{await nn({action:()=>l.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:l,logger:t})}catch(f){t.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;u<a&&(!h||h-d<c);){n.abortSignal.throwIfAborted(),u!==0&&await ee(s,n.abortSignal),h=Date.now();try{if(p=await nn({action:async()=>{let S=await PC(l,t,n.abortSignal);return m&&m.serializedTree===S.serializedTree&&m.screenshotBuff.equals(S.screenshotBuff)?p:(m=S,OC({command:r,state:S,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:t,source:o}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l}),p?.updatedMemory&&wc(r,p.updatedMemory,t),p?.success)break;throw p?.thoughts?new C("AssertionFailureError",p.thoughts):new C("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`),t.info({err:f},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!p?.success)try{p=await nn({action:async()=>OC({command:r,state:await PC(l,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l})}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new C("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:l.url()}}async function PC(r,e,t){let[n,o]=await Promise.all([mo(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function OC({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:l,source:c,logger:s}){let{browser:u,generator:d,abortSignal:p}=t,m={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,S=f.toString("base64"),E=u.url(),y=r.contextChoice??"MULTIMODAL",A=g;y!=="VISION_ONLY"&&(A=await hi({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:S,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:s,orgId:t.orgId}}),A!==g&&(m.ragUsed=!0),m.pageState=A);let R={goal:r.assertion,url:E,memory:o?r.cache?.memory:void 0,browserState:A,screenshot:S,contextChoice:y,source:c},x=await(y==="VISION_ONLY"?(_,P)=>d.getVisualAssertionResult(_,P):(_,P)=>d.getAssertionResult(_,P))(R,{useConsensus:n,attemptNumber:l,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:s,loggerTags:Ne(s)});return(x.result||i)&&x.relevantElements&&(m.relevantElementsSerialized=x.relevantElements.map(_=>u.getSerializedFormFromA11yId(_)).filter(_=>!!_),await cH(x.relevantElements,u,s)),{success:x.result,thoughts:x.thoughts,afterScreenshotOverride:f,updatedMemory:o?x.updatedMemory:void 0}}async function cH(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 H(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var uH=3e4;async function LC({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??uH/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let l;if(Qi(r.url)&&(l=r.url),t&&Zi(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);let s=await H((async()=>{try{return await n(l,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables?JSON.parse(r.variables):void 0}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!s)throw new C("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!s.ok){let d,p=await s.text();try{d=JSON.parse(p)}catch{throw new C("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new C("ActionFailureError",`GraphQL request failed with status ${s.status}: ${d.errors[0].message}`):new C("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}let u={};return s.headers.forEach((d,p)=>{u[p]=d}),{status:s.status,headers:u,json:await s.json()}}var go=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:l,visualDiffScreenshotStorage:c,options:s}){this.orgId=i,this.options=s,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=l,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=a,this.generator=t,this.logger=n}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:l=this.logger}){let[c,s]=await Promise.all([mo(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:l}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${s.toString("base64")}`,d=await hi({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:l,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...Ne(l)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:l}){let c=this.browser.url(),[s,u]=await Promise.all([mo(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 hi({type:"ai-action",description:e,screenshot:d,serializedTree:s.serializedTree,tree:s.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),m={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...Ne(a)},langfuseSessionId:l})}catch(g){throw new C("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return mo(this.browser,e)}async locateElement(e){return await kh({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return nn({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:l,options:c,retriesWithAI:s=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],m=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(m)}try{let d=await l(...u.map(g=>g.result)),p=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",m=u.map((g,h)=>g.thoughts?`${p(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:m}}catch(d){if(this.throwIfClosed(),s>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:l,options:c,retriesWithAI:s-1});throw new C("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 nn({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&&Wp(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(Kp(i)||qp(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Yp(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Kr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof C?n:new C("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:l}=o;if(t.type!=="description")throw new C("ActionFailureError","Cannot use selector with non-description target");let c,s=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){s=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:l,logger:a});return{result:await n({locator:d.locator}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;c=d,a.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-s<500&&await ee(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:l,command:c}=e,{disableCache:s,useSelector:u,targetName:d,targetHealingInProgress:p,source:m}=l,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=l.retriesWithAI??1,S=!1,E=NC(e.cache);if((!E||s)&&!Kd(o))throw new C("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);s&&(g.info("Cache explicitly disabled for this step"),S=!0,E=void 0),E&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&E.targetSource==="HEURISTIC_HEALED"&&(S=!0,E=void 0),E?.inputDescription&&!MC(o.elementDescriptor,E.inputDescription)&&(g.warn({old:E.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),S=!0,E=void 0);let y=R=>!!R&&El(R),A=!0;if(!y(E)){A=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:S,memory:l.memory,useMemory:h},"Prompting AI for an updated element location"),S&&await ee(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let R;try{R=await kh({description:o.elementDescriptor,disableCache:!!l.disableCache,iframeUrl:l.iframeUrl,source:m,useMemory:h,memory:h?l.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(_){if(_ instanceof Gi&&_.updatedLocatorMemory){let P={id:-1,...i,memory:_.updatedLocatorMemory};Ac({cmd:c,key:d,newTarget:P,logger:g})}throw new C("ActionFailureError",_.message)}R.frameConfig&&this.browser.setActiveFrameConfig(R.frameConfig);let w=l.disableGlobalLocatorRedirect?{locator:R.resolution.locator}:await this.attemptLocatorRedirect(R.resolution.locator,g),x=await a(w);return Ac({cmd:c,key:d,newTarget:R.target,logger:g}),p&&(n.recordTargetAutoHeal({healType:"AI"}),R.target.targetSource="AI_HEALED",R.target.targetUpdateTime=new Date().toUTCString(),R.target.targetUpdateLoggerTags=Ne(g)),{result:x,elementInteractedDisplayString:R.resolution.displayString,thoughts:R.thoughts}}try{let R=await this.browser.resolveTarget(t,E,{allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(R.locator);let w=l.disableGlobalLocatorRedirect?{locator:R.locator}:await this.attemptLocatorRedirect(R.locator,g),x=await a(w);if(nr.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!E.requirements}`,`hasAdditionalElements:${!!E.additionalElements}`]),Ac({cmd:c,key:d,newTarget:E,logger:g}),A){let _=R.decisions.filter(P=>P.matched);if(_.length!==1)g.warn({decisions:R.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let P=_[0].type;n.recordTargetAutoHeal({healType:P})}}return{result:x,elementInteractedDisplayString:R.displayString}}catch(R){this.throwIfClosed(),nr.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!E.requirements}`,`hasAdditionalElements:${!!E.additionalElements}`]);let w=!1;if((R instanceof Kr||Wp(R)||Kp(R)||Yp(R)||hy(R)||qp(R))&&(w=!0),R instanceof C&&!w)throw g.error({err:R},"Failed to execute action with cached target (fatal)"),R;if(f>0&&o){g.info({err:R},"Failed to execute action with cached target, retrying with AI");let x;return E.memory&&Tl(E.memory)&&(x=E.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...l,memory:x,retriesWithAI:f,targetHealingInProgress:!0}})}throw new C("ActionFailureError",R.message,{errOptions:{cause:R}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return Ls(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await ee(this.options.slowMoMs);let a=await this.browser.getOpenPages(),l=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(s){throw this.throwIfClosed(),new C("ActionFailureError",`Failed to substitute template strings in command: ${s.message}`,{errOptions:{cause:s}})}try{let s=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&Ff(n)?await this.browser.waitForDOMStability({timeout:2e3}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:1e3}),this.options?.autoFollowNewTabs&&await Wb({beforeUrl:l,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),s}catch(s){throw s.name!=="AbortError"&&this.logger.error({err:s},"Error thrown in action controller"),s}finally{Mb(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>dh(e)}}async resolveCommandTemplateStrings(e,t){return Yc({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,n,o,i){i=i||"disableCache"in n&&!!n.disableCache;let a=this.logger.child({commandId:n.id});switch(n.type){case"SUCCESS":let l=n.condition;return l?.assertion.trim()?cd({command:l,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!n.assertion.trim())throw new C("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new C("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return cd({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=IE(n.schema);if(f)throw new C("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:g,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:Ne(a)});if(f.result==="NOT_FOUND")throw new C("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let S=f.message;throw S.includes("MaxGenerationLengthExceededError")?new C("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."):S.includes("AIProviderError")&&S.includes("time")?new C("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(!Qi(n.url)&&!Zi(n.url,this.browser.baseUrl))throw new C("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let g,h;if(n.target&&Vr(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:E,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:A=>this.browser.hover(A),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});g=E,h=y}let f=this.browser.getViewport()?.height??Mt.height,S=this.browser.getViewport()?.width??Mt.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??S));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??S);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new C("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new C("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let s=n.delay*1e3;await ee(s,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Vr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:S}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:y=>this.browser.click(y,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),E={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:S,data:f};return Bc(g,E.urlAfterCommand)&&(E.succeedImmediately=!0,E.succeedImmediatelyReason="URL changed"),E}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(Vr(n.fromTarget)&&Vr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Vr(n.fromTarget)||Vr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,S)=>this.browser.dragAndDrop(f.locator,S.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(g)||isNaN(h))throw new C("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Vr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let S,E,y;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:A,result:R,thoughts:w}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async x=>x.locator,options:{disableCache:i,targetName:"target",...n}});S=R,E=A,y=w}return await this.browser.mouseDrag(g,h,f,S,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:y}}case"SELECT_OPTION":{if(!Un(n.target))throw new Error("Select with x/y is not supported yet");let g=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:S}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:g},cache:n.cache?.target,action:E=>this.browser.selectOption(E,h,n.force),options:{...n,targetName:"target",disableCache:i,source:Do(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:S}}case"TAB":{let g={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,g);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let g;try{n.environment==="BROWSER"?(g=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:g},"Executed JavaScript in browser")):g=await ro({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 C("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new C("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(n.target&&Vr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let g=this.browser.url(),h,f,S=NC(n.target);if(S){let{elementInteractedDisplayString:y,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:S,cache:n.cache?.target,action:R=>this.browser.typeIntoTarget(n.value,R,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!0,source:Do(n)}});h=y,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 E={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Bc(g,E.urlAfterCommand)&&(E.succeedImmediately=!0,E.succeedImmediatelyReason="URL changed"),E}case"HOVER":{if(Vr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!Un(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(n.target&&!Un(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Bc(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let g=new pH,h=dH(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await Fb({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:jS(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await LC({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return kb({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,g=await fw({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!g)throw new C("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!n.storageState.trim())g=void 0;else if(g=await ro({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new C("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=Yl.optional().parse(g)}catch(f){throw new C("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??jr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(Nb(n.assertion)&&!n.useSelector&&n.target.type==="description"&&h&&h!=="v1"){let S={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 E=await cd({command:S,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: ${E.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:E.afterScreenshotOverride}}finally{S.cache?.memory&&wc(n,S.cache?.memory.traces,a)}}let f=await Lb({command:n,tracer:t,timeoutMs:g,targetingWrapper:S=>this.wrapElementTargetingCommand(S),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let g=await nn({action:async()=>Jc({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new po(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await _h(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[n.key];if(!g)throw new C("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await H(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new po(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=td(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=td(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new C("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return n.requestMatcher&&(g=new po(n.requestMatcher)),this.browser.setHeader(n.name,n.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new po(n.requestMatcher),async(h,f)=>{let S=await ro({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"}),E=oy.parse(S);return new Response(E.body,{status:E.status,headers:E.headers})},n.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:Ne(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 nd({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:Ne(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Ne(this.logger)})}};import{cloneDeep as mH}from"lodash-es";var gH={showOverlay:!1},ud=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:t,cleanup:n,clientIp:o,sessionId:i,socket:a}){return this.sessions.set(i,{controller:e,context:t,cleanup:n,clientIp:o,browserBehavior:mH(gH),socket:a}),i}removeSession(e,t){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:i}=o;try{i.setClosed(),await i.browser.cleanup()}catch(a){t.error({err:a},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(a){t.error({err:a},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}};function DC(r,e,t,n){let o=Date.now(),i=Date.now(),a,l,c,s,u=!1,d=async(h,f)=>{if(!h.closed&&!h.isInPageLoad)try{let S=c;c=void 0;let E=h.url(),y=f.toEditorDisplayCopy();JSON.stringify(y)===JSON.stringify(a)&&E===s&&o>i||(r.emit("browserState",{logsPerPage:S?.logsPerPage,harPages:S?.harPages,harEntries:S?.harEntries,viewport:h.getViewport(),url:E,iframeSrcUrls:l??[],context:y,isInPageLoad:h.isInPageLoad}),o=Date.now()),s=E,a=y}catch(S){if(!r.connected)return;let E=S instanceof Error?S.message:`${S}`;if(E.includes("Frame was detached")||E.includes("Not attached to an active page")||E.includes("browser has been closed")||E.includes("UserInfrastructureError"))return;t.error({err:S,sessionId:e},"Error grabbing browser state")}},p=setInterval(()=>{let h=n.getSession(e),f=h?.controller?.browser;if(!f||f.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(p);return}d(f,h.context)},1e3),m=(h,f)=>!!(JSON.stringify(h)!==JSON.stringify(l)||f.logsPerPage.some(S=>S.length>0)||f.harPages&&Object.keys(f.harPages).length>0||f.harEntries&&Object.keys(f.harEntries).length>0),g=setInterval(async()=>{let f=n.getSession(e)?.controller?.browser;if(!f||f.closed){clearInterval(g);return}else if(u)return;u=!0;try{let S=await f.getAllFrameUrls(),E=f.retrieveAndClearDebugData();m(S,E)&&(l=S,c=E,i=Date.now())}catch(S){t.warn({err:S},"Failed to fetch extended details")}finally{u=!1}},2500);return{timers:[p,g]}}var hH=4;async function kC({socket:r,logger:e,storageFactory:t,uploadedFileStorage:n,visualDiffScreenshotStorage:o,devicePixelRatio:i,generatorFactory:a,enricherFactory:l,authorization:c,settingsFactory:s,getOrgId:u,branchGetter:d,globalE2eStateManager:p}){let m=r.id,g=r.handshake.query.testId;if(!g)throw new Error("Socket connection request is missing testId");let h=await u({type:"e2e",testId:g}),f=await d?.();e=e.child({testId:g,orgId:h,sessionId:m,branch:f});let S=await a(h,e),E=await l(h,e),y=await s(h,e),A=await t(h),{testMetadata:R,baseUrl:w,envName:x,browserConfig:_,aiSettings:P,environmentVariables:X,localCodeEvalTools:V}=await fi({testId:g,orgId:h,logger:e,storage:A,authorization:c,settings:y}),k=p.getSession(m);if(k)return e.info("Associating connection with existing session (likely reconnect)"),await k.controller.browser.clearAllCdpHighlights(),{type:"e2e",sessionId:m,orgId:h,testId:g};let Q=r.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:Q,event:"connect",args:r.handshake.query},"Websocket event (connect)"),Q&&p.getCurrentConnectionsByIp(Q)>=hH)throw e.error({clientIp:Q,sessions:p.getCurrentSessionsByIp(),...r.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close duplicate tabs and try again later.");p.reserveCapacityByIp(Q);try{await fH({socket:r,baseUrl:w,envName:x,testMetadata:R,orgId:h,sessionId:m,logger:e,environmentVariables:X,clientIp:Q,devicePixelRatio:i,storage:A,uploadedFileStorage:n,visualDiffScreenshotStorage:o,localCodeEvalTools:V,generator:S,enricher:E,browserConfig:_,aiSettings:P,globalE2eStateManager:p})}catch(I){throw e.warn({err:I},"Error setting up socket session, possibly due to client closing the connection"),p.releaseCapacityByIp(Q),I}return{type:"e2e",sessionId:m,testId:g,orgId:h}}async function fH({socket:r,baseUrl:e,envName:t,devicePixelRatio:n,testMetadata:o,orgId:i,sessionId:a,logger:l,storage:c,uploadedFileStorage:s,visualDiffScreenshotStorage:u,localCodeEvalTools:d,generator:p,environmentVariables:m,browserConfig:g,aiSettings:h,clientIp:f,enricher:S,globalE2eStateManager:E}){let y={viewport:o.advanced?.viewport??Mt,locale:o.advanced?.locale??Vn,timezoneId:o.advanced?.timezone??jn,geolocation:o.advanced?.geolocation??$n,colorScheme:o.advanced?.colorScheme};n&&(y.deviceScaleFactor=n);let A=o.id,R=await Yu({settings:g,orgId:i,baseUrl:e,envName:t,testName:o.name,localTools:d,envVariables:m,logger:l,customHeaders:void 0});l=l.child({orgId:i,sessionId:a,testId:A});let w=await wr.init({baseUrl:e,userBrowserSettings:R,enricher:S,storage:c,logger:l,contextArgs:y,iconKnowledgeBase:null,callbacks:{onTabsChange:(V,k)=>{r.emit("tabs",{tabs:V,activeTab:k})},onScreencastFrame:(V,k)=>{let Q=r;En&&(Q=r.compress(!0)),Q.emit("screenshot",{buffer:V},()=>{k()})},onSvgsCollected:V=>{r.emit("newIconDetected",{numIcons:V.newSvgs.length}),c.saveNewIcons(V,l)}}});await w.navigate({url:e,initialNavigation:!0});let x=new go({browser:w,generator:p,logger:l,orgId:i,options:{scratchPadId:void 0,slowMoMs:R.slowMoMs,autoFollowNewTabs:R.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering},storage:c,localCodeEvalTools:d,uploadedFileStorage:s,visualDiffScreenshotStorage:u}),_=DC(r,a,l,E),P=async()=>{_.timers.forEach(V=>clearInterval(V))},X=new qt({baseUrl:e,testName:o.name,currentUrl:x.browser.url(),variablesFromEnvironment:m,envName:t});if(!r.connected)throw await w.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");r.emit("session",{url:e,userAgent:wr.USER_AGENT,viewport:x.browser.getViewport(),sessionId:a}),E.registerSession({controller:x,context:X,sessionId:a,cleanup:P,clientIp:f,socket:r})}async function fi({testId:r,orgId:e,logger:t,storage:n,authorization:o,settings:i}){let a=await n.fetchTestMetadata(r,t);if(!a)throw new Error(`Test metadata could not found for test ${r}`);let l;o?.type==="API_KEY"&&(l=new Qr({httpClient:new At({...o,logger:t}),fakerSeed:void 0}));let c=a.envs?.find(h=>h.default),s;c&&(s=await n.fetchEnvironment(c.name,t));let u=s&&"browser"in s?s.browser:void 0,d={...i.browser,...u,...a.advanced},p=a.baseUrl||s?.variables?.[ht];if(!p)throw new Error("Base URL is empty in both test options and the configured environment");let m={...s?.variables};await Promise.all((a.parameters??[]).map(async h=>{let f=await tr({orgId:e,s:h.defaultValue,context:qt.dummyContext(a.name,s?.name,m),logger:t,localTools:l});m[h.name]=f}));let g={...i.ai,...a.advanced};return{localCodeEvalTools:l,baseUrl:p,envName:s?.name,testName:a.name,browserConfig:d,environmentVariables:m,testMetadata:a,aiSettings:g}}var Fh=class{parentTracer=null;socket;step;orgId;constructor({step:e,socket:t,parentTracer:n,orgId:o}){this.socket=t,this.parentTracer=n,this.step=e,this.orgId=o}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}async finish(e){switch(e.step.status){case"SUCCESS":this.socket.emit("success",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"FAILED":this.socket.emit("failure",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"CANCELLED":this.socket.emit("cancelled",{...e,parentStepIdChain:this.getParentStepIdChain()});return}}async startSubSteps(){return new ho({parentStep:this.step,socket:this.socket,parentTracer:this,orgId:this.orgId})}},ho=class{stepFrequenciesByType={};parentTracer;parentStep;socket;orgId;recordStepStat(e){e.type!=="PRESET_ACTION"?this.stepFrequenciesByType[e.type]=(this.stepFrequenciesByType[e.type]||0)+1:this.stepFrequenciesByType[e.command.type]=(this.stepFrequenciesByType[e.command.type]||0)+1}sendFinalizedStepStats(){for(let[e,t]of Object.entries(this.stepFrequenciesByType))nr.increment("test_step_execution",t,[`type:${e}`,`orgId:${this.orgId}`])}constructor({parentStep:e,socket:t,parentTracer:n,orgId:o}){this.parentTracer=n,this.parentStep=e,this.socket=t,this.orgId=o}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.recordStepStat(e.step),this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:this.getParentStepIdChain(),attempt:e.attempt}),new Fh({step:e.step,parentTracer:this,socket:this.socket,orgId:this.orgId})}async finish(){this.sendFinalizedStepStats()}},dd=class{constructor(e,t,n,o,i){this.socket=e;this.storage=t;this.orgId=n;this.testId=o;this.stepsBeforeRun=i}children=[];loggerBindings;async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}attachConsoleLogs(){}attachNetworkLogs(){}attachBrowserCrashDump(){}async finish(){this.socket.emit("finished"),await Promise.all(this.children.map(e=>e.finish()))}async startBeforeStepList(){let e=new ho({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startMainStepList(){let e=new ho({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startAfterStepList(){let e=new ho({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}};var Uh={currentlyExecutingRequests:{}},yH=r=>async(e,t)=>{let{testId:n,orgId:o}=r.metadata,i=await r.settingsFactory(o,r.logger),a=await r.storageFactory(o),l,c=await fi({testId:n,orgId:o,logger:r.logger,storage:a,authorization:r.authorization,settings:i}),s=`${n}|${c.baseUrl}`;try{let u=Uh.currentlyExecutingRequests[s]??0;Uh.currentlyExecutingRequests[s]=u+1,l=await EH({...r,...e,...c,done:t})}finally{r.logger.info({result:l,sessionId:r.metadata.sessionId},"Test execution complete"),Uh.currentlyExecutingRequests[s]--}},EH=async({socket:r,steps:e,baseUrl:t,testMetadata:n,reInitialize:o,toStep:i,fromStep:a,storageFactory:l,aiSettings:c,browserConfig:s,metadata:u,logger:d,envName:p,testName:m,environmentVariables:g,localCodeEvalTools:h,done:f,cacheStorageFactory:S,globalE2eStateManager:E})=>{let{testId:y,sessionId:A,orgId:R}=u,w=A,x=E.getSession(A);if(!x)throw new Error("No active session found");let{controller:_,context:P}=x;_.setOpen(),d=d.child({testId:y,orgId:R,sessionId:A,runId:w}),d.info({steps:e.map(K=>`${K.type}${"command"in K?` - ${K.command.type}`:""}`),toStep:i,fromStep:a,reInitialize:o,envName:p,testName:m,baseUrl:t,context:P,browserConfig:s,aiSettings:c},"Socket execution parameters");let X=g??{},V=async()=>{o&&(await _.browser.reset({newUrl:t}),P.reset({baseUrl:t,currentUrl:_.browser.url(),variablesFromEnvironment:X,envName:p,testName:m}))},k=await l(R),Q=await S(R),I=async()=>{try{await Q.resolveStepCacheEntries({schemaVersion:n.schemaVersion,testId:y,stepLists:{steps:e},logger:d})}catch(K){d.error({err:K},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await Rs({promiseGenerator:async()=>Promise.all([V(),I()]),signal:_.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),_.setOpen()}catch(K){if(r.emit("finished"),K.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${K}`)}let re=SH(e),me={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},q={orgId:R,runId:w,testMetadata:n,steps:e,fromStep:a,toStep:i,orgSettings:{ai:c,browser:s}},Qe={controller:_,context:P,storage:k,codeEvalTools:h,usageTracker:new Fi,logger:d},Ve={test:{},step:{onDynamicAIActionStatusUpdateEvent:K=>{r.emit("dynamicCommandStatusUpdate",K)},onDynamicAIActionEvaluatingEvent:K=>{r.emit("dynamicCommandEvaluating",K)},onDynamicCommandGenerated:K=>{r.emit("dynamicCommandGenerated",K)},onDynamicCommandExecuted:K=>{r.emit("dynamicCommandExecuted",K)}}},gt=new dd(r,k,R,y,re),bt=await Ku({fixtures:Qe,options:me,callbacks:Ve,inputs:q,testParams:{tracer:gt}});return bt?.status==="PASSED"?await Nc({logger:d,cacheStorage:Q,orgId:R,testId:y,originalSteps:{steps:re},updatedSteps:{steps:e}}):bt?.status==="FAILED"&&await Dc({logger:d,cacheStorage:Q,orgId:R,testId:y,originalSteps:{steps:re},updatedSteps:{steps:e}}),await gt.finish(),f?.(bt),bt.status};var FC={event:"execute",createHandler:yH};import{cloneDeep as TH}from"lodash-es";var bH=r=>async({command:e},t)=>{let{logger:n,generatorFactory:o,metadata:i}=r,a=TH(e),l=dT(a);if(l.category!=="NO_DESCRIPTION_PROVIDED"){if(l.category!=="NONE"){t?.({result:l});return}"cache"in a&&(a.cache=void 0);try{let s=await(await o(i.orgId,n)).getLintStepResult({command:a},{logger:n});t?.({result:s})}catch(c){n.error({event:"lint",err:c},"Failed to lint step"),t?.({result:void 0})}}},UC={event:"lintStep",createHandler:bH};var vH=({metadata:r,logger:e,storageFactory:t,globalE2eStateManager:n})=>{let{sessionId:o,orgId:i}=r;return async(a,l)=>{let{description:c,command:s,testMetadata:u,returnScreenshot:d}=a;e.info({params:a},`Locate handler called - ${c}`);let p=n.getSession(o);if(!p)throw new Error("No active session found");let{controller:m,context:g}=p;m.setOpen();let h=await t(i),f=zo.parse(u.advanced??{}),S={},E;if(c){if("useSelector"in s&&s.useSelector)try{let y=await m.locateElementWithSelector(c,"iframeUrl"in s?s.iframeUrl:void 0);E=y.resolution.locator,S={target:y.target,thoughts:y.thoughts}}catch(y){e.warn({err:y},"Failed resolving target with selector"),l({err:`Failed locating element: ${y.message}`,decisions:y instanceof qr?y.decisions:void 0});return}else try{let y=await m.locateElement({description:c,disableCache:f.disableAICaching??!1,skipWait:!0,testContext:g,source:Do(s),iframeUrl:"iframeUrl"in s?s.iframeUrl:void 0,memory:"cache"in s&&s.cache&&"target"in s.cache&&Tl(s.cache.target.memory)?s.cache.target.memory:void 0,logger:e});S={target:y.target,thoughts:y.thoughts},E=y.resolution.locator}catch(y){(async()=>{try{let A=await m.browser.getCondensedHtml({skipWait:!0});e.warn({err:y,html:A.slice(0,1e5)},"Failed locating element with AI")}catch(A){e.warn({err:A},"Failed grabbing HTML after trying to locate element with AI")}})(),l({err:`${y.message}`});return}if(s.type==="SELECT_OPTION"&&E)try{S.options=await m.browser.getSelectOptions(E)}catch(y){e.warn({err:y},"Failed getting select options"),l({err:`Failed getting select options: ${y.message}`});return}e.info({result:S},"Locate handler result")}if(d)try{let{buffer:y,width:A,height:R}=await m.screenshotWithDimensions({clearHighlights:!0,locator:E}),w=await h.uploadScreenshot(y);S.screenshot={data:w,width:A,height:R},e.info({width:A,height:R},"Captured screenshot during locate")}catch(y){e.error({err:y},"Error capturing screenshot during locate"),l({err:`Error taking screenshot: ${y.message}`});return}if(l({result:S}),E)try{await Promise.all([m.browser.scrollIntoViewIfNeeded(E),m.browser.highlight(E)])}catch(y){e.warn({err:y},"Error highlighting element, continuing...")}}},BC={event:"locate",createHandler:vH};var RH=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({event:o,percentX:i,percentY:a})=>{let l=t.getSession(n);if(!l)throw new Error("No active session found");let c=l.controller.browser;if(c.closed||c.getActivePage().isClosed()){e.warn("Ignoring mouse move because the browser is closed");return}try{await c.clickMouseFromPositionPercentages(o,i,a)}catch(s){e.error({err:s},"Error performing click during cloud recording in control mode")}}},zC={event:"mouseClickEvent",createHandler:RH};var AH=({metadata:r,generatorFactory:e,logger:t,socket:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:l}=r;return async({stepId:c,parentStepIdChain:s,attribute:u})=>{let d=o.getSession(i);if(!d)throw new Error("No active session found");let{controller:p}=d,m=await e(a,t);p.setOpen(),d.browserBehavior.showOverlay=!0;let g=new AbortController;g.signal.addEventListener("abort",async()=>{try{d.browserBehavior.showOverlay=!1,await p.stopRecordMode()}catch(S){t.warn({err:S},"Failed to stop record mode in target click socket handler")}});let h=!1,f=(S,E)=>{E.type!=="PRESET_ACTION"||E.command.type!=="CLICK"||(n.emit("targetRecordingUpdate",{type:S,stepId:c,parentStepIdChain:s,command:E.command,attribute:u}),g.abort(),h=!0)};setTimeout(()=>{h||(g.abort(),n.emit("targetRecordingUpdate",{type:"error",err:"Timed out waiting for click event",stepId:c,parentStepIdChain:s,attribute:u}))},1e4),await p.startRecordMode({params:{generator:m,logger:t,testId:l,orgId:a,callbacks:{onActionReceived:S=>f("clickReceived",S),onStepRecorded:S=>f("descriptionGenerated",S)}},abortController:g,isClickToRecord:!0}),n.emit("targetRecordingUpdate",{type:"listenersInitialized",stepId:c,parentStepIdChain:s,attribute:u})}},HC={event:"recordTargetClick",createHandler:AH};var wH=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({key:o})=>{let i=t.getSession(n);if(!i)throw new Error("No active session found");if(o==="Dead")return;let{controller:a}=i;if(a.browser.closed||a.browser.getActivePage().isClosed()){e.debug({sessionId:n},"Browser is closed, ignoring keyboard press socket event");return}try{a.setOpen(),await a.browser.keyDown(o,{})}catch(l){if(l.message.includes("has been closed")){e.debug({sessionId:n,err:l},"Browser is closed, ignoring key down socket event error");return}throw l}}},GC={event:"keyDownEvent",createHandler:wH};var CH=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({key:o})=>{let i=t.getSession(n);if(!i)throw new Error("No active session found");if(o==="Dead")return;let{controller:a}=i;if(a.browser.closed||a.browser.getActivePage().isClosed()){e.debug({sessionId:n},"Browser is closed, ignoring keyboard press socket event");return}try{a.setOpen(),await a.browser.keyUp(o,{})}catch(l){if(l.message.includes("has been closed")){e.debug({sessionId:n,err:l},"Browser is closed, ignoring key up socket event error");return}throw l}}},VC={event:"keyUpEvent",createHandler:CH};var xH=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r,o,i=0,a=(s,u)=>{let d=async()=>{o=void 0};clearTimeout(o),o=setTimeout(d,Math.min(1e3,250*(i+1)))},l,c=0;return async s=>{let u=t.getSession(n);if(!u)throw new Error("No active session found");let{controller:d,browserBehavior:p}=u,m=d.browser;if(m.closed||m.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}if(s.event==="scroll"){let g=await m.scrollFromPositionPercentages(s.percentX,s.percentY,l?.x??0,l?.y??0),h=u.browserBehavior.recordingState?.transformer;h&&g&&h.recordScroll(g);return}p.showOverlay&&a(m,s);try{let g=await m.moveMouseFromPositionPercentages(s.percentX,s.percentY);c=0,l=g}catch(g){c++,c%5===0&&e.warn({err:g,mouseErrors:c},"Error in socket mouse move handler")}}},jC={event:"mouseMoveEvent",createHandler:xH};var _H=({metadata:r,generatorFactory:e,socket:t,logger:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:l}=r;return async({stepId:c})=>{let s=o.getSession(i);if(!s)throw new Error("No active session found");let{controller:u,browserBehavior:d}=s,p=await e(a,n);n.info("Starting cloud recording");let m=new AbortController,g=await u.startRecordMode({params:{generator:p,logger:n,testId:l,orgId:a,callbacks:{onActionReceived:(h,f)=>{t.emit("stepRecorded",{stepId:c,step:h,offset:f})},onStepRecorded:(h,f)=>{t.emit("stepRecorded",{stepId:c,step:h,offset:f})}}},abortController:m,isClickToRecord:!1});d.recordingState={transformer:g}}},$C={event:"recordingStart",createHandler:_H};var IH=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async()=>{let o=t.getSession(n);if(!o)throw new Error("No active session found");e.info("Stopping cloud recording"),await o.controller.stopRecordMode(),o.browserBehavior.recordingState=void 0,o.browserBehavior.showOverlay=!1}},WC={event:"recordingStop",createHandler:IH};var MH=({socket:r,metadata:e,logger:t,storageFactory:n,authorization:o,settingsFactory:i,globalE2eStateManager:a})=>async(l,c)=>{let{testId:s,sessionId:u,orgId:d}=e;t.info({testId:s,sessionId:u},"Refresh event received");let p=await i(d,t),m=await n(d),{baseUrl:g}=await fi({testId:s,orgId:d,logger:t,storage:m,authorization:o,settings:p}),h=a.getSession(u);if(!h){r.emit("error",{message:"No session to refresh"});return}let{controller:f}=h;f.setOpen(),await f.browser.refresh();let S=f.browser.getViewport();t.info({baseUrl:g,viewport:S},`Session refreshed for test ${s} at ${g}`),c()},qC={event:"refresh",createHandler:MH};var PH=({socket:r,metadata:e,logger:t,storageFactory:n,authorization:o,settingsFactory:i,globalE2eStateManager:a})=>async()=>{let{testId:l,sessionId:c,orgId:s}=e;t.info({testId:l,sessionId:c},"Reset event received");let u=await i(s,t),d=await n(s),{baseUrl:p,envName:m,testName:g,environmentVariables:h}=await fi({testId:l,orgId:s,logger:t,storage:d,authorization:o,settings:u}),f=a.getSession(c);if(!f){r.emit("error",{message:"No session to reset"});return}let{controller:S,context:E}=f;await S.browser.reset({newUrl:p});let y=S.browser.baseUrl;E.reset({baseUrl:y,currentUrl:S.browser.url(),variablesFromEnvironment:h,envName:m,testName:g});let A=S.browser.getViewport(),R=wr.USER_AGENT;t.info({baseUrl:p,viewport:A},`Session reset for test ${l} at ${y}`),r.emit("session",{url:y,userAgent:R,viewport:A,sessionId:c})},KC={event:"reset",createHandler:PH};var OH=({metadata:r,globalE2eStateManager:e})=>{let{sessionId:t}=r;return async({url:n})=>{let o=e.getSession(t);if(!o)throw new Error("No active session found");await o.controller.browser.switchToPage({type:"SUBSTRING",substring:n})}},YC={event:"switchTab",createHandler:OH};async function XC(r){return kC(r)}var JC=[vb,FC,BC,KC,qC,Eb,YC,UC,HC,$C,WC,jC,zC,GC,VC,bb,Tb];var QC=r=>{let{logger:e}=r,t=new LH(r.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0});return t.on("connection",async n=>{let o;try{e.info({event:"connection",transport:n.conn.transport.name},"Websocket connection established"),o=await XC({...r,socket:n,logger:e}),e=e.child(o)}catch(i){e.error({event:"connection",type:"websocket",err:i},"Failed to setup connection"),n.emit("error",{message:i instanceof Error?i.message:`${i}`}),n.disconnect(!0);return}JC.forEach(i=>NH(i,{...r,socket:n,metadata:o,logger:e}))}),t},NH=(r,e)=>{let t=r.createHandler(e),n=(...o)=>{["mouseMoveEvent","keyDownEvent","keyUpEvent","mouseClickEvent","lintStep"].includes(r.event)||e.logger.debug({...e.metadata,event:r.event},`Websocket event (${r.event})`);let i=a=>{e.logger.error({event:r.event,type:"websocket",err:a instanceof Error?a:new Error(`${a}`)},"Unhandled exception in socket handler"),e.socket.emit("error",{message:a instanceof Error?a.message:`${a}`})};try{let a=t.apply(void 0,o);a&&typeof a.catch=="function"&&a.catch(i)}catch(a){i(a)}};e.socket.on(r.event,n)};import{Router as BH}from"express";import{Router as kH}from"express";import sl from"fs";import al from"path";import{v4 as FH}from"uuid";import UH from"yaml";import{hostname as DH}from"os";var Bh="2.17.11",Je=gc({app:"desktop-server",hostname:DH(),disableConsoleLogs:!0}).child({cliVersion:Bh});(async()=>{try{let r=await Ps(Je);r.gitBranchName&&Je.addBinding("branch",r.gitBranchName)}catch{}})();var _a=kH();async function zh(r){return(await jc(r,Je)).map(n=>{let o=r.modules[n.moduleId];if(!o){T.warn(`Found a dangling module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}_a.get("/",ye(async(r,e)=>{let t=ae(),n=W(t),o=await zh(n);e.status(200).json(o)}));_a.post("/",ye(async(r,e)=>{let t;try{t=Ay.parse(r.body)}catch(l){e.status(400).json({error:`Invalid request body: ${l}`});return}try{Wn(t.name)}catch(l){e.status(400).json({error:`Invalid module name: ${l}`});return}let n=ae(),o=W(n).modules;if(Object.values(o).find(l=>l.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let i=al.join(n.rootDir,t.folderPath??"");if(!sl.existsSync(i)||!sl.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let a=await Vc({...t,folder:i,project:n});e.status(201).json(a)}));_a.get("/:moduleId",ye(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=W(ae()),n=t.modules[r.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await yr(n,t,T);e.json(o)}catch(o){e.status(400).json({err:o})}}));_a.post("/:moduleId/duplicate",ye(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=Ry.parse(r.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}try{Wn(t.name)}catch(h){e.status(400).json({error:h.message});return}let n=ae(),o=W(n),i=o.modules[r.params.moduleId];if(!i){e.status(404).json({error:"Module not found."});return}if(Object.values(o.modules).find(h=>h.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let a=await yr(i,o,T),l=al.join(n.rootDir,al.dirname(i.relativePath));if(!sl.existsSync(l)||!sl.statSync(l).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${l}' does not exist.`});return}let c=xe(t.name),s=al.join(l,`${c}.module.yaml`),u=FH(),{stepsToSave:d}=await Ge({stepLists:{steps:a.steps},createNewCacheIds:!0,cacheCreationParams:{orgId:St()}}),p={fileType:de.MODULE,schemaVersion:se,moduleId:u,name:t.name,description:"",enabled:!0,steps:d.steps,parameters:a.parameters,defaultParameters:a.defaultParameters,parameterEnums:a.parameterEnums,defaultCacheKey:a.defaultCacheKey,defaultCacheTtl:a.defaultCacheTtl,defaultCacheAllInvocations:a.defaultCacheAllInvocations,autoAuth:a.autoAuth,advanced:a.advanced},m=UH.stringify(p);sl.writeFileSync(s,m,"utf-8");let g={relativeFilePath:al.relative(n.rootDir,s)};e.status(201).json(g)}));_a.patch("/:moduleId/metadata",ye(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=wy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ae(),o=W(n);eb({moduleId:r.params.moduleId,content:t,momenticFiles:o,logger:T,project:n}),e.status(201).json({message:"ok"})}));var ZC=_a;var ex=BH();ex.get("/",ye(async(r,e)=>{let t=ae(),n=W(t),o=new Set;n?.tests&&Object.values(n.tests).forEach(s=>{s.labels?.forEach(u=>o.add(u))});let i=Array.from(o).sort(),a=Object.values(n.tests),l=await zh(n),c={labels:i,tests:a,modules:l};e.status(200).json(c)}));var tx=ex;import{Router as zH}from"express";var Hh=zH();Hh.get("/",ye((r,e)=>{let t=$c(ae(),Je);e.status(200).json(t)}));Hh.get("/names",ye((r,e)=>{let n=ae().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var rx=Hh;import{Router as HH}from"express";var nx=HH();nx.get("/",ye((r,e)=>{e.status(200).json({userId:ra(),orgId:St()})}));var ox=nx;import{StreamableHTTPServerTransport as M1}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as P1}from"@modelcontextprotocol/sdk/types.js";import{randomUUID as O1}from"crypto";import{Router as L1}from"express";import{McpServer as _1}from"@modelcontextprotocol/sdk/server/mcp.js";import{SSEServerTransport as I1}from"@modelcontextprotocol/sdk/server/sse.js";import{tool as GH}from"ai";import{z as VH}from"zod";var pd=r=>({builder:(t,n)=>GH({description:r.schema.description,inputSchema:VH.object(r.schema.inputSchema),execute:async o=>{t.logger.info({input:o},`Executing tool ${r.schema.name}`);try{await r.handle(t,o,n,void 0)}catch(a){n.addError(String(a))}let i=await n.serialize();return i.isError?t.logger.error({toolName:r.schema.name,input:o,err:i.content.map(a=>a.text).join(`
|
|
3984
|
+
`)},"Tool execution resulted in error"):t.logger.info({toolName:r.schema.name,input:o},"Tool execution completed"),i}}),tool:r});var md=class{results=[];isError;addResult(e){this.results.push(e)}addError(e){this.results.push(`Error: ${e}`),this.isError=!0}getResult(){return this.results.join(`
|
|
4035
3985
|
`)}async serialize(){let e=[];return this.results.length&&(e.push("### Result"),e.push(this.results.join(`
|
|
4036
3986
|
`)),e.push("")),{content:[{type:"text",text:e.join(`
|
|
4037
|
-
`)}],isError:this.isError}}};var
|
|
4038
|
-
`))}return
|
|
4039
|
-
`))}return
|
|
3987
|
+
`)}],isError:this.isError}}};var mn=r=>{let e=(n,o)=>{let i=async(a,l)=>{let c=l.sessionId??void 0,s=Date.now(),u=n.logger.child({...c&&{sessionId:c},toolName:r.schema.name});u.debug({toolName:r.schema.name,params:Ji({json:a,maxJsonStringSize:500}),sessionId:c},`MCP tool invoked: ${r.schema.name}`);let d=new md,p;try{await r.handle(n,a,d,l)}catch(h){h instanceof Error?(p=h,d.addError(String(h))):d.addError(`Unknown value thrown: ${String(h)}`)}let m=Date.now()-s,g=await d.serialize();if(p)u.error({toolName:r.schema.name,sessionId:c,duration:m,err:p},`MCP tool failed: ${r.schema.name}`);else{let h=g.content.filter(f=>f.type==="text");u.debug({toolName:r.schema.name,sessionId:c,duration:m,responseIsError:g.isError,response:Ji({json:h,maxJsonStringSize:500})},`MCP tool completed: ${r.schema.name}`)}return g};o.registerTool(r.schema.name,{title:r.schema.name,description:r.schema.description,inputSchema:r.schema.inputSchema},i)};return{...pd(r),addToolToMcpServer:e,name:r.schema.name}};import{z as Gh}from"zod";var Ur=Gh.object({id:Gh.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:ki.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:Gh.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.");function Br(r,e,t){let n=W(r),o=t==="test"?n.tests:t==="module"?n.modules:n.mobileTests,i=jH(o,e);if(e.id){if(i.length===0)throw new _e(`No ${t} found with id '${e.id}' in project '${r.rootDir}'.`);return Vh(i,n)}else if(e.name){if(i.length===0)throw new _e(`No ${t} found with exact name '${e.name}' in project '${r.rootDir}'.`);if(i.length>1){let a=i.map(l=>({id:l.id,path:l.relativePath}));throw new _e([`Multiple ${t}s found with exact name '${e.name}'. Please disambiguate by id or path.`,JSON.stringify(a,null,2)].join(`
|
|
3988
|
+
`))}return Vh(i,n)}else if(e.path){let a=e.path;if(i.length===0)throw new _e(`No ${t} found at path '${a}'. Provide an absolute path or a path relative to '${r.rootDir}'.`);if(i.length>1){let l=i.map(c=>({id:c.id,path:c.fullFilePath}));throw new _e([`Multiple ${t}s matched the provided path '${a}'. Please pass the absolute path.`,JSON.stringify(l,null,2)].join(`
|
|
3989
|
+
`))}return Vh(i,n)}else throw new Error("No valid selector field provided. Exactly one of id, name, or path must be specified.")}function Vh(r,e){let t=r[0];if(!t)throw r.length>0?new Error("No entity found: matches array is not empty. Unknown error."):new Error("No entity found.");return{entity:t,momenticFiles:e}}function jH(r,e){if(e.id){let t=Object.values(r).find(n=>n.id===e.id);return t?[t]:[]}else{if(e.name)return Object.values(r).filter(t=>t.name===e.name);if(e.path){let t=e.path;return Object.values(r).filter(n=>n.fullFilePath.includes(t)||n.relativePath.includes(t))}else throw new Error("No valid selector field provided: expected exactly one of 'id', 'name', or 'path'.")}}var $H=mn({schema:{name:"momentic_module_get",description:"Get a single fully loaded module by id, exact name, or file path. Exactly one selector must be provided. Module names must follow valid entity name rules.",inputSchema:{selector:Ur}},handle:async(r,e,t,n)=>{let{project:o,logger:i}=r;try{let a=Br(o,e.selector,"module"),l=await yr(a.entity,a.momenticFiles,i);t.addResult(JSON.stringify({module:l},null,2))}catch(a){t.addError(String(a));return}}}),WH=mn({schema:{name:"momentic_module_list",description:"List modules.",inputSchema:{}},handle:async(r,e,t,n)=>{let{project:o}=r,i=W(o),l=Object.values(i.modules).map(c=>({id:c.id,name:c.name,description:c.description,relativePath:c.relativePath,fullFilePath:c.fullFilePath,platformSep:c.platformSep,fullPathSegments:c.fullPathSegments,relativePathSegments:c.relativePathSegments,fileName:c.fileName,lastModified:c.lastModified,createdAt:c.createdAt,type:c.type}));t.addResult(JSON.stringify({modules:l},null,2))}}),gd=[$H,WH];var qH=mn({schema:{name:"momentic_environment_list",description:"List environments defined in the project's momentic.config.yaml file.",inputSchema:{}},handle:async(r,e,t,n)=>{let{project:o,logger:i}=r,a=$c(o,i);t.addResult(JSON.stringify({environments:a},null,2))}}),ix=[qH];import{streamText as T1}from"ai";import b1 from"path";import{z as v1}from"zod";var hd=new ud;var fo=class extends qi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchTestMetadata(t){let n=ae(),i=W(n).tests[t];if(i)return _s(i.relativePath,n)}async fetchApiTestMetadata(){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(t,n){let o=ae();return Is(t,o,Tn)}async fetchIconKnowledgeBase(t){try{return await this.client.fetchIconKnowledgeBase(t)}catch(n){return t.error({err:n},"Failed to fetch icon knowledge base"),null}}};var Si=class{async prepareGoldenScreenshotForComparison(e,t,n){return await new la(ae(),!1).prepareGoldenScreenshotForComparison(e,t,n)}};import ax from"path";import{v4 as KH}from"uuid";async function fd({project:r,input:e}){try{Wn(e.name)}catch(s){throw new _e(`${s} when validating the test entity name`)}if(!e.baseUrl&&!e.environment)throw new _e("Either 'baseUrl' or 'environment' must be provided when creating a test.");let t=W(r);if(Object.values(t.tests).find(s=>s.name===e.name))throw new _e(`A test with the name "${e.name}" already exists. Please use a different name.`);let i={id:KH(),name:e.name,description:e.description,baseUrl:e.baseUrl,schemaVersion:se,advanced:{browserType:e.browserType??"Chromium",viewport:e.viewport??Mt},retries:0,steps:[]};e.environment&&(i.envs=[{name:e.environment,default:!0}]);let a=ax.join(r.rootDir,...e.pathSegments||[]),l=await rb({test:i,name:e.name,folder:a});return{...i,relativeFilePath:ax.relative(r.rootDir,l)}}import{stepCountIs as E1}from"ai";import{createAnthropic as YH}from"@ai-sdk/anthropic";import{randomUUID as XH}from"crypto";var sx=(r,e)=>t=>YH({baseURL:`${Or()}/v1/llm/anthropic/${t}`,headers:{Authorization:`Bearer ${r}`,...e&&{[zy]:e}},apiKey:r})(t);var jh=async({step:r,controller:e,storage:t,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:l})=>{let{results:c}=await $h({steps:[r],controller:e,storage:t,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:l});return c[0]},$h=async({steps:r,controller:e,storage:t,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:l})=>{let c={controller:e,storage:t,codeEvalTools:n,logger:o,context:a,usageTracker:new Fi},s=i?new ho({orgId:l,parentStep:null,parentTracer:null,socket:i}):new gs;return kr({listParams:{containerName:"copilot-steps",steps:r,tracer:s},fixtures:c,options:{collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},inputs:{orgId:l,runId:XH(),steps:r,testMetadata:null,orgSettings:{}},callbacks:{test:{},step:{}},work:{results:[],asyncTasks:[],state:{}}})};import JH from"dedent";var lx=JH`
|
|
4040
3990
|
<core-identity>
|
|
4041
3991
|
You are the Momentic Copilot. You are an experienced SDET who is building and editing a Momentic browser E2E test. Instead of CSS selectors, Momentic uses natural language descriptions to identify elements. Your responses must be specific, accurate, and concise.
|
|
4042
3992
|
</core-identity>
|
|
@@ -4153,36 +4103,36 @@ axios, moment, faker, assert, pg, Octokit (auto), createAppAuth (auto), OTPAuth
|
|
|
4153
4103
|
- Prefer step-by-step edits. Splice should be used for replacing steps or bulk changes when explicitly asked to do so.
|
|
4154
4104
|
- If and only if you must overwrite the entire test, use the splice tool to replace all steps in a single call and rerun all steps starting from a fresh reset state.
|
|
4155
4105
|
</safety>
|
|
4156
|
-
`;import
|
|
4106
|
+
`;import QH from"path";var Sd=class{_result=[];_includeSnapshot=!1;_includeTestContext=!1;_includeTest=!1;_isError;_browser;_testContext;_project;_logger;_testPath;constructor(e,t,n,o,i){this._browser=e,this._testContext=t,this._project=n,this._logger=o,this._testPath=i}addResult(e){this._result.push(e)}result(){return this._result.join(`
|
|
4157
4107
|
`)}setIncludeSnapshot(){this._includeSnapshot=!0}async snapshot(){if(!this._includeSnapshot)return"";let e=this._browser.getActivePage(),t=await this._browser.getBrowserState({skipWait:!1}),n=[];return n.push("### Page state",`- Page URL: ${e.url()}`,`- Page Title: ${await e.title()}`,"- Page Snapshot:","```xml",t.serialize(),"```"),n.join(`
|
|
4158
4108
|
`)}setIncludeTestContext(){this._includeTestContext=!0}testContext(){if(!this._includeTestContext)return"";let e=[],t=this._testContext.toObjectCopy();return e.push("### Environment variables","```json",JSON.stringify(t,null,2),"```"),e.join(`
|
|
4159
|
-
`)}setIncludeTest(){this._includeTest=!0}async test(){if(!this._includeTest)return"";let e=
|
|
4109
|
+
`)}setIncludeTest(){this._includeTest=!0}async test(){if(!this._includeTest)return"";let e=W(this._project),t=await it(QH.join(this._project.rootDir,this._testPath),this._logger,e),n=[];return n.push("### Test","```json",JSON.stringify(t,null,2),"```"),n.join(`
|
|
4160
4110
|
`)}addError(e){this._result.push(e),this._isError=!0}async serialize(){let e=[];this._result.length&&(e.push("### Result"),e.push(this._result.join(`
|
|
4161
4111
|
`)),e.push(""));let t=await this.snapshot();t&&e.push(t,"");let n=this.testContext();n&&e.push(n,"");let o=await this.test();return o&&e.push(o,""),{content:[{type:"text",text:e.join(`
|
|
4162
|
-
`)}],isError:this._isError}}};var gt=r=>({builder:ed(r).builder,name:r.schema.name});var Iz=gt({schema:{name:"observe_page",description:"Observe the current page's accessibility snapshot.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeSnapshot()}}),KC=[Iz];import kh from"path";import{v4 as Oz}from"uuid";import{z as ho}from"zod";import{randomUUID as Dh}from"crypto";import{z as go}from"zod";import{z as Pz}from"zod";var hi={id:!0,cache:!0},Ca=Pz.discriminatedUnion("type",[Ro.omit(hi),xo.omit(hi),wo.omit(hi),Un.omit(hi),Fn.omit(hi),Ao.omit(hi),Co.omit(hi),Wd.omit({id:!0}),Vd.omit({id:!0}),Jd.omit({id:!0}),Ai.omit({id:!0}),Xd.omit({id:!0}),Qd.omit({id:!0}),jd.omit({id:!0})]);var Mz=go.object({selector:Fr,inputs:go.record(go.string()).optional()}),YC=go.discriminatedUnion("type",[go.object({type:go.literal("PRESET_ACTION"),action:Ca}),go.object({type:go.literal("MODULE"),module:Mz})]).describe("The step types that can be ingested for a test change. The PRESET_ACTION's action can be seen as a single step command. The MODULE is a module step to use.");async function XC(r,e,t){switch(r.type){case"PRESET_ACTION":return{type:"PRESET_ACTION",command:{...r.action,id:Dh()},id:Dh()};case"MODULE":{let{selector:n,inputs:o}=r.module,{entity:i,momenticFiles:a}=Ur(e,n,"module"),l=await fr(i,a,t),s=Object.keys(o??{}).length>0?o:(l.parameters?.length??0)>0?{}:void 0,u={id:Dh(),inputs:s};return{...l,...u,type:"RESOLVED_MODULE"}}default:return(o=>{throw new Error("You missed a case in the switch above")})(r)}}var Lz=gt({schema:{name:"momentic_module_create",description:"Create a module. If startIndex is provided, the steps will be extracted from the current test, a module will be created with those steps, and the test will be updated to reference the new module. If no startIndex is provided, an unreferenced module will be created. Automatically splices and repairs the test to reference the new module.",inputSchema:{name:ho.string(),description:ho.string(),enabled:ho.boolean().default(!0),subDir:ho.string().optional().describe("sub directory to create the module in. If not provided, the module will be created in the project's root directory."),startIndex:ho.number().optional().describe("Start index of steps to extract from the current test (0-based)."),endIndex:ho.number().optional().describe("End index of steps to extract from the current test (exclusive). If not provided, extracts just the startIndex.")}},handle:async(r,e,t,n)=>{let{project:o,logger:i,testPath:a}=r,l=e.startIndex??0,c=e.endIndex??l+1,s=q(o);if(Object.values(s.modules).find(m=>m.name===e.name))throw new Ie(`A module with the name "${e.name}" already exists. Please use a different name.`);let d=[];if(e.startIndex!==void 0){if(!a)throw new Ie("testPath is required when extracting steps from the current test.");let m=await at(kh.join(o.rootDir,a),i,s);if(l<0||l>=m.steps.length)throw new Ie(`startIndex ${l} is out of bounds. Test has ${m.steps.length} steps.`);if(c<=l||c>m.steps.length)throw new Ie(`endIndex ${c} is out of bounds. Must be between ${l+1} and ${m.steps.length}.`);d=m.steps.slice(l,c);for(let g of d)if(g.type==="RESOLVED_MODULE")throw new Ie("Modules cannot be nested. Please select steps that do not include module references.")}let p=await Oc({name:e.name,description:e.description,enabled:e.enabled,steps:d,folder:e.subDir?kh.join(o.rootDir,e.subDir):o.rootDir,project:o});if(s=q(o),e.startIndex!==void 0){let m=await at(kh.join(o.rootDir,a),i,s),g={type:"RESOLVED_MODULE",id:Oz(),moduleId:p.moduleId,name:e.name,description:e.description,enabled:e.enabled,parameters:[],steps:d,inputs:{}};m.steps.splice(l,c-l,g);let{stepsToSave:h,moduleUpdates:f}=await Ge({stepLists:{steps:m.steps,beforeSteps:m.beforeSteps,afterSteps:m.afterSteps}});f.forEach(E=>{jt({content:E,schemaVersion:ue,momenticFiles:s,project:o})}),Dt({relativeTestPath:a,steps:h,schemaVersion:ue,project:o})}t.addResult(JSON.stringify(p,null,2))}});function Nz(r,e,t,n){if(r===void 0&&e!==void 0)throw new Ie("Validation Error: startIndex is required when endIndex is provided.");if(r!==void 0&&e===void 0&&t===0)throw new Ie("Validation Error: steps are required when startIndex is provided without an endIndex.");if(r!==void 0&&(r>n||r<0))throw new Ie(`Validation Error: startIndex is out of bounds for module with ${n} steps.`);if(e!==void 0&&r===void 0)throw new Ie("Validation Error: startIndex is required when endIndex is provided.");if(e!==void 0&&r!==void 0&&e<r)throw new Ie("Validation Error: endIndex must be greater than or equal to startIndex.");if(e!==void 0&&(e>n||e<0))throw new Ie(`Validation Error: endIndex ${e} is out of bounds for module with ${n} steps.`);let o=r??n;if((e??o)===o&&t===0)throw new Ie("Validation Error: Nothing to insert or delete. Provide steps or a valid delete range.")}var Dz=gt({schema:{name:"momentic_module_change",description:"Edit a module's steps. Provide startIndex (and optional endIndex) to replace or remove that range; omit endIndex to insert at startIndex; omit both indices to append new steps. Use an empty steps array with both indices to delete the range.",inputSchema:{selector:Fr,steps:YC.array(),startIndex:ho.number().optional(),endIndex:ho.number().optional()}},handle:async(r,e,t,n)=>{let{project:o,logger:i}=r,a=await Promise.all(e.steps.map(f=>XC(f,o,i))),{entity:l,momenticFiles:c}=Ur(o,e.selector,"module"),s=await fr(l,c,i),u=a.find(f=>!np(f));if(u){t.addError(`Validation Error: step type ${u.type} cannot be added to a module.`);return}try{Nz(e.startIndex,e.endIndex,e.steps.length,s.steps.length)}catch(f){t.addError(String(f));return}let d=[...s.steps],p=e.startIndex!==void 0?e.startIndex:d.length,m=e.endIndex!==void 0?e.endIndex:p;d.splice(p,m-p,...a);let{stepsToSave:g}=await Ge({stepLists:{steps:d}});jt({content:{...s,steps:g.steps},schemaVersion:ue,momenticFiles:c,project:o});let h={...s,steps:d,stepCount:d.length};t.addResult(JSON.stringify(h,null,2))}}),JC=[Lz,Dz];import{randomUUID as ad}from"crypto";import{z as QC}from"zod";var kz=gt({schema:{name:"preview_preflight",description:"Resolve and validate locators without changing the page. If found, it will return the locator ID and HTML.",inputSchema:{description:QC.string().describe("Description of the element to preview.")}},handle:async({controller:r,logger:e,testContext:t},n,o,i)=>{o.setIncludeSnapshot();try{let a=await r.locateElement({description:n.description,disableCache:!0,skipWait:!0,logger:e,testContext:t});a.resolution.locator&&await Promise.all([r.browser.scrollIntoViewIfNeeded(a.resolution.locator),r.browser.highlight(a.resolution.locator)]),o.addResult(`Found element matching description: ${a.target.id}`),a.target.nodeOnlySerializedHtml&&o.addResult(`HTML: ${a.target.nodeOnlySerializedHtml}`);return}catch(a){o.addError(`Failed to find any element matching description: ${a}`)}}}),Fz=gt({schema:{name:"preview_ensure",description:"Confirm page state.",inputSchema:{assertion:QC.string().describe("Assertion to confirm page state.")}},handle:async(r,e,t,n)=>{t.setIncludeSnapshot();let{logger:o,storage:i,controller:a,codeEvalTools:l,socket:c,orgId:s,testContext:u}=r,d={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.assertion,id:ad()},id:ad()},p=await Lh({step:d,controller:a,storage:i,codeEvalTools:l,logger:o,socket:c,orgId:s,testContext:u});if(!p){t.addError("Assertion executed with unknown result.");return}if(p.status==="SUCCESS"){t.addResult(`Assertion is true: ${p.message}`);return}t.addError(`Assertion is false: ${p.message}`)}}),Uz=gt({schema:{name:"preview_step",description:"Execute a step without adding it to the test.",inputSchema:{command:Ca}},handle:async(r,e,t,n)=>{t.setIncludeSnapshot(),t.setIncludeTestContext();let{logger:o,storage:i,controller:a,codeEvalTools:l,socket:c,orgId:s,testContext:u}=r;t.setIncludeSnapshot();let d={type:"PRESET_ACTION",command:{...e.command,id:ad()},id:ad()},p=await Lh({step:d,controller:a,storage:i,codeEvalTools:l,logger:o,socket:c,orgId:s,testContext:u});if(!p){t.addError("Assertion executed with unknown result.");return}if(p.status==="SUCCESS"){t.addResult(`Assertion is true: ${p.message}`);return}t.addError(`Assertion is false: ${p.message}`)}}),ZC=[kz,Fz,Uz];import Bz from"path";import{z as ex}from"zod";var Hz=gt({schema:{name:"get_environment_variables",description:"Get the current environment variables.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeTestContext()}}),zz=gt({schema:{name:"reset_session",description:"Reset the browser session. This will clear any authentication state and also navigate to the starting URL of the test.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeTestContext(),t.setIncludeSnapshot(),await r.controller.browser.reset({})}}),Gz=gt({schema:{name:"run_step",description:"Run the step in the test at the given startIndex. If there is no endIndex, the step at the startIndex will be executed. EndIndex is the last step that is run (end index isinclusive).",inputSchema:{fromIndex:ex.number(),toIndex:ex.number().optional()}},handle:async(r,e,t,n)=>{t.setIncludeTestContext(),t.setIncludeSnapshot();let{project:o,logger:i,testPath:a,storage:l,controller:c,codeEvalTools:s,socket:u,orgId:d,testContext:p}=r,m=e.fromIndex,g=e.toIndex??m,h=q(o),f=await at(Bz.join(o.rootDir,a),i,h);if(m<0||m>=f.steps.length){t.addError("startIndex is out of bounds.");return}if(g<m){t.addError("toIndex must be greater than or equal to fromIndex.");return}else if(g>=f.steps.length){t.addError("toIndex is out of bounds.");return}let E=f.steps.slice(m,g+1);if(E.length===0){t.addError("No steps were executed.");return}let{results:S}=await Nh({steps:E,controller:c,storage:l,codeEvalTools:s,logger:i,socket:u,orgId:d,testContext:p});if(!S||S.length===0){t.addError("No steps were executed.");return}let y=S.at(-1);if(!y){t.addError("No steps were executed.");return}if(y.status!=="SUCCESS"){let R=m+S.length-1;t.addError(`Step at index ${R} failed: ${y.message}`);return}let A=m===g?`Step at index ${g}`:`Steps ${m}-${g}`;if(y.status==="SUCCESS"){t.addResult(`${A} executed successfully. Last step result: ${y.message}`),y.data&&t.addResult(`Data: ${JSON.stringify(y.data,null,2)}`);return}t.addError(`${A} failed: ${y.message}`)}}),tx=[Hz,zz,Gz];import{randomUUID as Fh}from"crypto";import sd from"path";import{z as nr}from"zod";function tl(r,e,t,...n){t?.emit(r,...n),e.info({event:r,args:n},"Emitting copilot event")}var Vz=nr.object({selector:Fr,inputs:nr.record(nr.string()).optional()}),Uh=nr.discriminatedUnion("type",[nr.object({type:nr.literal("PRESET_ACTION"),action:Ca}),nr.object({type:nr.literal("MODULE"),module:Vz})]).describe("The step types that can be ingested for a test change. The PRESET_ACTION's action can be seen as a single step command. The MODULE is a module step to use.");async function Bh(r,e,t){switch(r.type){case"PRESET_ACTION":return{type:"PRESET_ACTION",command:{...r.action,id:Fh()},id:Fh()};case"MODULE":{let{selector:n,inputs:o}=r.module,{entity:i,momenticFiles:a}=Ur(e,n,"module"),l=await fr(i,a,t),s=Object.keys(o??{}).length>0?o:(l.parameters?.length??0)>0?{}:void 0,u={id:Fh(),inputs:s};return{...l,...u,type:"RESOLVED_MODULE"}}default:return(o=>{throw new Error("You missed a case in the switch above")})(r)}}var jz=gt({schema:{name:"test_get",description:"Get test contents.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeTest()}}),$z=gt({schema:{name:"test_insert_step",description:"Insert a step or module into the test.",inputSchema:{index:nr.number(),step:Uh}},handle:async(r,e,t,n)=>{t.setIncludeTest();let{project:o,logger:i,testPath:a,socket:l}=r,c=q(o),s=await at(sd.join(o.rootDir,a),i,c),u=await Bh(e.step,o,i);s.steps.splice(e.index,0,u);let{stepsToSave:d,moduleUpdates:p}=await Ge({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps}});p.forEach(m=>{jt({content:m,schemaVersion:ue,momenticFiles:c,project:o})}),Dt({relativeTestPath:a,steps:d,schemaVersion:ue,project:o}),tl("copilotStepsUpdated",i,l,s.steps)}}),Wz=gt({schema:{name:"test_replace_step",description:"Replace a step in the test.",inputSchema:{index:nr.number(),step:Uh}},handle:async(r,e,t,n)=>{t.setIncludeTest();let{project:o,logger:i,testPath:a,socket:l}=r,c=q(o),s=await at(sd.join(o.rootDir,a),i,c),u=await Bh(e.step,o,i);s.steps.splice(e.index,1,u);let{stepsToSave:d,moduleUpdates:p}=await Ge({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps}});p.forEach(m=>{jt({content:m,schemaVersion:ue,momenticFiles:c,project:o})}),Dt({relativeTestPath:a,steps:d,schemaVersion:ue,project:o}),tl("copilotStepsUpdated",i,l,s.steps)}}),qz=gt({schema:{name:"test_remove_step",description:"Remove a step from the test.",inputSchema:{index:nr.number()}},handle:async(r,e,t,n)=>{t.setIncludeTest();let{project:o,logger:i,testPath:a,socket:l}=r,c=q(o),s=await at(sd.join(o.rootDir,a),i,c);s.steps.splice(e.index,1);let{stepsToSave:u,moduleUpdates:d}=await Ge({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps}});d.forEach(p=>{jt({content:p,schemaVersion:ue,momenticFiles:c,project:o})}),Dt({relativeTestPath:a,steps:u,schemaVersion:ue,project:o}),tl("copilotStepsUpdated",i,l,s.steps)}}),Kz=gt({schema:{name:"test_splice_steps",description:"Splice steps in the test.",inputSchema:{startIndex:nr.number(),deleteCount:nr.number(),steps:Uh.array()}},handle:async(r,e,t,n)=>{t.setIncludeTest();let{project:o,logger:i,testPath:a,socket:l}=r,c=q(o),s=await at(sd.join(o.rootDir,a),i,c),u=await Promise.all(e.steps.map(m=>Bh(m,o,i)));s.steps.splice(e.startIndex,e.deleteCount,...u);let{stepsToSave:d,moduleUpdates:p}=await Ge({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps}});p.forEach(m=>{jt({content:m,schemaVersion:ue,momenticFiles:c,project:o})}),Dt({relativeTestPath:a,steps:d,schemaVersion:ue,project:o}),tl("copilotStepsUpdated",i,l,s.steps)}}),rx=[jz,$z,Wz,qz,Kz];var nx=[...JC,...KC,...tx,...ZC,...rx,...rd];function ld(r,e,t,n,o){let i=qo(),a=yt(),l=Mr(),c=te(),s=new Je({apiKey:i,baseUrl:l,logger:t}),u=new mo(s,a),d=new Qr(c.config),p=new Xr({httpClient:new At({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:t}),fakerSeed:c.config.advanced?.fakerConstantSeed?Bi:void 0}),m={project:c,apiKey:i,orgId:a,baseUrl:l,logger:t,storage:u,flagStore:d,codeEvalTools:p,testPath:r,testContext:n.context,controller:n.controller,socket:n.socket},g=nx.reduce((E,{name:S,builder:y})=>(E[S]=y(m,new id(m.controller.browser,m.testContext,m.project,m.logger,m.testPath)),E),{});return{model:WC(i,o)("claude-sonnet-4-5-20250929"),stopWhen:Yz(30),maxRetries:4,system:qC,messages:e,tools:g}}var Zz=un({schema:{name:"momentic_test_create",description:"Create a test. You must provide a name and either a baseUrl or environment or the tool will fail.",inputSchema:zp},handle:async(r,e,t,n)=>{let{project:o}=r;try{let i=await od({project:o,input:e});t.addResult(JSON.stringify(i,null,2))}catch(i){t.addError(String(i));return}}}),e1=un({schema:{name:"momentic_test_list",description:"List tests.",inputSchema:{}},handle:async(r,e,t,n)=>{let{project:o}=r,i=q(o),l=Object.values(i.tests).map(c=>({id:c.id,name:c.name,description:c.description,relativePath:c.relativePath,fullFilePath:c.fullFilePath,platformSep:c.platformSep,fullPathSegments:c.fullPathSegments,relativePathSegments:c.relativePathSegments,fileName:c.fileName,lastModified:c.lastModified,createdAt:c.createdAt,type:c.type,labels:c.labels||[]}));t.addResult(JSON.stringify({tests:l},null,2))}}),t1=un({schema:{name:"momentic_test_get",description:"Get a single fully loaded test by id, exact name, or file path. Exactly one selector must be provided.",inputSchema:{selector:Fr}},handle:async(r,e,t,n)=>{let{project:o,logger:i}=r;try{let a=Ur(o,e.selector,"test"),l=await at(a.entity.fullFilePath,i,a.momenticFiles);t.addResult(JSON.stringify({test:l},null,2))}catch(a){t.addError(String(a));return}}});async function r1(r,e,t){let n=qo(),o=yt(),i=Mr(),a=new gi,l=new Je({apiKey:n,baseUrl:i,logger:r}),c=new mo(l,o),s=new Qr(e.config),u=(await at(t.fullFilePath,r,q(e))).advanced?.viewport??Pt,d=new Tn(e.config.ai?.agentConfig,{baseUrl:i,apiKey:n,logger:r}),p=new Xn({baseUrl:i,apiKey:n,logger:r},d),m=await Rr.init({baseUrl:"about:blank",userBrowserSettings:{},enricher:p,storage:c,flagStore:s,logger:r,contextArgs:{viewport:u,locale:Hn,timezoneId:zn,geolocation:Gn},iconKnowledgeBase:null,callbacks:{}}),g=new uo({browser:m,generator:d,logger:r,flagStore:s,orgId:o,options:{scratchPadId:void 0,slowMoMs:void 0,autoFollowNewTabs:!0,useMemory:e.config.ai?.useMemory,aiPageFiltering:!0},storage:c,localCodeEvalTools:new Xr({httpClient:new At({baseUrl:i,apiKey:n,logger:r}),fakerSeed:e.config.advanced?.fakerConstantSeed?Bi:void 0}),visualDiffScreenshotStorage:a}),h=new qt({baseUrl:"about:blank",testName:Jz.basename(t.relativePath),currentUrl:m.url(),variablesFromEnvironment:{},envName:void 0});return{controller:g,context:h,socket:void 0}}var n1=un({schema:{name:"momentic_test_edit",description:"Edit a test.",inputSchema:{selector:Fr,message:Qz.string().describe("A single block of natural-language instructions describing the desired edits to the test. The test can also be edited to add modules, edit modules, or create new modules inside of the test. Can only be used to modify steps (including module steps) inside of the passed in test.")}},handle:async(r,e,t,n)=>{let{project:o,logger:i}=r,a=qo(),l=Mr(),s=await new Tn(o.config.ai?.agentConfig,{baseUrl:l,apiKey:a,logger:i}).getLintMcpCopilotMessageResult({message:e.message},{logger:i});if(s.category!=="NONE"){t.addError(`${s.thoughts}
|
|
4112
|
+
`)}],isError:this._isError}}};var mt=r=>({builder:pd(r).builder,name:r.schema.name});var ZH=mt({schema:{name:"observe_page",description:"Observe the current page's accessibility snapshot.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeSnapshot()}}),cx=[ZH];import qh from"path";import{v4 as r1}from"uuid";import{z as yo}from"zod";import{randomUUID as Wh}from"crypto";import{z as So}from"zod";import{z as e1}from"zod";var yi={id:!0,cache:!0},Ia=e1.discriminatedUnion("type",[Co.omit(yi),Mo.omit(yi),_o.omit(yi),Hn.omit(yi),zn.omit(yi),xo.omit(yi),Io.omit(yi),np.omit({id:!0}),ep.omit({id:!0}),lp.omit({id:!0}),Ci.omit({id:!0}),sp.omit({id:!0}),cp.omit({id:!0}),tp.omit({id:!0})]);var t1=So.object({selector:Ur,inputs:So.record(So.string()).optional()}),ux=So.discriminatedUnion("type",[So.object({type:So.literal("PRESET_ACTION"),action:Ia}),So.object({type:So.literal("MODULE"),module:t1})]).describe("The step types that can be ingested for a test change. The PRESET_ACTION's action can be seen as a single step command. The MODULE is a module step to use.");async function dx(r,e,t){switch(r.type){case"PRESET_ACTION":return{type:"PRESET_ACTION",command:{...r.action,id:Wh()},id:Wh()};case"MODULE":{let{selector:n,inputs:o}=r.module,{entity:i,momenticFiles:a}=Br(e,n,"module"),l=await yr(i,a,t),s=Object.keys(o??{}).length>0?o:(l.parameters?.length??0)>0?{}:void 0,u={id:Wh(),inputs:s};return{...l,...u,type:"RESOLVED_MODULE"}}default:return(o=>{throw new Error("You missed a case in the switch above")})(r)}}var n1=mt({schema:{name:"momentic_module_create",description:"Create a module. If startIndex is provided, the steps will be extracted from the current test, a module will be created with those steps, and the test will be updated to reference the new module. If no startIndex is provided, an unreferenced module will be created. Automatically splices and repairs the test to reference the new module.",inputSchema:{name:yo.string(),description:yo.string(),enabled:yo.boolean().default(!0),subDir:yo.string().optional().describe("sub directory to create the module in. If not provided, the module will be created in the project's root directory."),startIndex:yo.number().optional().describe("Start index of steps to extract from the current test (0-based)."),endIndex:yo.number().optional().describe("End index of steps to extract from the current test (exclusive). If not provided, extracts just the startIndex.")}},handle:async(r,e,t,n)=>{let{project:o,logger:i,testPath:a}=r,l=e.startIndex??0,c=e.endIndex??l+1,s=W(o);if(Object.values(s.modules).find(m=>m.name===e.name))throw new _e(`A module with the name "${e.name}" already exists. Please use a different name.`);let d=[];if(e.startIndex!==void 0){if(!a)throw new _e("testPath is required when extracting steps from the current test.");let m=await it(qh.join(o.rootDir,a),i,s);if(l<0||l>=m.steps.length)throw new _e(`startIndex ${l} is out of bounds. Test has ${m.steps.length} steps.`);if(c<=l||c>m.steps.length)throw new _e(`endIndex ${c} is out of bounds. Must be between ${l+1} and ${m.steps.length}.`);d=m.steps.slice(l,c);for(let g of d)if(g.type==="RESOLVED_MODULE")throw new _e("Modules cannot be nested. Please select steps that do not include module references.")}let p=await Vc({name:e.name,description:e.description,enabled:e.enabled,steps:d,folder:e.subDir?qh.join(o.rootDir,e.subDir):o.rootDir,project:o});if(s=W(o),e.startIndex!==void 0){let m=await it(qh.join(o.rootDir,a),i,s),g={type:"RESOLVED_MODULE",id:r1(),moduleId:p.moduleId,name:e.name,description:e.description,enabled:e.enabled,parameters:[],steps:d,inputs:{}};m.steps.splice(l,c-l,g);let{stepsToSave:h,moduleUpdates:f}=await Ge({stepLists:{steps:m.steps,beforeSteps:m.beforeSteps,afterSteps:m.afterSteps}});f.forEach(S=>{jt({content:S,schemaVersion:se,momenticFiles:s,project:o})}),Dt({relativeTestPath:a,steps:h,schemaVersion:se,project:o})}t.addResult(JSON.stringify(p,null,2))}});function o1(r,e,t,n){if(r===void 0&&e!==void 0)throw new _e("Validation Error: startIndex is required when endIndex is provided.");if(r!==void 0&&e===void 0&&t===0)throw new _e("Validation Error: steps are required when startIndex is provided without an endIndex.");if(r!==void 0&&(r>n||r<0))throw new _e(`Validation Error: startIndex is out of bounds for module with ${n} steps.`);if(e!==void 0&&r===void 0)throw new _e("Validation Error: startIndex is required when endIndex is provided.");if(e!==void 0&&r!==void 0&&e<r)throw new _e("Validation Error: endIndex must be greater than or equal to startIndex.");if(e!==void 0&&(e>n||e<0))throw new _e(`Validation Error: endIndex ${e} is out of bounds for module with ${n} steps.`);let o=r??n;if((e??o)===o&&t===0)throw new _e("Validation Error: Nothing to insert or delete. Provide steps or a valid delete range.")}var i1=mt({schema:{name:"momentic_module_change",description:"Edit a module's steps. Provide startIndex (and optional endIndex) to replace or remove that range; omit endIndex to insert at startIndex; omit both indices to append new steps. Use an empty steps array with both indices to delete the range.",inputSchema:{selector:Ur,steps:ux.array(),startIndex:yo.number().optional(),endIndex:yo.number().optional()}},handle:async(r,e,t,n)=>{let{project:o,logger:i}=r,a=await Promise.all(e.steps.map(f=>dx(f,o,i))),{entity:l,momenticFiles:c}=Br(o,e.selector,"module"),s=await yr(l,c,i),u=a.find(f=>!gp(f));if(u){t.addError(`Validation Error: step type ${u.type} cannot be added to a module.`);return}try{o1(e.startIndex,e.endIndex,e.steps.length,s.steps.length)}catch(f){t.addError(String(f));return}let d=[...s.steps],p=e.startIndex!==void 0?e.startIndex:d.length,m=e.endIndex!==void 0?e.endIndex:p;d.splice(p,m-p,...a);let{stepsToSave:g}=await Ge({stepLists:{steps:d}});jt({content:{...s,steps:g.steps},schemaVersion:se,momenticFiles:c,project:o});let h={...s,steps:d,stepCount:d.length};t.addResult(JSON.stringify(h,null,2))}}),px=[n1,i1];import{randomUUID as yd}from"crypto";import{z as mx}from"zod";var a1=mt({schema:{name:"preview_preflight",description:"Resolve and validate locators without changing the page. If found, it will return the locator ID and HTML.",inputSchema:{description:mx.string().describe("Description of the element to preview.")}},handle:async({controller:r,logger:e,testContext:t},n,o,i)=>{o.setIncludeSnapshot();try{let a=await r.locateElement({description:n.description,disableCache:!0,skipWait:!0,logger:e,testContext:t});a.resolution.locator&&await Promise.all([r.browser.scrollIntoViewIfNeeded(a.resolution.locator),r.browser.highlight(a.resolution.locator)]),o.addResult(`Found element matching description: ${a.target.id}`),a.target.nodeOnlySerializedHtml&&o.addResult(`HTML: ${a.target.nodeOnlySerializedHtml}`);return}catch(a){o.addError(`Failed to find any element matching description: ${a}`)}}}),s1=mt({schema:{name:"preview_ensure",description:"Confirm page state.",inputSchema:{assertion:mx.string().describe("Assertion to confirm page state.")}},handle:async(r,e,t,n)=>{t.setIncludeSnapshot();let{logger:o,storage:i,controller:a,codeEvalTools:l,socket:c,orgId:s,testContext:u}=r,d={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.assertion,id:yd()},id:yd()},p=await jh({step:d,controller:a,storage:i,codeEvalTools:l,logger:o,socket:c,orgId:s,testContext:u});if(!p){t.addError("Assertion executed with unknown result.");return}if(p.status==="SUCCESS"){t.addResult(`Assertion is true: ${p.message}`);return}t.addError(`Assertion is false: ${p.message}`)}}),l1=mt({schema:{name:"preview_step",description:"Execute a step without adding it to the test.",inputSchema:{command:Ia}},handle:async(r,e,t,n)=>{t.setIncludeSnapshot(),t.setIncludeTestContext();let{logger:o,storage:i,controller:a,codeEvalTools:l,socket:c,orgId:s,testContext:u}=r;t.setIncludeSnapshot();let d={type:"PRESET_ACTION",command:{...e.command,id:yd()},id:yd()},p=await jh({step:d,controller:a,storage:i,codeEvalTools:l,logger:o,socket:c,orgId:s,testContext:u});if(!p){t.addError("Assertion executed with unknown result.");return}if(p.status==="SUCCESS"){t.addResult(`Assertion is true: ${p.message}`);return}t.addError(`Assertion is false: ${p.message}`)}}),gx=[a1,s1,l1];import c1 from"path";import{z as hx}from"zod";var u1=mt({schema:{name:"get_environment_variables",description:"Get the current environment variables.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeTestContext()}}),d1=mt({schema:{name:"reset_session",description:"Reset the browser session. This will clear any authentication state and also navigate to the starting URL of the test.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeTestContext(),t.setIncludeSnapshot(),await r.controller.browser.reset({})}}),p1=mt({schema:{name:"run_step",description:"Run the step in the test at the given startIndex. If there is no endIndex, the step at the startIndex will be executed. EndIndex is the last step that is run (end index isinclusive).",inputSchema:{fromIndex:hx.number(),toIndex:hx.number().optional()}},handle:async(r,e,t,n)=>{t.setIncludeTestContext(),t.setIncludeSnapshot();let{project:o,logger:i,testPath:a,storage:l,controller:c,codeEvalTools:s,socket:u,orgId:d,testContext:p}=r,m=e.fromIndex,g=e.toIndex??m,h=W(o),f=await it(c1.join(o.rootDir,a),i,h);if(m<0||m>=f.steps.length){t.addError("startIndex is out of bounds.");return}if(g<m){t.addError("toIndex must be greater than or equal to fromIndex.");return}else if(g>=f.steps.length){t.addError("toIndex is out of bounds.");return}let S=f.steps.slice(m,g+1);if(S.length===0){t.addError("No steps were executed.");return}let{results:E}=await $h({steps:S,controller:c,storage:l,codeEvalTools:s,logger:i,socket:u,orgId:d,testContext:p});if(!E||E.length===0){t.addError("No steps were executed.");return}let y=E.at(-1);if(!y){t.addError("No steps were executed.");return}if(y.status!=="SUCCESS"){let R=m+E.length-1;t.addError(`Step at index ${R} failed: ${y.message}`);return}let A=m===g?`Step at index ${g}`:`Steps ${m}-${g}`;if(y.status==="SUCCESS"){t.addResult(`${A} executed successfully. Last step result: ${y.message}`),y.data&&t.addResult(`Data: ${JSON.stringify(y.data,null,2)}`);return}t.addError(`${A} failed: ${y.message}`)}}),fx=[u1,d1,p1];import{randomUUID as Kh}from"crypto";import Ed from"path";import{z as or}from"zod";function ll(r,e,t,...n){t?.emit(r,...n),e.info({event:r,args:n},"Emitting copilot event")}var m1=or.object({selector:Ur,inputs:or.record(or.string()).optional()}),Yh=or.discriminatedUnion("type",[or.object({type:or.literal("PRESET_ACTION"),action:Ia}),or.object({type:or.literal("MODULE"),module:m1})]).describe("The step types that can be ingested for a test change. The PRESET_ACTION's action can be seen as a single step command. The MODULE is a module step to use.");async function Xh(r,e,t){switch(r.type){case"PRESET_ACTION":return{type:"PRESET_ACTION",command:{...r.action,id:Kh()},id:Kh()};case"MODULE":{let{selector:n,inputs:o}=r.module,{entity:i,momenticFiles:a}=Br(e,n,"module"),l=await yr(i,a,t),s=Object.keys(o??{}).length>0?o:(l.parameters?.length??0)>0?{}:void 0,u={id:Kh(),inputs:s};return{...l,...u,type:"RESOLVED_MODULE"}}default:return(o=>{throw new Error("You missed a case in the switch above")})(r)}}var g1=mt({schema:{name:"test_get",description:"Get test contents.",inputSchema:{}},handle:async(r,e,t,n)=>{t.setIncludeTest()}}),h1=mt({schema:{name:"test_insert_step",description:"Insert a step or module into the test.",inputSchema:{index:or.number(),step:Yh}},handle:async(r,e,t,n)=>{t.setIncludeTest();let{project:o,logger:i,testPath:a,socket:l}=r,c=W(o),s=await it(Ed.join(o.rootDir,a),i,c),u=await Xh(e.step,o,i);s.steps.splice(e.index,0,u);let{stepsToSave:d,moduleUpdates:p}=await Ge({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps}});p.forEach(m=>{jt({content:m,schemaVersion:se,momenticFiles:c,project:o})}),Dt({relativeTestPath:a,steps:d,schemaVersion:se,project:o}),ll("copilotStepsUpdated",i,l,s.steps)}}),f1=mt({schema:{name:"test_replace_step",description:"Replace a step in the test.",inputSchema:{index:or.number(),step:Yh}},handle:async(r,e,t,n)=>{t.setIncludeTest();let{project:o,logger:i,testPath:a,socket:l}=r,c=W(o),s=await it(Ed.join(o.rootDir,a),i,c),u=await Xh(e.step,o,i);s.steps.splice(e.index,1,u);let{stepsToSave:d,moduleUpdates:p}=await Ge({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps}});p.forEach(m=>{jt({content:m,schemaVersion:se,momenticFiles:c,project:o})}),Dt({relativeTestPath:a,steps:d,schemaVersion:se,project:o}),ll("copilotStepsUpdated",i,l,s.steps)}}),S1=mt({schema:{name:"test_remove_step",description:"Remove a step from the test.",inputSchema:{index:or.number()}},handle:async(r,e,t,n)=>{t.setIncludeTest();let{project:o,logger:i,testPath:a,socket:l}=r,c=W(o),s=await it(Ed.join(o.rootDir,a),i,c);s.steps.splice(e.index,1);let{stepsToSave:u,moduleUpdates:d}=await Ge({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps}});d.forEach(p=>{jt({content:p,schemaVersion:se,momenticFiles:c,project:o})}),Dt({relativeTestPath:a,steps:u,schemaVersion:se,project:o}),ll("copilotStepsUpdated",i,l,s.steps)}}),y1=mt({schema:{name:"test_splice_steps",description:"Splice steps in the test.",inputSchema:{startIndex:or.number(),deleteCount:or.number(),steps:Yh.array()}},handle:async(r,e,t,n)=>{t.setIncludeTest();let{project:o,logger:i,testPath:a,socket:l}=r,c=W(o),s=await it(Ed.join(o.rootDir,a),i,c),u=await Promise.all(e.steps.map(m=>Xh(m,o,i)));s.steps.splice(e.startIndex,e.deleteCount,...u);let{stepsToSave:d,moduleUpdates:p}=await Ge({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps}});p.forEach(m=>{jt({content:m,schemaVersion:se,momenticFiles:c,project:o})}),Dt({relativeTestPath:a,steps:d,schemaVersion:se,project:o}),ll("copilotStepsUpdated",i,l,s.steps)}}),Sx=[g1,h1,f1,S1,y1];var yx=[...px,...cx,...fx,...gx,...Sx,...gd];function Td(r,e,t,n,o){let i=Xo(),a=St(),l=Or(),c=ae(),s=new Ye({apiKey:i,baseUrl:l,logger:t}),u=new fo(s,a),d=new Qr({httpClient:new At({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:t}),fakerSeed:c.config.advanced?.fakerConstantSeed?Hi:void 0}),p={project:c,apiKey:i,orgId:a,baseUrl:l,logger:t,storage:u,codeEvalTools:d,testPath:r,testContext:n.context,controller:n.controller,socket:n.socket},m=yx.reduce((f,{name:S,builder:E})=>(f[S]=E(p,new Sd(p.controller.browser,p.testContext,p.project,p.logger,p.testPath)),f),{});return{model:sx(i,o)("claude-sonnet-4-5-20250929"),stopWhen:E1(30),maxRetries:4,system:lx,messages:e,tools:m}}var R1=mn({schema:{name:"momentic_test_create",description:"Create a test. You must provide a name and either a baseUrl or environment or the tool will fail.",inputSchema:Qp},handle:async(r,e,t,n)=>{let{project:o}=r;try{let i=await fd({project:o,input:e});t.addResult(JSON.stringify(i,null,2))}catch(i){t.addError(String(i));return}}}),A1=mn({schema:{name:"momentic_test_list",description:"List tests.",inputSchema:{}},handle:async(r,e,t,n)=>{let{project:o}=r,i=W(o),l=Object.values(i.tests).map(c=>({id:c.id,name:c.name,description:c.description,relativePath:c.relativePath,fullFilePath:c.fullFilePath,platformSep:c.platformSep,fullPathSegments:c.fullPathSegments,relativePathSegments:c.relativePathSegments,fileName:c.fileName,lastModified:c.lastModified,createdAt:c.createdAt,type:c.type,labels:c.labels||[]}));t.addResult(JSON.stringify({tests:l},null,2))}}),w1=mn({schema:{name:"momentic_test_get",description:"Get a single fully loaded test by id, exact name, or file path. Exactly one selector must be provided.",inputSchema:{selector:Ur}},handle:async(r,e,t,n)=>{let{project:o,logger:i}=r;try{let a=Br(o,e.selector,"test"),l=await it(a.entity.fullFilePath,i,a.momenticFiles);t.addResult(JSON.stringify({test:l},null,2))}catch(a){t.addError(String(a));return}}});async function C1(r,e,t){let n=Xo(),o=St(),i=Or(),a=new Si,l=new Ye({apiKey:n,baseUrl:i,logger:r}),c=new fo(l,o),s=(await it(t.fullFilePath,r,W(e))).advanced?.viewport??Mt,u=new bn(e.config.ai?.agentConfig,{baseUrl:i,apiKey:n,logger:r}),d=new Zn({baseUrl:i,apiKey:n,logger:r},u),p=await wr.init({baseUrl:"about:blank",userBrowserSettings:{},enricher:d,storage:c,logger:r,contextArgs:{viewport:s,locale:Vn,timezoneId:jn,geolocation:$n},iconKnowledgeBase:null,callbacks:{}}),m=new go({browser:p,generator:u,logger:r,orgId:o,options:{scratchPadId:void 0,slowMoMs:void 0,autoFollowNewTabs:!0,useMemory:e.config.ai?.useMemory,aiPageFiltering:!0},storage:c,localCodeEvalTools:new Qr({httpClient:new At({baseUrl:i,apiKey:n,logger:r}),fakerSeed:e.config.advanced?.fakerConstantSeed?Hi:void 0}),visualDiffScreenshotStorage:a}),g=new qt({baseUrl:"about:blank",testName:b1.basename(t.relativePath),currentUrl:p.url(),variablesFromEnvironment:{},envName:void 0});return{controller:m,context:g,socket:void 0}}var x1=mn({schema:{name:"momentic_test_edit",description:"Edit a test.",inputSchema:{selector:Ur,message:v1.string().describe("A single block of natural-language instructions describing the desired edits to the test. The test can also be edited to add modules, edit modules, or create new modules inside of the test. Can only be used to modify steps (including module steps) inside of the passed in test.")}},handle:async(r,e,t,n)=>{let{project:o,logger:i}=r,a=Xo(),l=Or(),s=await new bn(o.config.ai?.agentConfig,{baseUrl:l,apiKey:a,logger:i}).getLintMcpCopilotMessageResult({message:e.message},{logger:i});if(s.category!=="NONE"){t.addError(`${s.thoughts}
|
|
4163
4113
|
|
|
4164
|
-
Category: ${s.category}`);return}let u,d;try{({entity:u,momenticFiles:d}=
|
|
4165
|
-
`).map(S=>S.trim()).filter(S=>S.length>0);t.addResult(JSON.stringify({editedTest:f,messages:E},null,2))}}),ox=[e1,Zz,t1,n1];var ix=[...jC,...ox,...rd];function Hh(r,e){let t=new o1({name:e.applicationName,version:e.cliVersion});for(let n of ix)n.addToolToMcpServer(r,t);return t}async function ax(r,e,t,n){let o=new i1(t,e,n);return await r.connect(o),{close:async()=>{try{await r.close()}catch{}},transport:o}}var u1="mcp-session-id",d1="sessionId",cd=c1(),rl=new Map;function sx(){let r={applicationName:"momentic-mcp-desktop-server",cliVersion:_h??"0.0.0"},e=te(),t=st.child({orgId:yt(),userId:ea(),...r});return{context:{project:e,logger:t},info:r}}cd.get("/sse",async(r,e)=>{let{context:t,info:n}=sx(),o=Hh(t,n),{transport:i}=await ax(o,e,"/api/mcp/sse",{enableDnsRebindingProtection:!1}),a=i.sessionId,l={transport:i,close:async()=>{rl.delete(a);try{await o.close()}catch(c){t.logger.warn({err:c},"Failed to close MCP server on SSE session cleanup")}}};rl.set(a,l),i.onclose=()=>{let c=rl.get(a);c&&c.close()}});cd.post("/sse",async(r,e)=>{let t=String(r.query[d1]??"");if(!t||!rl.has(t)){e.status(400).send("Invalid or missing sessionId");return}await rl.get(t).transport.handlePostMessage(r,e,r.body)});var lx=cd,xa=new Map;cd.all("/",async(r,e)=>{let t=String(r.headers[u1]??"");if(t&&xa.has(t)){await xa.get(t).handle(r,e,r.body);return}let n=r.method==="GET",o=r.method==="POST"&&s1(r.body);if(!n&&!o){e.status(400).send("Bad Request: No valid session ID provided");return}let{context:i,info:a}=sx(),l=Hh(i,a),c=new a1({sessionIdGenerator:()=>l1(),enableDnsRebindingProtection:!1,onsessioninitialized:s=>{xa.set(s,{handle:async(u,d,p)=>{await c.handleRequest(u,d,p)},close:async()=>{xa.delete(s);try{await c.close()}catch{}try{await l.close()}catch{}}})}});c.onclose=()=>{let s=c.sessionId;s&&xa.has(s)&&xa.get(s).close()},await l.connect(c),await c.handleRequest(r,e,r.body)});import{Router as p1}from"express";var ud=p1();ud.get("/",fe((r,e)=>{let t=Nm().map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(t)}));ud.get("/current",fe((r,e)=>{let t=te();if(!t){e.status(404).json({error:"No project found."});return}let n={name:t.config.name,configFilePath:t.configFilePath};e.status(200).json(n)}));ud.post("/set",fe((r,e)=>{let t;try{t=fy.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=Tt({configFilePath:t.configFilePath});Mc(n,o=>Tt({configFilePath:o}))}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var cx=ud;import{Router as m1}from"express";var ux=m1();ux.get("/",fe((r,e)=>{let n={ai:te().config.ai};e.status(200).json(n)}));var dx=ux;import{convertToModelMessages as f1,streamText as S1}from"ai";import{Router as y1}from"express";import px from"fs";import ol from"path";import{v4 as E1}from"uuid";import T1 from"yaml";import{randomUUID as g1}from"node:crypto";import{PostHog as h1}from"posthog-node";var dd=class r{bindings;client;options;constructor(e,t={}){this.bindings=e,this.options=t,this.client=new h1("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...t})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new r({...this.bindings,...e},this.options)}track(e,t){if(!_S(this.bindings))return console.error(`Cannot track ${e.type} event without required bindings.`,this.bindings),this;let{type:n,...o}=e;return this.client.capture({distinctId:g1(),event:n,timestamp:t?.timestamp,properties:{...this.bindings,...o}}),this}};var nl=new dd({platform:"local_app"},{flushAt:1,flushInterval:0});var fo=y1();fo.post("/",fe(async(r,e)=>{let t;try{t=uy.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=te(),o=await od({project:n,input:t});nl.track({type:"test_editor:test_create"}),e.status(201).json(o)}catch(n){if(n instanceof Ie){e.status(400).json({error:n.message});return}throw n}}));fo.get("/:testPath",fe(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n=te(),o=q(n),i;try{i=await at(ol.join(n.rootDir,t),st,o),e.status(200).json(i)}catch(a){e.status(400).send({error:a.message});return}(async()=>{try{let{stepsToSave:a,moduleUpdates:l}=await Ge({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});l.forEach(c=>{jt({content:c,schemaVersion:ue,momenticFiles:o,project:n})}),Dt({relativeTestPath:t,steps:a,schemaVersion:ue,project:n})}catch(a){st.error({err:a},"Failed to save migrated test to disk after initial fetch")}})()}));fo.patch("/:testPath/metadata",fe(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=cy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o={message:"ok",newRelativeTestPath:xm(r.params.testPath,t,te()).newRelativeTestPath};e.status(200).json(o)}));fo.patch("/:testPath",fe(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=ly.parse(r.body)}catch(m){st.warn({err:m},"Invalid save request"),e.status(400).json({error:`Invalid request body: ${m}`});return}st.info({testPath:t},"Save received");let o=te(),i=q(o),a;try{a=vs(t,o)}catch(m){e.status(400).json({error:`Existing test file on disk is invalid: ${m}`});return}let{stepsToSave:l,moduleUpdates:c,cachesToSave:s}=await Ge({stepLists:n.stepLists,cacheCreationParams:{testId:a.id,orgId:yt()}}),u=new Je({apiKey:qo(),baseUrl:Mr(),logger:st}),d=await Qn(st,u,o);await Qi({orgId:yt(),client:u,gitMetadata:d}).saveStepCacheEntries({logger:st,testId:a.id,entries:s}),c.forEach(m=>{jt({content:m,schemaVersion:n.schemaVersion,momenticFiles:i,project:o})}),Dt({relativeTestPath:t,steps:l,schemaVersion:n.schemaVersion,project:o}),e.status(201).json({message:"ok"})}));fo.patch("/:testPath/environments",fe(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=hy.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}xm(t,{envs:n.defaultEnv?[{name:n.defaultEnv,default:!0}]:[]},te()),e.status(201).json({message:"ok"})}));fo.post("/:testPath/duplicate",fe(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=dy.parse(r.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{Vn(n.name)}catch(f){e.status(400).json({error:f.message});return}let o=te(),i=ol.join(o.rootDir,t);if(!px.existsSync(i)){e.status(404).json({error:"Test not found."});return}let a=q(o),l;try{l=await at(i,st,a)}catch(f){e.status(400).send({error:f.message});return}let c=E1(),s=mr.parse({...l,name:n.name,id:c}),{stepsToSave:u}=await Ge({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps},createNewCacheIds:!0,cacheCreationParams:{testId:c,orgId:yt()}}),d=vn({fileType:Se.TEST,...s,beforeSteps:u.beforeSteps??void 0,steps:u.steps,afterSteps:u.afterSteps??void 0}),p=ol.dirname(i),m=ol.join(p,`${n.name}.${St.TEST}`),g=T1.stringify(d);px.writeFileSync(m,g,"utf-8");let h={relativeFilePath:ol.relative(o.rootDir,m)};nl.track({type:"test_editor:test_create"}),e.status(201).json(h)}));fo.post("/:testPath/chat",fe(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let{messages:n}=r.body;if(!n){e.status(400).json({error:"Missing messages in request body."});return}let o=f1(n),i=nd.getLatestSession();if(!i){e.status(400).json({error:"No active browser session. Start a session first."});return}let a=te(),l=vs(t,a),c=st.child({orgId:yt(),applicationName:"momentic-desktop-server-copilot",testId:l.id}),s=ld(t,o,c,i);S1(s).pipeUIMessageStreamToResponse(e,{onError:d=>d instanceof Error?d.message:String(d)})}));var mx=fo;async function Sx(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,staticDir:o,devicePixelRatio:i,alwaysSaveCache:a,noCache:l,initialProject:c}=r;e&&UT(e),await BT(t);let s=yt(),u=ea();nl.identify({user_id:u,org_id:s});let d=r.logger??st;d=d.child({orgId:s,userId:u}),d.debug({params:r},"Desktop server init and api key check done");let p=x1(o,n,d),m=`http://localhost:${n}`;T.info(`Desktop server is running at ${m}`),Mc(c,A=>Tt({configFilePath:A})),await new Promise(A=>{try{p.listen(n,()=>{d.info(`Desktop server is running at ${m}`),A()})}catch(R){R.message.includes("EADDRINUSE")?yx(n):T.error(`An unexpected error occurred while starting the server: ${R.message}`),process.exit(1)}});let h={type:"API_KEY",baseUrl:Mr(),apiKey:t,logger:d},f=async()=>{let A=te();return new Tn(A.config.ai?.agentConfig,h)},E=async()=>new Xn(h,await f()),S=new Je(h),y=new gi;FC({baseServer:p,getOrgId:async()=>yt(),generatorFactory:f,enricherFactory:E,cacheStorageFactory:async A=>{let R=te(),w=await Qn(d,S,R);return Qi({orgId:A,client:S,gitMetadata:w,alwaysSaveCache:a,noCache:l})},branchGetter:async()=>{try{return(await Fm(d))?.gitBranchName}catch(A){d.error({err:A},"Failed to get environment git metadata");return}},flagStoreFactory:async A=>{let R=te();return new Qr(R.config)},settingsFactory:async()=>{let A=te();return{ai:{},browser:{},...A.config}},storageFactory:async A=>new mo(S,A),logger:d,devicePixelRatio:i,authorization:h,visualDiffScreenshotStorage:y,globalE2eStateManager:nd})}var fx="25mb";function x1(r,e,t){let n=hx();n.use(b1()),n.use(gx.json({limit:fx})),n.use(gx.urlencoded({extended:!1,limit:fx}));let o=A1();if(o.use("/tests",mx),o.use("/modules",UC),o.use("/environments",zC),o.use("/projects",cx),o.use("/folders",Cm),o.use("/settings",dx),o.use("/identify",VC),o.use("/entities",HC),o.use("/mcp",lx),n.use("/api",o),n.use((a,l,c)=>{a.path!=="/healthcheck"&&!a.path.startsWith("/assets")&&t.debug({url:a.url,path:a.path,query:a.query,method:a.method,body:a.body,headers:a.rawHeaders,client:a.ip},"Received desktop-server request"),l.on("close",()=>{l.statusCode>=400&&t.error({url:a.url,method:a.method,statusCode:l.statusCode},"Request completed in error")}),c()}),n.use((a,l,c,s)=>{if(a instanceof Error&&a.message.includes("BadRequestError: request aborted")){c.status(400).send("Client disconnected");return}t.error({stack:a.stack,msg:a.message,err:a,url:l.url,method:l.method},"Unhandled exception leading to 500 on desktop-server"),T.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${a.message}
|
|
4166
|
-
${a.stack}`),c.status(500).send(`Internal Server Error: ${a.message}`)}),r){let a=
|
|
4114
|
+
Category: ${s.category}`);return}let u,d;try{({entity:u,momenticFiles:d}=Br(o,e.selector,"test"))}catch(E){t.addError(String(E));return}let p=i.child({applicationName:"momentic-mcp-copilot",testId:u.id}),m=Td(u.relativePath,[{role:"user",content:e.message}],p,await C1(p,o,u),n?.sessionId),g=T1({...m}),h=[];for await(let E of g.textStream)h.push(E);let f=await it(u.fullFilePath,i,d),S=h.join("").split(`
|
|
4115
|
+
`).map(E=>E.trim()).filter(E=>E.length>0);t.addResult(JSON.stringify({editedTest:f,messages:S},null,2))}}),Ex=[A1,R1,w1,x1];var Tx=[...ix,...Ex,...gd];function Jh(r,e){let t=new _1({name:e.applicationName,version:e.cliVersion});for(let n of Tx)n.addToolToMcpServer(r,t);return t}async function bx(r,e,t,n){let o=new I1(t,e,n);return await r.connect(o),{close:async()=>{try{await r.close()}catch{}},transport:o}}var N1="mcp-session-id",D1="sessionId",bd=L1(),cl=new Map;function vx(){let r={applicationName:"momentic-mcp-desktop-server",cliVersion:Bh??"0.0.0"},e=ae(),t=Je.child({orgId:St(),userId:ra(),...r});return{context:{project:e,logger:t},info:r}}bd.get("/sse",async(r,e)=>{let{context:t,info:n}=vx(),o=Jh(t,n),{transport:i}=await bx(o,e,"/api/mcp/sse",{enableDnsRebindingProtection:!1}),a=i.sessionId,l={transport:i,close:async()=>{cl.delete(a);try{await o.close()}catch(c){t.logger.warn({err:c},"Failed to close MCP server on SSE session cleanup")}}};cl.set(a,l),i.onclose=()=>{let c=cl.get(a);c&&c.close()}});bd.post("/sse",async(r,e)=>{let t=String(r.query[D1]??"");if(!t||!cl.has(t)){e.status(400).send("Invalid or missing sessionId");return}await cl.get(t).transport.handlePostMessage(r,e,r.body)});var Rx=bd,Ma=new Map;bd.all("/",async(r,e)=>{let t=String(r.headers[N1]??"");if(t&&Ma.has(t)){await Ma.get(t).handle(r,e,r.body);return}let n=r.method==="GET",o=r.method==="POST"&&P1(r.body);if(!n&&!o){e.status(400).send("Bad Request: No valid session ID provided");return}let{context:i,info:a}=vx(),l=Jh(i,a),c=new M1({sessionIdGenerator:()=>O1(),enableDnsRebindingProtection:!1,onsessioninitialized:s=>{Ma.set(s,{handle:async(u,d,p)=>{await c.handleRequest(u,d,p)},close:async()=>{Ma.delete(s);try{await c.close()}catch{}try{await l.close()}catch{}}})}});c.onclose=()=>{let s=c.sessionId;s&&Ma.has(s)&&Ma.get(s).close()},await l.connect(c),await c.handleRequest(r,e,r.body)});import{Router as k1}from"express";var vd=k1();vd.get("/",ye((r,e)=>{let t=Wm().map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(t)}));vd.get("/current",ye((r,e)=>{let t=ae();if(!t){e.status(404).json({error:"No project found."});return}let n={name:t.config.name,configFilePath:t.configFilePath};e.status(200).json(n)}));vd.post("/set",ye((r,e)=>{let t;try{t=xy.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=Et({configFilePath:t.configFilePath});Gc(n,o=>Et({configFilePath:o}))}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var Ax=vd;import{Router as F1}from"express";var wx=F1();wx.get("/",ye((r,e)=>{let n={ai:ae().config.ai};e.status(200).json(n)}));var Cx=wx;import{convertToModelMessages as U1,streamText as B1}from"ai";import{Router as z1}from"express";import xx from"fs";import dl from"path";import{v4 as H1}from"uuid";import G1 from"yaml";var ul=new tu({platform:"local_app"},{flushAt:1,flushInterval:0});var Eo=z1();Eo.post("/",ye(async(r,e)=>{let t;try{t=by.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=ae(),o=await fd({project:n,input:t});ul.track({type:"test_editor:test_create"}),e.status(201).json(o)}catch(n){if(n instanceof _e){e.status(400).json({error:n.message});return}throw n}}));Eo.get("/:testPath",ye(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n=ae(),o=W(n),i;try{i=await it(dl.join(n.rootDir,t),Je,o),e.status(200).json(i)}catch(a){e.status(400).send({error:a.message});return}(async()=>{try{let{stepsToSave:a,moduleUpdates:l}=await Ge({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});l.forEach(c=>{jt({content:c,schemaVersion:se,momenticFiles:o,project:n})}),Dt({relativeTestPath:t,steps:a,schemaVersion:se,project:n})}catch(a){Je.error({err:a},"Failed to save migrated test to disk after initial fetch")}})()}));Eo.patch("/:testPath/metadata",ye(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=Ty.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o={message:"ok",newRelativeTestPath:Bm(r.params.testPath,t,ae()).newRelativeTestPath};e.status(200).json(o)}));Eo.patch("/:testPath",ye(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Ey.parse(r.body)}catch(m){Je.warn({err:m},"Invalid save request"),e.status(400).json({error:`Invalid request body: ${m}`});return}Je.info({testPath:t},"Save received");let o=ae(),i=W(o),a;try{a=_s(t,o)}catch(m){e.status(400).json({error:`Existing test file on disk is invalid: ${m}`});return}let{stepsToSave:l,moduleUpdates:c,cachesToSave:s}=await Ge({stepLists:n.stepLists,cacheCreationParams:{testId:a.id,orgId:St()}}),u=new Ye({apiKey:Xo(),baseUrl:Or(),logger:Je}),d=await to(Je,u,o);await ea({orgId:St(),client:u,gitMetadata:d}).saveStepCacheEntries({logger:Je,testId:a.id,entries:s}),c.forEach(m=>{jt({content:m,schemaVersion:n.schemaVersion,momenticFiles:i,project:o})}),Dt({relativeTestPath:t,steps:l,schemaVersion:n.schemaVersion,project:o}),e.status(201).json({message:"ok"})}));Eo.patch("/:testPath/environments",ye(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Cy.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}Bm(t,{envs:n.defaultEnv?[{name:n.defaultEnv,default:!0}]:[]},ae()),e.status(201).json({message:"ok"})}));Eo.post("/:testPath/duplicate",ye(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=vy.parse(r.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{Wn(n.name)}catch(f){e.status(400).json({error:f.message});return}let o=ae(),i=dl.join(o.rootDir,t);if(!xx.existsSync(i)){e.status(404).json({error:"Test not found."});return}let a=W(o),l;try{l=await it(i,Je,a)}catch(f){e.status(400).send({error:f.message});return}let c=H1(),s=hr.parse({...l,name:n.name,id:c}),{stepsToSave:u}=await Ge({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps},createNewCacheIds:!0,cacheCreationParams:{testId:c,orgId:St()}}),d=Zr({fileType:de.TEST,...s,beforeSteps:u.beforeSteps??void 0,steps:u.steps,afterSteps:u.afterSteps??void 0}),p=dl.dirname(i),m=dl.join(p,`${n.name}.test.yaml`),g=G1.stringify(d);xx.writeFileSync(m,g,"utf-8");let h={relativeFilePath:dl.relative(o.rootDir,m)};ul.track({type:"test_editor:test_create"}),e.status(201).json(h)}));Eo.post("/:testPath/chat",ye(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let{messages:n}=r.body;if(!n){e.status(400).json({error:"Missing messages in request body."});return}let{sessionId:o}=r.body;if(!o){e.status(401).json({error:"Missing sessionId in request body."});return}let i=U1(n),a=hd.getSession(o);if(!a){e.status(400).json({error:"No active browser session. Start a session first."});return}let l=ae(),c=_s(t,l),s=Je.child({orgId:St(),applicationName:"momentic-desktop-server-copilot",testId:c.id,sessionId:o});s.debug("Initializing copilot with sessionId",o);let u=Td(t,i,s,a,o);B1(u).pipeUIMessageStreamToResponse(e,{onError:p=>p instanceof Error?p.message:String(p)})}));var _x=Eo;async function Ox(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,staticDir:o,devicePixelRatio:i,alwaysSaveCache:a,noCache:l,initialProject:c}=r;e&&JT(e),await QT(t);let s=St(),u=ra();ul.identify({user_id:u,org_id:s});let d=r.logger??Je;d=d.child({orgId:s,userId:u}),d.debug({params:r},"Desktop server init and api key check done");let p=Y1(o,n,d),m=`http://localhost:${n}`;T.info(`Desktop server is running at ${m}`),Gc(c,A=>Et({configFilePath:A})),await new Promise(A=>{try{p.listen(n,()=>{d.info(`Desktop server is running at ${m}`),A()})}catch(R){R.message.includes("EADDRINUSE")?Lx(n):T.error(`An unexpected error occurred while starting the server: ${R.message}`),process.exit(1)}});let h={type:"API_KEY",baseUrl:Or(),apiKey:t,logger:d},f=async()=>{let A=ae();return new bn(A.config.ai?.agentConfig,h)},S=async()=>new Zn(h,await f()),E=new Ye(h),y=new Si;QC({baseServer:p,getOrgId:async()=>St(),generatorFactory:f,enricherFactory:S,cacheStorageFactory:async A=>{let R=ae(),w=await to(d,E,R);return ea({orgId:A,client:E,gitMetadata:w,alwaysSaveCache:a,noCache:l})},branchGetter:async()=>{try{return(await Ps(d))?.gitBranchName}catch(A){d.error({err:A},"Failed to get environment git metadata");return}},settingsFactory:async()=>{let A=ae();return{ai:{},browser:{},...A.config}},storageFactory:async A=>new fo(E,A),logger:d,devicePixelRatio:i,authorization:h,visualDiffScreenshotStorage:y,globalE2eStateManager:hd})}var Px="25mb";function Y1(r,e,t){let n=Mx();n.use(V1()),n.use(Ix.json({limit:Px})),n.use(Ix.urlencoded({extended:!1,limit:Px}));let o=W1();if(o.use("/tests",_x),o.use("/modules",ZC),o.use("/environments",rx),o.use("/projects",Ax),o.use("/folders",Um),o.use("/settings",Cx),o.use("/identify",ox),o.use("/entities",tx),o.use("/mcp",Rx),n.use("/api",o),n.use((a,l,c)=>{a.path!=="/healthcheck"&&!a.path.startsWith("/assets")&&t.debug({url:a.url,path:a.path,query:a.query,method:a.method,body:a.body,headers:a.rawHeaders,client:a.ip},"Received desktop-server request"),l.on("close",()=>{l.statusCode>=400&&t.error({url:a.url,method:a.method,statusCode:l.statusCode},"Request completed in error")}),c()}),n.use((a,l,c,s)=>{if(a instanceof Error&&a.message.includes("BadRequestError: request aborted")){c.status(400).send("Client disconnected");return}t.error({stack:a.stack,msg:a.message,err:a,url:l.url,method:l.method},"Unhandled exception leading to 500 on desktop-server"),T.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${a.message}
|
|
4116
|
+
${a.stack}`),c.status(500).send(`Internal Server Error: ${a.message}`)}),r){let a=Mx.static(r,{setHeaders:l=>{l.setHeader("Cache-Control","no-cache")},redirect:!1});n.use(a),n.use("*",(l,c)=>{c.sendFile(K1.join(r,"index.html"))})}let i=q1.createServer(n);return i.once("error",a=>{"code"in a&&a.code==="EADDRINUSE"?(Lx(e),process.exit(1)):console.error("An unexpected server error occurred:",a.message)}),i}$1.setMaxListeners(50);process.on("warning",r=>{Je.warn({err:r},`Node warning received on desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{Je.error({err:r},"Uncaught exception on desktop-server"),T.error(`Oh no! The Momentic desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",(r,e)=>{Je.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on desktop-server (promise rejection)"),T.error(`Oh no! The Momentic desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function Lx(r){T.error(j1`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4167
4117
|
Using Bash on MacOS or Linux:
|
|
4168
4118
|
lsof -t -i :58888 | xargs kill -9
|
|
4169
4119
|
|
|
4170
4120
|
Using Command Prompt on Windows:
|
|
4171
4121
|
for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
|
|
4172
|
-
`)}import
|
|
4173
|
-
${[...n].map(i=>`${
|
|
4122
|
+
`)}import eV from"events";import zd from"fs";import tV from"open";import{cpus as N_}from"os";import Bd from"path";import{fileURLToPath as rV}from"url";import X1 from"diff-lines";import{gt as J1}from"semver";async function Nx({test:r,fragment:e,entities:t,client:n,logger:o,yes:i}){J1(e.schemaVersion,se)&&(T.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),eT(e.steps).forEach(g=>{t.modules[g]||(T.error(`The test patch contains a module with id ${g} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!i&&!await Nt("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let l=r.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<l&&!i&&!await Nt("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?",!0)&&process.exit(1);let c=Qo(r.fullFilePath,o,t),s=c.steps;if(!Array.isArray(s))throw new Error(`Test ${r.fullFilePath} is missing steps array`);let u,d;if(e.schemaVersion!==se){let{steps:g,newVersion:h}=await bs({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:T});u=h,d=Ze.array().parse(g)}else d=Ze.array().parse(e.steps);let{stepsToSave:p}=await Ge({stepLists:{steps:d}});p.beforeSteps=c.beforeSteps??void 0,p.afterSteps=c.afterSteps??void 0;let m=X1(JSON.stringify(s,void 0,2),JSON.stringify(p,void 0,2),{n_surrounding:5});T.dimmed("=".repeat(30)),T.dimmed(m),T.dimmed("=".repeat(30)),T.dimmed(""),u&&T.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${u}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await Nt("Do you want to apply this patch?")&&(T.dimmed("Cancelled."),process.exit(1)),Dt({relativeTestPath:r.relativePath,steps:p,schemaVersion:u??e.schemaVersion,project:t.project}),T.success("Patch applied successfully."),await n.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as ir}from"crypto";import{z as Dx}from"zod";function pl(r){return Dx.string().uuid().safeParse(r).success}async function Rd({fix:r,project:e}){let t=W(e),n=Object.values(t.tests),o={},i={},a=new Set,l={},c=new Set,s=0;for(let d of n)try{let p=Qo(d.fullFilePath,Z,t),m=!1,g=!1;pl(d.id)||(T.error(`Test '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${d.id}'`),s++,g=!0,r&&(d.id=ir(),m=!0)),t.duplicateEntities[d.id]&&(T.error(`Test '${d.name}' (${d.relativePath}) has a duplicate ID: '${d.id}'`),s++,g=!0,r&&(d.id=ir(),m=!0));let h=p.steps;if(!h||h.length===0||!Array.isArray(h)){T.debug(`Test ${d.name} (${d.relativePath}) has no steps, skipping...`);continue}let f=Ot.parse(p),S=await Wo(f,h,T);S.steps=S.steps.map((E,y)=>{E.id||(T.error(`Step ${y} in test '${d.name}' (${d.relativePath}) does not have an ID`),g=!0,r&&(m=!0,E.id=ir())),pl(E.id)||(T.error(`Step ${y} in test '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${E.id}'`),s++,g=!0,r&&(m=!0,E.id=ir()));let A=o[E.id]?.testId,R=o[E.id]?.testRelativePath;if(A?(s++,g=!0,A===d.id?T.error(`Multiple steps in the test '${d.name}' (${d.relativePath}) have the same ID '${E.id}'`):T.error(`Step ${y} in test '${d.name}' (${d.relativePath}) has the ID ${E.id} which is duplicated in ${R}`),r&&(m=!0,E.id=ir())):o[E.id]={testId:d.id,testRelativePath:d.relativePath},E.type==="PRESET_ACTION"){let w=E.command.id;pl(w)||(T.error(`Command ${y} in test '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${w}'`),s++,g=!0,r&&(m=!0,E.command.id=ir()));let x=i[w]?.testId,_=i[w]?.testRelativePath;x?(s++,g=!0,x===d.id?T.error(`Multiple commands in the test '${d.name}' (${d.relativePath}) have the same ID '${w}'`):T.error(`Command ${y} in test '${d.name}' (${d.relativePath}) has the ID ${w} which is duplicated in test ${_}`),r&&(m=!0,E.command.id=ir())):i[w]={testId:d.id,testRelativePath:d.relativePath}}return Pe.parse(E)}),g&&T.dimmed("=".repeat(80)),m&&r&&(Dt({relativeTestPath:d.relativePath,steps:{beforeSteps:p.beforeSteps,steps:S.steps,afterSteps:p.afterSteps},schemaVersion:se,project:e}),a.add(d.fullFilePath))}catch(p){T.error({err:p},`Failed to parse test ${d.name} (${d.relativePath})`);continue}let u=Object.values(t.modules);for(let d of u)try{let p=!1,m=!1;pl(d.id)||(T.error(`Module '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${d.id}'`),s++,m=!0,r&&(d.id=ir(),p=!0)),t.duplicateEntities[d.id]&&(T.error(`Module '${d.name}' (${d.relativePath}) has a duplicate ID: '${d.id}'`),s++,m=!0,r&&(d.id=ir(),p=!0));let g=An(d.fullFilePath,T),h=g.steps;if(!h||h.length===0||!Array.isArray(h)){T.debug(`Module ${d.name} (${d.relativePath}) has no steps, skipping...`);continue}let f,S;try{let y=await Wo({id:g.moduleId,schemaVersion:g.schemaVersion},g.steps,T);f=y.steps,S=y.newVersion}catch(y){T.error({err:y},`Failed to migrate module ${d.name} (${d.relativePath})`);continue}let E=f.map((y,A)=>{if(Dx.string().uuid().safeParse(y.id)||(T.error(`Step ${A} in module '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${y.id}'`),s++,m=!0,r&&(p=!0,y.id=ir())),o[y.id]?.testId){let w=o[y.id]?.testRelativePath;s++,m=!0,T.error(`Step ${A} in module '${d.name}' (${d.relativePath}) has the ID ${y.id} which is duplicated in test ${w}`),r&&(p=!0,y.id=ir())}if(y.type==="PRESET_ACTION"){let w=y.command.id;pl(w)||(T.error(`Command ${A} in module '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${w}'`),s++,m=!0,r&&(p=!0,y.command.id=ir()));let x=i[w],_=l[w];x||_?(s++,m=!0,_?.moduleId===d.id?T.error(`Multiple commands in module '${d.name}' (${d.relativePath}) have the same ID '${w}'`):x?T.error(`Command in module '${d.name}' (${d.relativePath}) has the ID ${w} which is duplicated in test ${x.testRelativePath}`):T.error(`Command ${A} in module '${d.name}' (${d.relativePath}) has the ID ${w} which is duplicated in module ${_.moduleRelativePath}`),r&&(p=!0,y.command.id=ir())):l[w]={moduleId:d.id,moduleRelativePath:d.relativePath}}return Pe.parse(y)});m&&T.dimmed("=".repeat(80)),p&&r&&(jt({content:{...g,steps:E},schemaVersion:S,momenticFiles:t,project:e,forceSaveOnNoDiffs:!0}),c.add(d.fullFilePath))}catch(p){T.error({err:p},`Failed to parse module ${d.name} (${d.relativePath})`);continue}return{errors:s,modifiedTestFilePaths:a,modifiedModuleFilePaths:c}}async function kx({fix:r,project:e}){let{errors:t,modifiedTestFilePaths:n,modifiedModuleFilePaths:o}=await Rd({fix:r,project:e});t>0?(T.error(`Found errors in ${t} steps`),r?(T.warn(`Modified the following test files:
|
|
4123
|
+
${[...n].map(i=>`${ot}- ${i}`).join(`
|
|
4174
4124
|
`)}`),o.size>0&&T.warn(`Modified the following module files:
|
|
4175
|
-
${[...o].map(i=>`${
|
|
4176
|
-
`)}`)):T.warn("To fix these errors automatically, re-run this check with the --fix flag and then commit the resulting changes"),process.exit(1)):(T.success("No duplicates detected. All test, module, step and command IDs are unique."),process.exit(0))}async function Rx({project:r}){let e=q(r),t=Object.values(e.tests),n=await Lc(e,Q),o={},i={},a=new Set,l=new Set;for(let s of t)o[s.name]?i[s.name]?i[s.name].push(s.fullFilePath):i[s.name]=[o[s.name],s.fullFilePath]:o[s.name]=s.fullFilePath;for(let s of n)l.has(s.name)&&a.add(s.name),l.add(s.name);if(Object.entries(i).length>0||a.size>0){for(let[s,u]of Object.entries(i))for(let d of u)T.error(`Test Name ${s} is duplicated in ${d}`);for(let s of a)T.error(`Module name ${s} is duplicated in your project`);process.exit(1)}T.success("No duplicates detected. All test and module names are unique."),process.exit(0)}import{cloneDeep as M1}from"lodash-es";async function Ax({client:r,skipPrompts:e,project:t}){let n=await r.getAllEnvironments(),o=M1(t.config);o.environments||(o.environments=[]);for(let i of n){let a=o.environments?.find(l=>l.name===i.name);if(a)!e&&!await Nt(`Environment ${i.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),a.baseUrl=i.variables[ht],delete i.variables[ht],a.envVariables=i.variables;else{let l=i.variables[ht];delete i.variables[ht],o.environments.push({name:i.name,baseUrl:l,envVariables:i.variables})}}na(o,t.configFilePath),T.success(`Pulled ${n.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as wx}from"crypto";import Cx from"fs";async function zh({testsToFetch:r,client:e,all:t,yes:n}){let{tests:o,modules:i}=await e.getTestYAMLExport({paths:r,all:t}),a=0;for(let[c,s]of Object.entries(o)){let u=xx(c,Se.TEST);!n&&!await im(u)||(a+=1,Cx.writeFileSync(u,s,"utf-8"),Q.info({checksum:wx("md5").update(s).digest("hex")},`Wrote '${u}'`))}let l=0;for(let[c,s]of Object.entries(i)){let u=xx(c,Se.MODULE);!n&&!await im(u)||(l+=1,Cx.writeFileSync(u,s,"utf-8"),Q.info({checksum:wx("md5").update(s).digest("hex")},`Wrote '${u}'`))}a===0?T.success("Pulled 0 tests."):T.success(`Pulled ${a} test${a>1?"s":""}${l?` and ${l} module${l>1?"s":""}`:""}!`)}function xx(r,e){switch(e){case Se.TEST:return`${_e(r)}.${St.TEST}`;case Se.MODULE:return`${_e(r)}.${St.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function _x(r){let{project:e,client:t,skipPrompts:n}=r;T.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),T.info("Importing environments from Momentic Cloud."),T.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await Nt("Are you sure you want to proceed?",!0)||(T.info("Aborting..."),process.exit(1)),await Ax({client:t,project:e,skipPrompts:n}),T.success(`Successfully imported environments from Momentic Cloud. We recommend pulling secrets out of ${e.configFilePath} into .env files or dynamically set environment variables for security.`),T.info("Importing tests and modules from Momentic Cloud."),await zh({testsToFetch:[],client:t,all:!0,yes:n}),T.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}async function Ix(r){let{client:e,skipPrompts:t,paths:n}=r;await zh({testsToFetch:n,client:e,all:void 0,yes:t}),T.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}import{Argument as fi,InvalidArgumentError as al,Option as Oe}from"@commander-js/extra-typings";import{validateHeaderValue as O1}from"http";import{z as Px}from"zod";var gd=58888;function So(r){let e=parseInt(r,10);if(isNaN(e))throw new al("Not a number.");return e}function hd(r){if(r===void 0)return;let e={};for(let t of r){let n=t.indexOf("=");if(n===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,n),i=t.slice(n+1);O1(o,i),e[o]=i}return e}var Br=new Oe("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new al("API key is required.");return r}).makeOptionMandatory(),Hr=new Oe("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return Px.string().url().parse(r),r}catch{throw new al("Not a valid URL.")}}),yo=new Oe("-y, --yes","Skip all confirmation prompts.").env("CI"),Gh=new Oe("-w, --wait","Wait for tests to finish running before exiting."),Vh=new Oe("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${18e5/1e3} seconds.`).default(18e5/1e3).implies({wait:!0}).argParser(So),fd=new Oe("--custom-headers <customHeaders...>","Specify custom headers in the form HEADER=VALUE to be sent with each request during the test. Multiple entries can be provided."),Mx=new Oe("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(Fl)),Ox=new Oe("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml.").default("reports"),jh=new Oe("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),Lx=new Oe("--upload-results","Upload test results to Momentic Cloud.").default(!1),$h=new Oe("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),Wh=new Oe("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),qh=new Oe("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio.").argParser(So),Kh=new Oe("--input-csv <inputCsv>","Path to a CSV file on disk where each row represents a set of inputs that will be made available to all tests that are ran. The first line of the CSV must be the input names."),Sd=new Oe("--env <env>","Name of the environment to use when running tests."),yd=new Oe("--url-override <urlOverride>","Fully qualified URL (e.g. https://www.google.com) to start all tests from. Overrides any default starting URL set from the test or environment.").argParser(r=>{try{return Px.string().url().parse(r),r}catch{throw new al("Not a valid URL.")}}),Nx=new Oe("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(r=>{let e=So(r);if(e<1)throw new al("Shard index must be greater than 0.");return e}),Dx=new Oe("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(So),ir=new Oe("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),_a=new Oe("-f, --filter <filter>","Run tests within the project that has a name equal to the filter provided. This option cannot be used together with file path or directory arguments, but substring matches are allowed."),kx=new Oe("--fix","Attempt to fix any issues found."),Yh=new Oe("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),Xh=new Oe("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes."),Fx=new Oe("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),Ux=new Oe("--only-quarantined","Run only tests that are currently quarantined. When running with this option, any test failures will cause the pipeline to fail, even though the tests are quarantined.").implies({skipQuarantined:!1,ignoreQuarantine:!1}),Bx=new Oe("--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}),Hx=new fi("<tests...>","One or more test paths to queue on Momentic Cloud."),zx=new fi("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),Jh=new fi("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),Gx=new fi("<suites...>","One or more suite paths that exist on Momentic Cloud."),Vx=new fi("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),jx=new fi("<results>","Path to the results archive.").argRequired(),Qh=new Oe("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),Zh=new fi("<test>","Name of the test to quarantine.").argOptional();async function $x(r){let e=q(r),t=Object.values(e.tests);for(let n of t)try{let o=Xo(n.fullFilePath,T,e),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){T.debug(`Test ${n.name} (${n.relativePath}) has no steps, skipping...`);continue}let a=Ot.parse(o),l=await jo(a,i,T);T.dimmed(`Updating ${n.relativePath}`),Dt({relativeTestPath:n.relativePath,steps:{beforeSteps:o.beforeSteps,steps:l.steps,afterSteps:o.afterSteps},schemaVersion:ue,project:r,forceSaveOnNoDiffs:!0})}catch(o){T.error({err:o},`Failed to read or migrate test ${n.name} (${n.relativePath}), continuing...`)}for(let n of Object.values(e.modules)){T.dimmed(`Updating ${n.relativePath}`);try{let o=Rn(n.fullFilePath,T),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){T.debug(`Module ${n.name} (${n.relativePath}) has no steps, skipping...`);continue}let a=await jo({id:o.moduleId,schemaVersion:o.schemaVersion},i,T);jt({content:{...o,steps:a.steps},schemaVersion:ue,momenticFiles:e,project:r,forceSaveOnNoDiffs:!0})}catch(o){T.error({err:o},`Failed to read or migrate module ${n.name} (${n.relativePath}), continuing...`)}}}import{spawnSync as N1}from"child_process";function D1(){try{let e=N1("git remote show origin",{encoding:"utf8",maxBuffer:5242880}).stdout.match(/HEAD branch: (.*)$/m);if(e&&e[1])return e[1].trim();T.warn("Could not determine your Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field.");return}catch(r){let e=r instanceof Error?r.message:String(r);T.warn(`Could not determine Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field. Error:
|
|
4177
|
-
${e}`)}}async function Wx({project:r,orgId:e,apiClient:t}){T.info("Pulling browser and AI configuration options from Cloud");let n=await pd.init(e);r.config.browser={autoExpandIframes:n.isBooleanFlagEnabled("auto_expand_iframes"),disableSecondaryCacheResolution:n.isBooleanFlagEnabled("disable_secondary_cache_resolution"),globalLocatorRedirect:n.isBooleanFlagEnabled("global_locator_redirect"),visualActions:n.isBooleanFlagEnabled("visual_actions"),...r.config.browser},r.config.advanced={fakerConstantSeed:n.isBooleanFlagEnabled("faker_constant_seed"),...r.config.advanced},r.config.ai={aiPageFiltering:n.isBooleanFlagEnabled("rag_v2"),agentConfig:await t.getAgentConfig(),...r.config.ai},T.info(`Updated ${r.configFilePath} to include V2 browser and AI configuration options`),T.info("Determining main Git branch"),r.config.gitMainBranch=D1(),na(r.config,r.configFilePath),T.success("Migration complete!")}import{input as k1,search as F1}from"@inquirer/prompts";import U1 from"fuse.js";async function Ed({prompt:r,inputtedTest:e,testOptions:t}){if(e){let a=t.find(l=>l.name===e);if(!a)T.error(`${e} is not a valid test option.`);else return{name:a.name,id:a.value}}let n=new U1(t,{keys:[{name:"name",weight:1}],threshold:.4,includeScore:!0,findAllMatches:!0,ignoreLocation:!0,useExtendedSearch:!0,shouldSort:!0,includeMatches:!0,distance:100,ignoreFieldNorm:!1}),o=await F1({message:r,source:async a=>!a||a.length===0?t:n.search({name:a}).map(c=>c.item)}),i=t.find(a=>a.value===o);return{name:i.name,id:i.value}}async function Td({prompt:r,inputtedReason:e}){return e||k1({message:r})}async function qx({test:r,reason:e,apiClient:t,project:n,logger:o,identity:i}){let a=q(n).tests,l=Object.values(a).map(u=>({value:u.id,name:u.name})),c=await Ed({prompt:"Select a test to quarantine.",inputtedTest:r,testOptions:l}),s=await Td({prompt:"Enter a reason for quarantining the test.",inputtedReason:e});await t.quarantineTest(c,s,i),T.success(`Test ${c.name} has been successfully quarantined. Navigate to ${t.getAppUrl()}/quarantine to view all quarantined tests. Remove this test from quarantine by running 'npx momentic quarantine remove ${c.name}'.`)}async function Kx({test:r,reason:e,apiClient:t,project:n,logger:o,identity:i}){let a=q(n).tests,l=Object.values(a).map(m=>({value:m.id,name:m.name})),c=(await t.getQuarantinedTests()).quarantined,s=new Set(c.map(m=>m.testId)),u=l.filter(m=>s.has(m.value)),d=await Ed({prompt:"Select a test to unquarantine.",inputtedTest:r,testOptions:u}),p=await Td({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await t.unquarantineTest(d,p,i),T.success(`Test ${d.name} has been successfully removed from quarantine.`)}function Yx(r){return r?_e(r):"Unknown suite"}async function Xx({client:r,orgId:e,suitePaths:t,wait:n,waitTimeout:o,...i}){let{suiteRunIds:a,runGroupIds:l}=await r.queueSuiteRuns({paths:t,...i});Q.info({orgId:e,suiteRunIds:a,runGroupIds:l,suitePaths:t},"Queued suites remotely"),T.dimmed(`Queued ${t.length} suites.`),n||process.exit(0);let c=Date.now();T.dimmed(`Waiting for ${t.length} suites to finish. You can view results upon completion at:`);for(let f of l)T.dimmed(`${it}- ${r.getAppUrl()}/run-groups/${f}`);let s=new Set,u=[],d=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(S=>S.status==="FAILED"&&(S.failureReason||S.finishedAt&&Date.now()-S.finishedAt.getTime()>30*1e3)||S.status==="PASSED"||S.status==="CANCELLED"),p=await ac({name:"suites",getResults:async()=>{let f=l.filter(y=>!u.some(A=>A.id===y)),E=await r.bulkGetRunGroupStatus(f),S=[];for(let y of E)d(y)?u.push(y):S.push(y);return[...u,...S]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(E=>{E.status==="RUNNING"&&(s.has(E.id)||(s.add(E.id),T.log(`${s.size}/${l.length} ${Yx(E.suite?.name)}`)))}),f.every(d))}),m=r.getAppUrl(),h=ji({results:p,startTime:c,onFailed:f=>{let E=Yx(f.suite?.name),S=f.runs.filter(A=>A.status==="FAILED").length,y=f.runs.length;T.error(`${E} (${S}/${y} tests failed):`);for(let A of f.runs)if(A.status==="FAILED"){let R=A.testName||A.test?.name;T.error(` ${R?_e(R):"Unknown test"} (${m}/runs/${A.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?_e(f.suite.name):"Unknown suite name"} (${m}/run-groups/${f.id})`});process.exit(h.failed>0?1:0)}async function Jx({tests:r,client:e,orgId:t,...n}){!n.yes&&!await Nt(`This command will queue ${r.length} tests to run remotely on Momentic's infrastructure. Results will be available on ${e.getAppUrl()}. Continue?`)&&process.exit(1);let{queuedTests:o,runIds:i}=await e.queueTests({testPaths:r,...n});if(Q.info({queuedTests:o,runIds:i,orgId:t},"Queued tests remotely"),T.dimmed(`Queued ${o.length} tests. Processing time may depend on a variety of factors, including how many tests have already been queued from your organization.`),n.wait||process.exit(0),!i.length)return;T.dimmed(`Waiting for ${o.length} tests to complete.`);let a=new Set,l=[],c=m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED",s=e.getAppUrl(),u=Date.now(),d=await ac({name:"runs",getResults:async()=>{let m=i.filter(f=>!l.some(E=>E.id===f)),g=await e.bulkGetRunStatus(m),h=[];for(let f of g)c(f)?l.push(f):h.push(f);return[...l,...h]},timeoutMs:n.waitTimeout?n.waitTimeout*1e3:void 0,checkDone:m=>(m.forEach(g=>{if(g.status==="RUNNING"&&!a.has(g.id)){a.add(g.id);let h=g.testName||g.test?.name;h&&T.log(`${a.size}/${o.length} ${_e(h)}`)}}),m.every(c))}),p=ji({results:d,startTime:u,onFailed:m=>{let g=m.testName||m.test?.name;sc(m,g?_e(g):"Unknown test")},getDisplayLine:m=>{let g=m.testName||m.test?.name,h=` ${g?_e(g):"Unknown test"}`;return m.id&&(h+=` (${s}/runs/${m.id})`),h},entity:"test"});process.exit(p.failed>0?1:0)}import{randomUUID as AG}from"crypto";import wG from"fs";import{existsSync as Q1,mkdirSync as Z1,statSync as eG}from"fs";import{randomUUID as Qx}from"crypto";import ef from"fs";import{hostname as B1}from"os";import tf from"path";async function bd(r,e,t,n){if(n){let o=await e.getScreenshot(r,n);if(o){let i=`${n}-screenshot.jpeg`,a=tf.join(t,i);return ef.writeFileSync(a,o),i}}}async function H1(r,e,t,n){let o=n.runId??Qx(),i={uuid:o,historyId:o,testCaseId:n.test.id,fullName:n.test.name,name:_e(n.test.name),status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"skipped":"failed",start:n.lastAttemptStartedAt.getTime(),stop:n.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:t.suiteName},{name:"host",value:B1()},{name:"platform",value:"momentic"},{name:"attempts",value:n.attempts.toString()}],steps:[]};n.runId&&i.labels?.push({name:"runUrl",value:`https://app.momentic.ai/runs/${n.runId}`});for(let[l,c]of Object.entries(n.parameters))c!=null&&i.parameters.push({name:l,value:JSON.stringify(c)});n.results&&await z1(r,e,t.folder,i.steps,n.results);let a=`${o}-result.json`;ef.writeFileSync(tf.join(t.folder,a),JSON.stringify(i,void 0,2))}async function Ia(r,e,t,n){let o={name:Jn(n),start:n.startedAt.getTime(),stop:n.finishedAt.getTime(),status:n.status==="SUCCESS"?"passed":n.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};n.beforeUrl&&o.labels?.push({name:"URL before step",value:n.beforeUrl}),n.afterUrl&&o.labels?.push({name:"URL after step",value:n.afterUrl});let i=await bd(r,e,t,n.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let a=await bd(r,e,t,n.afterSnapshot);if(a&&o.attachments.push({name:"Screenshot after step",source:a,type:"image/jpeg"}),n.message&&(o.statusDetails={message:n.message}),n.data){let l=`${Qx()}-attachment.json`,c=tf.join(t,l);ef.writeFileSync(c,JSON.stringify(n.data,null,2)),o.attachments.push({name:"Step output data",source:l,type:"text/plain"})}return o}async function z1(r,e,t,n,o){for(let i of o)switch(i.type){case"PRESET_ACTION":{n.push(await Ia(r,e,t,i));break}case"CONDITIONAL":{let a=await Ia(r,e,t,i);a.steps=[],i.assertionResult&&a.steps.push(await Ia(r,e,t,i.assertionResult)),a.steps.push(...await Promise.all(i.results.map(l=>Ia(r,e,t,l)))),n.push(a);break}case"AI_ACTION":case"SECTION":case"MODULE":{let a=await Ia(r,e,t,i);if(a.steps=await Promise.all(i.results.map(l=>Ia(r,e,t,l))),i.type==="MODULE"&&i.inputs){a.parameters=[];for(let[l,c]of Object.entries(i.inputs))a.parameters.push({name:l,value:c})}n.push(a)}}}async function Zx(r,e,t,n){for(let o of n.runs)await H1(r,e,{folder:t,suiteName:n.suiteName},o)}import G1 from"junit-report-builder";import vd from"path";function V1(r,e){if(e.name(r.test.name).className(r.test.name).file(vd.relative(".",r.filePath)).property("id",r.test.id).property("dd_tags[id]",r.test.id),r.test.labels&&(e.property("labels",r.test.labels.join(",")),r.test.labels.forEach(t=>{e.property("dd_tags[label]",t)})),r.baseUrl&&(e.property("base_url",r.baseUrl),e.property("dd_tags[base_url]",r.baseUrl)),r.runId&&(e.property("run_url",`https://app.momentic.ai/runs/${r.runId}`),e.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${r.runId}`)),r.quarantined&&(e.property("quarantined","true"),e.property("dd_tags[quarantined]","true"),r.quarantinedReason&&(e.property("quarantined_reason",r.quarantinedReason),e.property("dd_tags[quarantined_reason]",r.quarantinedReason))),r.beforeResults?.some(t=>t.status==="FAILED")&&(e.property("setup_failed","true"),e.property("dd_tags[setup_failed]","true")),r.results?.some(t=>t.status==="FAILED")&&(e.property("main_failed","true"),e.property("dd_tags[main_failed]","true")),r.afterResults?.some(t=>t.status==="FAILED")&&(e.property("teardown_failed","true"),e.property("dd_tags[teardown_failed]","true")),r.status==="FAILED"){if(r.failureReason){let t=Cl[r.failureDetails?.classification?.reason||r.failureReason],n=r.failureDetails?.classification?.summary||Pi[r.failureReason];r.runId&&(n+=` Visit https://app.momentic.ai/runs/${r.runId} for more details.`),e.failure(n,t)}r.failureDetails?.errorStack&&e.stacktrace(r.failureDetails.errorStack)}else r.status==="CANCELLED"&&e.skipped();return e.time((r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime())/1e3).property("started_at",r.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",r.lastAttemptStartedAt.toISOString()).property("finished_at",r.finishedAt.toISOString()).property("dd_tags[finished_at]",r.finishedAt.toISOString()),e.property("attempts",r.attempts.toString()).property("dd_tags[attempts]",r.attempts.toString()),r.parameters.envName&&(e.property("environment",r.parameters.envName),e.property("dd_tags[environment]",r.parameters.envName)),r.parameters.urlOverride&&e.property("url_override",r.parameters.urlOverride),e}function j1(r,{suiteId:e,suiteName:t,startedAt:n,finishedAt:o,runs:i,testsToSkip:a,quarantinedTestsToSkip:l,quarantinedTestReasons:c}){let s=r.testSuite().name(t);e&&s.property("id",e),s.timestamp(n).property("startedAt",n.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-n.getTime())/1e3);for(let u of i){let d=s.testCase();V1(u,d)}for(let u of a){let d=s.testCase();d.name(u.name).className(u.name).file(vd.relative(".",u.relativeFilePath)).property("id",u.id),u.baseUrl&&d.property("baseUrl",u.baseUrl),u.labels&&(d.property("labels",u.labels.join(",")),u.labels.forEach(p=>{d.property("dd_tags[label]",p)})),d.skipped()}for(let u of l){let d=s.testCase();d.name(u.name).className(u.name).file(vd.relative(".",u.relativeFilePath)).property("id",u.id).property("quarantined","true");let p=c[u.id];p&&d.property("quarantinedReason",p),u.baseUrl&&d.property("baseUrl",u.baseUrl),u.labels&&(d.property("labels",u.labels.join(",")),u.labels.forEach(m=>{d.property("dd_tags[label]",m)})),d.skipped()}return s}function e_(r,e){let t=G1.newBuilder();j1(t,e),t.writeTo(vd.join(r,`${e.suiteName}.xml`))}import $1 from"fs";import W1 from"path";function t_(r){return{title:Jn(r),duration:r.finishedAt.getTime()-r.startedAt.getTime(),error:r.status==="FAILED"?{value:r.failureReason}:void 0,steps:r.results&&r.type!=="PRESET_ACTION"?r.results.map(t_):[]}}async function q1(r,e,t,n){if(n.results?.length){let o=await bd(r,e,t,n.results[n.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function K1(r,e,t,n){return{status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"interrupted":"failed",duration:n.finishedAt.getTime()-n.lastAttemptStartedAt.getTime(),error:n.status==="FAILED"&&n.failureReason?{value:n.failureDetails?.classification?.reason||n.failureReason,message:n.failureDetails?.classification?.summary||Pi[n.failureReason]}:void 0,retry:n.attempts-1,steps:n.results?.map(t_)||[],startTime:n.lastAttemptStartedAt.toISOString(),attachments:await q1(r,e,t,n)}}async function Y1(r,e,t,n){return{expectedStatus:"passed",status:n.status==="PASSED"?"expected":"unexpected",results:[await K1(r,e,t,n)]}}async function X1(r,e,t,n){return{tags:[],title:n.test.name,ok:n.status==="PASSED",tests:[await Y1(r,e,t,n)],id:n.runId,file:n.filePath}}function rf(r,e){return r.reduce((t,n)=>e(n)?t+1:t,0)}async function J1(r,e,t,n){return{suites:[{title:n.suiteName,file:n.projectConfigPath,specs:await Promise.all(n.runs.map(o=>X1(r,e,t,o)))}],errors:[],stats:{startTime:n.startedAt.toISOString(),duration:n.finishedAt.getTime()-n.startedAt.getTime(),expected:rf(n.runs,o=>o.status==="PASSED"),unexpected:rf(n.runs,o=>o.status!=="PASSED"),flaky:rf(n.runs,o=>!!o.isFlake),skipped:0}}}async function r_(r,e,t,n){let o=await J1(r,e,t,n);$1.writeFileSync(W1.join(t,`${n.suiteName}.json`),JSON.stringify(o,null,2))}async function n_(r,e,t,n,o){switch(Q1(o)?eG(o).isDirectory()||(T.error(`The specified reporter output directory '${o}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(T.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),Z1(o,{recursive:!0})),t){case"junit":e_(o,n);return;case"allure":case"allure-json":await Zx(r,e,o,n);return;case"playwright-json":await r_(r,e,o,n);return;default:throw new Error(`Unknown reporter format requested: '${t}'`)}}import CG from"wait-on";import{execSync as tG}from"child_process";import{platform as rG}from"os";function nf(){return o_()?(T.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),T.dimmed(`If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
|
|
4125
|
+
${[...o].map(i=>`${ot}- ${i}`).join(`
|
|
4126
|
+
`)}`)):T.warn("To fix these errors automatically, re-run this check with the --fix flag and then commit the resulting changes"),process.exit(1)):(T.success("No duplicates detected. All test, module, step and command IDs are unique."),process.exit(0))}async function Fx({project:r}){let e=W(r),t=Object.values(e.tests),n=await jc(e,Z),o={},i={},a=new Set,l=new Set;for(let s of t)o[s.name]?i[s.name]?i[s.name].push(s.fullFilePath):i[s.name]=[o[s.name],s.fullFilePath]:o[s.name]=s.fullFilePath;for(let s of n)l.has(s.name)&&a.add(s.name),l.add(s.name);if(Object.entries(i).length>0||a.size>0){for(let[s,u]of Object.entries(i))for(let d of u)T.error(`Test Name ${s} is duplicated in ${d}`);for(let s of a)T.error(`Module name ${s} is duplicated in your project`);process.exit(1)}T.success("No duplicates detected. All test and module names are unique."),process.exit(0)}import{cloneDeep as Q1}from"lodash-es";async function Ux({client:r,skipPrompts:e,project:t}){let n=await r.getAllEnvironments(),o=Q1(t.config);o.environments||(o.environments=[]);for(let i of n){let a=o.environments?.find(l=>l.name===i.name);if(a)!e&&!await Nt(`Environment ${i.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),a.baseUrl=i.variables[ht],delete i.variables[ht],a.envVariables=i.variables;else{let l=i.variables[ht];delete i.variables[ht],o.environments.push({name:i.name,baseUrl:l,envVariables:i.variables})}}aa(o,t.configFilePath),T.success(`Pulled ${n.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as Bx}from"crypto";import zx from"fs";async function Qh({testsToFetch:r,client:e,all:t,yes:n}){let{tests:o,modules:i}=await e.getTestYAMLExport({paths:r,all:t}),a=0;for(let[c,s]of Object.entries(o)){let u=Hx(c,de.TEST);!n&&!await Sm(u)||(a+=1,zx.writeFileSync(u,s,"utf-8"),Z.info({checksum:Bx("md5").update(s).digest("hex")},`Wrote '${u}'`))}let l=0;for(let[c,s]of Object.entries(i)){let u=Hx(c,de.MODULE);!n&&!await Sm(u)||(l+=1,zx.writeFileSync(u,s,"utf-8"),Z.info({checksum:Bx("md5").update(s).digest("hex")},`Wrote '${u}'`))}a===0?T.success("Pulled 0 tests."):T.success(`Pulled ${a} test${a>1?"s":""}${l?` and ${l} module${l>1?"s":""}`:""}!`)}function Hx(r,e){switch(e){case de.TEST:return`${xe(r)}.test.yaml`;case de.MODULE:return`${xe(r)}.module.yaml`;default:throw new Error(`Unknown entity type ${e}`)}}async function Gx(r){let{project:e,client:t,skipPrompts:n}=r;T.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),T.info("Importing environments from Momentic Cloud."),T.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await Nt("Are you sure you want to proceed?",!0)||(T.info("Aborting..."),process.exit(1)),await Ux({client:t,project:e,skipPrompts:n}),T.success(`Successfully imported environments from Momentic Cloud. We recommend pulling secrets out of ${e.configFilePath} into .env files or dynamically set environment variables for security.`),T.info("Importing tests and modules from Momentic Cloud."),await Qh({testsToFetch:[],client:t,all:!0,yes:n}),T.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}async function Vx(r){let{client:e,skipPrompts:t,paths:n}=r;await Qh({testsToFetch:n,client:e,all:void 0,yes:t}),T.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}import{Argument as Ei,InvalidArgumentError as ml,Option as Me}from"@commander-js/extra-typings";import{validateHeaderValue as Z1}from"http";import{z as jx}from"zod";var Ad=58888;function To(r){let e=parseInt(r,10);if(isNaN(e))throw new ml("Not a number.");return e}function wd(r){if(r===void 0)return;let e={};for(let t of r){let n=t.indexOf("=");if(n===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,n),i=t.slice(n+1);Z1(o,i),e[o]=i}return e}var zr=new Me("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new ml("API key is required.");return r}).makeOptionMandatory(),Hr=new Me("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return jx.string().url().parse(r),r}catch{throw new ml("Not a valid URL.")}}),bo=new Me("-y, --yes","Skip all confirmation prompts.").env("CI"),Zh=new Me("-w, --wait","Wait for tests to finish running before exiting."),ef=new Me("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${18e5/1e3} seconds.`).default(18e5/1e3).implies({wait:!0}).argParser(To),Cd=new Me("--custom-headers <customHeaders...>","Specify custom headers in the form HEADER=VALUE to be sent with each request during the test. Multiple entries can be provided."),$x=new Me("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(jl)),Wx=new Me("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml.").default("reports"),tf=new Me("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),qx=new Me("--upload-results","Upload test results to Momentic Cloud.").default(!1),rf=new Me("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),nf=new Me("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),of=new Me("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio.").argParser(To),af=new Me("--input-csv <inputCsv>","Path to a CSV file on disk where each row represents a set of inputs that will be made available to all tests that are ran. The first line of the CSV must be the input names."),xd=new Me("--env <env>","Name of the environment to use when running tests."),_d=new Me("--url-override <urlOverride>","Fully qualified URL (e.g. https://www.google.com) to start all tests from. Overrides any default starting URL set from the test or environment.").argParser(r=>{try{return jx.string().url().parse(r),r}catch{throw new ml("Not a valid URL.")}}),Kx=new Me("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(r=>{let e=To(r);if(e<1)throw new ml("Shard index must be greater than 0.");return e}),Yx=new Me("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(To),ar=new Me("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),Pa=new Me("-f, --filter <filter>","Run tests within the project that has a name equal to the filter provided. This option cannot be used together with file path or directory arguments, but substring matches are allowed."),Xx=new Me("--fix","Attempt to fix any issues found."),sf=new Me("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),lf=new Me("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes."),Jx=new Me("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),Qx=new Me("--only-quarantined","Run only tests that are currently quarantined. When running with this option, any test failures will cause the pipeline to fail, even though the tests are quarantined.").implies({skipQuarantined:!1,ignoreQuarantine:!1}),Zx=new Me("--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}),e_=new Ei("<tests...>","One or more test paths to queue on Momentic Cloud."),t_=new Ei("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),cf=new Ei("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),r_=new Ei("<suites...>","One or more suite paths that exist on Momentic Cloud."),n_=new Ei("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),o_=new Ei("<results>","Path to the results archive.").argRequired(),uf=new Me("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),df=new Ei("<test>","Name of the test to quarantine.").argOptional();async function i_(r){let e=W(r),t=Object.values(e.tests);for(let n of t)try{let o=Qo(n.fullFilePath,T,e),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){T.debug(`Test ${n.name} (${n.relativePath}) has no steps, skipping...`);continue}let a=Ot.parse(o),l=await Wo(a,i,T);T.dimmed(`Updating ${n.relativePath}`),Dt({relativeTestPath:n.relativePath,steps:{beforeSteps:o.beforeSteps,steps:l.steps,afterSteps:o.afterSteps},schemaVersion:se,project:r,forceSaveOnNoDiffs:!0})}catch(o){T.error({err:o},`Failed to read or migrate test ${n.name} (${n.relativePath}), continuing...`)}for(let n of Object.values(e.modules)){T.dimmed(`Updating ${n.relativePath}`);try{let o=An(n.fullFilePath,T),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){T.debug(`Module ${n.name} (${n.relativePath}) has no steps, skipping...`);continue}let a=await Wo({id:o.moduleId,schemaVersion:o.schemaVersion},i,T);jt({content:{...o,steps:a.steps},schemaVersion:se,momenticFiles:e,project:r,forceSaveOnNoDiffs:!0})}catch(o){T.error({err:o},`Failed to read or migrate module ${n.name} (${n.relativePath}), continuing...`)}}}import{spawnSync as tG}from"child_process";function rG(){try{let e=tG("git remote show origin",{encoding:"utf8",maxBuffer:5242880}).stdout.match(/HEAD branch: (.*)$/m);if(e&&e[1])return e[1].trim();T.warn("Could not determine your Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field.");return}catch(r){let e=r instanceof Error?r.message:String(r);T.warn(`Could not determine Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field. Error:
|
|
4127
|
+
${e}`)}}async function a_({project:r,orgId:e,apiClient:t}){T.info("Pulling browser and AI configuration options from Cloud");let n=await eu.init(e);r.config.browser={autoExpandIframes:n.isBooleanFlagEnabled("auto_expand_iframes"),disableSecondaryCacheResolution:n.isBooleanFlagEnabled("disable_secondary_cache_resolution"),globalLocatorRedirect:n.isBooleanFlagEnabled("global_locator_redirect"),visualActions:n.isBooleanFlagEnabled("visual_actions"),showZeroOpacityElements:n.isBooleanFlagEnabled("show_zero_opacity_elements"),...r.config.browser},r.config.advanced={fakerConstantSeed:n.isBooleanFlagEnabled("faker_constant_seed"),...r.config.advanced},r.config.ai={aiPageFiltering:n.isBooleanFlagEnabled("rag_v2"),agentConfig:await t.getAgentConfig(),...r.config.ai},T.info(`Updated ${r.configFilePath} to include V2 browser and AI configuration options`),T.info("Determining main Git branch"),r.config.gitMainBranch=rG(),aa(r.config,r.configFilePath),T.success("Migration complete!")}import{input as nG,search as oG}from"@inquirer/prompts";import iG from"fuse.js";async function Id({prompt:r,inputtedTest:e,testOptions:t}){if(e){let a=t.find(l=>l.name===e);if(!a)T.error(`${e} is not a valid test option.`);else return{name:a.name,id:a.value}}let n=new iG(t,{keys:[{name:"name",weight:1}],threshold:.4,includeScore:!0,findAllMatches:!0,ignoreLocation:!0,useExtendedSearch:!0,shouldSort:!0,includeMatches:!0,distance:100,ignoreFieldNorm:!1}),o=await oG({message:r,source:async a=>!a||a.length===0?t:n.search({name:a}).map(c=>c.item)}),i=t.find(a=>a.value===o);return{name:i.name,id:i.value}}async function Md({prompt:r,inputtedReason:e}){return e||nG({message:r})}async function s_({test:r,reason:e,apiClient:t,project:n,logger:o,identity:i}){let a=W(n).tests,l=Object.values(a).map(u=>({value:u.id,name:u.name})),c=await Id({prompt:"Select a test to quarantine.",inputtedTest:r,testOptions:l}),s=await Md({prompt:"Enter a reason for quarantining the test.",inputtedReason:e});await t.quarantineTest(c,s,i),T.success(`Test ${c.name} has been successfully quarantined. Navigate to ${t.getAppUrl()}/quarantine to view all quarantined tests. Remove this test from quarantine by running 'npx momentic quarantine remove ${c.name}'.`)}async function l_({test:r,reason:e,apiClient:t,project:n,logger:o,identity:i}){let a=W(n).tests,l=Object.values(a).map(m=>({value:m.id,name:m.name})),c=(await t.getQuarantinedTests()).quarantined,s=new Set(c.map(m=>m.testId)),u=l.filter(m=>s.has(m.value)),d=await Id({prompt:"Select a test to unquarantine.",inputtedTest:r,testOptions:u}),p=await Md({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await t.unquarantineTest(d,p,i),T.success(`Test ${d.name} has been successfully removed from quarantine.`)}function c_(r){return r?xe(r):"Unknown suite"}async function u_({client:r,orgId:e,suitePaths:t,wait:n,waitTimeout:o,...i}){let{suiteRunIds:a,runGroupIds:l}=await r.queueSuiteRuns({paths:t,...i});Z.info({orgId:e,suiteRunIds:a,runGroupIds:l,suitePaths:t},"Queued suites remotely"),T.dimmed(`Queued ${t.length} suites.`),n||process.exit(0);let c=Date.now();T.dimmed(`Waiting for ${t.length} suites to finish. You can view results upon completion at:`);for(let f of l)T.dimmed(`${ot}- ${r.getAppUrl()}/run-groups/${f}`);let s=new Set,u=[],d=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(E=>E.status==="FAILED"&&(E.failureReason||E.finishedAt&&Date.now()-E.finishedAt.getTime()>30*1e3)||E.status==="PASSED"||E.status==="CANCELLED"),p=await fc({name:"suites",getResults:async()=>{let f=l.filter(y=>!u.some(A=>A.id===y)),S=await r.bulkGetRunGroupStatus(f),E=[];for(let y of S)d(y)?u.push(y):E.push(y);return[...u,...E]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(S=>{S.status==="RUNNING"&&(s.has(S.id)||(s.add(S.id),T.log(`${s.size}/${l.length} ${c_(S.suite?.name)}`)))}),f.every(d))}),m=r.getAppUrl(),h=Wi({results:p,startTime:c,onFailed:f=>{let S=c_(f.suite?.name),E=f.runs.filter(A=>A.status==="FAILED").length,y=f.runs.length;T.error(`${S} (${E}/${y} tests failed):`);for(let A of f.runs)if(A.status==="FAILED"){let R=A.testName||A.test?.name;T.error(` ${R?xe(R):"Unknown test"} (${m}/runs/${A.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?xe(f.suite.name):"Unknown suite name"} (${m}/run-groups/${f.id})`});process.exit(h.failed>0?1:0)}async function d_({tests:r,client:e,orgId:t,...n}){!n.yes&&!await Nt(`This command will queue ${r.length} tests to run remotely on Momentic's infrastructure. Results will be available on ${e.getAppUrl()}. Continue?`)&&process.exit(1);let{queuedTests:o,runIds:i}=await e.queueTests({testPaths:r,...n});if(Z.info({queuedTests:o,runIds:i,orgId:t},"Queued tests remotely"),T.dimmed(`Queued ${o.length} tests. Processing time may depend on a variety of factors, including how many tests have already been queued from your organization.`),n.wait||process.exit(0),!i.length)return;T.dimmed(`Waiting for ${o.length} tests to complete.`);let a=new Set,l=[],c=m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED",s=e.getAppUrl(),u=Date.now(),d=await fc({name:"runs",getResults:async()=>{let m=i.filter(f=>!l.some(S=>S.id===f)),g=await e.bulkGetRunStatus(m),h=[];for(let f of g)c(f)?l.push(f):h.push(f);return[...l,...h]},timeoutMs:n.waitTimeout?n.waitTimeout*1e3:void 0,checkDone:m=>(m.forEach(g=>{if(g.status==="RUNNING"&&!a.has(g.id)){a.add(g.id);let h=g.testName||g.test?.name;h&&T.log(`${a.size}/${o.length} ${xe(h)}`)}}),m.every(c))}),p=Wi({results:d,startTime:u,onFailed:m=>{let g=m.testName||m.test?.name;Sc(m,g?xe(g):"Unknown test")},getDisplayLine:m=>{let g=m.testName||m.test?.name,h=` ${g?xe(g):"Unknown test"}`;return m.id&&(h+=` (${s}/runs/${m.id})`),h},entity:"test"});process.exit(p.failed>0?1:0)}import{randomUUID as WG}from"crypto";import qG from"fs";import{existsSync as EG,mkdirSync as TG,statSync as bG}from"fs";import{randomUUID as p_}from"crypto";import pf from"fs";import{hostname as aG}from"os";import mf from"path";async function Pd(r,e,t,n){if(n){let o=await e.getScreenshot(r,n);if(o){let i=`${n}-screenshot.jpeg`,a=mf.join(t,i);return pf.writeFileSync(a,o),i}}}async function sG(r,e,t,n){let o=n.runId??p_(),i={uuid:o,historyId:o,testCaseId:n.test.id,fullName:n.test.name,name:xe(n.test.name),status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"skipped":"failed",start:n.lastAttemptStartedAt.getTime(),stop:n.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:t.suiteName},{name:"host",value:aG()},{name:"platform",value:"momentic"},{name:"attempts",value:n.attempts.toString()}],steps:[]};n.runId&&i.labels?.push({name:"runUrl",value:`https://app.momentic.ai/runs/${n.runId}`});for(let[l,c]of Object.entries(n.parameters))c!=null&&i.parameters.push({name:l,value:JSON.stringify(c)});n.results&&await lG(r,e,t.folder,i.steps,n.results);let a=`${o}-result.json`;pf.writeFileSync(mf.join(t.folder,a),JSON.stringify(i,void 0,2))}async function Oa(r,e,t,n){let o={name:eo(n),start:n.startedAt.getTime(),stop:n.finishedAt.getTime(),status:n.status==="SUCCESS"?"passed":n.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};n.beforeUrl&&o.labels?.push({name:"URL before step",value:n.beforeUrl}),n.afterUrl&&o.labels?.push({name:"URL after step",value:n.afterUrl});let i=await Pd(r,e,t,n.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let a=await Pd(r,e,t,n.afterSnapshot);if(a&&o.attachments.push({name:"Screenshot after step",source:a,type:"image/jpeg"}),n.message&&(o.statusDetails={message:n.message}),n.data){let l=`${p_()}-attachment.json`,c=mf.join(t,l);pf.writeFileSync(c,JSON.stringify(n.data,null,2)),o.attachments.push({name:"Step output data",source:l,type:"text/plain"})}return o}async function lG(r,e,t,n,o){for(let i of o)switch(i.type){case"PRESET_ACTION":{n.push(await Oa(r,e,t,i));break}case"CONDITIONAL":{let a=await Oa(r,e,t,i);a.steps=[],i.assertionResult&&a.steps.push(await Oa(r,e,t,i.assertionResult)),a.steps.push(...await Promise.all(i.results.map(l=>Oa(r,e,t,l)))),n.push(a);break}case"AI_ACTION":case"SECTION":case"MODULE":{let a=await Oa(r,e,t,i);if(a.steps=await Promise.all(i.results.map(l=>Oa(r,e,t,l))),i.type==="MODULE"&&i.inputs){a.parameters=[];for(let[l,c]of Object.entries(i.inputs))a.parameters.push({name:l,value:c})}n.push(a)}}}async function m_(r,e,t,n){for(let o of n.runs)await sG(r,e,{folder:t,suiteName:n.suiteName},o)}import cG from"junit-report-builder";import Od from"path";function uG(r,e){if(e.name(r.test.name).className(r.test.name).file(Od.relative(".",r.filePath)).property("id",r.test.id).property("dd_tags[id]",r.test.id),r.test.labels&&(e.property("labels",r.test.labels.join(",")),r.test.labels.forEach(t=>{e.property("dd_tags[label]",t)})),r.baseUrl&&(e.property("base_url",r.baseUrl),e.property("dd_tags[base_url]",r.baseUrl)),r.runId&&(e.property("run_url",`https://app.momentic.ai/runs/${r.runId}`),e.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${r.runId}`)),r.quarantined&&(e.property("quarantined","true"),e.property("dd_tags[quarantined]","true"),r.quarantinedReason&&(e.property("quarantined_reason",r.quarantinedReason),e.property("dd_tags[quarantined_reason]",r.quarantinedReason))),r.beforeResults?.some(t=>t.status==="FAILED")&&(e.property("setup_failed","true"),e.property("dd_tags[setup_failed]","true")),r.results?.some(t=>t.status==="FAILED")&&(e.property("main_failed","true"),e.property("dd_tags[main_failed]","true")),r.afterResults?.some(t=>t.status==="FAILED")&&(e.property("teardown_failed","true"),e.property("dd_tags[teardown_failed]","true")),r.status==="FAILED"){if(r.failureReason){let t=Ll[r.failureDetails?.classification?.reason||r.failureReason],n=r.failureDetails?.classification?.summary||Oi[r.failureReason];r.runId&&(n+=` Visit https://app.momentic.ai/runs/${r.runId} for more details.`),e.failure(n,t)}r.failureDetails?.errorStack&&e.stacktrace(r.failureDetails.errorStack)}else r.status==="CANCELLED"&&e.skipped();return e.time((r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime())/1e3).property("started_at",r.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",r.lastAttemptStartedAt.toISOString()).property("finished_at",r.finishedAt.toISOString()).property("dd_tags[finished_at]",r.finishedAt.toISOString()),e.property("attempts",r.attempts.toString()).property("dd_tags[attempts]",r.attempts.toString()),r.parameters.envName&&(e.property("environment",r.parameters.envName),e.property("dd_tags[environment]",r.parameters.envName)),r.parameters.urlOverride&&e.property("url_override",r.parameters.urlOverride),e}function dG(r,{suiteId:e,suiteName:t,startedAt:n,finishedAt:o,runs:i,testsToSkip:a,quarantinedTestsToSkip:l,quarantinedTestReasons:c}){let s=r.testSuite().name(t);e&&s.property("id",e),s.timestamp(n).property("startedAt",n.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-n.getTime())/1e3);for(let u of i){let d=s.testCase();uG(u,d)}for(let u of a){let d=s.testCase();d.name(u.name).className(u.name).file(Od.relative(".",u.relativeFilePath)).property("id",u.id),u.baseUrl&&d.property("baseUrl",u.baseUrl),u.labels&&(d.property("labels",u.labels.join(",")),u.labels.forEach(p=>{d.property("dd_tags[label]",p)})),d.skipped()}for(let u of l){let d=s.testCase();d.name(u.name).className(u.name).file(Od.relative(".",u.relativeFilePath)).property("id",u.id).property("quarantined","true");let p=c[u.id];p&&d.property("quarantinedReason",p),u.baseUrl&&d.property("baseUrl",u.baseUrl),u.labels&&(d.property("labels",u.labels.join(",")),u.labels.forEach(m=>{d.property("dd_tags[label]",m)})),d.skipped()}return s}function g_(r,e){let t=cG.newBuilder();dG(t,e),t.writeTo(Od.join(r,`${e.suiteName}.xml`))}import pG from"fs";import mG from"path";function h_(r){return{title:eo(r),duration:r.finishedAt.getTime()-r.startedAt.getTime(),error:r.status==="FAILED"?{value:r.failureReason}:void 0,steps:r.results&&r.type!=="PRESET_ACTION"?r.results.map(h_):[]}}async function gG(r,e,t,n){if(n.results?.length){let o=await Pd(r,e,t,n.results[n.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function hG(r,e,t,n){return{status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"interrupted":"failed",duration:n.finishedAt.getTime()-n.lastAttemptStartedAt.getTime(),error:n.status==="FAILED"&&n.failureReason?{value:n.failureDetails?.classification?.reason||n.failureReason,message:n.failureDetails?.classification?.summary||Oi[n.failureReason]}:void 0,retry:n.attempts-1,steps:n.results?.map(h_)||[],startTime:n.lastAttemptStartedAt.toISOString(),attachments:await gG(r,e,t,n)}}async function fG(r,e,t,n){return{expectedStatus:"passed",status:n.status==="PASSED"?"expected":"unexpected",results:[await hG(r,e,t,n)]}}async function SG(r,e,t,n){return{tags:[],title:n.test.name,ok:n.status==="PASSED",tests:[await fG(r,e,t,n)],id:n.runId,file:n.filePath}}function gf(r,e){return r.reduce((t,n)=>e(n)?t+1:t,0)}async function yG(r,e,t,n){return{suites:[{title:n.suiteName,file:n.projectConfigPath,specs:await Promise.all(n.runs.map(o=>SG(r,e,t,o)))}],errors:[],stats:{startTime:n.startedAt.toISOString(),duration:n.finishedAt.getTime()-n.startedAt.getTime(),expected:gf(n.runs,o=>o.status==="PASSED"),unexpected:gf(n.runs,o=>o.status!=="PASSED"),flaky:gf(n.runs,o=>!!o.isFlake),skipped:0}}}async function f_(r,e,t,n){let o=await yG(r,e,t,n);pG.writeFileSync(mG.join(t,`${n.suiteName}.json`),JSON.stringify(o,null,2))}async function S_(r,e,t,n,o){switch(EG(o)?bG(o).isDirectory()||(T.error(`The specified reporter output directory '${o}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(T.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),TG(o,{recursive:!0})),t){case"junit":g_(o,n);return;case"allure":case"allure-json":await m_(r,e,o,n);return;case"playwright-json":await f_(r,e,o,n);return;default:throw new Error(`Unknown reporter format requested: '${t}'`)}}import KG from"wait-on";import{execSync as vG}from"child_process";import{platform as RG}from"os";function hf(){return y_()?(T.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),T.dimmed(`If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
|
|
4178
4128
|
`),2):(T.dimmed("Setting device pixel ratio to 1."),T.dimmed(`If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
|
|
4179
|
-
l.`),1)}function
|
|
4180
|
-
${r.map(p=>`${
|
|
4129
|
+
l.`),1)}function y_(){return RG()==="darwin"&&vG("system_profiler SPDisplaysDataType").toString().includes("Retina")}function ff(r){y_()&&r===1&&(T.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),T.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import AG from"@actions/exec";import wG from"@actions/io";import CG from"quote";import xG from"string-argv";async function E_(r,e=!0){let t=xG(r),n=await wG.which(t[0],!0),o=t.slice(1),i=AG.exec(CG(n),o,{delay:100});if(e)return i}import _G from"csv-parser";import{createReadStream as IG}from"fs";function Sf(r){return new Promise((e,t)=>{let n=[];IG(r).pipe(_G()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>t(o))})}import Ld from"semver";import{z as Nd}from"zod";var Pn="2.17.11",MG="https://registry.npmjs.org/momentic",PG=Nd.object({versions:Nd.record(Nd.string(),Nd.unknown()).optional()});async function T_(r){try{await OG(r)}catch(e){T.warn({err:e},"Failed to check CLI version against NPM servers")}}async function OG(r){if(!Pn){r.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let n=0;n<2;n++)try{let o=await H(fetch(MG),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=PG.parse(i).versions;break}catch(o){r.warn({err:o},"Failed to fetch npm registry data")}if(!e){r.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let n of Object.keys(e))Ld.valid(n)&&(!t||Ld.gt(n,t))&&Ld.gt(n,Pn)&&Ld.lt(n,"2.0.0")&&!n.includes("alpha")&&(t=n);t&&(T.warn(`Update available: v${Pn} -> v${t}`),T.warn("This version may be missing critical fixes, features, and security updates."),T.warn(`Run "npx momentic@${t} -V" to update`))}import yf from"fs";import{compact as LG,partition as Dd}from"lodash-es";import Ef from"path";import{cwd as NG}from"process";import DG from"semver";async function kd({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,labels:a,logger:l}){let c=new Set;if(r&&r.length>0){let u=r.some(p=>yf.existsSync(p)),d=NG();u?(d!==t.rootDir&&l.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.`),l.info(`Reading tests from the following local file paths:
|
|
4130
|
+
${r.map(p=>`${ot}- ${p}`).join(`
|
|
4181
4131
|
`)}
|
|
4182
|
-
`),r.forEach(p=>{if(!
|
|
4183
|
-
${r.map(p=>`${
|
|
4184
|
-
`)}`),Object.values(e.tests).forEach(p=>{r.some(m=>p.relativePath.includes(m))&&c.add(p.fullFilePath)}))}else{!n&&!await Nt("No test paths or substrings were provided. Do you want to run all tests?")&&(l.error("Cancelled by user."),process.exit(1));let u=Object.values(e.tests);l.info(`Reading all ${u.length} tests in the project from local disk.`),u.forEach(d=>{c.add(d.fullFilePath)})}for(let u of c){let d=lf.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)}let s=Array.from(c).map(async u=>{try{let d=await at(u,Q,e);if(gG.gt(d.schemaVersion,ue)&&l.warn(`Test ${u} has schema version ${d.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),a&&a.length>0){let p=d.labels||[];if(!a.some(g=>p.includes(g)))return null}return{...d,fullFilePath:u,relativeFilePath:lf.relative(t.rootDir,u)}}catch(d){l.error(`Failed to read and resolve test at '${u}': ${d}`),process.exit(1)}});return Promise.all(s).then(pG)}function s_({testDefinitions:r,quarantinedTestReasons:e,onlyQuarantined:t=!1,skipQuarantined:n=!1}){if(t){let[u,d]=wd(r,g=>g.id in e),[p,m]=wd(u,g=>g.disabled||n);return{testsToSkip:p,quarantinedTestsToSkip:[],testsToRun:m,quarantinedTestsToRun:[]}}let[o,i]=wd(r,u=>u.disabled),[a,l]=wd(i,u=>u.id in e);return{testsToSkip:o,testsToRun:l,quarantinedTestsToRun:n?[]:a,quarantinedTestsToSkip:n?a:[]}}function l_({testsToRun:r,quarantinedTestsToRun:e,quarantinedTestReasons:t,testInputMatrix:n}){let o=[],i=(a,l,c)=>{n?n.forEach((s,u)=>{o.push({inputs:s,inputIndex:u,testDefinition:a,quarantined:l,quarantinedReason:c})}):o.push({inputs:void 0,testDefinition:a,quarantined:l,quarantinedReason:c})};return r.forEach(a=>i(a,!1)),e.forEach(a=>i(a,!0,t[a.id])),o}import{partition as hG}from"lodash-es";function xd(r){return r.length===1?"test":"tests"}function c_(r){return r===1?"1 worker":`${r} workers`}function u_(r){r.length!==0&&(T.info(`Skipping ${r.length} disabled ${xd(r)}:`),r.forEach(e=>{T.info(`${it}- ${[e.relativeFilePath]}`)}),T.log(""))}function d_(r,e){r.length!==0&&(T.info(`Skipping ${r.length} quarantined ${xd(r)}:`),r.forEach(t=>{T.info(`${it}- ${[t.relativeFilePath]}: ${e[t.id]}`)}),T.log(""))}function fG(r,e){r.length!==0&&(T.info(`Running ${r.length} quarantined ${xd(r)} with ${c_(e)}:`),r.forEach(t=>{T.info(`${it}- ${[t.testDefinition.relativeFilePath]}${typeof t.inputIndex=="number"?` with input set ${t.inputIndex}`:""}`)}),T.log(""))}function SG(r,e,t){e.length===0&&r.length>0||(T.info(`Running ${e.length} ${xd(e)} with ${c_(t)}:`),e.forEach(n=>{T.info(`${it}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),T.log(""))}function p_({logger:r,localTestsToRunWithInputs:e,parallel:t,shardCount:n,shardIndex:o}){r.info({tests:e.length,shardCount:n,shardIndex:o,parallel:t},"Running local tests");let[i,a]=hG(e,l=>l.quarantined);fG(i,t),SG(i,a,t)}import{cloneDeep as Pa}from"lodash-es";async function m_({orgId:r,codeEvalTools:e,logger:t,outputDefinitions:n,testContext:o,flagStore:i}){let a={};for(let l of n){let{name:c,value:s}=l;a[c]=await er({orgId:r,s,localTools:e,logger:t,context:o})}return a}async function g_({baseUrl:r,envName:e,testName:t,devicePixelRatio:n,apiClient:o,test:i,storageClient:a,codeEvalTools:l,generator:c,orgId:s,variables:u,logger:d,customHeaders:p,testInputs:m,localBrowserConfig:g,aiSettings:h,visualDiffScreenshotStorage:f,flagStore:E}){let S=await ku({settings:g,customHeaders:p,envVariables:u,envName:e,testName:t,baseUrl:r,logger:d,localTools:l,orgId:s}),y={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:Q},A=E.isBooleanFlagEnabled("icon_knowledge_base")?await a.fetchIconKnowledgeBase(d):null,R=S.browserType??"Chromium";if(!kE(R)){let M=`Browser ${R} is required by the test named ${i.name} but does not appear to be installed on this machine. Please install it using 'momentic install-browsers' before running tests. Attempting to continue...`;T.warn(M),Q.warn(M)}let w=await Rr.init({baseUrl:r,logger:d,userBrowserSettings:S,storage:a,flagStore:E,enricher:new Xn(y,c),contextArgs:{viewport:i.advanced.viewport??Pt,locale:i.advanced.locale??Hn,geolocation:i.advanced.geolocation??Gn,timezoneId:i.advanced.timezone??zn,colorScheme:i.advanced.colorScheme,deviceScaleFactor:n},iconKnowledgeBase:A}),x=new uo({browser:w,generator:c,logger:d,orgId:s,options:{scratchPadId:void 0,slowMoMs:S.slowMoMs,autoFollowNewTabs:S.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering??E.isBooleanFlagEnabled("rag_v2")},storage:a,flagStore:E,localCodeEvalTools:l,visualDiffScreenshotStorage:f}),_=new qt({baseUrl:r,currentUrl:x.browser.url(),variablesFromEnvironment:u,envName:e,testName:t});return i.parameters&&await Promise.all(i.parameters.map(async M=>{let{name:K,defaultValue:$,required:k}=M,Y=m?.[K];k&&Y===void 0&&(T.error(`Required parameter '${K}' is required by test '${i.name}' but not provided`),process.exit(1));let I=await er({orgId:s,s:Y??$,localTools:l,logger:d,context:qt.dummyContext(_.getEnvName())});_.setMomenticSystemVariable(K,I)})),{controller:x,context:_}}async function h_({testAdvancedSettings:r,orgSettings:e,logger:t}){if(r.failureRecovery===!1||r.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!Da){let n="This test is ineligible for failure recovery since this does not appear to be a CI environment";return t.warn(n),T.warn(n),!1}return!0}async function f_({attemptInputs:r,attemptFixtures:e,attemptMetadata:t}){let{orgId:n,runId:o}=t,{controller:i,context:a,codeEvalTools:l,storageClient:c,logger:s,usageTracker:u,tracer:d}=e,{test:p,orgSettings:m}=r;s.info(`Running test '${p.name}' locally (run link: https://app.momentic.ai/runs/${o})`);let g={controller:i,storage:c,usageTracker:u,context:a,logger:s,codeEvalTools:l},h={orgId:n,runId:o,testMetadata:p,steps:p.steps,beforeSteps:p.beforeSteps,afterSteps:p.afterSteps,orgSettings:m},f={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await h_({testAdvancedSettings:p.advanced,orgSettings:m.ai,logger:s})};return await Du({fixtures:g,inputs:h,options:f,callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()}}},testParams:{tracer:d}})}async function S_(r){let{testDefinition:e,logger:t}=r,n=new Date;try{return await yG(r)}catch(o){let i="Fatal error running test";return T.error(`${i}: ${o.message}`),t.error({err:o},i),{results:[],parameters:r,failureReason:"UnknownError",failureDetails:{errorMessage:o.message,errorStack:o.stack},status:"FAILED",attempts:0,test:e,filePath:e.relativeFilePath,startedAt:n,lastAttemptStartedAt:n,finishedAt:new Date,outputs:{}}}}async function yG(r){let{testDefinition:e,project:t,apiClient:n,orgId:o,urlOverride:i,runSigIntHandlers:a,runGroupTracer:l,logger:c,gitMetadata:s,alwaysSaveCache:u,noCache:d,runId:p,testInputs:m,quarantined:g,quarantinedReason:h,usageTracker:f}=r,E=new $i(n,o),S=Qi({orgId:o,client:n,gitMetadata:s,alwaysSaveCache:u,noCache:d}),y=Pa(e.steps),A=Pa(e.beforeSteps)??void 0,R=Pa(e.afterSteps)??void 0;try{await S.resolveStepCacheEntries({testId:e.id,stepLists:{steps:y,beforeSteps:A,afterSteps:R},schemaVersion:e.schemaVersion,logger:c})}catch(k){throw c.error({err:k},"Failed to resolve step cache entries"),new Error(`Failed to resolve step cache entries. Please ensure you are running using a supported version of Momentic. If you believe this is a Momentic issue, please contact Support with the following error: ${k}`)}let w=r.envName??TG(e),x,_={};if(w){try{x=Rs(w,t,c)}catch(k){let Y=`Failed to resolve environment ${w} for test ${e.name}: ${k}`;throw new Error(Y)}_=x.variables}let M=e.baseUrl;if(i)M=i;else if(!M){let k=_[ht];typeof k=="string"&&(M=k)}if(!M){let k=`Cannot run test with no base URL and no ${ht} variable defined in its environment`;throw new Error(k)}let K=await l.startRun({logger:c,runId:p,originalSteps:{beforeSteps:e.beforeSteps,steps:e.steps,afterSteps:e.afterSteps},testId:e.id,testName:e.name,testDescription:e.description??void 0,testLabels:e.labels,baseUrl:M,environmentName:w,schemaVersion:e.schemaVersion,resolvedInputs:m,quarantined:g,quarantinedReason:h}),$=c.child(K.loggerBindings||{});Object.entries(K.envVarBindings||{}).forEach(([k,Y])=>{_[k]=Y});try{let k=await EG({...r,variables:_,envName:w,resolvedEnv:x,baseUrl:M,storageClient:E,tracer:K,logger:$,cacheStorage:S,stepsWithCaches:y,beforeStepsWithCaches:A,afterStepsWithCaches:R,usageTracker:f});return await K.finish({logger:c,status:k.status,finishedAt:k.finishedAt,failureDetails:k.failureDetails,failureReason:k.failureReason,isFlake:k.isFlake,failureRecoveryDetails:k.failureRecoveryDetails}),{runId:K.runId,...k}}finally{a?.pop()}}async function EG(r){let{testDefinition:e,stepsWithCaches:t,beforeStepsWithCaches:n,afterStepsWithCaches:o,project:i,regenerateGoldenFiles:a,apiClient:l,generator:c,baseUrl:s,storageClient:u,orgId:d,envName:p,urlOverride:m,customHeaders:g,testInputs:h,variables:f,resolvedEnv:E,retriesOverride:S,devicePixelRatio:y,logUpdate:A,tracer:R,logger:w,flagStore:x,cacheStorage:_,gitMetadata:M,quarantined:K,quarantinedReason:$,usageTracker:k}=r,Y=i.config.ai?.aiFailureAnalysis??!1,I=new Date,j=new ia(i,a),ce={...i.config},ne={envName:p,urlOverride:m,customHeaders:g,testInputs:h},Re,He=Math.abs(S??i.config.retries??e.retries??0),Ar=[];w.info({...M,labels:e.labels,name:e.name,cwd:process.cwd()},"Starting test run using CLI");for(let tt=0;tt<=He;tt++){let oe=await R.startAttempt(),xe=w.child(oe.loggerBindings||{}),ze={...e,steps:Pa(t),beforeSteps:Pa(n),afterSteps:Pa(o)};tt!==0&&A("RETRY",`attempt ${tt+1}/${He+1}`);let wr=new Date,Si=ce.advanced?.fakerConstantSeed??x.isBooleanFlagEnabled("faker_constant_seed"),La=new Xr({httpClient:new At({baseUrl:l.baseUrl,apiKey:l.apiKey,logger:xe}),fakerSeed:Si?Bi:void 0}),Md=oe;try{let{controller:Ut,context:Cr}=await g_({baseUrl:s,envName:p,testName:ze.name,apiClient:l,devicePixelRatio:y,logger:xe,storageClient:u,codeEvalTools:La,test:ze,generator:c,orgId:d,variables:f,customHeaders:g,testInputs:h,localBrowserConfig:{...i.config.browser||{},...E?.browser||{},...ze.advanced},aiSettings:{...i.config.ai||{},...ze.advanced||{}},visualDiffScreenshotStorage:j,flagStore:x});Re=await f_({attemptMetadata:{attemptNumber:tt+1,orgId:d,runId:R.runId},attemptFixtures:{logger:xe,storageClient:u,usageTracker:k,codeEvalTools:La,flagStore:x,apiClient:l,context:Cr,controller:Ut,tracer:oe},attemptInputs:{test:ze,orgSettings:ce}});let To=new Date,zr={logger:w,cacheStorage:_,orgId:d,testId:e.id,originalSteps:{steps:e.steps,beforeSteps:e.beforeSteps,afterSteps:e.afterSteps},updatedSteps:{steps:ze.steps,beforeSteps:ze.beforeSteps,afterSteps:ze.afterSteps}};Re?.status==="PASSED"?await hc(zr):Re?.status==="FAILED"&&await fc(zr),await oe.finish({logger:xe,result:Re}),Ar.unshift(Re.status);let G=await m_({orgId:d,codeEvalTools:La,logger:xe,outputDefinitions:e.outputs??[],testContext:Cr,flagStore:x}),Mn=aS(Ar),yi=tt+1;if(Re.status!=="FAILED")return{...Re,parameters:ne,test:ze,filePath:ze.relativeFilePath,startedAt:I,lastAttemptStartedAt:wr,finishedAt:To,attempts:yi,baseUrl:s,outputs:G,isFlake:Mn,quarantined:K,quarantinedReason:$};let Ei=Re.failedStepResult,dn=Ei?.message||"Unknown failure",xr=Ei?.failureReason??ny(dn)??"UnknownError",Od=xe.child({errResult:Ei,failureReason:xr,errorMessage:dn,numAttempts:He+1,name:ze.name});if(tt<He){Od.warn(`Retrying failed execution attempt for run: ${dn}`);continue}Od.error(`Test failed after all exhausting attempts: ${dn}`);let sl=new Error(dn),Ct={errorMessage:dn,errorStack:sl.stack},bo;if(Y){let On;try{if(Re.results&&Re.results.length>0){let{classification:vt,aiFailureReason:pn}=await DT({logger:xe,browserStateStorage:Md,generator:c,fullResults:Re,failureReason:xr,error:sl,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});On=vt,bo=pn}}catch(vt){xe.warn({err:vt},"Failed to classify test results")}On&&(Ct.classification=On,xr=bo??xr)}return{...Re,parameters:ne,failureDetails:Ct,failureReason:xr,test:ze,filePath:ze.relativeFilePath,startedAt:I,lastAttemptStartedAt:wr,finishedAt:To,attempts:tt+1,baseUrl:s,outputs:G,quarantined:K,quarantinedReason:$}}catch(Ut){Na(Ut);let Cr=`Encountered fatal platform error while running test '${ze.name}': ${Ut}`,To=new Date,zr=tt+1;xe.error({err:Ut},Cr),T.error(Cr);let G={errorMessage:Ut.message,errStack:Ut.stack},Mn={status:"FAILED",failureDetails:G,failureReason:"InternalPlatformError",finishedAt:To};return await oe.finish({logger:xe,result:{status:"FAILED",results:[]}}),{...Mn,results:[],parameters:ne,test:ze,filePath:ze.relativeFilePath,startedAt:I,lastAttemptStartedAt:wr,finishedAt:new Date,attempts:zr,baseUrl:s,outputs:{},quarantined:K,quarantinedReason:$}}}throw new Error("This code should not be reachable")}function TG(r){for(let e of r.envs??[])if(e.default)return e.name}import{randomUUID as bG}from"crypto";var Eo="assets";function vG(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 RG(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var cf=class{constructor(e,t,n,o,i){this.orgId=e;this.testId=t;this.testName=n;this.metadata=o;this.diskStorage=i}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:`${Eo}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:`${Eo}/${t}.jpeg`,contents:n})}attachBeforeHtmlSnapshot(e){let{snapshotId:t,html:n}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:`${Eo}/${t}.html`,contents:n})}attachAfterHtmlSnapshot(e){let{snapshotId:t,html:n}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:`${Eo}/${t}.html`,contents:n})}recordTargetAutoHeal(e){let{healType:t}=e,n=t==="AI"?"ai-target-heal":"cache-heal";rr.increment("test_event",1,[`name:${n}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:t,healedAt:new Date}}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finish({status:RG(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=new Ma(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Ma=class{constructor(e,t,n,o){this.orgId=e;this.testId=t;this.testName=n;this.diskStorage=o}children=[];finished=!1;stepFrequenciesByType={};async getScreenshot(e,t){return this.diskStorage.readFile(`${Eo}/${t}.jpeg`)}async getHtmlSnapshot(e,t){return this.diskStorage.readFile(`${Eo}/${t}.html`)?.toString()}getParentStepIdChain(){return[]}recordStepStat(e){e.type!=="PRESET_ACTION"?this.stepFrequenciesByType[e.type]=(this.stepFrequenciesByType[e.type]||0)+1:this.stepFrequenciesByType[e.command.type]=(this.stepFrequenciesByType[e.command.type]||0)+1}sendFinalizedStepStats(){for(let[e,t]of Object.entries(this.stepFrequenciesByType))rr.increment("test_step_execution",t,[`type:${e}`,`orgId:${this.orgId}`])}async startStep(e){let{step:t}=e;this.recordStepStat(t);let n={step:t,status:"RUNNING",startedAt:new Date},o=new cf(this.orgId,this.testId,this.testName,n,this.diskStorage);return this.children.push(o),o}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:vG(e.status),finishedAt:e.finishedAt}))),this.sendFinalizedStepStats())}},uf=class{constructor(e,t,n,o,i,a){this.orgId=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.diskStorage.mkdir("assets")}finished=!1;children=[];get loggerBindings(){return{runAttemptId:this.runAttemptId}}attachNetworkLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(t,null,2)})}attachConsoleLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(t,null,2)})}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,result:n}=e,o={...this.metadata,status:n.status,finishedAt:new Date,results:bc(n.results,t),beforeResults:n.beforeResults?bc(n.beforeResults,t):void 0,afterResults:n.afterResults?bc(n.afterResults,t):void 0};await Promise.all(this.children.map(i=>i.finish({status:o.status,finishedAt:o.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)})}async startBeforeStepList(){let e=new Ma(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Ma(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Ma(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${Eo}/${t}.jpeg`)}async getHtmlSnapshot(e,t){return this.diskStorage.readFile(`${Eo}/${t}.html`)?.toString()}},df=class{constructor(e,t,n,o,i,a){this.orgId=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}}get envVarBindings(){return{[Ob]: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,result:{status:t.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(){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 e=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),t=bG(),n={id:t,schemaVersion:ue,runAttemptSchemaVersion:TE,startedAt:new Date,status:"RUNNING"};e.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new uf(this.orgId,this.testId,this.testName,t,n,e);return this.children.push(o),o}},_d=class r{constructor(e,t,n,o){this.orgId=e;this.runGroupId=t;this.metadata=n;this.diskStorage=o}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start(e,t,n,o,i){let a={...o,id:t,trigger:ur.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Pn,labels:i??[]},l=new ws(n);return l.storeFile({name:"metadata.json",contents:JSON.stringify(a,null,2)}),new r(e,t,a,l)}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",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,resolvedInputs:e.resolvedInputs,cliVersion:Pn,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined??!1,quarantinedReason:e.quarantinedReason,executionType:"WEB"};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new df(this.orgId,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function y_(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 E_(r){let{logger:e,tests:t,yes:n,start:o,waitOn:i,client:a,debugDataStorage:l,flagStore:c,project:s,retriesOverride:u,urlOverride:d,envName:p,orgId:m,devicePixelRatio:g,customHeaders:h,testInputMatrix:f,reporter:E,include:S,exclude:y,labels:A,reporterDir:R=ZT,outputDir:w=eb,uploadResults:x=!1,waitOnTimeout:_=60,parallel:M,shardIndex:K=1,shardCount:$=1,regenerateGoldenFiles:k,gitMetadata:Y,alwaysSaveCache:I,noCache:j,ignoreQuarantine:ce,skipQuarantined:ne,onlyQuarantined:Re,runGroupId:He}=r;o&&(e.info({orgId:m},`Executing start command: ${o}`),await i_(o,!1)),i&&(e.info({orgId:m},`Waiting for url: ${i} with timeout: ${_} seconds.`),await CG({resources:[i],interval:2500,timeout:_*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let Ar=new Tn(s.config.ai?.agentConfig,{baseUrl:a.baseUrl,apiKey:a.apiKey,logger:e}),tt=q(s),oe=await Cd({tests:t,momenticFiles:tt,yes:n,project:s,include:S,exclude:y,labels:A,logger:T}),xe=await y_(e,a,ce),{testsToSkip:ze,quarantinedTestsToSkip:wr,testsToRun:Si,quarantinedTestsToRun:La}=s_({testDefinitions:oe,quarantinedTestReasons:xe,onlyQuarantined:Re,skipQuarantined:ne});u_(ze),d_(wr,xe);let Md=l_({testsToRun:Si,quarantinedTestsToRun:La,quarantinedTestReasons:xe,testInputMatrix:f}),Ut=_G({globalTestsToRunWithInputs:Md,shardIndex:K,shardCount:$});p_({logger:e,localTestsToRunWithInputs:Ut,parallel:M,shardCount:$,shardIndex:K});let Cr=[],To=new Date,zr=new Set,G=async()=>{let Ct=a.getAppUrl(),bo=ji({results:Cr,startTime:To.getTime(),onFailed:vt=>{sc(vt,vt.filePath)},getDisplayLine:vt=>{let pn=`${it}- ${vt.filePath}${vt.failureRecoveryDetails?" [recovered] ":""}`;return vt.runId&&(pn+=` ( link when uploaded: ${Ct}/runs/${vt.runId} )`),pn},entity:"test"}),On=Cr.filter(vt=>!!vt.failureRecoveryDetails?.attempts);return On.length>0&&T.warn(`Our AI agent automatically prevented ${On.length} tests from failing due to transient issues. Use the run links above to review the additional steps that were executed.`),T.log(""),x?(T.success(`Test results have been saved to the folder ${w}. Uploading to Momentic Cloud...`),await Fc({client:a,consoleLogger:T,resultsPath:w})):T.success(`Test results have been saved to the folder ${w}. Upload them to Momentic Cloud by running 'npx momentic results upload ${w}'.`),bo};wG.existsSync(w)&&T.warn(`Output directory ${w} already exists, removing before test execution...`);let Mn=await _d.start(m,He,w,Y,A),yi=e.child(Mn.loggerBindings||{}),Ei=[],dn=async()=>{T.warn("SIGINT received. Stopping tests and printing latest results..."),await Mn.finish({logger:yi,status:"CANCELLED"}),await G(),await Promise.allSettled(Ei.map(Ct=>Ct())),process.exit(1)};process.once("SIGINT",dn);let xr={};for(let Ct=0;Ct<Ut.length;Ct++){let bo=Object.values(xr);bo.length===M&&await Promise.race(bo.map(pn=>pn.promise));let On=Ut[Ct],vt=`test-${Ct}`;xr[vt]={done:!1,promise:(async({inputs:pn,quarantined:w_,quarantinedReason:C_,testDefinition:vo})=>{zr.add({inputs:pn});let ll=vo.relativeFilePath.includes("..")?vo.fullFilePath:vo.relativeFilePath;ds({status:"START",testLogRef:ll,getRunningTestsCount:()=>zr.size,getTotalTestsCount:()=>Ut.length});let x_=setInterval(()=>ds({status:"RUN",testLogRef:ll,getRunningTestsCount:()=>zr.size,getTotalTestsCount:()=>Ut.length}),5*60*1e3),Ld=AG(),Nd=yi.child({testId:vo.id,runId:Ld}),gf=new Ic({logger:Nd,reporter:new cc(a),runType:"test-run",runId:Ld,testMetadata:vo,suiteMetadata:void 0});try{let cl=await S_({testDefinition:vo,project:s,testInputs:pn,quarantined:w_,quarantinedReason:C_,orgId:m,runId:Ld,devicePixelRatio:g,apiClient:a,runGroupTracer:Mn,generator:Ar,retriesOverride:u,urlOverride:d,envName:p,customHeaders:h,regenerateGoldenFiles:k,logUpdate:(ul,__)=>ds({status:ul,testLogRef:ll,getRunningTestsCount:()=>zr.size,getTotalTestsCount:()=>Ut.length,additionalText:__}),runSigIntHandlers:Ei,logger:Nd,flagStore:c,gitMetadata:Y,alwaysSaveCache:I,noCache:j,usageTracker:gf});ds({status:cl.status,testLogRef:ll,getRunningTestsCount:()=>zr.size,getTotalTestsCount:()=>Ut.length}),Cr.push(cl)}catch(cl){let ul=`Encountered unexpected fatal error when running test '${vo.name}': ${cl.message}`;T.error(ul),Nd.error(ul)}finally{clearInterval(x_),xr[vt].done=!0,delete xr[vt]}await gf.flush(e)})(On)}}await Promise.allSettled(Object.values(xr).map(Ct=>Ct.promise));let sl=Cr.some(Ct=>!Ct.quarantined&&Ct.status==="FAILED")?"FAILED":"PASSED";return await Mn.finish({logger:yi,status:sl}),process.off("SIGINT",dn),E&&await n_(yi,l,E,{projectConfigPath:s.configFilePath,suiteName:s.config.name,startedAt:To,finishedAt:new Date,runs:Cr,testsToSkip:ze,quarantinedTestsToSkip:wr,quarantinedTestReasons:xe},R),G()}function xG(r,e,t){if(t>r.length&&(T.warn(`Shard count ${t} is greater than the number of tests ${r.length}! Some workers won't have any tests to run.`),t=Math.max(t,r.length),e>t))return[];let n=Math.floor((e-1)*(r.length/t)),o=Math.floor(e*(r.length/t));return r.sort().filter((a,l)=>l>=n&&l<o)}function _G({globalTestsToRunWithInputs:r,shardIndex:e,shardCount:t}){return t&&t>1?xG(r,e,t):r}Dd||Q.warn("Sentry is not enabled in this environment due to unsupported node version");HA({serviceName:"cli"});var DG=process.argv.some(r=>r.includes("--log-level"))&&process.argv.some(r=>r.includes("debug")),pf=r=>{DG&&T.dimmed(r)},Ft=new IG;Ft.name("momentic").description("Momentic CLI").version(Pn);Ft.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: ${am.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(T.error("No browsers specified"),process.exit(1)),await FE({rawBrowsers:r,force:e.force,all:e.all})});Ft.addOption(new Jt("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",r=>{r==="debug"&&T.info("Enabling debug logging"),T.setMinLevel(r.toLowerCase())});Ft.addOption(new Jt("--verbose","enable verbose logging")).on("option:verbose",()=>{Q.enableConsoleLogs(),T.setMinLevel(20)});var mf=Ft.command("checks").alias("check").description("Perform various project checks");mf.command("config").addOption(ir).action(async r=>{Tt({configFilePath:r.config})});mf.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(ir).addOption(kx).action(async r=>{let e=Tt({configFilePath:r.config});await vx({project:e,fix:r.fix})});mf.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(ir).action(async r=>{let e=Tt({configFilePath:r.config});await Rx({project:e})});var b_=Ft.command("migrate").description("Migrate and upgrade tooling");b_.command("steps").description("Migrate steps in all tests and modules to the latest schema version. Note that this is always done when a test is loaded through the interactive editor, so is generally not needed.").addOption(ir).action(async r=>{let e=Tt({configFilePath:r.config});await $x(e)});b_.command("v1-v2").description("Migrate from v1 of the Momentic CLI to v2").addOption(Hr).addOption(ir).addOption(Br).addOption(yo).action(async r=>{!r.yes&&!await Nt("This command will modify your existing Momentic configuration. Please backup your local directory using Git or another version control system before proceeding. Continue?",!0)&&process.exit(1);let e=Tt({configFilePath:r.config}),t=new Je({baseUrl:r.server,apiKey:r.apiKey,logger:Q}),{orgId:n}=await t.getAuthInfo();await Wx({project:e,orgId:n,apiClient:t}),process.exit(0)});Ft.command("import").addOption(Br).addOption(Hr).addOption(ir).addOption(yo).addArgument(zx).action(async(r,e)=>{let{apiKey:t,server:n,config:o,yes:i}=e,a=Tt({configFilePath:o}),l=new Je({baseUrl:n,apiKey:t,logger:Q});!r||r.length===0?await _x({client:l,project:a,skipPrompts:i}):await Ix({client:l,project:a,paths:r,skipPrompts:i}),process.exit(0)});Ft.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new Jt("--name <name>","Name of the project")).action(async r=>{T.info(`Welcome to the Momentic project setup wizard! \u{1F680}
|
|
4185
|
-
`),T.info("This wizard will help you bootstrap a new Momentic project. If you need to import existing assets from Momentic Cloud, you can call the 'import' command after initialization."),
|
|
4186
|
-
`)),process.exit(0)});var
|
|
4132
|
+
`),r.forEach(p=>{if(!yf.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m,g;try{m=yf.statSync(p),g=m.isDirectory()}catch(f){l.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=Ef.resolve(p);Object.values(e.tests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(l.info(`Reading all tests from the project and running those matching the following substring filters:
|
|
4133
|
+
${r.map(p=>`${ot}- ${p}`).join(`
|
|
4134
|
+
`)}`),Object.values(e.tests).forEach(p=>{r.some(m=>p.relativePath.includes(m))&&c.add(p.fullFilePath)}))}else{!n&&!await Nt("No test paths or substrings were provided. Do you want to run all tests?")&&(l.error("Cancelled by user."),process.exit(1));let u=Object.values(e.tests);l.info(`Reading all ${u.length} tests in the project from local disk.`),u.forEach(d=>{c.add(d.fullFilePath)})}for(let u of c){let d=Ef.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)}let s=Array.from(c).map(async u=>{try{let d=await it(u,Z,e);if(DG.gt(d.schemaVersion,se)&&l.warn(`Test ${u} has schema version ${d.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),a&&a.length>0){let p=d.labels||[];if(!a.some(g=>p.includes(g)))return null}return{...d,fullFilePath:u,relativeFilePath:Ef.relative(t.rootDir,u)}}catch(d){l.error(`Failed to read and resolve test at '${u}': ${d}`),process.exit(1)}});return Promise.all(s).then(LG)}function b_({testDefinitions:r,quarantinedTestReasons:e,onlyQuarantined:t=!1,skipQuarantined:n=!1}){if(t){let[u,d]=Dd(r,g=>g.id in e),[p,m]=Dd(u,g=>g.disabled||n);return{testsToSkip:p,quarantinedTestsToSkip:[],testsToRun:m,quarantinedTestsToRun:[]}}let[o,i]=Dd(r,u=>u.disabled),[a,l]=Dd(i,u=>u.id in e);return{testsToSkip:o,testsToRun:l,quarantinedTestsToRun:n?[]:a,quarantinedTestsToSkip:n?a:[]}}function v_({testsToRun:r,quarantinedTestsToRun:e,quarantinedTestReasons:t,testInputMatrix:n}){let o=[],i=(a,l,c)=>{n?n.forEach((s,u)=>{o.push({inputs:s,inputIndex:u,testDefinition:a,quarantined:l,quarantinedReason:c})}):o.push({inputs:void 0,testDefinition:a,quarantined:l,quarantinedReason:c})};return r.forEach(a=>i(a,!1)),e.forEach(a=>i(a,!0,t[a.id])),o}import{partition as kG}from"lodash-es";function Fd(r){return r.length===1?"test":"tests"}function R_(r){return r===1?"1 worker":`${r} workers`}function A_(r){r.length!==0&&(T.info(`Skipping ${r.length} disabled ${Fd(r)}:`),r.forEach(e=>{T.info(`${ot}- ${[e.relativeFilePath]}`)}),T.log(""))}function w_(r,e){r.length!==0&&(T.info(`Skipping ${r.length} quarantined ${Fd(r)}:`),r.forEach(t=>{T.info(`${ot}- ${[t.relativeFilePath]}: ${e[t.id]}`)}),T.log(""))}function FG(r,e){r.length!==0&&(T.info(`Running ${r.length} quarantined ${Fd(r)} with ${R_(e)}:`),r.forEach(t=>{T.info(`${ot}- ${[t.testDefinition.relativeFilePath]}${typeof t.inputIndex=="number"?` with input set ${t.inputIndex}`:""}`)}),T.log(""))}function UG(r,e,t){e.length===0&&r.length>0||(T.info(`Running ${e.length} ${Fd(e)} with ${R_(t)}:`),e.forEach(n=>{T.info(`${ot}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),T.log(""))}function C_({logger:r,localTestsToRunWithInputs:e,parallel:t,shardCount:n,shardIndex:o}){r.info({tests:e.length,shardCount:n,shardIndex:o,parallel:t},"Running local tests");let[i,a]=kG(e,l=>l.quarantined);FG(i,t),UG(i,a,t)}import{cloneDeep as La}from"lodash-es";async function x_({orgId:r,codeEvalTools:e,logger:t,outputDefinitions:n,testContext:o}){let i={};for(let a of n){let{name:l,value:c}=a;i[l]=await tr({orgId:r,s:c,localTools:e,logger:t,context:o})}return i}async function __({baseUrl:r,envName:e,testName:t,devicePixelRatio:n,apiClient:o,test:i,storageClient:a,codeEvalTools:l,generator:c,orgId:s,variables:u,logger:d,customHeaders:p,testInputs:m,localBrowserConfig:g,aiSettings:h,visualDiffScreenshotStorage:f}){let S=await Yu({settings:g,customHeaders:p,envVariables:u,envName:e,testName:t,baseUrl:r,logger:d,localTools:l,orgId:s}),E={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:Z},y=S.browserType??"Chromium";if(!qE(y)){let x=`Browser ${y} is required by the test named ${i.name} but does not appear to be installed on this machine. Please install it using 'momentic install-browsers' before running tests. Attempting to continue...`;T.warn(x),Z.warn(x)}let A=await wr.init({baseUrl:r,logger:d,userBrowserSettings:S,storage:a,enricher:new Zn(E,c),contextArgs:{viewport:i.advanced.viewport??Mt,locale:i.advanced.locale??Vn,geolocation:i.advanced.geolocation??$n,timezoneId:i.advanced.timezone??jn,colorScheme:i.advanced.colorScheme,deviceScaleFactor:n},iconKnowledgeBase:null}),R=new go({browser:A,generator:c,logger:d,orgId:s,options:{scratchPadId:void 0,slowMoMs:S.slowMoMs,autoFollowNewTabs:S.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering},storage:a,localCodeEvalTools:l,visualDiffScreenshotStorage:f}),w=new qt({baseUrl:r,currentUrl:R.browser.url(),variablesFromEnvironment:u,envName:e,testName:t});return i.parameters&&await Promise.all(i.parameters.map(async x=>{let{name:_,defaultValue:P,required:X}=x,V=m?.[_];X&&V===void 0&&(T.error(`Required parameter '${_}' is required by test '${i.name}' but not provided`),process.exit(1));let k=await tr({orgId:s,s:V??P,localTools:l,logger:d,context:qt.dummyContext(w.getEnvName())});w.setMomenticSystemVariable(_,k)})),{controller:R,context:w}}async function I_({testAdvancedSettings:r,orgSettings:e,logger:t}){if(r.failureRecovery===!1||r.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!Fa){let n="This test is ineligible for failure recovery since this does not appear to be a CI environment";return t.warn(n),T.warn(n),!1}return!0}async function M_({attemptInputs:r,attemptFixtures:e,attemptMetadata:t}){let{orgId:n,runId:o}=t,{controller:i,context:a,codeEvalTools:l,storageClient:c,logger:s,usageTracker:u,tracer:d}=e,{test:p,orgSettings:m}=r;s.info(`Running test '${p.name}' locally (run link: https://app.momentic.ai/runs/${o})`);let g={controller:i,storage:c,usageTracker:u,context:a,logger:s,codeEvalTools:l},h={orgId:n,runId:o,testMetadata:p,steps:p.steps,beforeSteps:p.beforeSteps,afterSteps:p.afterSteps,orgSettings:m},f={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await I_({testAdvancedSettings:p.advanced,orgSettings:m.ai,logger:s})};return await Ku({fixtures:g,inputs:h,options:f,callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()}}},testParams:{tracer:d}})}async function P_(r){let{testDefinition:e,logger:t}=r,n=new Date;try{return await BG(r)}catch(o){let i="Fatal error running test";return T.error(`${i}: ${o.message}`),t.error({err:o},i),{results:[],parameters:r,failureReason:"UnknownError",failureDetails:{errorMessage:o.message,errorStack:o.stack},status:"FAILED",attempts:0,test:e,filePath:e.relativeFilePath,startedAt:n,lastAttemptStartedAt:n,finishedAt:new Date,outputs:{}}}}async function BG(r){let{testDefinition:e,project:t,apiClient:n,orgId:o,urlOverride:i,runSigIntHandlers:a,runGroupTracer:l,logger:c,gitMetadata:s,alwaysSaveCache:u,noCache:d,runId:p,testInputs:m,quarantined:g,quarantinedReason:h,usageTracker:f}=r,S=new qi(n,o),E=ea({orgId:o,client:n,gitMetadata:s,alwaysSaveCache:u,noCache:d}),y=La(e.steps),A=La(e.beforeSteps)??void 0,R=La(e.afterSteps)??void 0;try{await E.resolveStepCacheEntries({testId:e.id,stepLists:{steps:y,beforeSteps:A,afterSteps:R},schemaVersion:e.schemaVersion,logger:c})}catch(k){throw c.error({err:k},"Failed to resolve step cache entries"),new Error(`Failed to resolve step cache entries. Please ensure you are running using a supported version of Momentic. If you believe this is a Momentic issue, please contact Support with the following error: ${k}`)}let w=r.envName??HG(e),x,_={};if(w){try{x=Is(w,t,c)}catch(k){let Q=`Failed to resolve environment ${w} for test ${e.name}: ${k}`;throw new Error(Q)}_=x.variables}let P=e.baseUrl;if(i)P=i;else if(!P){let k=_[ht];typeof k=="string"&&(P=k)}if(!P){let k=`Cannot run test with no base URL and no ${ht} variable defined in its environment`;throw new Error(k)}let X=await l.startRun({logger:c,runId:p,originalSteps:{beforeSteps:e.beforeSteps,steps:e.steps,afterSteps:e.afterSteps},testId:e.id,testName:e.name,testDescription:e.description??void 0,testLabels:e.labels,baseUrl:P,environmentName:w,schemaVersion:e.schemaVersion,resolvedInputs:m,quarantined:g,quarantinedReason:h}),V=c.child(X.loggerBindings||{});Object.entries(X.envVarBindings||{}).forEach(([k,Q])=>{_[k]=Q});try{let k=await zG({...r,variables:_,envName:w,resolvedEnv:x,baseUrl:P,storageClient:S,tracer:X,logger:V,cacheStorage:E,stepsWithCaches:y,beforeStepsWithCaches:A,afterStepsWithCaches:R,usageTracker:f});return await X.finish({logger:c,status:k.status,finishedAt:k.finishedAt,failureDetails:k.failureDetails,failureReason:k.failureReason,isFlake:k.isFlake,failureRecoveryDetails:k.failureRecoveryDetails}),{runId:X.runId,...k}}finally{a?.pop()}}async function zG(r){let{testDefinition:e,stepsWithCaches:t,beforeStepsWithCaches:n,afterStepsWithCaches:o,project:i,regenerateGoldenFiles:a,apiClient:l,generator:c,baseUrl:s,storageClient:u,orgId:d,envName:p,urlOverride:m,customHeaders:g,testInputs:h,variables:f,resolvedEnv:S,retriesOverride:E,devicePixelRatio:y,logUpdate:A,tracer:R,logger:w,cacheStorage:x,gitMetadata:_,quarantined:P,quarantinedReason:X,usageTracker:V}=r,k=i.config.ai?.aiFailureAnalysis??!1,Q=new Date,I=new la(i,a),re={...i.config},me={envName:p,urlOverride:m,customHeaders:g,testInputs:h},q,Qe=Math.abs(E??i.config.retries??e.retries??0),Ve=[];w.info({..._,labels:e.labels,name:e.name,cwd:process.cwd()},"Starting test run using CLI");for(let gt=0;gt<=Qe;gt++){let bt=await R.startAttempt(),K=w.child(bt.loggerBindings||{}),Ee={...e,steps:La(t),beforeSteps:La(n),afterSteps:La(o)};gt!==0&&A("RETRY",`attempt ${gt+1}/${Qe+1}`);let sr=new Date,Ln=re.advanced?.fakerConstantSeed,Nn=new Qr({httpClient:new At({baseUrl:l.baseUrl,apiKey:l.apiKey,logger:K}),fakerSeed:Ln?Hi:void 0}),Hd=bt;try{let{controller:Ut,context:Cr}=await __({baseUrl:s,envName:p,testName:Ee.name,apiClient:l,devicePixelRatio:y,logger:K,storageClient:u,codeEvalTools:Nn,test:Ee,generator:c,orgId:d,variables:f,customHeaders:g,testInputs:h,localBrowserConfig:{...i.config.browser||{},...S?.browser||{},...Ee.advanced},aiSettings:{...i.config.ai||{},...Ee.advanced||{}},visualDiffScreenshotStorage:I});q=await M_({attemptMetadata:{attemptNumber:gt+1,orgId:d,runId:R.runId},attemptFixtures:{logger:K,storageClient:u,usageTracker:V,codeEvalTools:Nn,apiClient:l,context:Cr,controller:Ut,tracer:bt},attemptInputs:{test:Ee,orgSettings:re}});let vo=new Date,Gr={logger:w,cacheStorage:x,orgId:d,testId:e.id,originalSteps:{steps:e.steps,beforeSteps:e.beforeSteps,afterSteps:e.afterSteps},updatedSteps:{steps:Ee.steps,beforeSteps:Ee.beforeSteps,afterSteps:Ee.afterSteps}};q?.status==="PASSED"?await Nc(Gr):q?.status==="FAILED"&&await Dc(Gr),await bt.finish({logger:K,result:q}),Ve.unshift(q.status);let Ro=await x_({orgId:d,codeEvalTools:Nn,logger:K,outputDefinitions:e.outputs??[],testContext:Cr}),G=fS(Ve),Ti=gt+1;if(q.status!=="FAILED")return{...q,parameters:me,test:Ee,filePath:Ee.relativeFilePath,startedAt:Q,lastAttemptStartedAt:sr,finishedAt:vo,attempts:Ti,baseUrl:s,outputs:Ro,isFlake:G,quarantined:P,quarantinedReason:X};let bi=q.failedStepResult,gn=bi?.message||"Unknown failure",xr=bi?.failureReason??gy(gn)??"UnknownError",Gd=K.child({errResult:bi,failureReason:xr,errorMessage:gn,numAttempts:Qe+1,name:Ee.name});if(gt<Qe){Gd.warn(`Retrying failed execution attempt for run: ${gn}`);continue}Gd.error(`Test failed after all exhausting attempts: ${gn}`);let gl=new Error(gn),Ct={errorMessage:gn,errorStack:gl.stack},Ao;if(k){let Dn;try{if(q.results&&q.results.length>0){let{classification:vt,aiFailureReason:hn}=await qT({logger:K,browserStateStorage:Hd,generator:c,fullResults:q,failureReason:xr,error:gl,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Dn=vt,Ao=hn}}catch(vt){K.warn({err:vt},"Failed to classify test results")}Dn&&(Ct.classification=Dn,xr=Ao??xr)}return{...q,parameters:me,failureDetails:Ct,failureReason:xr,test:Ee,filePath:Ee.relativeFilePath,startedAt:Q,lastAttemptStartedAt:sr,finishedAt:vo,attempts:gt+1,baseUrl:s,outputs:Ro,quarantined:P,quarantinedReason:X}}catch(Ut){ka(Ut);let Cr=`Encountered fatal platform error while running test '${Ee.name}': ${Ut}`,vo=new Date,Gr=gt+1;K.error({err:Ut},Cr),T.error(Cr);let Ro={errorMessage:Ut.message,errStack:Ut.stack},G={status:"FAILED",failureDetails:Ro,failureReason:"InternalPlatformError",finishedAt:vo};return await bt.finish({logger:K,result:{status:"FAILED",results:[]}}),{...G,results:[],parameters:me,test:Ee,filePath:Ee.relativeFilePath,startedAt:Q,lastAttemptStartedAt:sr,finishedAt:new Date,attempts:Gr,baseUrl:s,outputs:{},quarantined:P,quarantinedReason:X}}}throw new Error("This code should not be reachable")}function HG(r){for(let e of r.envs??[])if(e.default)return e.name}import GG from"adm-zip";import{randomUUID as VG}from"crypto";var On="assets";function jG(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 $G(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var Tf=class{constructor(e,t,n,o,i){this.orgId=e;this.testId=t;this.testName=n;this.metadata=o;this.diskStorage=i}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:`${On}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:`${On}/${t}.jpeg`,contents:n})}attachBeforeHtmlSnapshot(e){let{snapshotId:t,html:n}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:`${On}/${t}.html`,contents:n})}attachAfterHtmlSnapshot(e){let{snapshotId:t,html:n}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:`${On}/${t}.html`,contents:n})}recordTargetAutoHeal(e){let{healType:t}=e,n=t==="AI"?"ai-target-heal":"cache-heal";nr.increment("test_event",1,[`name:${n}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:t,healedAt:new Date}}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finish({status:$G(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=new Na(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Na=class{constructor(e,t,n,o){this.orgId=e;this.testId=t;this.testName=n;this.diskStorage=o}children=[];finished=!1;stepFrequenciesByType={};async getScreenshot(e,t){return this.diskStorage.readFile(`${On}/${t}.jpeg`)}async getHtmlSnapshot(e,t){return this.diskStorage.readFile(`${On}/${t}.html`)?.toString()}getParentStepIdChain(){return[]}recordStepStat(e){e.type!=="PRESET_ACTION"?this.stepFrequenciesByType[e.type]=(this.stepFrequenciesByType[e.type]||0)+1:this.stepFrequenciesByType[e.command.type]=(this.stepFrequenciesByType[e.command.type]||0)+1}sendFinalizedStepStats(){for(let[e,t]of Object.entries(this.stepFrequenciesByType))nr.increment("test_step_execution",t,[`type:${e}`,`orgId:${this.orgId}`])}async startStep(e){let{step:t}=e;this.recordStepStat(t);let n={step:t,status:"RUNNING",startedAt:new Date},o=new Tf(this.orgId,this.testId,this.testName,n,this.diskStorage);return this.children.push(o),o}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:jG(e.status),finishedAt:e.finishedAt}))),this.sendFinalizedStepStats())}},bf=class{constructor(e,t,n,o,i,a){this.orgId=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.diskStorage.mkdir("assets")}finished=!1;children=[];get loggerBindings(){return{runAttemptId:this.runAttemptId}}attachNetworkLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(t,null,2)})}attachConsoleLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(t,null,2)})}attachBrowserCrashDump(e){let{crashReportDirFetcher:t,logger:n}=e,o=t();if(!o)return;let i=new GG;i.addLocalFolder(o,void 0,a=>a!==".DS_Store"),this.diskStorage.storeFile({name:`${On}/${mm}`,contents:i.toBuffer()}),n.info({browserCrashZipName:mm},"Wrote browser crash ZIP to disk")}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,result:n}=e,o={...this.metadata,status:n.status,finishedAt:new Date,results:Mc(n.results,t),beforeResults:n.beforeResults?Mc(n.beforeResults,t):void 0,afterResults:n.afterResults?Mc(n.afterResults,t):void 0};await Promise.all(this.children.map(i=>i.finish({status:o.status,finishedAt:o.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)})}async startBeforeStepList(){let e=new Na(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Na(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Na(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${On}/${t}.jpeg`)}async getHtmlSnapshot(e,t){return this.diskStorage.readFile(`${On}/${t}.html`)?.toString()}},vf=class{constructor(e,t,n,o,i,a){this.orgId=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}}get envVarBindings(){return{[qb]: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,result:{status:t.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(){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 e=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),t=VG(),n={id:t,schemaVersion:se,runAttemptSchemaVersion:PE,startedAt:new Date,status:"RUNNING"};e.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new bf(this.orgId,this.testId,this.testName,t,n,e);return this.children.push(o),o}},Ud=class r{constructor(e,t,n,o){this.orgId=e;this.runGroupId=t;this.metadata=n;this.diskStorage=o}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start(e,t,n,o,i){let a={...o,id:t,trigger:pr.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Pn,labels:i??[]},l=new Os(n);return l.storeFile({name:"metadata.json",contents:JSON.stringify(a,null,2)}),new r(e,t,a,l)}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",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,resolvedInputs:e.resolvedInputs,cliVersion:Pn,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined??!1,quarantinedReason:e.quarantinedReason,executionType:"WEB"};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new vf(this.orgId,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function O_(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 L_(r){let{logger:e,tests:t,yes:n,start:o,waitOn:i,client:a,debugDataStorage:l,project:c,retriesOverride:s,urlOverride:u,envName:d,orgId:p,devicePixelRatio:m,customHeaders:g,testInputMatrix:h,reporter:f,include:S,exclude:E,labels:y,reporterDir:A=pb,outputDir:R=mb,uploadResults:w=!1,waitOnTimeout:x=60,parallel:_,shardIndex:P=1,shardCount:X=1,regenerateGoldenFiles:V,gitMetadata:k,alwaysSaveCache:Q,noCache:I,ignoreQuarantine:re,skipQuarantined:me,onlyQuarantined:q,runGroupId:Qe}=r;o&&(e.info({orgId:p},`Executing start command: ${o}`),await E_(o,!1)),i&&(e.info({orgId:p},`Waiting for url: ${i} with timeout: ${x} seconds.`),await KG({resources:[i],interval:2500,timeout:x*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let Ve=new bn(c.config.ai?.agentConfig,{baseUrl:a.baseUrl,apiKey:a.apiKey,logger:e}),gt=W(c),bt=await kd({tests:t,momenticFiles:gt,yes:n,project:c,include:S,exclude:E,labels:y,logger:T}),K=await O_(e,a,re),{testsToSkip:Ee,quarantinedTestsToSkip:sr,testsToRun:Ln,quarantinedTestsToRun:Nn}=b_({testDefinitions:bt,quarantinedTestReasons:K,onlyQuarantined:q,skipQuarantined:me});A_(Ee),w_(sr,K);let Hd=v_({testsToRun:Ln,quarantinedTestsToRun:Nn,quarantinedTestReasons:K,testInputMatrix:h}),Ut=XG({globalTestsToRunWithInputs:Hd,shardIndex:P,shardCount:X});C_({logger:e,localTestsToRunWithInputs:Ut,parallel:_,shardCount:X,shardIndex:P});let Cr=[],vo=new Date,Gr=new Set,Ro=async()=>{let Ct=a.getAppUrl(),Ao=Wi({results:Cr,startTime:vo.getTime(),onFailed:vt=>{Sc(vt,vt.filePath)},getDisplayLine:vt=>{let hn=`${ot}- ${vt.filePath}${vt.failureRecoveryDetails?" [recovered] ":""}`;return vt.runId&&(hn+=` ( link when uploaded: ${Ct}/runs/${vt.runId} )`),hn},entity:"test"}),Dn=Cr.filter(vt=>!!vt.failureRecoveryDetails?.attempts);return Dn.length>0&&T.warn(`Our AI agent automatically prevented ${Dn.length} tests from failing due to transient issues. Use the run links above to review the additional steps that were executed.`),T.log(""),w?(T.success(`Test results have been saved to the folder ${R}. Uploading to Momentic Cloud...`),await Kc({client:a,consoleLogger:T,resultsPath:R})):T.success(`Test results have been saved to the folder ${R}. Upload them to Momentic Cloud by running 'npx momentic results upload ${R}'.`),Ao};qG.existsSync(R)&&T.warn(`Output directory ${R} already exists, removing before test execution...`);let G=await Ud.start(p,Qe,R,k,y),Ti=e.child(G.loggerBindings||{}),bi=[],gn=async()=>{T.warn("SIGINT received. Stopping tests and printing latest results..."),await G.finish({logger:Ti,status:"CANCELLED"}),await Ro(),await Promise.allSettled(bi.map(Ct=>Ct())),process.exit(1)};process.once("SIGINT",gn);let xr={};for(let Ct=0;Ct<Ut.length;Ct++){let Ao=Object.values(xr);Ao.length===_&&await Promise.race(Ao.map(hn=>hn.promise));let Dn=Ut[Ct],vt=`test-${Ct}`;xr[vt]={done:!1,promise:(async({inputs:hn,quarantined:B_,quarantinedReason:z_,testDefinition:wo})=>{Gr.add({inputs:hn});let hl=wo.relativeFilePath.includes("..")?wo.fullFilePath:wo.relativeFilePath;Ss({status:"START",testLogRef:hl,getRunningTestsCount:()=>Gr.size,getTotalTestsCount:()=>Ut.length});let H_=setInterval(()=>Ss({status:"RUN",testLogRef:hl,getRunningTestsCount:()=>Gr.size,getTotalTestsCount:()=>Ut.length}),5*60*1e3),Vd=WG(),jd=Ti.child({testId:wo.id,runId:Vd}),wf=new zc({logger:jd,reporter:new Ec(a),runType:"test-run",runId:Vd,testMetadata:wo,suiteMetadata:void 0});try{let fl=await P_({testDefinition:wo,project:c,testInputs:hn,quarantined:B_,quarantinedReason:z_,orgId:p,runId:Vd,devicePixelRatio:m,apiClient:a,runGroupTracer:G,generator:Ve,retriesOverride:s,urlOverride:u,envName:d,customHeaders:g,regenerateGoldenFiles:V,logUpdate:(Sl,G_)=>Ss({status:Sl,testLogRef:hl,getRunningTestsCount:()=>Gr.size,getTotalTestsCount:()=>Ut.length,additionalText:G_}),runSigIntHandlers:bi,logger:jd,gitMetadata:k,alwaysSaveCache:Q,noCache:I,usageTracker:wf});Ss({status:fl.status,testLogRef:hl,getRunningTestsCount:()=>Gr.size,getTotalTestsCount:()=>Ut.length}),Cr.push(fl)}catch(fl){let Sl=`Encountered unexpected fatal error when running test '${wo.name}': ${fl.message}`;T.error(Sl),jd.error(Sl)}finally{clearInterval(H_),xr[vt].done=!0,delete xr[vt]}await wf.flush(e)})(Dn)}}await Promise.allSettled(Object.values(xr).map(Ct=>Ct.promise));let gl=Cr.some(Ct=>!Ct.quarantined&&Ct.status==="FAILED")?"FAILED":"PASSED";return await G.finish({logger:Ti,status:gl}),process.off("SIGINT",gn),f&&await S_(Ti,l,f,{projectConfigPath:c.configFilePath,suiteName:c.config.name,startedAt:vo,finishedAt:new Date,runs:Cr,testsToSkip:Ee,quarantinedTestsToSkip:sr,quarantinedTestReasons:K},A),Ro()}function YG(r,e,t){if(t>r.length&&(T.warn(`Shard count ${t} is greater than the number of tests ${r.length}! Some workers won't have any tests to run.`),t=Math.max(t,r.length),e>t))return[];let n=Math.floor((e-1)*(r.length/t)),o=Math.floor(e*(r.length/t));return r.sort().filter((a,l)=>l>=n&&l<o)}function XG({globalTestsToRunWithInputs:r,shardIndex:e,shardCount:t}){return t&&t>1?YG(r,e,t):r}$d||Z.warn("Sentry is not enabled in this environment due to unsupported node version");tw({serviceName:"cli"});var nV=process.argv.some(r=>r.includes("--log-level"))&&process.argv.some(r=>r.includes("debug")),Rf=r=>{nV&&T.dimmed(r)},Ft=new JG;Ft.name("momentic").description("Momentic CLI").version(Pn);Ft.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: ${ym.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(T.error("No browsers specified"),process.exit(1)),await KE({rawBrowsers:r,force:e.force,all:e.all})});Ft.addOption(new Qt("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",r=>{r==="debug"&&T.info("Enabling debug logging"),T.setMinLevel(r.toLowerCase())});Ft.addOption(new Qt("--verbose","enable verbose logging")).on("option:verbose",()=>{Z.enableConsoleLogs(),T.setMinLevel(20)});var Af=Ft.command("checks").alias("check").description("Perform various project checks");Af.command("config").addOption(ar).action(async r=>{Et({configFilePath:r.config})});Af.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(ar).addOption(Xx).action(async r=>{let e=Et({configFilePath:r.config});await kx({project:e,fix:r.fix})});Af.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(ar).action(async r=>{let e=Et({configFilePath:r.config});await Fx({project:e})});var D_=Ft.command("migrate").description("Migrate and upgrade tooling");D_.command("steps").description("Migrate steps in all tests and modules to the latest schema version. Note that this is always done when a test is loaded through the interactive editor, so is generally not needed.").addOption(ar).action(async r=>{let e=Et({configFilePath:r.config});await i_(e)});D_.command("v1-v2").description("Migrate from v1 of the Momentic CLI to v2").addOption(Hr).addOption(ar).addOption(zr).addOption(bo).action(async r=>{!r.yes&&!await Nt("This command will modify your existing Momentic configuration. Please backup your local directory using Git or another version control system before proceeding. Continue?",!0)&&process.exit(1);let e=Et({configFilePath:r.config}),t=new Ye({baseUrl:r.server,apiKey:r.apiKey,logger:Z}),{orgId:n}=await t.getAuthInfo();await a_({project:e,orgId:n,apiClient:t}),process.exit(0)});Ft.command("import").addOption(zr).addOption(Hr).addOption(ar).addOption(bo).addArgument(t_).action(async(r,e)=>{let{apiKey:t,server:n,config:o,yes:i}=e,a=Et({configFilePath:o}),l=new Ye({baseUrl:n,apiKey:t,logger:Z});!r||r.length===0?await Gx({client:l,project:a,skipPrompts:i}):await Vx({client:l,project:a,paths:r,skipPrompts:i}),process.exit(0)});Ft.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new Qt("--name <name>","Name of the project")).action(async r=>{T.info(`Welcome to the Momentic project setup wizard! \u{1F680}
|
|
4135
|
+
`),T.info("This wizard will help you bootstrap a new Momentic project. If you need to import existing assets from Momentic Cloud, you can call the 'import' command after initialization."),zd.existsSync(ia)&&(T.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 VE("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Hm};aa(t,ia),T.success(`Initialized Momentic project file at ${Bd.resolve(ia)}`)});Ft.command("app").addOption(zr).addOption(Hr).addOption(bo).addOption(of).addOption(ar).addOption(sf).addOption(lf).action(async r=>{let{apiKey:e,yes:t,server:n,pixelRatio:o,disableCache:i,saveCache:a}=r,l=Et({configFilePath:r.config,nameFilter:void 0}),{errors:c}=await Rd({project:l,fix:!1});c>0&&(T.error(`Found ${c} errors`),T.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));let s=new Ye({baseUrl:n,apiKey:e,logger:Z});await Rm({client:s,skipPrompts:t});let u=rV(import.meta.url),d=Bd.dirname(u),p=Bd.resolve(d,"..","static"),m=Bd.resolve(d,"..","assets"),g=o??hf();ff(g),await Ox({momenticServerUrl:n,apiKey:e,serverPort:Ad,appPort:Ad,staticDir:p,assetsDir:m,devicePixelRatio:g,noCache:i,alwaysSaveCache:a,initialProject:l});let h=`http://localhost:${Ad}`;await tV(h)});var k_=Ft.command("queue").description("Queue tests or suites to run on Momentic Cloud");k_.command("suites").description("Run one or more suites on Momentic Cloud").addOption(zr).addOption(Hr).addOption(Zh).addOption(ef).addOption(bo).addArgument(r_).addOption(_d).addOption(xd).addOption(Cd).action(async(r,e)=>{let{apiKey:t,server:n,wait:o,waitTimeout:i,env:a,urlOverride:l}=e,c=wd(e.customHeaders),s=new Ye({baseUrl:n,apiKey:t,logger:Z});(!r||!Array.isArray(r)||!r.length)&&(T.error("Must pass at least one suite to run."),process.exit(1));let{orgId:u}=await s.getAuthInfo();await u_({client:s,orgId:u,wait:o,suitePaths:r,waitTimeout:i,env:a,urlOverride:l,customHeaders:c}),Da()});k_.command("tests").description("Run one or more tests on Momentic Cloud").addOption(zr).addOption(Hr).addOption(bo).addOption(Cd).addOption(af).addOption(_d).addOption(xd).addOption(new Qt("--all","Run all tests.").default(!1)).addOption(Zh).addOption(ef).addArgument(e_).action(async(r,e)=>{let{all:t,apiKey:n,env:o,server:i,inputCsv:a,urlOverride:l,wait:c,waitTimeout:s,yes:u}=e,d=wd(e.customHeaders);for(let h of r)(h.endsWith(".yaml")||zd.existsSync(h))&&T.warn("Are you trying to run a test on your local machine? If so, please use the 'run' command instead of the 'queue' command");let p=new Ye({baseUrl:i,apiKey:n,logger:Z}),{orgId:m}=await p.getAuthInfo(),g;a&&(g=await Sf(a)),await d_({client:p,orgId:m,tests:r,all:t,customHeaders:d,env:o,urlOverride:l,wait:c,waitTimeout:s,testInputMatrix:g,yes:u}),Da(),process.exit(0)});var oV=Ft.command("list").description("List test paths");oV.addOption(ar).addOption(Pa).addOption(rf).addOption(nf).addOption(new Qt("--labels <labels...>","Only run tests with the specified label(s).")).addArgument(cf).action(async(r,e)=>{let t=Et({configFilePath:e.config,nameFilter:e.filter}),n=W(t),o=await kd({tests:r,momenticFiles:n,yes:!0,project:t,include:e.include,exclude:e.exclude,labels:e.labels,logger:new ps(40,{})});T.info(o.map(i=>i.relativeFilePath).join(`
|
|
4136
|
+
`)),process.exit(0)});var iV=Ft.command("run").alias("test").description("Run tests on the local machine");iV.addOption(zr).addOption(Hr).addOption(ar).addOption(Pa).addOption(bo).addOption(Cd).addOption(af).addOption(sf).addOption(lf).addOption(Jx).addOption(Qx).addOption(Zx).addOption(xd).addOption(_d).addOption(of).addOption(new Qt("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new Qt("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new Qt("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(To)).addOption(new Qt("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(To)).addOption(new Qt("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(To)).addOption(new Qt("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new Qt("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption($x).addOption(Wx).addOption(tf).addOption(qx).addOption(Yx).addOption(Kx).addOption(rf).addOption(nf).addArgument(cf).action(async(r,e)=>{if(e.shardIndex>e.shardCount)throw new Error("Shard index cannot be greater than shard count");let t=wd(e.customHeaders),n=Et({configFilePath:e.config,nameFilter:e.filter}),o=e.parallel??n.config.parallel??1;N_().length<o*2&&T.warn(`You requested to run tests in parallel ${o} at a time on a machine with ${N_().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`),T.debug({projectName:n.config.name},"Identified project config");let{errors:i}=await Rd({project:n,fix:!1});i>0&&(T.error(`Found ${i} errors`),T.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));let a=new Ye({baseUrl:e.server,apiKey:e.apiKey,logger:Z});T.debug("Checking API key and dependencies");let{orgId:l,userId:c}=await Rm({client:a,skipPrompts:e.yes});T.debug("API key check and browser installation complete");let s=new ls,u=e.outputDir??n.config.outputDir,d=e.reporterDir??n.config.reporterDir,p=ZG(),m=Z.child({cliVersion:Pn,orgId:l,userId:c,runGroupId:p}),g=await to(Z,a,n);m.info({gitMetadata:g,config:n.config},"Got local metadata");let h;e.inputCsv&&(h=await Sf(e.inputCsv));let f=e.pixelRatio??hf();ff(f);try{let S=await L_({...e,parallel:o,retriesOverride:e.retries,devicePixelRatio:f,tests:r,project:n,client:a,debugDataStorage:s,outputDir:u,uploadResults:e.uploadResults,reporterDir:d,customHeaders:t,envName:e.env,orgId:l,testInputMatrix:h,logger:m,regenerateGoldenFiles:e.updateGoldenFiles,gitMetadata:g,alwaysSaveCache:e.saveCache,noCache:e.disableCache,runGroupId:p});Da(),S.failed>0?process.exit(1):process.exit(0)}catch(S){T.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),T.error(S),Da(),process.exit(1)}});var aV=Ft.command("apply").description("Apply an operation to local resources");aV.command("patch").addOption(zr).addOption(Hr).addOption(ar).addOption(Pa).addOption(bo).addOption(new Qt("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new Qt("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async r=>{let{apiKey:e,server:t,config:n,yes:o}=r,i=Et({configFilePath:n}),a=Z,l=new Ye({baseUrl:t,apiKey:e,logger:a}),c=W(i),s=c.tests[r.to]??Object.values(c.tests).find(d=>xe(d.name)===r.to.trim());s||(T.error(`No test matching '${r.to}' could be found in the current project.`),process.exit(1));let u=await l.fetchTestFragment(r.from);await Nx({client:l,test:s,fragment:u,yes:o,entities:c,logger:Z}),process.exit(0)});var F_=Ft.command("results").description("Merge and upload test results.");F_.command("merge").description("Merge test results files.").addOption(tf).addArgument(n_).action(async(r,e)=>{let{outputDir:t}=e;t||(T.error("Output directory is required."),process.exit(1)),zd.existsSync(r)||(T.warn("Results path does not exist, skipping merge."),process.exit(0)),zd.existsSync(t)&&T.warn(`Output directory ${t} already exists, removing before merging...`),Sb(Z,t,r)});F_.command("upload").description("Upload test results to Momentic cloud.").addOption(zr).addOption(Hr).addArgument(o_).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=Z,i=new Ye({baseUrl:n,apiKey:t,logger:o});await Kc({consoleLogger:T,resultsPath:r,client:i}),process.exit(0)});var U_=Ft.command("quarantine").description("Manage test quarantines");U_.command("add").description("Add a test to the quarantine. This will prevent it from running.").addOption(zr).addOption(Hr).addOption(ar).addOption(Pa).addOption(uf).addArgument(df).action(async(r,e)=>{let{apiKey:t,server:n,config:o,reason:i}=e,a=Z,l=Et({configFilePath:o}),c=new Ye({baseUrl:n,apiKey:t,logger:a}),s=await to(Z,c,l);await s_({test:r,reason:i,apiClient:c,project:l,logger:a,identity:s})});U_.command("remove").description("Remove a test from the quarantine. This will allow it to run again.").addOption(zr).addOption(Hr).addOption(ar).addOption(Pa).addOption(uf).addArgument(df).action(async(r,e)=>{let{apiKey:t,server:n,config:o,reason:i}=e,a=Z,l=Et({configFilePath:o}),c=new Ye({baseUrl:n,apiKey:t,logger:a}),s=await to(Z,c,l);await l_({test:r,reason:i,apiClient:c,project:l,logger:a,identity:s})});async function Da(){try{await nr.flush(),zE()}catch{}}async function sV(){Rf("Main program started"),await T_(Z),Rf("CLI version check complete");try{await Ft.parseAsync(process.argv),Da()}catch(r){let e={};try{e.playwrightVersion=QG("npx playwright --version").toString()}catch(t){Z.error({err:t},"Error fetching debug information")}Z.error({err:r,debugInfo:e},"Uncaught error in CLI"),ka(r,e),T.error(r),Da(),process.exit(1)}}eV.setMaxListeners(50);process.on("warning",r=>{Z.warn({err:r},`Node warning received on CLI: ${r.message}`)});Rf("CLI parsing setup complete");sV();
|
|
4187
4137
|
//# sourceMappingURL=cli.js.map
|
|
4188
|
-
//# debugId=
|
|
4138
|
+
//# debugId=bf42114a-a45b-5cd4-a429-d5942e4bdd43
|