momentic 0.0.19 → 0.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/bin/cli.js +23 -23
  2. package/dist/index.js +19 -19
  3. package/package.json +1 -1
package/bin/cli.js CHANGED
@@ -1,21 +1,21 @@
1
1
  #!/usr/bin/env node
2
- var un=Object.defineProperty,mn=Object.defineProperties;var pn=Object.getOwnPropertyDescriptors;var Re=Object.getOwnPropertySymbols;var _t=Object.prototype.hasOwnProperty,zt=Object.prototype.propertyIsEnumerable;var Pt=(n,e,t)=>e in n?un(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,C=(n,e)=>{for(var t in e||(e={}))_t.call(e,t)&&Pt(n,t,e[t]);if(Re)for(var t of Re(e))zt.call(e,t)&&Pt(n,t,e[t]);return n},O=(n,e)=>mn(n,pn(e));var ne=(n,e)=>{var t={};for(var o in n)_t.call(n,o)&&e.indexOf(o)<0&&(t[o]=n[o]);if(n!=null&&Re)for(var o of Re(n))e.indexOf(o)<0&&zt.call(n,o)&&(t[o]=n[o]);return t};var l=(n,e,t)=>new Promise((o,r)=>{var s=c=>{try{i(t.next(c))}catch(d){r(d)}},a=c=>{try{i(t.throw(c))}catch(d){r(d)}},i=c=>c.done?o(c.value):Promise.resolve(c.value).then(s,a);i((t=t.apply(n,e)).next())});import{Command as si,Option as te}from"commander";import ai from"dedent";import{existsSync as li}from"fs";import*as k from"zod";var Ie=k.object({id:k.number().int(),role:k.string().optional(),name:k.string().optional(),numChildren:k.number().optional(),content:k.string().optional(),pathFromRoot:k.string().optional(),serializedForm:k.string().optional()});function Le(n){return n.name||n.role||n.content||n.serializedForm}import{z as me}from"zod";var Ut=me.object({thoughts:me.string(),result:me.boolean(),relevantElements:me.array(me.number()).optional()});import Ti from"string-argv";import{z as ge}from"zod";import hn from"dedent";import*as f from"zod";var B=(u=>(u.AI_ASSERTION="AI_ASSERTION",u.CLICK="CLICK",u.SELECT_OPTION="SELECT_OPTION",u.TYPE="TYPE",u.PRESS="PRESS",u.NAVIGATE="NAVIGATE",u.SCROLL_UP="SCROLL_UP",u.SCROLL_DOWN="SCROLL_DOWN",u.GO_BACK="GO_BACK",u.GO_FORWARD="GO_FORWARD",u.WAIT="WAIT",u.REFRESH="REFRESH",u.TAB="TAB",u.COOKIE="COOKIE",u.HOVER="HOVER",u.CAPTCHA="CAPTCHA",u.SUCCESS="SUCCESS",u))(B||{}),re=f.object({elementDescriptor:f.string(),a11yData:Ie.optional()}),D=f.object({thoughts:f.string().optional()}),gn=D.merge(f.object({type:f.literal("NAVIGATE"),url:f.string()})).describe("NAVIGATE <URL> - Go to the specified URL. Only navigate to URLs relevant to the user goal."),fn=D.merge(f.object({target:re.optional(),type:f.literal("SCROLL_UP"),useVision:f.boolean().default(!1)})).describe("SCROLL_UP [id] - Scroll up while hovering over the element with the specified id. If no id is provided, scroll the entire page."),yn=D.merge(f.object({target:re.optional(),type:f.literal("SCROLL_DOWN"),useVision:f.boolean().default(!1)})).describe("SCROLL_DOWN [id] - Scroll down while hovering over the element with the specified id. If no id is provided, scroll the entire page."),Sn=D.merge(f.object({type:f.literal("WAIT"),delay:f.number()})),wn=D.merge(f.object({type:f.literal("REFRESH")})),bn=D.merge(f.object({type:f.literal("GO_BACK")})),An=D.merge(f.object({type:f.literal("GO_FORWARD")})),En=D.merge(f.object({type:f.literal("CAPTCHA"),useVision:f.boolean().default(!1)})),Tn=D.merge(f.object({type:f.literal("CLICK"),target:re,doubleClick:f.boolean().default(!1),rightClick:f.boolean().default(!1),useVision:f.boolean().default(!1)})).describe(hn`CLICK <id> - click on the element that has the specified id.
2
+ var fn=Object.defineProperty,gn=Object.defineProperties;var yn=Object.getOwnPropertyDescriptors;var De=Object.getOwnPropertySymbols;var Dt=Object.prototype.hasOwnProperty,Pt=Object.prototype.propertyIsEnumerable;var Nt=(n,e,t)=>e in n?fn(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,T=(n,e)=>{for(var t in e||(e={}))Dt.call(e,t)&&Nt(n,t,e[t]);if(De)for(var t of De(e))Pt.call(e,t)&&Nt(n,t,e[t]);return n},M=(n,e)=>gn(n,yn(e));var pe=(n,e)=>{var t={};for(var o in n)Dt.call(n,o)&&e.indexOf(o)<0&&(t[o]=n[o]);if(n!=null&&De)for(var o of De(n))e.indexOf(o)<0&&Pt.call(n,o)&&(t[o]=n[o]);return t};var l=(n,e,t)=>new Promise((o,r)=>{var s=c=>{try{i(t.next(c))}catch(m){r(m)}},a=c=>{try{i(t.throw(c))}catch(m){r(m)}},i=c=>c.done?o(c.value):Promise.resolve(c.value).then(s,a);i((t=t.apply(n,e)).next())});import{Command as pi,Option as me}from"commander";import hi from"dedent";import{existsSync as fi}from"fs";import*as H from"zod";var Pe=H.object({id:H.number().int(),role:H.string().optional(),name:H.string().optional(),numChildren:H.number().optional(),content:H.string().optional(),pathFromRoot:H.string().optional(),serializedForm:H.string().optional()});function _e(n){return n.name||n.role||n.content||n.serializedForm}import{z as Ae}from"zod";var _t=Ae.object({thoughts:Ae.string(),result:Ae.boolean(),relevantElements:Ae.array(Ae.number()).optional()});import Oi from"string-argv";import{z as ee}from"zod";import Sn from"dedent";import*as g from"zod";var G=(d=>(d.AI_ASSERTION="AI_ASSERTION",d.CLICK="CLICK",d.SELECT_OPTION="SELECT_OPTION",d.TYPE="TYPE",d.PRESS="PRESS",d.NAVIGATE="NAVIGATE",d.SCROLL_UP="SCROLL_UP",d.SCROLL_DOWN="SCROLL_DOWN",d.GO_BACK="GO_BACK",d.GO_FORWARD="GO_FORWARD",d.WAIT="WAIT",d.REFRESH="REFRESH",d.TAB="TAB",d.COOKIE="COOKIE",d.HOVER="HOVER",d.CAPTCHA="CAPTCHA",d.SUCCESS="SUCCESS",d))(G||{}),he=g.object({elementDescriptor:g.string(),a11yData:Pe.optional()}),P=g.object({thoughts:g.string().optional()}),wn=P.merge(g.object({type:g.literal("NAVIGATE"),url:g.string()})).describe("NAVIGATE <URL> - Go to the specified URL. Only navigate to URLs relevant to the user goal."),bn=P.merge(g.object({target:he.optional(),type:g.literal("SCROLL_UP"),useVision:g.boolean().default(!1),deltaY:g.number().optional()})).describe("SCROLL_UP [id] - Scroll up while hovering over the element with the specified id. If no id is provided, scroll the entire page."),An=P.merge(g.object({target:he.optional(),type:g.literal("SCROLL_DOWN"),useVision:g.boolean().default(!1),deltaY:g.number().optional()})).describe("SCROLL_DOWN [id] - Scroll down while hovering over the element with the specified id. If no id is provided, scroll the entire page."),En=P.merge(g.object({type:g.literal("WAIT"),delay:g.number()})),Cn=P.merge(g.object({type:g.literal("REFRESH")})),Tn=P.merge(g.object({type:g.literal("GO_BACK")})),vn=P.merge(g.object({type:g.literal("GO_FORWARD")})),Rn=P.merge(g.object({type:g.literal("CAPTCHA"),useVision:g.boolean().default(!1)})),xn=P.merge(g.object({type:g.literal("CLICK"),target:he,doubleClick:g.boolean().default(!1),rightClick:g.boolean().default(!1),useVision:g.boolean().default(!1)})).describe(Sn`CLICK <id> - click on the element that has the specified id.
3
3
  You are NOT allowed to click on disabled, hidden or StaticText elements.
4
4
  Only click on elements on the Current Page.
5
5
  Only click on elements with the following tag names: button, input, link, image, generic.
6
6
  `.replaceAll(`
7
- `," ")),Cn=D.merge(f.object({type:f.literal("HOVER"),target:re,useVision:f.boolean().default(!1)})),vn=D.merge(f.object({type:f.literal("SELECT_OPTION"),target:re,option:f.string()})).describe('SELECT_OPTION <id> "<option>" - select an option from a combobox, listbox, or menu element on the page. Provide the id of the parent combobox, listbox, or menu element in <id>. Provide the name of the option in <option> enclosed by single quotes.'),Ft=D.merge(f.object({type:f.literal("AI_ASSERTION"),assertion:f.string(),useVision:f.boolean().default(!1),disableCache:f.boolean().default(!1),cancelOnFailure:f.boolean().default(!1)})),xn=f.object({clearContent:f.boolean().default(!0),pressKeysSequentially:f.boolean().default(!1)}),Rn=D.merge(f.object({type:f.literal("TYPE"),target:re,value:f.string(),pressEnter:f.boolean().default(!1),useVision:f.boolean().default(!1)})).merge(xn).describe('TYPE <id> "<text>" - type the specified text into the input with the specified id. The text should be specified by the user - do not use text from the EXAMPLES or generate text yourself. Make sure to include quotes around the text.'),In=D.merge(f.object({type:f.literal("PRESS"),value:f.string()})).describe('PRESS <key> - press the specified key, such as "ArrowLeft", "Enter", or "a". You must specify at least one key.'),Ln=D.merge(f.object({type:f.literal("TAB"),url:f.string()})),On=D.merge(f.object({type:f.literal("COOKIE"),value:f.string()})),Nn=D.merge(f.object({type:f.literal("SUCCESS"),condition:Ft.optional()})).describe("SUCCESS - the user goal has been successfully achieved"),ie=f.discriminatedUnion("type",[Tn,Rn,In,vn,gn,yn,fn,Nn]),Mn=f.discriminatedUnion("type",[bn,An,wn,Ft,Sn,Ln,On,Cn,En]),kt=f.discriminatedUnion("type",[...ie.options,...Mn.options]),Dn=D.merge(f.object({type:f.literal("FAILURE")})).describe("FAILURE - there are no commands to suggest that could make progress that have not already been tried before"),qe=f.discriminatedUnion("type",[...ie.options,Dn]);var pe=(i=>(i.AI_PROVIDER="AIProviderError",i.AI_TIMEOUT="AITimeoutError",i.JOB_TIMEOUT="JobTimeoutError",i.ACTION_FAILURE="ActionFailureError",i.ASSERTION_FAILURE="AssertionFailureError",i.WEB_AGENT_PLATFORM="InternalWebAgentError",i.UNKNOWN_PLATFORM="InternalPlatformError",i))(pe||{});var he=class extends Error{constructor(e,t={}){super(e,t),this.name="BrowserExecutionError"}};var Oe=class extends Error{constructor(e={}){super("Got empty a11y tree",e),this.name="EmptyA11yTreeError"}};var M=class extends Error{constructor(e,t,o={}){var s;let r=!1;for(let a of Object.values(pe))if(t.startsWith(a)){r=!0,e=a;break}r?super(t,o):super(`${e}: ${t}`,o),this.name="TestFailureError",this.stack=(s=this.stack)==null?void 0:s.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}};var Ri=ge.object({command:ge.string(),thoughts:ge.string()}),Ii=ge.string().pipe(ge.coerce.number());import*as N from"zod";var K="1.0.6",z=(o=>(o.AI_ACTION="AI_ACTION",o.PRESET_ACTION="PRESET_ACTION",o.MODULE="MODULE",o))(z||{}),fe=N.object({type:N.literal("AI_ACTION"),text:N.string(),commands:N.array(ie).optional()}),ye=N.object({type:N.literal("PRESET_ACTION"),command:kt}),Xe=N.object({type:N.literal("MODULE"),moduleId:N.string().uuid()}),Se=N.union([fe,ye]),Je=N.object({type:N.literal("RESOLVED_MODULE"),moduleId:N.string().uuid(),name:N.string(),steps:Se.array()}),we=N.union([fe,ye,Xe]),Qe=N.union([fe,ye,Je]);var _i=new Set(Object.values(B));var Ze={AI_ACTION:"AI action",MODULE:"Module",AI_ASSERTION:"AI check",CLICK:"Click",HOVER:"Hover",SELECT_OPTION:"Select",TYPE:"Type",PRESS:"Press",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",CAPTCHA:"Captcha",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",COOKIE:"Set cookie",SUCCESS:"Done"},zi={AI_ACTION:"Ask AI to plan and execute something on the page.",MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI whether something is true on the page.",CLICK:"Click on an element on the page based on a description.",HOVER:"Hover over an element on the page based on a description.",SELECT_OPTION:"Select an option from a dropdown based on a description.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Ctrl+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up one page.",SCROLL_DOWN:"Scroll down one page.",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.",COOKIE:"Set a cookie that will persist throughout the browser session",CAPTCHA:"Solve captchas on the page. This may take 10-60 seconds.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."};import*as v from"zod";var se=(s=>(s.SUCCESS="SUCCESS",s.FAILED="FAILED",s.RUNNING="RUNNING",s.IDLE="IDLE",s.CANCELLED="CANCELLED",s))(se||{}),Ne=(o=>(o.SUCCESS="SUCCESS",o.FAILED="FAILED",o.CANCELLED="CANCELLED",o))(Ne||{}),Pn=v.object({beforeUrl:v.string(),beforeScreenshot:v.string().or(v.instanceof(Buffer)),afterUrl:v.string().optional(),afterScreenshot:v.string().or(v.instanceof(Buffer)).optional(),startedAt:v.coerce.date(),finishedAt:v.coerce.date(),viewport:v.object({height:v.number(),width:v.number()}),status:v.nativeEnum(Ne),message:v.string().optional(),elementInteracted:v.string().optional()}),et=v.object({startedAt:v.coerce.date(),finishedAt:v.coerce.date(),status:v.nativeEnum(se),message:v.string().optional(),userAgent:v.string().optional()}),tt=ye.merge(et).merge(v.object({results:Pn.array()})),$t=fe.merge(et).merge(v.object({results:tt.array()})),_n=Xe.merge(et).merge(v.object({results:v.union([$t,tt]).array()})),Me=v.discriminatedUnion("type",[$t,tt,_n]);function zn(n,e){return n.length<e?n:n.slice(0,e-3)+"[...]"}function Y(n){var e,t,o;switch(n.type){case"SUCCESS":return(e=n.condition)!=null&&e.assertion?`Check success condition: ${n.condition.assertion}`:"All commands completed";case"NAVIGATE":return`Go to URL: ${zn(n.url,30)}`;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 one page${n.target?` in the container of: ${n.target.elementDescriptor}`:""}`;case"SCROLL_UP":return`Scroll up one page${n.target?` in the container of: ${n.target.elementDescriptor}`:""}`;case"WAIT":return`Wait for ${n.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":return`Click on '${n.target.elementDescriptor}'`;case"TYPE":{let s="";return(t=n.target.a11yData)!=null&&t.serializedForm?s=`in element: ${n.target.a11yData.serializedForm}`:n.target.elementDescriptor.length>0&&(s=`in element: ${n.target.elementDescriptor}`),`Type '${n.value}' ${s}`}case"HOVER":{let s="";return(o=n.target.a11yData)!=null&&o.serializedForm?s=` over element: ${n.target.a11yData.serializedForm}`:n.target.elementDescriptor.length>0&&(s=` over element: ${n.target.elementDescriptor}`),`Hover${s}`}case"PRESS":return`Press '${n.value}'`;case"SELECT_OPTION":return`Select option '${n.option}' in '${n.target.elementDescriptor}'`;case"TAB":return`Switch to tab: ${n.url}`;case"COOKIE":return`Set cookie: ${n.value}`;case"AI_ASSERTION":return`${n.useVision?"Visual assertion":"Assertion"}: '${n.assertion}'`;default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}import*as $ from"zod";import*as X from"zod";var Ht=X.object({type:X.nativeEnum(z),generatedStep:ie.optional(),serializedCommand:X.string().optional(),elementInteracted:X.string().optional()});var ae=$.object({goal:$.string(),url:$.string(),browserState:$.string(),history:$.string(),numPrevious:$.number(),lastCommand:Ht.or($.null())});import{parseString as Un}from"set-cookie-parser";function Bt(n){let e=Un(n);if(!e.name)throw new Error("Name missing from cookie");if(!e.value)throw new Error("Value missing from cookie");let t;if(e.sameSite){let r=e.sameSite.trim().toLowerCase();if(r==="strict")t="Strict";else if(r==="lax")t="Lax";else if(r==="none")t="None";else throw new Error(`Invalid sameSite setting in cookie: ${r}`)}return!e.path&&e.domain&&(e.path="/"),O(C({},e),{expires:e.expires?e.expires.getTime()/1e3:void 0,sameSite:t})}import{z as U}from"zod";var Fn="1.0.0",jt=U.object({run:U.string().describe("Run a single command in the shell. The working directory will be set to where the CLI was invoked from."),waitForCompletion:U.boolean().optional().describe("Defaults to true")}),Gt=U.object({type:U.literal("momentic/fixture"),schemaVersion:U.string(),name:U.string(),description:U.string().optional(),setup:U.object({steps:jt.array(),timeout:U.number().optional().describe("Timeout for all steps in seconds")}).optional(),teardown:U.object({steps:jt.array(),timeout:U.number().optional().describe("Timeout for all steps in seconds")}).optional()}),Zi={type:"momentic/fixture",schemaVersion:Fn,name:"example",description:"An example fixture",setup:{steps:[{run:"./scripts/seed_db.sh",waitForCompletion:!0},{run:"npm run start",waitForCompletion:!1}],timeout:30},teardown:{steps:[{run:"./scripts/shutdown_db.sh"}]}};import{z as kn}from"zod";var os=kn.string().array();import*as G from"zod";var Vt=G.object({thoughts:G.string(),id:G.number().int(),options:G.array(G.string()).optional()});var Wt={DEBUG:0,INFO:1,WARN:2,ERROR:3},$n={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},Hn={0:"\x1B[90m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},nt=class n{constructor(e,t){this.minLogLevel=e,this.logBindings=t}log(e,...t){let o=$n[e],r;Array.isArray(t[0])?(r=t[0],t=t.slice(1)):typeof t[0]=="object"&&!(t[0]instanceof Error)&&(r=C(C({},t[0]),this.logBindings),t=t.slice(1));let s=Hn[e],a=[`${s}[${new Date().toTimeString().slice(0,8)}][${o}]`];if(e!==0&&a.push("\x1B[39m"),a.push(...t),console.log(...a),r&&!Array.isArray(r))for(let[i,c]of Object.entries(r)){let d=c;typeof c=="object"&&(d=JSON.stringify(c,void 0,2),d=d.split(`
8
- `).map((h,p)=>p>0?` ${h}`:h).join(`
9
- `)),console.log(e===0?`${s} ${i}:`:` ${i}:`,d)}else if(r)for(let i of r){let c=i;typeof i=="object"&&(c=JSON.stringify(i,void 0,2),c=c.split(`
10
- `).map((d,h)=>h>0?` ${d}`:d).join(`
11
- `)),console.log(e===0?`${s} `:" ",c)}e===0&&process.stdout.write("\x1B[39m")}setMinLevel(e){this.minLogLevel=e}info(...e){1<this.minLogLevel||this.log(1,...e)}debug(...e){0<this.minLogLevel||this.log(0,...e)}warn(...e){2<this.minLogLevel||this.log(2,...e)}error(...e){3<this.minLogLevel||this.log(3,...e)}child(e){return new n(this.minLogLevel,C(C({},this.logBindings),e))}flush(){}bindings(){return this.logBindings}},S=new nt(1,{});import{z as V}from"zod";var Bn=V.object({id:V.string(),createdAt:V.coerce.date(),createdBy:V.string(),organizationId:V.string(),name:V.string(),schemaVersion:V.string(),numSteps:V.number()}),cs=V.object({steps:Se.array()}).merge(Bn.omit({numSteps:!0}));import*as y from"zod";import{z as I}from"zod";var rt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},it={PENDING:"PENDING",RUNNING:"RUNNING",PASSED:"PASSED",FAILED:"FAILED",CANCELLED:"CANCELLED"},jn={PASSED:"PASSED",FAILED:"FAILED"},De=I.string().pipe(I.coerce.date()).or(I.date()),Gn=I.object({id:I.string(),createdAt:De,createdBy:I.string(),organizationId:I.string(),scheduledAt:De.or(I.null()),startedAt:De.or(I.null()),finishedAt:De.or(I.null()),testId:I.string().or(I.null()),status:I.nativeEnum(it),expectedStatus:I.nativeEnum(jn).or(I.null()),runKey:I.string(),trigger:I.nativeEnum(rt),attempts:I.number(),test:I.object({name:I.string(),id:I.string()}).or(I.null())}),st=Gn.merge(I.object({results:Me.array(),test:I.object({name:I.string(),id:I.string(),baseUrl:I.string()}).or(I.null())}));import{z as P}from"zod";import{z as Pe}from"zod";var Kt=Pe.object({name:Pe.string(),fixtures:Pe.array(Pe.string().describe("Name of the fixture (must be available locally in the fixtures directory).")).optional()});import{isValidCron as Vn}from"cron-validator";import{z as H}from"zod";var _e=H.object({availableAsModule:H.boolean().default(!1),disableAICaching:H.boolean().default(!1)}),Yt=H.object({cron:H.string().refine(n=>Vn(n),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:H.boolean().default(!1),timeZone:H.string().default("America/Los_Angeles"),jobKey:H.string().optional()}),qt=H.object({onSuccess:H.boolean().default(!1),onFailure:H.boolean().default(!0)});var Wn=P.string().min(1).max(255).superRefine((n,e)=>{try{Xn(n)}catch(t){return e.addIssue({code:P.ZodIssueCode.custom,message:t.message,fatal:!0}),P.NEVER}}),le=P.object({id:P.string(),name:Wn,baseUrl:P.string(),schemaVersion:P.string(),advanced:_e,retries:P.number(),envSettings:Kt.array().optional()}),Ts=le.pick({name:!0,baseUrl:!0,retries:!0,advanced:!0}),Kn=P.object({createdAt:P.coerce.date(),updatedAt:P.coerce.date(),schedule:Yt,notification:qt,createdBy:P.string(),organizationId:P.string()}),Xt=le.merge(Kn).merge(P.object({steps:P.array(Qe)})),Jt=le.merge(P.object({steps:P.array(Qe)}));var Yn=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,qn=["modules","fixtures"];function Xn(n){if(n=n.toLowerCase().trim(),n.length===0||n.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"\/\\|?*\x00]/.test(n))throw new Error("Name can only contain alphanumeric characters, dashes, and underscores.");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(n))throw new Error(`"${n}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(n)||/^\s|\s$/.test(n))throw new Error("Name cannot start or end with a space or dot.");if(n.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(qn.includes(n))throw new Error("'modules' is a reserved folder name in Momentic. Please choose a different name.");if(n.match(Yn))throw new Error("Name cannot be a UUID. Please choose a different name.")}var be=y.object({disableCache:y.boolean()}),Ms=y.object({error:y.boolean(),reason:y.string(),message:y.string()}),Ds=ae.merge(be),Qt=qe,Ps=y.discriminatedUnion("vision",[ae.merge(be).merge(y.object({vision:y.literal(!1)})),ae.pick({goal:!0,url:!0}).merge(be).merge(y.object({screenshot:y.string(),vision:y.literal(!0)}))]),at=Ut,_s=ae.pick({browserState:!0,goal:!0}).merge(be),lt=Vt,zs=ae.pick({goal:!0,url:!0}).merge(be),Zt=y.string().array(),Us=y.object({testPaths:y.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),all:y.boolean().optional()}),eo=y.object({message:y.string(),queuedTests:y.object({name:y.string(),id:y.string()}).array()}),to=Xt,oo=y.string().array(),Fs=y.union([y.object({paths:y.string().array().describe("run specific test paths (e.g. todo-test)")}),y.object({path:y.string().describe("deprecated; present for backcompat")}),y.object({all:y.boolean().describe("run all tests")})]),no=y.object({tests:y.record(y.string().describe("Test name"),y.string().describe("Test YAML")),modules:y.record(y.string().describe("Module name"),y.string().describe("Module YAML"))}),Jn=y.object({test:y.string().describe("test YAML"),modules:y.record(y.string().describe("moduleId"),y.string().describe("module YAML"))}),ks=Jn.array();var $s=y.object({testPath:y.string(),testId:y.string()}).partial().merge(y.object({trigger:y.nativeEnum(rt)})),ro=st,io=st,Hs=y.object({startedAt:y.coerce.date(),finishedAt:y.coerce.date(),results:Me.array(),status:y.nativeEnum(it)}).partial(),Bs=y.object({screenshot:y.string()}),so=y.object({key:y.string()});function ze(n){switch(n.type){case"AI_ACTION":return`AI action: ${n.text}`;case"PRESET_ACTION":return Y(n.command);case"RESOLVED_MODULE":return`Module: ${n.moduleId}`}}import{stringify as Xs}from"yaml";import{z as L}from"zod";var na=L.object({test:L.string().describe("YAML for the test, including metadata and steps"),modules:L.record(L.string(),L.string()).describe("Map of module name to YAML for the module")}),ra=le.merge(L.object({steps:we.array(),fileType:L.literal("momentic/test")})),ia=Je.omit({type:!0}).merge(L.object({schemaVersion:L.string(),fileType:L.literal("momentic/module")})),sa=le.merge(L.object({steps:L.array(L.record(L.string(),L.unknown()))})),aa=L.object({moduleId:L.string().uuid(),name:L.string(),schemaVersion:L.string(),steps:L.array(L.record(L.string(),L.unknown()))});var ao="0.0.19";var W="v1",ce=class{constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey}getRun(e){return l(this,null,function*(){let t=yield this.sendRequest(`/${W}/runs/${e}`,{method:"GET"});return io.parse(t)})}createRun(e){return l(this,null,function*(){let t=yield this.sendRequest(`/${W}/runs`,{method:"POST",body:e});return ro.parse(t)})}updateRun(e,t){return l(this,null,function*(){yield this.sendRequest(`/${W}/runs/${e}`,{method:"PATCH",body:t})})}getTest(e){return l(this,null,function*(){let t=yield this.sendRequest(`/${W}/tests/${e}`,{method:"GET"});return to.parse(t)})}getAllTestIds(){return l(this,null,function*(){let e=yield this.sendRequest(`/${W}/tests`,{method:"GET"});return oo.parse(e)})}getTestYAMLExport(e){return l(this,null,function*(){let t=yield this.sendRequest(`/${W}/tests/export`,{method:"POST",body:e});return no.parse(t)})}updateTestWithYAML(e){return l(this,null,function*(){yield this.sendRequest(`/${W}/tests/update`,{method:"POST",body:e})})}queueTests(e){return l(this,null,function*(){let t=yield this.sendRequest(`/${W}/tests/queue`,{method:"POST",body:e});return eo.parse(t)})}uploadScreenshot(e){return l(this,null,function*(){let t=yield this.sendRequest(`/${W}/screenshots`,{method:"POST",body:e});return so.parse(t)})}sendRequest(e,t){return l(this,null,function*(){let o=yield fetch(`${this.baseURL}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!o.ok)throw new Error(`Request to ${e} failed with status ${o.status}: ${yield o.text()}`);return o.status===204?o.text():o.json()})}};import{existsSync as tr,mkdirSync as ct,statSync as or}from"fs";import{join as lo}from"path";import Zn from"chalk";import er from"readline/promises";function de(n,e){return l(this,null,function*(){if(process.env.CI)return!0;let t=er.createInterface({input:process.stdin,output:process.stdout});n=`${n} (y/N) `;let o=e?Zn.bold.yellow(n):n,r=yield t.question(o);return t.close(),r.toLowerCase()==="y"})}var Fe="momentic",ke="modules",nr="fixtures",Ue=Fe,dt=lo(Fe,ke),ut=lo(Fe,nr);function rr(n){return tr(n)&&or(n).isDirectory()}function mt(n=!1){return l(this,null,function*(){rr(Ue)||(!n&&!(yield de(`A '${Fe}' folder was not found in the current directory. Setup the required Momentic folder structure?`))&&(S.error("Setup cancelled"),process.exit(1)),ct(Ue),ct(dt),ct(ut),S.info("Setup complete!"))})}import{registry as pt}from"playwright-core/lib/server";function ir(n){let e=[],t=[];for(let o of n){let r=pt.findExecutable(o);!r||r.installType==="none"?e.push(o):t.push(r)}return t}function co(){return l(this,null,function*(){let n=ir(["chromium"]);yield pt.installDeps(n,!1),yield pt.install(n,!1)})}import{Argument as ht,Option as Ae}from"commander";var $e=new Ae("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var.").env("MOMENTIC_API_KEY").makeOptionMandatory(!0),He=new Ae("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise.").default("https://api.momentic.ai"),gt=new Ae("-y, --yes","Skip confirmation prompts.").env("CI").default(!1),uo=new Ae("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").default(!0),ft=new Ae("-a --all","Select all tests in your organization from Momentic Cloud. Cannot be used together with <tests> arguments.").default(!1).preset(!0),mo=new ht("<tests...>",`One or more test paths to pull from Momentic Cloud.
7
+ `," ")),In=P.merge(g.object({type:g.literal("HOVER"),target:he,useVision:g.boolean().default(!1)})),Ln=P.merge(g.object({type:g.literal("SELECT_OPTION"),target:he,option:g.string()})).describe('SELECT_OPTION <id> "<option>" - select an option from a combobox, listbox, or menu element on the page. Provide the id of the parent combobox, listbox, or menu element in <id>. Do NOT provide the id of the option: instead, provide the name of the option in <option> enclosed by single quotes.'),zt=P.merge(g.object({type:g.literal("AI_ASSERTION"),assertion:g.string(),useVision:g.boolean().default(!1),disableCache:g.boolean().default(!1),cancelOnFailure:g.boolean().default(!1)})),On=g.object({clearContent:g.boolean().default(!0),pressKeysSequentially:g.boolean().default(!1)}),Mn=P.merge(g.object({type:g.literal("TYPE"),target:he,value:g.string(),pressEnter:g.boolean().default(!1),useVision:g.boolean().default(!1)})).merge(On).describe('TYPE <id> "<text>" - type the specified text into the input with the specified id. The text should be specified by the user - do not use text from the EXAMPLES or generate text yourself. Make sure to include quotes around the text.'),Nn=P.merge(g.object({type:g.literal("PRESS"),value:g.string()})).describe('PRESS <key> - press the specified key, such as "ArrowLeft", "Enter", or "a". You must specify at least one key.'),Dn=P.merge(g.object({type:g.literal("TAB"),url:g.string()})),Pn=P.merge(g.object({type:g.literal("COOKIE"),value:g.string()})),_n=P.merge(g.object({type:g.literal("SUCCESS"),condition:zt.optional()})).describe("SUCCESS - the user goal has been successfully achieved"),fe=g.discriminatedUnion("type",[xn,Mn,Nn,Ln,wn,An,bn,_n]),zn=g.discriminatedUnion("type",[Tn,vn,Cn,zt,En,Dn,Pn,In,Rn]),Ft=g.discriminatedUnion("type",[...fe.options,...zn.options]),Fn=P.merge(g.object({type:g.literal("FAILURE")})).describe("FAILURE - there are no commands to suggest that could make progress that have not already been tried before"),Qe=g.discriminatedUnion("type",[...fe.options,Fn]);var Ee=(i=>(i.AI_PROVIDER="AIProviderError",i.AI_TIMEOUT="AITimeoutError",i.JOB_TIMEOUT="JobTimeoutError",i.ACTION_FAILURE="ActionFailureError",i.ASSERTION_FAILURE="AssertionFailureError",i.WEB_AGENT_PLATFORM="InternalWebAgentError",i.UNKNOWN_PLATFORM="InternalPlatformError",i))(Ee||{});var Ce=class extends Error{constructor(e,t={}){super(e,t),this.name="BrowserExecutionError"}};var ze=class extends Error{constructor(e={}){super("Got empty a11y tree",e),this.name="EmptyA11yTreeError"}};var D=class extends Error{constructor(e,t,o={}){var s;let r=!1;for(let a of Object.values(Ee))if(t.startsWith(a)){r=!0,e=a;break}r?super(t,o):super(`${e}: ${t}`,o),this.name="TestFailureError",this.stack=(s=this.stack)==null?void 0:s.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}};var Pi=ee.object({command:ee.string(),thoughts:ee.string()}),_i=ee.string().pipe(ee.coerce.number());var Ut=ee.object({phrase:ee.string()});import*as N from"zod";var W="1.0.6",k=(o=>(o.AI_ACTION="AI_ACTION",o.PRESET_ACTION="PRESET_ACTION",o.MODULE="MODULE",o))(k||{}),Te=N.object({type:N.literal("AI_ACTION"),text:N.string(),commands:N.array(fe).optional()}),ve=N.object({type:N.literal("PRESET_ACTION"),command:Ft}),Ze=N.object({type:N.literal("MODULE"),moduleId:N.string().uuid()}),te=N.union([Te,ve]),et=N.object({type:N.literal("RESOLVED_MODULE"),moduleId:N.string().uuid(),name:N.string(),steps:te.array()}),oe=N.union([Te,ve,Ze]),Re=N.union([Te,ve,et]);var Bi=new Set(Object.values(G));var tt={AI_ACTION:"AI action",MODULE:"Module",AI_ASSERTION:"AI check",CLICK:"Click",HOVER:"Hover",SELECT_OPTION:"Select",TYPE:"Type",PRESS:"Press",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",CAPTCHA:"Captcha",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",COOKIE:"Set cookie",SUCCESS:"Done"},ji={AI_ACTION:"Ask AI to plan and execute something on the page.",MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI whether something is true on the page.",CLICK:"Click on an element on the page based on a description.",HOVER:"Hover over an element on the page based on a description.",SELECT_OPTION:"Select an option from a dropdown based on a description.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Ctrl+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up one page.",SCROLL_DOWN:"Scroll down one page.",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.",COOKIE:"Set a cookie that will persist throughout the browser session",CAPTCHA:"Solve captchas on the page. This may take 10-60 seconds.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."};import*as x from"zod";var ge=(s=>(s.SUCCESS="SUCCESS",s.FAILED="FAILED",s.RUNNING="RUNNING",s.IDLE="IDLE",s.CANCELLED="CANCELLED",s))(ge||{}),Fe=(o=>(o.SUCCESS="SUCCESS",o.FAILED="FAILED",o.CANCELLED="CANCELLED",o))(Fe||{}),Un=x.object({beforeUrl:x.string(),beforeScreenshot:x.string().or(x.instanceof(Buffer)),afterUrl:x.string().optional(),afterScreenshot:x.string().or(x.instanceof(Buffer)).optional(),startedAt:x.coerce.date(),finishedAt:x.coerce.date(),viewport:x.object({height:x.number(),width:x.number()}),status:x.nativeEnum(Fe),message:x.string().optional(),elementInteracted:x.string().optional()}),ot=x.object({startedAt:x.coerce.date(),finishedAt:x.coerce.date(),status:x.nativeEnum(ge),message:x.string().optional(),userAgent:x.string().optional()}),nt=ve.merge(ot).merge(x.object({results:Un.array()})),kt=Te.merge(ot).merge(x.object({results:nt.array()})),kn=Ze.merge(ot).merge(x.object({results:x.union([kt,nt]).array()})),Ue=x.discriminatedUnion("type",[kt,nt,kn]);function $n(n,e){return n.length<e?n:n.slice(0,e-3)+"[...]"}function ye(n){var e,t,o;switch(n.type){case"SUCCESS":return(e=n.condition)!=null&&e.assertion?`Check success condition: ${n.condition.assertion}`:"All commands completed";case"NAVIGATE":return`Go to URL: ${$n(n.url,30)}`;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 one page${n.target?` in the container of: ${n.target.elementDescriptor}`:""}`;case"SCROLL_UP":return`Scroll up one page${n.target?` in the container of: ${n.target.elementDescriptor}`:""}`;case"WAIT":return`Wait for ${n.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":return`Click on '${n.target.elementDescriptor}'`;case"TYPE":{let s="";return(t=n.target.a11yData)!=null&&t.serializedForm?s=`in element: ${n.target.a11yData.serializedForm}`:n.target.elementDescriptor.length>0&&(s=`in element: ${n.target.elementDescriptor}`),`Type '${n.value}' ${s}`}case"HOVER":{let s="";return(o=n.target.a11yData)!=null&&o.serializedForm?s=` over element: ${n.target.a11yData.serializedForm}`:n.target.elementDescriptor.length>0&&(s=` over element: ${n.target.elementDescriptor}`),`Hover${s}`}case"PRESS":return`Press '${n.value}'`;case"SELECT_OPTION":return`Select option '${n.option}' in '${n.target.elementDescriptor}'`;case"TAB":return`Switch to tab: ${n.url}`;case"COOKIE":return`Set cookie: ${n.value}`;case"AI_ASSERTION":return`${n.useVision?"Visual assertion":"Assertion"}: '${n.assertion}'`;default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}import*as B from"zod";import*as ne from"zod";var $t=ne.object({type:ne.nativeEnum(k),generatedStep:fe.optional(),serializedCommand:ne.string().optional(),elementInteracted:ne.string().optional()});var Q=B.object({goal:B.string(),url:B.string(),browserState:B.string(),history:B.string(),numPrevious:B.number(),lastCommand:$t.or(B.null())});import{parseString as Hn}from"set-cookie-parser";function Ht(n){let e=Hn(n);if(!e.name)throw new Error("Name missing from cookie");if(!e.value)throw new Error("Value missing from cookie");let t;if(e.sameSite){let r=e.sameSite.trim().toLowerCase();if(r==="strict")t="Strict";else if(r==="lax")t="Lax";else if(r==="none")t="None";else throw new Error(`Invalid sameSite setting in cookie: ${r}`)}return!e.path&&e.domain&&(e.path="/"),M(T({},e),{expires:e.expires?e.expires.getTime()/1e3:void 0,sameSite:t})}import{z as $}from"zod";var Bn="1.0.0",Bt=$.object({run:$.string().describe("Run a single command in the shell. The working directory will be set to where the CLI was invoked from."),waitForCompletion:$.boolean().optional().describe("Defaults to true")}),jt=$.object({type:$.literal("momentic/fixture"),schemaVersion:$.string(),name:$.string(),description:$.string().optional(),setup:$.object({steps:Bt.array(),timeout:$.number().optional().describe("Timeout for all steps in seconds")}).optional(),teardown:$.object({steps:Bt.array(),timeout:$.number().optional().describe("Timeout for all steps in seconds")}).optional()}),ss={type:"momentic/fixture",schemaVersion:Bn,name:"example",description:"An example fixture",setup:{steps:[{run:"./scripts/seed_db.sh",waitForCompletion:!0},{run:"npm run start",waitForCompletion:!1}],timeout:30},teardown:{steps:[{run:"./scripts/shutdown_db.sh"}]}};import{z as jn}from"zod";var cs=jn.string().array();import{z}from"zod";import{z as _}from"zod";import{z as ke}from"zod";var Gt=ke.object({name:ke.string(),fixtures:ke.array(ke.string().describe("Name of the fixture (must be available locally in the fixtures directory).")).optional()});import{isValidCron as Gn}from"cron-validator";import{z as j}from"zod";var $e=j.object({availableAsModule:j.boolean().default(!1),disableAICaching:j.boolean().default(!1)}),Vt=j.object({cron:j.string().refine(n=>Gn(n),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:j.boolean().default(!1),timeZone:j.string().default("America/Los_Angeles"),jobKey:j.string().optional()}),Wt=j.object({onSuccess:j.boolean().default(!1),onFailure:j.boolean().default(!0)});var Vn=_.string().min(1).max(255).superRefine((n,e)=>{try{qn(n)}catch(t){return e.addIssue({code:_.ZodIssueCode.custom,message:t.message,fatal:!0}),_.NEVER}}),re=_.object({id:_.string(),name:Vn,baseUrl:_.string(),schemaVersion:_.string(),advanced:$e,retries:_.number(),envSettings:Gt.array().optional()}),bs=re.pick({name:!0,baseUrl:!0,retries:!0,advanced:!0}),Wn=_.object({createdAt:_.coerce.date(),updatedAt:_.coerce.date(),schedule:Vt,notification:Wt,createdBy:_.string(),organizationId:_.string()}),Kt=re.merge(Wn).merge(_.object({steps:_.array(Re)})),it=re.merge(_.object({steps:_.array(Re)})),As=re.merge(_.object({steps:oe.array()}));var Kn=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Yn=["modules","fixtures"];function qn(n){if(n=n.toLowerCase().trim(),n.length===0||n.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"\/\\|?*\x00]/.test(n))throw new Error("Name can only contain alphanumeric characters, dashes, and underscores.");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(n))throw new Error(`"${n}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(n)||/^\s|\s$/.test(n))throw new Error("Name cannot start or end with a space or dot.");if(n.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(Yn.includes(n))throw new Error("'modules' is a reserved folder name in Momentic. Please choose a different name.");if(n.match(Kn))throw new Error("Name cannot be a UUID. Please choose a different name.")}var xe="momentic",Yt="modules",qt="fixtures",Xn="momentic-frame",Rs=`${Xn}-0`,xs=z.array(z.object({path:z.string(),lastModified:z.date(),createdAt:z.date()})),Is=z.object({name:z.string(),steps:Re.array()}),Ls=z.object({name:z.string(),baseUrl:z.string().url()});var Os=z.object({name:z.string(),steps:te.array()}),Ms=z.array(z.object({name:z.string(),moduleId:z.string().uuid(),numSteps:z.number()}));import*as K from"zod";var Xt=K.object({thoughts:K.string(),id:K.number().int(),options:K.array(K.string()).optional()});var Jt={DEBUG:0,INFO:1,WARN:2,ERROR:3},Jn={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},Qn={0:"\x1B[90m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},st=class n{constructor(e,t){this.minLogLevel=e,this.logBindings=t}log(e,...t){let o=Jn[e],r;Array.isArray(t[0])?(r=t[0],t=t.slice(1)):typeof t[0]=="object"&&!(t[0]instanceof Error)&&(r=T(T({},t[0]),this.logBindings),t=t.slice(1));let s=Qn[e],a=[`${s}[${new Date().toTimeString().slice(0,8)}][${o}]`];if(e!==0&&a.push("\x1B[39m"),a.push(...t),console.log(...a),r&&!Array.isArray(r))for(let[i,c]of Object.entries(r)){let m=c;c instanceof Error?m=c.message:typeof c=="object"&&(m=JSON.stringify(c,void 0,2),m=m.split(`
8
+ `).map((u,h)=>h>0?` ${u}`:u).join(`
9
+ `)),console.log(e===0?`${s} ${i}:`:` ${i}:`,m)}else if(r)for(let i of r){let c=i;typeof i=="object"&&(c=JSON.stringify(i,void 0,2),c=c.split(`
10
+ `).map((m,u)=>u>0?` ${m}`:m).join(`
11
+ `)),console.log(e===0?`${s} `:" ",c)}e===0&&process.stdout.write("\x1B[39m")}setMinLevel(e){this.minLogLevel=e}info(...e){1<this.minLogLevel||this.log(1,...e)}debug(...e){0<this.minLogLevel||this.log(0,...e)}warn(...e){2<this.minLogLevel||this.log(2,...e)}error(...e){3<this.minLogLevel||this.log(3,...e)}child(e){return new n(this.minLogLevel,T(T({},this.logBindings),e))}flush(){}bindings(){return this.logBindings}},A=new st(1,{});import{z as Y}from"zod";var Zn=Y.object({id:Y.string(),createdAt:Y.coerce.date(),createdBy:Y.string(),organizationId:Y.string(),name:Y.string(),schemaVersion:Y.string(),numSteps:Y.number()}),Us=Y.object({steps:te.array()}).merge(Zn.omit({numSteps:!0}));import*as y from"zod";import{z as I}from"zod";var at={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},lt={PENDING:"PENDING",RUNNING:"RUNNING",PASSED:"PASSED",FAILED:"FAILED",CANCELLED:"CANCELLED"},er={PASSED:"PASSED",FAILED:"FAILED"},He=I.string().pipe(I.coerce.date()).or(I.date()),tr=I.object({id:I.string(),createdAt:He,createdBy:I.string(),organizationId:I.string(),scheduledAt:He.or(I.null()),startedAt:He.or(I.null()),finishedAt:He.or(I.null()),testId:I.string().or(I.null()),status:I.nativeEnum(lt),expectedStatus:I.nativeEnum(er).or(I.null()),runKey:I.string(),trigger:I.nativeEnum(at),attempts:I.number(),test:I.object({name:I.string(),id:I.string()}).or(I.null())}),ct=tr.merge(I.object({results:Ue.array(),test:I.object({name:I.string(),id:I.string(),baseUrl:I.string()}).or(I.null())}));var ie=y.object({disableCache:y.boolean()}),Js=y.object({error:y.boolean(),reason:y.string(),message:y.string()}),Qs=Q.merge(ie),Qt=Qe,Zs=y.discriminatedUnion("vision",[Q.merge(ie).merge(y.object({vision:y.literal(!1)})),Q.pick({goal:!0,url:!0}).merge(ie).merge(y.object({screenshot:y.string(),vision:y.literal(!0)}))]),dt=_t,ea=Q.pick({browserState:!0,goal:!0}).merge(ie),ta=Q.pick({goal:!0}).merge(ie).merge(y.object({screenshot:y.string().describe("base64 encoded image"),hintActivatedScreenshot:y.string().describe("base64 encoded image")})),mt=Xt,oa=Q.pick({goal:!0,url:!0}).merge(ie),Zt=y.string().array(),na=Q.pick({goal:!0,browserState:!0}).merge(ie),eo=Ut,ra=y.object({testPaths:y.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),all:y.boolean().optional()}),to=y.object({message:y.string(),queuedTests:y.object({name:y.string(),id:y.string()}).array()}),oo=Kt,no=y.string().array(),ia=y.union([y.object({paths:y.string().array().describe("run specific test paths (e.g. todo-test)")}),y.object({path:y.string().describe("deprecated; present for backcompat")}),y.object({all:y.boolean().describe("run all tests")})]),ro=y.object({tests:y.record(y.string().describe("Test name"),y.string().describe("Test YAML")),modules:y.record(y.string().describe("Module name"),y.string().describe("Module YAML"))}),or=y.object({test:y.string().describe("test YAML"),modules:y.record(y.string().describe("moduleId"),y.string().describe("module YAML"))}),sa=or.array();var aa=y.object({testPath:y.string(),testId:y.string()}).partial().merge(y.object({trigger:y.nativeEnum(at)})),io=ct,so=ct,la=y.object({startedAt:y.coerce.date(),finishedAt:y.coerce.date(),results:Ue.array(),status:y.nativeEnum(lt)}).partial(),ca=y.object({screenshot:y.string()}),ao=y.object({key:y.string()}),da=y.object({orgId:y.string()});function Be(n){switch(n.type){case"AI_ACTION":return`AI action: ${n.text}`;case"PRESET_ACTION":return ye(n.command);case"RESOLVED_MODULE":return`Module: ${n.moduleId}`}}import{stringify as Sa}from"yaml";import{z as O}from"zod";var va=O.object({test:O.string().describe("YAML for the test, including metadata and steps"),modules:O.record(O.string(),O.string()).describe("Map of module name to YAML for the module")}),Ra=re.merge(O.object({steps:oe.array(),fileType:O.literal("momentic/test")})),xa=et.omit({type:!0}).merge(O.object({schemaVersion:O.string(),fileType:O.literal("momentic/module")})),Ia=re.merge(O.object({steps:O.array(O.record(O.string(),O.unknown()))})),La=O.object({moduleId:O.string().uuid(),name:O.string(),schemaVersion:O.string(),steps:O.array(O.record(O.string(),O.unknown()))});var lo="0.0.20";var q="v1",Se=class{constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey}getRun(e){return l(this,null,function*(){let t=yield this.sendRequest(`/${q}/runs/${e}`,{method:"GET"});return so.parse(t)})}createRun(e){return l(this,null,function*(){let t=yield this.sendRequest(`/${q}/runs`,{method:"POST",body:e});return io.parse(t)})}updateRun(e,t){return l(this,null,function*(){yield this.sendRequest(`/${q}/runs/${e}`,{method:"PATCH",body:t})})}getTest(e){return l(this,null,function*(){let t=yield this.sendRequest(`/${q}/tests/${e}`,{method:"GET"});return oo.parse(t)})}getAllTestIds(){return l(this,null,function*(){let e=yield this.sendRequest(`/${q}/tests`,{method:"GET"});return no.parse(e)})}getTestYAMLExport(e){return l(this,null,function*(){let t=yield this.sendRequest(`/${q}/tests/export`,{method:"POST",body:e});return ro.parse(t)})}updateTestWithYAML(e){return l(this,null,function*(){yield this.sendRequest(`/${q}/tests/update`,{method:"POST",body:e})})}queueTests(e){return l(this,null,function*(){let t=yield this.sendRequest(`/${q}/tests/queue`,{method:"POST",body:e});return to.parse(t)})}uploadScreenshot(e){return l(this,null,function*(){let t=yield this.sendRequest(`/${q}/screenshots`,{method:"POST",body:e});return ao.parse(t)})}sendRequest(e,t){return l(this,null,function*(){let o=yield fetch(`${this.baseURL}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!o.ok)throw new Error(`Request to ${e} failed with status ${o.status}: ${yield o.text()}`);return o.status===204?o.text():o.json()})}};import{existsSync as sr,mkdirSync as ut,statSync as ar}from"fs";import{join as co}from"path";import rr from"chalk";import ir from"readline/promises";function we(n,e){return l(this,null,function*(){if(process.env.CI)return!0;let t=ir.createInterface({input:process.stdin,output:process.stdout});n=`${n} (y/N) `;let o=e?rr.bold.yellow(n):n,r=yield t.question(o);return t.close(),r.toLowerCase()==="y"})}var je=xe,se=co(xe,Yt),pt=co(xe,qt);function lr(n){return sr(n)&&ar(n).isDirectory()}function ht(n=!1){return l(this,null,function*(){lr(je)||(!n&&!(yield we(`A '${xe}' folder was not found in the current directory. Setup the required Momentic folder structure?`))&&(A.error("Setup cancelled"),process.exit(1)),ut(je),ut(se),ut(pt),A.info("Setup complete!"))})}import{registry as ft}from"playwright-core/lib/server";function cr(n){let e=[],t=[];for(let o of n){let r=ft.findExecutable(o);!r||r.installType==="none"?e.push(o):t.push(r)}return t}function mo(){return l(this,null,function*(){let n=cr(["chromium"]);yield ft.installDeps(n,!1),yield ft.install(n,!1)})}import{Argument as gt,Option as Ie}from"commander";var Ge=new Ie("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var.").env("MOMENTIC_API_KEY").makeOptionMandatory(!0),Ve=new Ie("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise.").default("https://api.momentic.ai"),yt=new Ie("-y, --yes","Skip confirmation prompts.").env("CI").default(!1),uo=new Ie("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").default(!0),St=new Ie("-a --all","Select all tests in your organization from Momentic Cloud. Cannot be used together with <tests> arguments.").default(!1).preset(!0),po=new gt("<tests...>",`One or more test paths to pull from Momentic Cloud.
12
12
 
13
- A test path is a lowercased version of your test name where spaces are replaced with underscores: 'npx momentic pull hello-world'.`).argOptional(),po=new ht("<tests...>",`One or more test identifiers.
13
+ A test path is a lowercased version of your test name where spaces are replaced with underscores: 'npx momentic pull hello-world'.`).argOptional(),ho=new gt("<tests...>",`One or more test identifiers.
14
14
 
15
15
  To use tests stored on your local file system, pass '--local' and specify file paths to Momentic YAML files or folders that exist locally: 'npx momentic run --local momentic/hello-world.yaml'.
16
16
 
17
- To use tests stored remotely on Momentic Cloud, pass '--remote' and specify one or more test paths. A test path is a lowercased version of your test name where spaces are replaced with underscores: 'npx momentic run --remote hello-world'.`).argRequired(),ho=new ht("<paths...>","File paths pointing to one or more YAML files containing Momentic tests, or a directory of Momentic YAML files.");import{existsSync as ar,writeFileSync as go}from"fs";import{join as fo}from"path";function wo(o){return l(this,arguments,function*({testsToFetch:n,client:e,all:t}){let{tests:r,modules:s}=yield e.getTestYAMLExport({paths:n,all:t}),a=Object.keys(r).length;for(let[c,d]of Object.entries(r)){let h=fo(Ue,So(c));if(!(yield yo(h))){S.error("Pull cancelled");return}go(h,d,"utf-8"),S.info(`Wrote '${h}'`)}let i=Object.keys(s).length;for(let[c,d]of Object.entries(s)){let h=fo(dt,So(c));if(!(yield yo(h))){S.error("Pull cancelled");return}go(h,d,"utf-8"),S.info(`Wrote '${h}'`)}S.info(`Pulled ${a} test${a>1?"s":""}${i?` and ${i} module${i>1?"s":""}`:""}!`)})}function yo(n){return l(this,null,function*(){return ar(n)?de(`File '${n.replace(/(\s+)/g,"\\$1")}' already exists. Overwrite existing content?`,!0):!0})}function So(n){return`${n.toLowerCase().replaceAll(" ","-")}.yaml`}import{existsSync as yt,readFileSync as St,readdirSync as Ao,statSync as bo}from"fs";import Ee from"path";function Eo(n){return l(this,null,function*(){let e=To(n.paths);S.info(`Found ${e.size} test(s) to push:`),e.forEach(r=>S.info(` - ${r}`)),S.info("Loading file contents and resolving dependent modules");let t=Array.from(e).map(wt),o=new Set(t.flatMap(r=>Object.keys(r.modules)));if(S.info(`Resolved ${e.size} test(s) and ${o.size} module(s)`),!n.yes&&!(yield de("Pushing tests overwrites tests on production and will instantly affect scheduled runs. Continue?",!0))){S.error("Push cancelled");return}yield n.client.updateTestWithYAML(t),S.info("Update successful!")})}function wt(n){let e;try{e=St(n,"utf8"),e=e.replace(/\r\n|\r/g,`
18
- `)}catch(a){throw new Error(`Could not read test file ${n}: ${a}`)}let t=new Set,o=/moduleId: (.*)/g,r;for(;(r=o.exec(e))!==null;)t.add(r[1].trim());let s={};if(t.size>0){let a=lr(n);t.forEach(i=>{s[i]||(s[i]=cr(a,i))})}return{test:e,modules:s}}function lr(n){let e=n;for(;e!=="/";){let t=Ee.join(e,ke);if(yt(t))return t;e=Ee.dirname(e)}throw new Error(`No '${ke}' directory found in the path ${n} or any of its parents`)}function cr(n,e){let t=Ao(n);for(let o of t){let r=Ee.join(n,o),s=St(r,"utf8");if(s.includes(e))return s}throw new Error(`Could not find module file for module ${e} in ${n}`)}function dr(n){if(!n.endsWith(".yaml"))return!1;let e=St(n,"utf8");return e.includes("momentic/test")?e.match(/localOnly:.*true/)?(S.warn(`Skipping local-only test: ${n}`),!1):!0:(S.warn(`Skipping YAML that is not a Momentic test: ${n}`),!1)}function To(n,e=new Set){for(let t of n){let o=Ee.resolve(t);if(o&&yt(o)&&bo(o).isDirectory()){let r=Ao(o).map(s=>Ee.join(o,s));To(r,e);continue}if(o.endsWith(".yaml")){if(!yt(o)||!bo(o).isFile())throw new Error(`File not found or unreadable: ${o}`);if(!dr(o))continue;e.add(o)}}return e}import{existsSync as ln,statSync as ri}from"fs";import ii from"wait-on";import{distance as Nr}from"fastest-levenshtein";import{chromium as Mr,devices as Vo}from"playwright";import{addExtra as Dr}from"playwright-extra";import Pr from"puppeteer-extra-plugin-recaptcha";import _r from"puppeteer-extra-plugin-stealth";var bt={js:'var K=Object.defineProperty;var P=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var H=(t,e,n)=>e in t?K(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e)=>{for(var n in e||(e={}))z.call(e,n)&&H(t,n,e[n]);if(P)for(var n of P(e))B.call(e,n)&&H(t,n,e[n]);return t};var g=(t,e,n)=>(H(t,typeof e!="symbol"?e+"":e,n),n);var _=(t,e,n)=>new Promise((o,r)=>{var i=s=>{try{d(n.next(s))}catch(l){r(l)}},a=s=>{try{d(n.throw(s))}catch(l){r(l)}},d=s=>s.done?o(s.value):Promise.resolve(s.value).then(i,a);d((n=n.apply(t,e)).next())});var E=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=E);var k={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?[k.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 N={_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=E(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=E(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(k.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),a=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>a,a};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let a of Array.from(t.children)){i=window.getComputedStyle(a,null);let d=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(d)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(a,!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=k.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,a,d,s=o.coords.split(",").map(p=>parseInt(p,10)),l=o.shape.toLowerCase();if(["rect","rectangle"].includes(l))s.length==4&&([r,a,i,d]=s);else if(["circle","circ"].includes(l)){if(s.length==3){let[p,w,v]=s,u=v/Math.sqrt(2);r=p-u,i=p+u,a=w-u,d=w+u}}else l==="default"?s.length==2&&([r,a,i,d]=[0,0,t.width,t.height]):s.length>=4&&([r,a,i,d]=s);let c=k.translate(k.create(r,a,i,d),t.left,t.top);c=this.cropRectToVisible(c),c&&!isNaN(c.top)&&!isNaN(c.left)&&!isNaN(c.width)&&!isNaN(c.height)&&n.push({element:o,rect:c})}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(e){}},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:a}=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&&a===!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 N.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!=null?n.parentNode:void 0),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 O={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){var r,i;let e={};this.addAttributes(t,this.commonAttributes,e);let n=((i=(r=t.tagName).toLowerCase)==null?void 0:i.call(r))||"";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,D({tag:n,attributes:e},o&&{content:o}))},getContent(t){var n,o;let e=((o=(n=t.tagName).toLowerCase)==null?void 0:o.call(n))||"";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){var o,r;if((((r=(o=t.tagName).toLowerCase)==null?void 0:r.call(o))||"")=="label"&&t.hasAttribute("for")){let i=t.getAttribute("for"),a=document.getElementById(i);a&&(e.target=this.describe(a))}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 x=null,C=()=>G()||document.scrollingElement||document.body,W=function(t){return t?t<0?-1:1:0},U={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},X=function(t,e,n){if(N.isString(n)){let o=n;return o==="viewSize"&&t===C()?e==="x"?window.innerWidth:window.innerHeight:t[U[e][o]]}else return n},V=function(t,e,n){let o=U[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},q=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},T=function(t,e,n,o){let r=o*X(t,e,n)||-1;return r=W(r),V(t,e,r)&&V(t,e,-r)},$=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),T(t,e,n,o)&&q(t,e)},j=function(t=null){let e;if(!t){let n=C();if(T(n,"y",1,1)||T(n,"y",-1,1))return n;t=document.body||C()}if(T(t,"y",1,1)||T(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=j(e.element);if(o)return o}return null}},L={init(){x=null},isScrollableElement(t){return x||(x=C()&&j()||C()),t!==x&&$(t)}},G=function(){let t=J[window.location.host];if(t)return document.querySelector(t)},J={"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=L;var A=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",E(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",E(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:A});var R=class{constructor(e){g(this,"element");g(this,"image");g(this,"rect");g(this,"linkText");g(this,"showLinkText");g(this,"reason");g(this,"secondClassCitizen");g(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},M={getLocalHintsForElement(t){var p,w,v;let e=((w=(p=t.tagName).toLowerCase)==null?void 0:w.call(p))||"",n=!1,o=!1,r=!1,i=[],a=[],d=null;if(e==="img"){let u=t.getAttribute("usemap");if(u){let h=t.getClientRects();u=u.replace(/^#/,"").replace(\'"\',\'\\\\"\');let m=document.querySelector(`map[name="${u}"]`);if(m&&h.length>0){n=!0;let y=m.getElementsByTagName("area"),S=f.getClientRectsForAreas(h[0],y);S=S.map(F=>Object.assign(F,{image:t})),a.push(...S)}}}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 h=[];for(let m of["","data-","x-"])for(let y of["-",":","_"])h.push(`${m}ng${y}click`);return function(m){for(let y of h)if(m.hasAttribute(y))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let u=t.getAttribute("role"),h=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(u!=null&&h.includes(u.toLowerCase()))n=!0;else{let m=t.getAttribute("contentEditable");m!=null&&["","contenteditable","true","plaintext-only"].includes(m.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let u=t.getAttribute("jsaction").split(";");for(let h of u){let m=h.trim().split(":");if(m.length>=1&&m.length<=2){let[y,S,F]=m.length===1?["click",...m[0].trim().split("."),"_"]:[m[0],...m[1].trim().split("."),"_"];n||(n=y==="click"&&S!=="none"&&F!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||(n=!t.disabled&&!t.readOnly);break;case"input":n||(n=!(((v=t.getAttribute("type"))==null?void 0:v.toLowerCase())=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t)));break;case"button":case"select":n||(n=!t.disabled);break;case"object":case"embed":n=!0;break;case"label":n||(n=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0);break;case"body":n||(n=t===document.body&&!A()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?d="Frame.":void 0),n||(n=t===document.body&&A()&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"img":n||(n=["zoom-in","zoom-out"].includes(t.style.cursor));break;case"div":case"ol":case"ul":n||(n=t.clientHeight<t.scrollHeight&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"details":n=!0,d="Open.";break}let l=t.getAttribute("class");!n&&(l!=null&&l.toLowerCase().includes("button"))&&(n=!0,r=!0);let c=t.getAttribute("tabindex"),b=c?parseInt(c):-1;if(!n&&!(b<0)&&!isNaN(b)&&(n=!0,o=!0),n)if(a.length>0){let u=a.map(h=>new R({element:h.element,image:t,rect:h.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:d}));i.push(...u)}else{let u=f.getVisibleClientRect(t,!0);if(u!==null){let h=new R({element:t,rect:u,secondClassCitizen:o,possibleFalsePositive:r,reason:d});i.push(h)}}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?M.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,l)=>{l==null&&(l=[]);for(let c of Array.from(s.querySelectorAll("*")))l.push(c),c.shadowRoot&&e(c.shadowRoot,l);return l},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let l=this.getLocalHintsForElement(s);o.push(...l)}o=o.reverse();let r=[1,2,3];o=o.filter((s,l)=>{if(!s.possibleFalsePositive)return!0;let b=Math.max(0,l-6);for(;b<l;){let p=o[b].element;for(let w of r)if(p=p==null?void 0:p.parentElement,p===s.element)return!1;b+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let l=s.rect,c=M.getElementFromPoint(l.left+l.width*.5,l.top+l.height*.5);if(c&&(s.element.contains(c)||c.contains(s.element))||s.element.localName=="area"&&c==s.image)return!0;let p=[l.top+.1,l.bottom-.1],w=[l.left+.1,l.right-.1];for(let v of p)for(let u of w){let h=M.getElementFromPoint(u,v);if(h&&(s.element.contains(h)||h.contains(s.element)))return!0}});i.reverse();let{top:a,left:d}=f.getViewportTopLeft();for(let s of i)s.rect.top+=a,s.rect.left+=d;return i}};var I=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}capture(){return _(this,null,function*(){this.reset(),this.createMarkers(),this.displayMarkers()})}createMarkers(){this.hints=M.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{var i,a;let o=f.createElement("div"),r=(a=(i=e.element.attributes["data-momentic-id"])==null?void 0:i.value)!=null?a: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(O.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=I;\n',css:`/* Reproduced from https://github.com/philc/vimium/blob/master/content_scripts/vimium.css */
17
+ To use tests stored remotely on Momentic Cloud, pass '--remote' and specify one or more test paths. A test path is a lowercased version of your test name where spaces are replaced with underscores: 'npx momentic run --remote hello-world'.`).argRequired(),fo=new gt("<paths...>","File paths pointing to one or more YAML files containing Momentic tests, or a directory of Momentic YAML files.");import{existsSync as mr,writeFileSync as go}from"fs";import{join as yo}from"path";function bo(o){return l(this,arguments,function*({testsToFetch:n,client:e,all:t}){let{tests:r,modules:s}=yield e.getTestYAMLExport({paths:n,all:t}),a=Object.keys(r).length;for(let[c,m]of Object.entries(r)){let u=yo(je,wo(c));if(!(yield So(u))){A.error("Pull cancelled");return}go(u,m,"utf-8"),A.info(`Wrote '${u}'`)}let i=Object.keys(s).length;for(let[c,m]of Object.entries(s)){let u=yo(se,wo(c));if(!(yield So(u))){A.error("Pull cancelled");return}go(u,m,"utf-8"),A.info(`Wrote '${u}'`)}A.info(`Pulled ${a} test${a>1?"s":""}${i?` and ${i} module${i>1?"s":""}`:""}!`)})}function So(n){return l(this,null,function*(){return mr(n)?we(`File '${n.replace(/(\s+)/g,"\\$1")}' already exists. Overwrite existing content?`,!0):!0})}function wo(n){return`${n.toLowerCase().replaceAll(" ","-")}.yaml`}import bt,{readFileSync as Lo,readdirSync as hr,statSync as fr}from"fs";import At from"path";import ur from"diff-lines";import Ke from"semver";var Ao={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:n=>l(void 0,null,function*(){return n=n.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),n=n.map(e=>{var t,o;return e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=(o=(t=e.commands)!=null?t:e.results)!=null?o:[]),e}),n})};var Eo={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:n=>l(void 0,null,function*(){return n.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,o=t[t.length-1];return o&&o.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})})};var Co={name:"Migrate AI assertions to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:n=>l(void 0,null,function*(){return n.map(e=>{if(e.type!=="AI_ASSERTION")return e;let o={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},r=T(T({},e),o);return delete r.text,r})}),stopOnFailure:!0};var We=new Set(["CLICK","TYPE","SELECT_OPTION"]),To={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:n=>l(void 0,null,function*(){return n.map(e=>{let t=e.command,o=t==null?void 0:t.type,r=t==null?void 0:t.elementDescriptor;return(r!==void 0||We.has(o))&&(t.target={elementDescriptor:r!=null?r:""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let i=a==null?void 0:a.elementDescriptor,c=a==null?void 0:a.type;(i!==void 0||We.has(c))&&(a.target={elementDescriptor:i!=null?i:""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let i=a.command,c=i==null?void 0:i.elementDescriptor,m=i==null?void 0:i.type;(c!==void 0||We.has(m))&&(i.target={elementDescriptor:c!=null?c:""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(h=>{let w=h==null?void 0:h.elementDescriptor,S=h==null?void 0:h.type;(w!==void 0||We.has(S))&&(h.target={elementDescriptor:w!=null?w:""})})}),e})}),stopOnFailure:!0};var vo={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:n=>l(void 0,null,function*(){return n.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(o=>{if(o&&typeof o=="object"){let r=o;(r==null?void 0:r.status)==="FAILURE"&&(r.status="FAILED")}}),t})}),stopOnFailure:!0};var Ro={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:n=>l(void 0,null,function*(){return n.map(e=>{let t=e.command,o=t==null?void 0:t.type;return o!=null&&o.startsWith("PRESET_")&&(t.type=o.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(s=>{let a=s.type;a!=null&&a.startsWith("PRESET_")&&(s.type=a.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(s=>{let a=s.command,i=a==null?void 0:a.type;i!=null&&i.startsWith("PRESET_")&&(a.type=i.slice(7)),s.commands&&Array.isArray(s.commands)&&s.commands.forEach(m=>{let u=m.type;u!=null&&u.startsWith("PRESET_")&&(m.type=u.slice(7))})}),e})}),stopOnFailure:!0};var ae=[Co,vo,Ro,To,Ao,Eo];if(W!==ae[ae.length-1].toVersion)throw new Error("Please bump LATEST_VERSION in types package after adding a migration");ae.forEach((n,e)=>{if(!Ke.valid(n.toVersion)||!Ke.valid(n.fromVersion))throw new Error(`Migration '${n.name}' has invalid version`);if(!Ke.gt(n.toVersion,n.fromVersion))throw new Error(`Migration '${n.name}' has toVersion <= fromVersion`);if(e===0)return;if(ae[e-1].toVersion!==n.fromVersion)throw new Error(`Migration '${n.name}' at index ${e} is not contiguous with previous migration`)});function pr(n){return n.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var wt=o=>l(void 0,[o],function*({metadata:n,steps:e,logger:t}){let r=e,{schemaVersion:s,id:a}=n,i=ae.findIndex(u=>Ke.gt(u.toVersion,s));if(i===-1)return t.debug({id:a},"Step migrations up to date"),{steps:r,newVersion:s};let c=s;for(let u=i;u<ae.length;u++){let h=ae[u],w={id:a,migration:h.name,toVersion:h.toVersion};t.debug(w,"Starting migration");try{r=yield xo(r,h),c=h.toVersion}catch(S){throw t.error(T({err:S},w),"Migration failed"),new Error(`Step migration ${h.name} failed: ${S}`)}}let m=ur(JSON.stringify(e,void 0,2),JSON.stringify(r,void 0,2),{n_surrounding:1});return t.debug({diffs:m,id:a},"Migration diffs"),{newVersion:c,steps:r}});function xo(n,e){return l(this,null,function*(){let t=yield e.execute(n);for(let o of t)for(let r of Object.keys(o)){if(!e.recursiveKeys.has(r))continue;let s=o[r];!s||!Array.isArray(s)||pr(s)&&(o[r]=yield xo(s,e))}return t})}import{parse as Io}from"yaml";var gr=new Set(["modules","fixtures","node_modules","dist","bin",".git","logs",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"]);function Et(n){var r;let e=(r=n.split(At.sep).pop())!=null?r:"";if(gr.has(e))return e!=="modules"&&e!=="fixtures"&&A.warn(`Skipping directory '${n}' because it is likely an artifact folder.`),[];let t=bt.readdirSync(n),o=[];return t.forEach(s=>{let a=At.join(n,s);if(bt.statSync(a).isDirectory())o=o.concat(Et(a));else if(s.endsWith(".yaml"))if(bt.readFileSync(a,"utf-8").includes("momentic/test")){let c=fr(a);o.push({path:a,lastModified:c.mtime,createdAt:c.ctime})}else A.warn(`Skipping file '${a}' because it does not appear to be a valid Momentic test.`)}),o}function Ct(n,e){let t;try{t=Lo(n,"utf8"),t=t.replace(/\r\n|\r/g,`
18
+ `)}catch(i){throw new Error(`Could not read test file ${n}: ${i}`)}let o=new Set,r=/moduleId: (.*)/g,s;for(;(s=r.exec(t))!==null;)o.add(s[1].trim());let a={};return o.size>0&&o.forEach(i=>{a[i]||(a[i]=yr(e,i).content)}),{test:t,modules:a}}function yr(n,e){let t=hr(n);for(let o of t){let r=At.join(n,o),s=Lo(r,"utf8");if(s.includes(e))return{path:r,content:s}}throw new Error(`Could not find module file for module ${e} in ${n}`)}function Oo(n,e){return l(this,null,function*(){let{test:t,modules:o}=Ct(n,e),r=Io(t);if(!r.steps||!Array.isArray(r.steps))throw new Error(`Test ${n} is missing steps`);if(!r.schemaVersion||!r.id)throw new Error(`Test ${n} is missing an ID or schema version`);let s;if(r.schemaVersion<W){A.warn(`Test ${n} has schema version ${r.schemaVersion}, which is lower than the version used by this SDK, ${W}. Your test will be migrated to the latest version before execution.`);let{steps:c}=yield wt({metadata:r,steps:r.steps,logger:A});s=oe.array().parse(c)}else s=oe.array().parse(r.steps);let a={};for(let[c,m]of Object.entries(o)){let u=Io(m);if(!u.schemaVersion||!u.moduleId)throw new Error(`Module ${c} is missing an ID or schema version`);if(!u.steps||!Array.isArray(u.steps))throw new Error(`Module ${c} is missing steps`);if(u.schemaVersion<W){A.warn(`Module ${c} has schema version ${u.schemaVersion}, which is lower than the version used by this SDK, ${W}. Your module will be migrated to the latest version before execution.`);let{steps:h}=yield wt({metadata:{id:u.moduleId,schemaVersion:u.schemaVersion},steps:u.steps,logger:A});a[c]=M(T({},u),{steps:te.array().parse(h)})}else a[c]=u}let i=s.map(c=>{if(c.type!=="MODULE")return c;let m=a[c.moduleId];if(!m)throw new Error(`Could not resolve module ${c.moduleId} required in test ${n}`);return{type:"RESOLVED_MODULE",moduleId:c.moduleId,name:m.name,steps:m.steps}});return it.parse(M(T({},r),{steps:i}))})}import{spawn as Sr}from"child_process";function Mo(n){return l(this,null,function*(){return new Promise((e,t)=>{let o={stdio:"inherit",env:process.env,detached:!0},r=Sr("bash",["-c",n],o),s=!1;process.on("exit",()=>r.pid!==void 0&&!s&&process.kill(-r.pid)),r.on("close",a=>{if(s=!0,a===0){e();return}t(`command exited with code ${a}`)})})})}import{distance as kr}from"fastest-levenshtein";import{chromium as $r,devices as en}from"playwright";import{addExtra as Hr}from"playwright-extra";import Br from"puppeteer-extra-plugin-recaptcha";import jr from"puppeteer-extra-plugin-stealth";var Tt={js:'var K=Object.defineProperty;var P=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var H=(t,e,n)=>e in t?K(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e)=>{for(var n in e||(e={}))z.call(e,n)&&H(t,n,e[n]);if(P)for(var n of P(e))B.call(e,n)&&H(t,n,e[n]);return t};var g=(t,e,n)=>(H(t,typeof e!="symbol"?e+"":e,n),n);var _=(t,e,n)=>new Promise((o,r)=>{var i=s=>{try{d(n.next(s))}catch(l){r(l)}},a=s=>{try{d(n.throw(s))}catch(l){r(l)}},d=s=>s.done?o(s.value):Promise.resolve(s.value).then(i,a);d((n=n.apply(t,e)).next())});var E=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=E);var k={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?[k.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 N={_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=E(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=E(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(k.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),a=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>a,a};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let a of Array.from(t.children)){i=window.getComputedStyle(a,null);let d=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(d)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(a,!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=k.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,a,d,s=o.coords.split(",").map(p=>parseInt(p,10)),l=o.shape.toLowerCase();if(["rect","rectangle"].includes(l))s.length==4&&([r,a,i,d]=s);else if(["circle","circ"].includes(l)){if(s.length==3){let[p,w,v]=s,u=v/Math.sqrt(2);r=p-u,i=p+u,a=w-u,d=w+u}}else l==="default"?s.length==2&&([r,a,i,d]=[0,0,t.width,t.height]):s.length>=4&&([r,a,i,d]=s);let c=k.translate(k.create(r,a,i,d),t.left,t.top);c=this.cropRectToVisible(c),c&&!isNaN(c.top)&&!isNaN(c.left)&&!isNaN(c.width)&&!isNaN(c.height)&&n.push({element:o,rect:c})}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(e){}},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:a}=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&&a===!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 N.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!=null?n.parentNode:void 0),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 O={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){var r,i;let e={};this.addAttributes(t,this.commonAttributes,e);let n=((i=(r=t.tagName).toLowerCase)==null?void 0:i.call(r))||"";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,D({tag:n,attributes:e},o&&{content:o}))},getContent(t){var n,o;let e=((o=(n=t.tagName).toLowerCase)==null?void 0:o.call(n))||"";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){var o,r;if((((r=(o=t.tagName).toLowerCase)==null?void 0:r.call(o))||"")=="label"&&t.hasAttribute("for")){let i=t.getAttribute("for"),a=document.getElementById(i);a&&(e.target=this.describe(a))}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 x=null,C=()=>G()||document.scrollingElement||document.body,W=function(t){return t?t<0?-1:1:0},U={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},X=function(t,e,n){if(N.isString(n)){let o=n;return o==="viewSize"&&t===C()?e==="x"?window.innerWidth:window.innerHeight:t[U[e][o]]}else return n},V=function(t,e,n){let o=U[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},q=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},T=function(t,e,n,o){let r=o*X(t,e,n)||-1;return r=W(r),V(t,e,r)&&V(t,e,-r)},$=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),T(t,e,n,o)&&q(t,e)},j=function(t=null){let e;if(!t){let n=C();if(T(n,"y",1,1)||T(n,"y",-1,1))return n;t=document.body||C()}if(T(t,"y",1,1)||T(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=j(e.element);if(o)return o}return null}},L={init(){x=null},isScrollableElement(t){return x||(x=C()&&j()||C()),t!==x&&$(t)}},G=function(){let t=J[window.location.host];if(t)return document.querySelector(t)},J={"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=L;var A=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",E(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",E(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:A});var R=class{constructor(e){g(this,"element");g(this,"image");g(this,"rect");g(this,"linkText");g(this,"showLinkText");g(this,"reason");g(this,"secondClassCitizen");g(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},M={getLocalHintsForElement(t){var p,w,v;let e=((w=(p=t.tagName).toLowerCase)==null?void 0:w.call(p))||"",n=!1,o=!1,r=!1,i=[],a=[],d=null;if(e==="img"){let u=t.getAttribute("usemap");if(u){let h=t.getClientRects();u=u.replace(/^#/,"").replace(\'"\',\'\\\\"\');let m=document.querySelector(`map[name="${u}"]`);if(m&&h.length>0){n=!0;let y=m.getElementsByTagName("area"),S=f.getClientRectsForAreas(h[0],y);S=S.map(F=>Object.assign(F,{image:t})),a.push(...S)}}}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 h=[];for(let m of["","data-","x-"])for(let y of["-",":","_"])h.push(`${m}ng${y}click`);return function(m){for(let y of h)if(m.hasAttribute(y))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let u=t.getAttribute("role"),h=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(u!=null&&h.includes(u.toLowerCase()))n=!0;else{let m=t.getAttribute("contentEditable");m!=null&&["","contenteditable","true","plaintext-only"].includes(m.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let u=t.getAttribute("jsaction").split(";");for(let h of u){let m=h.trim().split(":");if(m.length>=1&&m.length<=2){let[y,S,F]=m.length===1?["click",...m[0].trim().split("."),"_"]:[m[0],...m[1].trim().split("."),"_"];n||(n=y==="click"&&S!=="none"&&F!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||(n=!t.disabled&&!t.readOnly);break;case"input":n||(n=!(((v=t.getAttribute("type"))==null?void 0:v.toLowerCase())=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t)));break;case"button":case"select":n||(n=!t.disabled);break;case"object":case"embed":n=!0;break;case"label":n||(n=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0);break;case"body":n||(n=t===document.body&&!A()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?d="Frame.":void 0),n||(n=t===document.body&&A()&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"img":n||(n=["zoom-in","zoom-out"].includes(t.style.cursor));break;case"div":case"ol":case"ul":n||(n=t.clientHeight<t.scrollHeight&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"details":n=!0,d="Open.";break}let l=t.getAttribute("class");!n&&(l!=null&&l.toLowerCase().includes("button"))&&(n=!0,r=!0);let c=t.getAttribute("tabindex"),b=c?parseInt(c):-1;if(!n&&!(b<0)&&!isNaN(b)&&(n=!0,o=!0),n)if(a.length>0){let u=a.map(h=>new R({element:h.element,image:t,rect:h.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:d}));i.push(...u)}else{let u=f.getVisibleClientRect(t,!0);if(u!==null){let h=new R({element:t,rect:u,secondClassCitizen:o,possibleFalsePositive:r,reason:d});i.push(h)}}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?M.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,l)=>{l==null&&(l=[]);for(let c of Array.from(s.querySelectorAll("*")))l.push(c),c.shadowRoot&&e(c.shadowRoot,l);return l},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let l=this.getLocalHintsForElement(s);o.push(...l)}o=o.reverse();let r=[1,2,3];o=o.filter((s,l)=>{if(!s.possibleFalsePositive)return!0;let b=Math.max(0,l-6);for(;b<l;){let p=o[b].element;for(let w of r)if(p=p==null?void 0:p.parentElement,p===s.element)return!1;b+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let l=s.rect,c=M.getElementFromPoint(l.left+l.width*.5,l.top+l.height*.5);if(c&&(s.element.contains(c)||c.contains(s.element))||s.element.localName=="area"&&c==s.image)return!0;let p=[l.top+.1,l.bottom-.1],w=[l.left+.1,l.right-.1];for(let v of p)for(let u of w){let h=M.getElementFromPoint(u,v);if(h&&(s.element.contains(h)||h.contains(s.element)))return!0}});i.reverse();let{top:a,left:d}=f.getViewportTopLeft();for(let s of i)s.rect.top+=a,s.rect.left+=d;return i}};var I=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}capture(){return _(this,null,function*(){this.reset(),this.createMarkers(),this.displayMarkers()})}createMarkers(){this.hints=M.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{var i,a;let o=f.createElement("div"),r=(a=(i=e.element.attributes["data-momentic-id"])==null?void 0:i.value)!=null?a: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(O.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=I;\n',css:`/* Reproduced from https://github.com/philc/vimium/blob/master/content_scripts/vimium.css */
19
19
 
20
20
  /*
21
21
  * Many CSS class names in this file use the verbose "vimiumXYZ" as the class name. This is so we
@@ -568,19 +568,19 @@ To use tests stored remotely on Momentic Cloud, pass '--remote' and specify one
568
568
  color: white;
569
569
  }
570
570
  }
571
- `};var J=(n,e)=>{let{hostname:t,pathname:o}=new URL(n),{hostname:r,pathname:s}=new URL(e);return t!==r||o!==s};import{distance as Io}from"fastest-levenshtein";var Co=new Set(["about:blank","chrome-error://chromewebdata/"]),vo=2;var mr=["focusable","keyshortcuts","controls"],pr=["textbox","checkbox","combobox","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch"],hr=["notRendered","notVisible","ariaHiddenSubtree","ariaHiddenElement"],gr=80,fr={paragraph:"p",searchbox:"input"},Oo=["paragraph","option","StaticText"],Lo={indentLevel:0,noID:!1,noChildren:!1,noProperties:!1,maxLevel:void 0,neighbors:void 0},At=class{constructor(e){this.id=e.id,this.role=e.role,this.name=e.name,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeID=e.backendNodeID,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value})}getLogForm(){var e,t;return JSON.stringify({id:this.id,name:(e=this.name)!=null?e:"",role:(t=this.role)!=null?t:"",backendNodeId:this.backendNodeID})}isInteresting(){return pr.includes(this.role)||this.children.some(e=>e.role==="StaticText")?!0:!!this.name.trim()||!!this.content}serialize(e=Lo){var w,b;let{indentLevel:t,noChildren:o,noProperties:r,noID:s}=Object.assign({},Lo,e),a=" ".repeat(t),i=fr[this.role]||this.role,c=this.name,d=C({},this.properties);i==="heading"&&(d.level&&(i=`h${d.level}`,delete d.level),c==="heading"&&(c=""));let h=!Oo.includes(this.role);if(this.role==="StaticText")return`${a}${c}
572
- `;let p=`${a}<${i}`;!s&&h&&(p+=` id="${this.id}"`),c&&(p+=` name="${c}"`),this.content&&(p+=` content="${this.content}"`),Object.keys(this.properties).length>0&&!r&&Object.entries(this.properties).forEach(([m,g])=>{mr.includes(m)||(typeof g=="string"?p+=` ${m}="${g}"`:typeof g=="boolean"?g?p+=` ${m}`:p+=` ${m}={false}`:typeof g!="undefined"&&(p+=` ${m}={${JSON.stringify(g)}}`))});let A=e.maxLevel!==void 0&&t/2>=e.maxLevel;if(this.children.length===0||o||A)return p+=` />
573
- `,p;{let m="";for(let u of this.children)m+=u.serialize(O(C({},e),{indentLevel:t+2}));let g=m.trim();g.length<=gr&&!g.includes(`
574
- `)?p+=`>${g}</${i}>
575
- `:p+=`>
576
- ${m}${a}</${i}>
577
- `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let m=this.parent.children.findIndex(E=>E.id===this.id),g=m>0?(w=this.parent.children[m-1])==null?void 0:w.serialize(O(C({},e),{neighbors:0})):"",u=m<this.parent.children.length-1?(b=this.parent.children[m+1])==null?void 0:b.serialize(O(C({},e),{neighbors:0})):"";return`${g||""}
578
- ${p}
579
- ${u||""}`}return p}},Et=class{constructor(e,t,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=o}serialize(){return this.root?this.root.serialize():""}};function yr(n){var e,t;return(e=n.name)!=null&&e.value?`"${n.name.value}"`:(t=n.role)!=null&&t.value&&n.role.value!=="none"&&n.role.value!=="generic"?`"${n.role.value}"`:`"${n.nodeId}"`}function No(n,e,t){var i,c,d,h,p,A,w;if(!e&&n.parentId)throw new Error(`Got no parent for accessibility node ${n.nodeId}: ${JSON.stringify(n)}`);let o=new At({id:parseInt(n.nodeId),role:((i=n.role)==null?void 0:i.value)||"",name:((c=n.name)==null?void 0:c.value)||"",content:((d=n.value)==null?void 0:d.value)||"",properties:n.properties,children:[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+yr(n),backendNodeID:n.backendDOMNodeId});(h=n.value)!=null&&h.value&&(o.content=`${(p=n.value)==null?void 0:p.value}`);let r=(A=n.childIds)!=null?A:[];for(let b of r){if(!b)continue;let m=t.get(parseInt(b));if(!m)continue;let g=No(m,o,t);g.length&&(o.children=o.children.concat(g))}if(o.role==="StaticText"&&(o.children=[]),o.children.length===1&&o.children[0].role==="StaticText"){let b=o.name,m=(w=o.children[0])==null?void 0:w.name;(b===m||!m)&&(o.children=[])}let s=[];for(let b=o.children.length-1;b>=0;b--){let m=o.children[b];if(m.role!=="StaticText"){s.push(m);continue}if(b===0||o.children[b-1].role!=="StaticText"){s.push(m);continue}o.children[b-1].name+=` ${m.name}`}if(o.children=s.reverse(),o.role==="generic"&&o.children.length===1){let b=o.children[0];if(!Oo.includes(b.role)&&o.name===b.name)return o.children}if(!o.isInteresting()&&n.parentId)return o.children;for(let b of o.children)b.parent=o;return[o]}function Mo(n,e,t,o,r=1){n.id=r,r+=1,e.set(n.id,n),n.dataMomenticId?t.set(n.dataMomenticId,n):n.role!=="StaticText"&&n.role!=="RootWebArea"&&n.role!=="paragraph"&&o.debug({node:n.serialize({neighbors:1,maxLevel:1})},"Node has no data-momentic-id");for(let s of n.children)r=Mo(s,e,t,o,r);return r}function Do(n,e){if(!n.root)throw new Error("a11y tree has null root");n.allNodes=n.allNodes.filter(a=>{var c;return a.ignored?!((c=a.ignoredReasons)==null?void 0:c.find(d=>hr.includes(d.name))):!0});let t=new Map;for(let a of n.allNodes)t.set(parseInt(a.nodeId),a);let o=No(n.root,null,t);if(o.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(o)}`);if(o.length===0)throw new Oe;let r=new Map,s=new Map;return Mo(o[0],r,s,e),new Et(o[0],r,s)}var Te=(n,e)=>{e.id=n.id,e.content=n.content,e.name=n.name,e.role=n.role,e.numChildren=n.children.length,e.serializedForm=n.serialize({noID:!0,maxLevel:1,neighbors:1})},Tt=(n,e)=>{var r;let t=1;n.role===e.role&&t++;let o=["name","content"];for(let s of o){if(!((r=n[s])!=null&&r.trim()))continue;let a=Io(n[s],e[s])/Math.min(n[s].length,e[s].length);a===0?t+=2:a<=.1&&t++}if(e.numChildren!==void 0&&(n.children.length===e.numChildren&&e.numChildren>0?t++:(e.numChildren>0&&n.children.length===0||Math.abs(n.children.length-e.numChildren)>2)&&t--),e.serializedForm){let s=n.serialize({noID:!0,maxLevel:1,neighbors:1}),a=Io(s,e.serializedForm)/Math.min(s.length,e.serializedForm.length);a===0?t+=2:a<=.1&&t++}return t};var Q={r:147,g:196,b:125,a:.55},Po={showInfo:!1,showRulers:!1,showStyles:!1,showAccessibilityInfo:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:Q,paddingColor:Q,borderColor:Q,marginColor:Q,eventTargetColor:Q,shapeColor:Q,shapeMarginColor:Q};var Z=(n=1e3)=>new Promise(e=>setTimeout(()=>e(),n));function _o(){cursor=document.createElement("img"),cursor.setAttribute("src","data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjMyIiB2aWV3Qm94PSIwIDAgMzIgMzIiIHdpZHRoPSIzMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDEwIDcpIj48cGF0aCBkPSJtNi4xNDggMTguNDczIDEuODYzLTEuMDAzIDEuNjE1LS44MzktMi41NjgtNC44MTZoNC4zMzJsLTExLjM3OS0xMS40MDh2MTYuMDE1bDMuMzE2LTMuMjIxeiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Im02LjQzMSAxNyAxLjc2NS0uOTQxLTIuNzc1LTUuMjAyaDMuNjA0bC04LjAyNS04LjA0M3YxMS4xODhsMi41My0yLjQ0MnoiIGZpbGw9IiMwMDAiLz48L2c+PC9zdmc+"),cursor.setAttribute("id","selenium_cursor"),cursor.setAttribute("style","position: absolute; z-index: 99999999999; pointer-events: none; left:0; top:0"),cursor.style.filter="invert(0%) sepia(6%) saturate(24%) hue-rotate(315deg) brightness(89%) contrast(110%)",document.body.appendChild(cursor),document.onmousemove=function(n){n=n||window.event,document.getElementById("selenium_cursor").style.left=n.pageX+"px",document.getElementById("selenium_cursor").style.top=n.pageY+"px"}}function zo(){window.globalHintManager||(window.globalHintManager=new window.HintManager),window.globalHintManager.capture()}function Uo(){window.globalHintManager&&window.globalHintManager.reset()}function Fo(){let n=document.body.getElementsByTagName("*"),e=1;for(let t=0;t<n.length;t++){let o=e.toString();for(;[6].some(s=>o.includes(s.toString()));)e++,o=e.toString();let r=n[t];r==null||r.setAttribute("data-momentic-id",`${e}`),r==null||r.setAttribute("aria-keyshortcuts",`${e}`),e++}}var Sr=new Set(["document","script","XMLHttpRequest","fetch","xhr"]),wr=new Set(["script","document"]),br=["intercom.io","googletagmanager.com","google-analytics.com","www.gstatic.com","gstatic.com","apis.google.com","sentry.io","newrelic.com","p.retool.com","m.stripe.com","m.stripe.network","js.stripe.com","assets.trybento.co","udon.trybento.co","cdn.lr-in-prod.com","r.lr-in-prod.com","content.product-usage.assembledhq.com","data.product-usage.assembledhq.com","static.zdassets.com","o.clarity.ms/collect"],Ar=["api.stripe.com","supabase.co"];function Ct(n){return`${n.resourceType()} ${n.method()} ${n.url()}`}function ko(n){return n=n.replace(/^www\./,""),n}function $o(n){return Ar.some(e=>n.includes(e))}function Ho(n,e){if(!Sr.has(n.resourceType()))return!1;let t=new URL(e),o=new URL(n.url());return br.some(r=>o.hostname.includes(r))?!1:wr.has(n.resourceType())||n.method()!=="GET"?!0:ko(o.hostname).includes(ko(t.hostname))}var Rt=Dr(Mr);Rt.use(_r());Rt.use(Pr({provider:{id:"2captcha",token:process.env.TWO_CAPTCHA_KEY},visualFeedback:!0}));function xt(n){return l(this,null,function*(){yield n.send("Accessibility.enable"),yield n.send("DOM.enable"),yield n.send("Overlay.enable")})}var q=class q{constructor({browser:e,context:t,page:o,baseURL:r,cdpClient:s,logger:a}){this.a11yIdToNodeMap=new Map;this.dataMomenticIdToNodeMap=new Map;this.browser=e,this.context=t,this.page=o,this.baseURL=r,this.cdpClient=s,this.logger=a}static init(s,a,i){return l(this,arguments,function*(e,t,o,r=8e3){let c=yield Rt.launch({headless:!0,handleSIGTERM:!1}),d=yield c.newContext({viewport:q.VIEWPORT,deviceScaleFactor:process.platform==="darwin"?2:1,userAgent:Vo["Desktop Chrome"].userAgent,geolocation:{latitude:37.7749,longitude:-122.4194},locale:"en-US",timezoneId:"America/Los_Angeles"}),h=yield d.newPage(),p=yield d.newCDPSession(h),A=new q({browser:c,context:d,page:h,baseURL:e,cdpClient:p,logger:t}),w=!1;l(this,null,function*(){try{yield A.navigate(e,!1),yield xt(p)}catch(E){t.error({err:E},"Failed to initialize chrome browser")}finally{w=!0}});let m=()=>l(this,null,function*(){if(o)try{o({viewport:A.viewport,buffer:yield A.screenshot()})}catch(E){t.error({err:E},"Failed to take screenshot")}});m();let g=setInterval(()=>{m()},250),u=Date.now();for(;!w&&Date.now()-u<r;)yield Z(250);return clearInterval(g),w||t.warn("Timeout elapsed waiting for browser to initialize - are you sure this page is accessible?"),A})}reset(e){return l(this,null,function*(){this.a11yIdToNodeMap.clear(),this.dataMomenticIdToNodeMap.clear();let t=yield this.context.pages();this.page=t[0];for(let o=1;o<t.length;o++)yield t[o].close();e.clearCookies&&(yield this.context.clearCookies()),e.clearStorage&&(yield this.page.evaluate(()=>{localStorage.clear()})),yield this.page.goto(this.baseURL,{waitUntil:"load",timeout:3e3})})}pageSetup(){return l(this,null,function*(){try{yield this.page.evaluate(_o)}catch(e){}})}wait(e){return l(this,null,function*(){yield this.page.waitForTimeout(e)})}toggleHints(e){return l(this,null,function*(){e.state==="on"?(yield this.page.addStyleTag({content:bt.css}),yield this.page.addScriptTag({content:bt.js}),yield this.page.evaluate(zo)):yield this.page.evaluate(Uo)})}showHints(){return l(this,null,function*(){yield this.toggleHints({state:"on"});let e=()=>l(this,null,function*(){try{yield this.toggleHints({state:"off"})}catch(t){this.logger.debug({err:t},"Failed to remove vision hints")}});setTimeout(()=>{e()},3e3)})}cleanup(){return l(this,null,function*(){yield this.page.close(),yield this.context.close(),yield this.browser.close()})}get closed(){return this.page.isClosed()||!this.browser.isConnected()}html(){return l(this,null,function*(){return yield this.page.content()})}get url(){return this.page.url()}screenshotWithHints(e=100,t="device",o="/tmp/screenshots/test.jpg"){return l(this,null,function*(){let r=o==null?void 0:o.split("."),s=r==null?void 0:r.slice(0,-1).join("."),a=r==null?void 0:r.slice(-1)[0],i=yield this.screenshot(e,t,o?`${s}-before-hint.${a}`:void 0);yield this.showHints();let c=yield this.screenshot(e,t,o?`${s}-after-hint.${a}`:void 0);return{before:i,after:c}})}screenshot(e=100,t="device",o){return l(this,null,function*(){return this.page.screenshot({fullPage:!1,quality:e,scale:t,type:"jpeg",caret:"initial",path:o})})}get viewport(){let e=this.page.viewportSize();if(!e)throw new Error("failed to get viewport");return e}navigate(e,t=!0){return l(this,null,function*(){this.logger.debug(`Navigating to ${e}`);let o=Date.now(),r=()=>l(this,null,function*(){try{yield this.page.goto(e,{waitUntil:"load",timeout:3e3}),this.logger.debug({url:e},`Got load event in ${Math.floor(Date.now()-o)}ms`)}catch(s){this.logger.warn({url:e},"Timeout elapsed waiting for page to fire load event, continuing anyways...")}});if(t?yield this.wrapPossibleNavigation(r):yield r(),Co.has(this.url)&&process.env.NODE_ENV==="production")throw new Error(`${e} took too long to load \u{1F61E}. Please ensure the site and your internet are working.`);this.logger.debug({url:e},"Navigation complete")})}fill(r,s){return l(this,arguments,function*(e,t,o={}){let a=yield this.click(e,{doubleClick:!1,rightClick:!1});return yield this.type(t,o),a})}type(o){return l(this,arguments,function*(e,t={}){let{clearContent:r=!0,pressKeysSequentially:s=!1}=t;r&&(process.platform==="darwin"?yield this.page.keyboard.press("Meta+A"):yield this.page.keyboard.press("Control+A"),yield this.page.keyboard.press("Backspace")),s?yield this.page.keyboard.type(e):yield this.page.keyboard.insertText(e)})}clickByA11yID(o){return l(this,arguments,function*(e,t={}){let r=this.a11yIdToNodeMap.get(e);if(!r)throw new Error(`Could not find DOM node during click: ${e}`);let s=yield this.clickUsingCDP(r,t);return yield this.highlightNode(s),r.serialize({noChildren:!0,noProperties:!0,noID:!0})})}selectOptionByA11yID(e,t){return l(this,null,function*(){let o=this.a11yIdToNodeMap.get(e);if(!o)throw new Error(`Could not find DOM node while selecting option: ${e}`);if(!o.backendNodeID)throw new Error(`Select target missing backend node id: ${o.getLogForm()}`);return yield(yield this.getLocatorFromBackendID(o.backendNodeID)).selectOption(t,{timeout:8e3}),yield this.highlightNode(o),o.serialize({noChildren:!0,noProperties:!0,noID:!0})})}scrollIntoView(e){return l(this,null,function*(){let t=yield this.resolveCachedTargetToID(e),o=this.a11yIdToNodeMap.get(t);if(!o)throw new Error(`Could not find node in DOM with a11y id: ${t}`);if(!o.backendNodeID)throw new Error(`Focus target missing backend node id: ${o.getLogForm()}`);yield(yield this.getLocatorFromBackendID(o.backendNodeID)).scrollIntoViewIfNeeded({timeout:8e3})})}highlight(e){return l(this,null,function*(){try{let t=yield this.resolveCachedTargetToID(e),o=this.a11yIdToNodeMap.get(t);if(!o)throw new Error(`Could not find DOM node during highlight: ${t}`);if(!o.backendNodeID)throw new Error(`Select target missing backend node id: ${o.getLogForm()}`);yield this.highlightNode(o)}catch(t){this.logger.warn({err:t,target:e},"Failed to highlight target")}})}highlightNode(e){return l(this,null,function*(){try{yield this.cdpClient.send("Overlay.highlightNode",{highlightConfig:Po,backendNodeId:e.backendNodeID})}catch(o){this.logger.warn("Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests.")}let t=()=>l(this,null,function*(){try{yield this.cdpClient.send("Overlay.hideHighlight",{backendNodeId:e.backendNodeID})}catch(o){this.logger.debug({err:o},"Failed to remove node highlight")}});setTimeout(()=>{t()},3e3)})}wrapPossibleNavigation(r){return l(this,arguments,function*(e,t=8e3,o=!0){let s=Date.now(),a=this.url,i=Date.now(),c=new Map,d=new Map,h=T=>{var xe;let x=Ct(T.request());d.set(x,((xe=d.get(x))!=null?xe:0)+1);let F=T.status();F>=500&&this.logger.warn({request:x,status:F},"Received 500 level response")},p=T=>{var F;if(!Ho(T,this.url))return;let x=Ct(T);c.set(x,((F=c.get(x))!=null?F:0)+1),i=Date.now()};this.page.on("response",h),this.page.on("request",p);let A=[];o&&(A=(yield this.context.pages()).map(T=>T.url()));let w=!1,b=e().catch(T=>(w=!0,T instanceof Error?T:new Error(`${T}`)));yield Z(250);let m=T=>l(this,null,function*(){let x=yield T;if(x instanceof Error)throw x;return x}),g=new Set,u=!1,R=yield l(this,null,function*(){for(;!w&&!(!u&&Date.now()-s>t);){if(yield Z(250),u=!1,g=new Set,Date.now()-i<=1250)continue;let T=!1;for(let x of c.keys())c.get(x)!==d.get(x)&&($o(x)&&(u=!0),T=!0,g.add(x));if(!T)return this.logger.debug({url:this.url,requests:JSON.stringify(Array.from(c.entries()))},`Network idle in ${Math.floor(Date.now()-s)}ms`),!0}return!w&&g.size>0&&this.logger.warn({url:this.url,unfinishedRequests:JSON.stringify(Array.from(g.entries()))},"Timeout elapsed waiting for network idle, continuing anyways..."),!1});if(this.page.off("response",h),this.page.off("request",p),!R)return m(b);let j=this.url;if(!w&&J(j,a)){this.logger.debug({startURL:a,newURL:this.url},"Detected url change in wrapPossibleNavigation, waiting for load state");let T=Math.max(t-(Date.now()-s),0);if(T>0)try{yield this.page.waitForLoadState("load",{timeout:T})}catch(x){this.logger.warn({url:this.url},"Timeout elapsed waiting for load state to fire, continuing anyways...")}}if(o){let T=(yield this.context.pages()).map(x=>x.url());if(T.length>A.length)for(let x of T)x!==j&&(yield this.switchToPage(x))}return m(b)})}resolveCachedTargetToID(e){return l(this,null,function*(){if(!Le(e)){let i=this.a11yIdToNodeMap.get(e.id);if(!i)throw new Error(`Resolving target failed, fresh value did not exist in node map: ${e.id}`);return Te(i,e),e.id}let t=(yield this.getA11yTree()).serialize();this.logger.debug({tree:t},"Refreshed a11y tree before resolving target");let o=this.a11yIdToNodeMap.get(e.id);if(o){let i=Tt(o,e);if(i>=5)return this.logger.debug({target:e,proposedNode:o.getLogForm(),comparisonScore:i},"Resolved cached a11y target to node with exact same id"),Te(o,e),e.id}let r=1/0,s=1/0,a;for(let i of this.a11yIdToNodeMap.values()){let c=Tt(i,e);if(c>=5)return this.logger.debug({newNode:i.getLogForm(),target:e,comparisonScore:c},"Resolved cached a11y target to new node with field comparison"),Te(i,e),i.id;if(!e.serializedForm)continue;let d=i.serialize({noID:!0,maxLevel:1,neighbors:1});if(Math.abs(d.length-e.serializedForm.length)>15)continue;let h=Nr(e.serializedForm,d),p=h/Math.min(e.serializedForm.length,d.length);h<r&&p<.2&&(r=h,s=p,a=i)}if(a&&r<15)return this.logger.debug({newNode:a.getLogForm(),target:e,distance:r,ratio:s},"Resolved cached a11y target to new node with pure levenshtein distance"),Te(a,e),a.id;throw new Error(`Could not find any relevant node given cached target: ${JSON.stringify(e)}`)})}click(o){return l(this,arguments,function*(e,t={}){let r=yield this.resolveCachedTargetToID(e);return yield this.wrapPossibleNavigation(()=>this.clickByA11yID(r,t))})}hover(e){return l(this,null,function*(){let t=yield this.resolveCachedTargetToID(e),o=this.a11yIdToNodeMap.get(t);if(!o)throw new Error(`Could not find DOM node for hover: ${t}`);if(!o.backendNodeID)throw new Error(`Hover target missing backend node id: ${o.getLogForm()}`);return yield(yield this.getLocatorFromBackendID(o.backendNodeID)).hover({timeout:8e3}),yield this.highlightNode(o),o.serialize({noChildren:!0,noProperties:!0,noID:!0})})}selectOption(e,t){return l(this,null,function*(){let o=yield this.resolveCachedTargetToID(e);return this.selectOptionByA11yID(o,t)})}press(e){return l(this,null,function*(){yield this.wrapPossibleNavigation(()=>this.page.keyboard.press(e))})}refresh(){return l(this,null,function*(){yield this.page.reload(),yield this.pageSetup()})}getA11yTree(){return l(this,null,function*(){yield xt(this.cdpClient),yield this.page.evaluate(Fo);let e=null,t=0,o=this.url;for(;!e;)try{let r=yield this.getRawA11yTree();if(!r.root||r.allNodes.length===0)throw new Error("No a11y tree found on page");e=Do(r,this.logger)}catch(r){if(this.logger.error({err:r,url:o},"Error fetching a11y tree"),t===0)yield Z(1e3),t++;else throw new Error(`Max retries exceeded fetching a11y tree: ${r}`)}return e.root||this.logger.warn("A11y tree was pruned entirely"),this.a11yIdToNodeMap=e.a11yIdNodeMap,this.dataMomenticIdToNodeMap=e.dataMomenticIdMap,e})}getA11yIdFromDataMomenticId(e){var t;return(t=this.dataMomenticIdToNodeMap.get(e))==null?void 0:t.id}getRawA11yTree(){return l(this,null,function*(){let e=this.page.url(),t=Date.now(),o=()=>{t=Date.now()};this.cdpClient.addListener("Accessibility.nodesUpdated",o);let r=!1,s=()=>{this.logger.info({url:e},"Load event fired on page"),r=!0,t=Date.now()};this.cdpClient.addListener("Accessibility.loadComplete",s);let a=Date.now(),i=!0;for(;Date.now()-a<3e3;){if(yield Z(250),!r&&Date.now()-a<1e3){process.env.NODE_ENV!=="production"&&this.logger.debug({url:e},"A11y tree not loaded yet, waiting...");continue}if(Date.now()-t>=1250){i=!1;break}this.logger.debug({url:e},"A11y tree not stable yet, waiting...")}this.logger.debug({duration:Date.now()-a,eventReceived:r,timeoutTriggered:i},"A11y wait phase completed");let{node:c}=yield this.cdpClient.send("Accessibility.getRootAXNode"),{nodes:d}=yield this.cdpClient.send("Accessibility.queryAXTree",{backendNodeId:c.backendDOMNodeId});return this.cdpClient.removeListener("Accessibility.loadComplete",s),this.cdpClient.removeListener("Accessibility.nodesUpdated",o),{root:c,allNodes:d}})}clickUsingVisualCoordinates(e){return l(this,null,function*(){let t=yield this.getElementLocation(e);if(!t)throw new Error(`Could not find element location with backend node id: ${e}`);this.logger.debug({location:t},"Executing mouse click"),yield this.page.mouse.click(t.centerX,t.centerY)})}getIDAttributeUsingCDP(e){return l(this,null,function*(){yield this.cdpClient.send("DOM.getDocument",{depth:0});let t=yield this.cdpClient.send("DOM.requestNode",{objectId:e}),r=(yield this.cdpClient.send("DOM.getAttributes",{nodeId:t.nodeId})).attributes,s=r.findIndex(a=>a==="data-momentic-id");return s===-1?"":r[s+1]||""})}getLocatorFromBackendID(e){return l(this,null,function*(){let t=yield this.cdpClient.send("DOM.resolveNode",{backendNodeId:e});if(!t||!t.object.objectId)throw new Error(`Could not resolve backend node ${e}`);try{let o=yield this.getIDAttributeUsingCDP(t.object.objectId);if(!o)throw new Error("Failed getting data-momentic-id attribute using CDP");return this.page.locator(`[data-momentic-id="${o}"]`)}catch(o){throw this.logger.error({err:o},"Failed to get ID attribute"),o}})}clickUsingCDP(o){return l(this,arguments,function*(e,t={}){let r=0,s=e;for(;r<vo;){if(!s||s.role==="RootWebArea")throw new Error(`Attempted to click node with no clickable surrounding elements: ${e.getLogForm()}`);if(s.role==="StaticText"){s=s.parent;continue}let a=s.backendNodeID;if(!a){this.logger.warn({node:s.getLogForm()},"Click candidate had no backend node ID"),s=s.parent;continue}try{let i=yield this.getLocatorFromBackendID(a);return t.doubleClick?yield i.dblclick({timeout:8e3}):yield i.click({timeout:8e3,button:t.rightClick?"right":"left"}),s.id!==e.id&&this.logger.info({oldNode:e.getLogForm(),newNode:s.getLogForm()},"Redirected click successfully to new element"),s}catch(i){this.logger.error({err:i,node:s.getLogForm()},"Failed click or click timed out"),r++,s=s.parent}}throw new Error(`Max click redirection attempts exhausted on original element: ${e.getLogForm()}`)})}getElementLocation(e){return l(this,null,function*(){let t=yield this.cdpClient.send("DOMSnapshot.captureSnapshot",{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0}),o=yield this.page.evaluate(()=>window.devicePixelRatio);process.platform==="darwin"&&o===1&&(o=2);let r=t.documents[0],s=r.layout,a=r.nodes,i=a.nodeName||[],c=a.backendNodeId||[],d=s.nodeIndex,h=s.bounds,p=-1;for(let E=0;E<i.length;E++)if(c[E]===e){p=d.indexOf(E);break}if(p===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[A=0,w=0,b=0,m=0]=h[p];A/=o,w/=o,b/=o,m/=o;let g=A+b/2,u=w+m/2;return{centerX:g,centerY:u}})}scrollUp(){return l(this,null,function*(){yield this.page.mouse.wheel(0,-q.VIEWPORT.height)})}scrollDown(){return l(this,null,function*(){yield this.page.mouse.wheel(0,q.VIEWPORT.height)})}goForward(){return l(this,null,function*(){yield this.wrapPossibleNavigation(()=>this.page.goForward({timeout:8e3})),yield this.pageSetup()})}goBack(){return l(this,null,function*(){yield this.wrapPossibleNavigation(()=>this.page.goBack({timeout:8e3})),yield this.pageSetup()})}switchToPage(e){return l(this,null,function*(){let t=yield this.context.pages();for(let o=0;o<t.length;o++){let r=t[o];if(r.url().includes(e)){this.logger.info(`Switching to tab ${o} with url ${r.url()}`),this.page=r,yield r.waitForLoadState("load",{timeout:3e3}),yield this.pageSetup(),this.cdpClient=yield this.context.newCDPSession(r),yield xt(this.cdpClient);return}}throw new Error(`Could not find page with url containing ${e}`)})}setCookie(e){return l(this,null,function*(){let t=Bt(e);yield this.context.addCookies([t])})}solveCaptcha(){return l(this,null,function*(){yield this.getA11yTree();let e;for(let i of this.a11yIdToNodeMap.values())if(i.role==="image"&&i.name.toLowerCase().includes("captcha")){if(!i.backendNodeID)continue;e=yield this.getLocatorFromBackendID(i.backendNodeID);break}if(!e){let i=yield this.page.solveRecaptchas();if(!i.captchas||!i.captchas.length)throw new Error("No captchas found on the page");return}let t=yield e.screenshot({type:"jpeg",animations:"allow",quality:100}),o=yield fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:process.env.TWO_CAPTCHA_KEY,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!o.ok){let i=`Captcha solver API returned error response: ${o.statusText}`;throw this.logger.error({text:yield o.text()},i),new Error(i)}let{taskId:r}=yield o.json(),s=Date.now(),a="";for(;Date.now()-s<6e4;){yield Z(2500);let i=yield fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:process.env.TWO_CAPTCHA_KEY,taskId:r})});if(!i.ok){let d=`Captcha solution API returned error response: ${i.statusText}`;throw this.logger.error({text:yield i.text()},d),new Error(d)}let c=yield i.json();if(c.errorId){let d=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(d),new Error(d)}if(c.status==="ready"){a=c.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a})}};q.USER_AGENT=Vo["Desktop Chrome"].userAgent,q.VIEWPORT={width:1920,height:1080};var _=q;var zr={type:"a11y",version:"1.0.0",useHistory:"diff",useGoalSplitter:!0},It=zr;import Ur from"dedent";import Fr from"diff-lines";var kr=1e4,Ce=class{constructor({browser:e,config:t,generator:o,logger:r}){this.browser=e,this.generator=o,this.config=t,this.logger=r,this.pendingInstructions=[],this.commandHistory=[]}get history(){return this.commandHistory.filter(e=>e.state==="DONE")}get lastExecutedCommand(){let e=this.history;return e.length===0?null:e[e.length-1]}resetHistory(){this.commandHistory=[],this.pendingInstructions=[]}resetState(){return l(this,null,function*(){this.resetHistory(),yield this.browser.navigate(this.browser.baseURL)})}getBrowserState(){return l(this,null,function*(){let t=yield(yield this.browser.getA11yTree()).serialize();return this.logger.debug({tree:t},"Got a11y tree"),t})}getSerializedHistory(e,t){let o;return this.config.useHistory==="diff"?o=this.getDiffHistory(e,t):o=this.getListHistory(),o}splitUserGoal(e,t,o){return l(this,null,function*(){if(e==="AI_ACTION"&&t.match(/[,!;.]|(?:and)|(?:then)/)&&this.config.useGoalSplitter){let r=yield this.generator.getGranularGoals({goal:t,url:this.browser.url},o);this.pendingInstructions=r.reverse()}else this.pendingInstructions=[t]})}promptToCommand(e,t,o){return l(this,null,function*(){try{return yield this.promptToCommandHelper(e,t,o)}catch(r){throw r instanceof M?r:new M("InternalWebAgentError",r instanceof Error?r.message:`${r}`,{cause:r})}})}promptToCommandHelper(e,t,o){return l(this,null,function*(){if(this.pendingInstructions.length===0){if(!t.trim())throw new Error("Cannot generate commands for empty goal");yield this.splitUserGoal(e,t,o)}let r=this.pendingInstructions[this.pendingInstructions.length-1];this.logger.info({goal:r},"Starting prompt translation");let s=Date.now(),a=this.browser.url,i=yield this.getBrowserState();this.logger.info({duration:Date.now()-s,url:a},"Got browser state");let c=this.commandHistory.length;this.commandHistory.push({state:"PENDING",browserStateBeforeCommand:i,urlBeforeCommand:a,type:e});let d=this.getSerializedHistory(a,i),h=yield this.generator.getProposedCommand({url:a,numPrevious:c,browserState:i,history:d,goal:r,lastCommand:this.lastExecutedCommand},o);if(this.logger.info({type:h.type,thoughts:h.thoughts},"Got proposed command"),h.type==="SUCCESS"){let p=this.pendingInstructions.pop();if(this.logger.info({finishedInstruction:p,remainingInstructions:this.pendingInstructions},"Removing pending instruction due to SUCCESS"),this.pendingInstructions.length!==0)return this.commandHistory=[],this.promptToCommand(e,"",o)}else h.type==="FAILURE"&&(this.logger.info({remainingInstructions:this.pendingInstructions},"Removing pending instructions due to FAILURE"),this.pendingInstructions=[]);return h})}locateElement(e,t,o){return l(this,null,function*(){if(!e)throw new M("InternalWebAgentError","Cannot locate element with empty description");let r=yield this.getBrowserState(),s;if(t){let{before:a,after:i}=yield this.browser.screenshotWithHints();if(s=yield this.generator.getElementLocationWithVision({goal:e,screenshot:a,hintActivatedScreenshot:i},o),s.id>0){let c=this.browser.getA11yIdFromDataMomenticId(s.id);if(!c)throw new M("InternalWebAgentError",`Unable to find corresponding DOM node for id ${s.id}`);s.id=c}}else s=yield this.generator.getElementLocation({browserState:r,goal:e},o);if(s.id<0)throw new M("ActionFailureError",`Unable to locate element: ${s.thoughts?s.thoughts:"please ensure the element is visible and conforms to Accessibility guidelines"}`);return s})}getDiffHistory(e,t){let o=this.history.filter(s=>s.type==="AI_ACTION");if(o.length===0)return"<NONE/>";let r=[`
580
- You have already executed the following commands successfully (most recent listed first)`,"-".repeat(10)];return o.reverse().forEach((s,a)=>{if(r.push(`COMMAND ${o.length-a}${a===0?" (command just executed)":""}: ${s.serializedCommand}`),a===0)if(J(s.urlBeforeCommand,e))r.push(` URL CHANGE: '${s.urlBeforeCommand}' -> '${e}'`);else{let i=Fr(s.browserStateBeforeCommand,t,{n_surrounding:1});i?i.length<kr?(r.push("PAGE CONTENT CHANGE:"),i.split(`
571
+ `};var le=(n,e)=>{let{hostname:t,pathname:o}=new URL(n),{hostname:r,pathname:s}=new URL(e);return t!==r||o!==s};import{distance as zo}from"fastest-levenshtein";var No=new Set(["about:blank","chrome-error://chromewebdata/"]),Do=2;var br=["focusable","keyshortcuts","controls"],Ar=["textbox","checkbox","combobox","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch"],Er=["notRendered","notVisible","ariaHiddenSubtree","ariaHiddenElement"],Cr=80,Tr={paragraph:"p",searchbox:"input"},Uo=["paragraph","option","StaticText"],Fo={indentLevel:0,noID:!1,noChildren:!1,noProperties:!1,maxLevel:void 0,neighbors:void 0},vt=class{constructor(e){this.id=e.id,this.role=e.role,this.name=e.name,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeID=e.backendNodeID,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value})}getLogForm(){var e,t;return JSON.stringify({id:this.id,name:(e=this.name)!=null?e:"",role:(t=this.role)!=null?t:"",backendNodeId:this.backendNodeID})}isInteresting(){return Ar.includes(this.role)||this.children.some(e=>e.role==="StaticText")?!0:!!this.name.trim()||!!this.content}serialize(e=Fo){var S,b;let{indentLevel:t,noChildren:o,noProperties:r,noID:s}=Object.assign({},Fo,e),a=" ".repeat(t),i=Tr[this.role]||this.role,c=this.name,m=T({},this.properties);i==="heading"&&(m.level&&(i=`h${m.level}`,delete m.level),c==="heading"&&(c=""));let u=!Uo.includes(this.role);if(this.role==="StaticText")return`${a}${c}
572
+ `;let h=`${a}<${i}`;!s&&u&&(h+=` id="${this.id}"`),c&&(h+=` name="${c}"`),this.content&&(h+=` content="${this.content}"`),Object.keys(this.properties).length>0&&!r&&Object.entries(this.properties).forEach(([f,p])=>{br.includes(f)||(typeof p=="string"?h+=` ${f}="${p}"`:typeof p=="boolean"?p?h+=` ${f}`:h+=` ${f}={false}`:typeof p!="undefined"&&(h+=` ${f}={${JSON.stringify(p)}}`))});let w=e.maxLevel!==void 0&&t/2>=e.maxLevel;if(this.children.length===0||o||w)h+=` />
573
+ `;else{let f="";for(let d of this.children)f+=d.serialize(M(T({},e),{indentLevel:t+2}));let p=f.trim();p.length<=Cr&&!p.includes(`
574
+ `)?h+=`>${p}</${i}>
575
+ `:h+=`>
576
+ ${f}${a}</${i}>
577
+ `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let f=this.parent.children.findIndex(E=>E.id===this.id),p=f>0?(S=this.parent.children[f-1])==null?void 0:S.serialize(M(T({},e),{neighbors:0})):"",d=f<this.parent.children.length-1?(b=this.parent.children[f+1])==null?void 0:b.serialize(M(T({},e),{neighbors:0})):"";return`${p||""}
578
+ ${h}
579
+ ${d||""}`}return h}},Rt=class{constructor(e,t,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=o}serialize(){return this.root?this.root.serialize():""}};function vr(n){var e,t;return(e=n.name)!=null&&e.value?`"${n.name.value}"`:(t=n.role)!=null&&t.value&&n.role.value!=="none"&&n.role.value!=="generic"?`"${n.role.value}"`:`"${n.nodeId}"`}function ko(n,e,t){var i,c,m,u,h,w,S;if(!e&&n.parentId)throw new Error(`Got no parent for accessibility node ${n.nodeId}: ${JSON.stringify(n)}`);let o=new vt({id:parseInt(n.nodeId),role:((i=n.role)==null?void 0:i.value)||"",name:((c=n.name)==null?void 0:c.value)||"",content:((m=n.value)==null?void 0:m.value)||"",properties:n.properties,children:[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+vr(n),backendNodeID:n.backendDOMNodeId});(u=n.value)!=null&&u.value&&(o.content=`${(h=n.value)==null?void 0:h.value}`);let r=(w=n.childIds)!=null?w:[];for(let b of r){if(!b)continue;let f=t.get(parseInt(b));if(!f)continue;let p=ko(f,o,t);p.length&&(o.children=o.children.concat(p))}if(o.role==="StaticText"&&(o.children=[]),o.children.length===1&&o.children[0].role==="StaticText"){let b=o.name,f=(S=o.children[0])==null?void 0:S.name;(b===f||!f)&&(o.children=[])}let s=[];for(let b=o.children.length-1;b>=0;b--){let f=o.children[b];if(f.role!=="StaticText"){s.push(f);continue}if(b===0||o.children[b-1].role!=="StaticText"){s.push(f);continue}o.children[b-1].name+=` ${f.name}`}if(o.children=s.reverse(),o.role==="generic"&&o.children.length===1){let b=o.children[0];if(!Uo.includes(b.role)&&o.name===b.name)return o.children}if(!o.isInteresting()&&n.parentId)return o.children;for(let b of o.children)b.parent=o;return[o]}function $o(n,e,t,o,r=1){n.id=r,r+=1,e.set(n.id,n),n.dataMomenticId?t.set(n.dataMomenticId,n):n.role!=="StaticText"&&n.role!=="RootWebArea"&&n.role!=="paragraph"&&o.debug({node:n.serialize({neighbors:1,maxLevel:1})},"Node has no data-momentic-id");for(let s of n.children)r=$o(s,e,t,o,r);return r}function Ho(n,e){if(!n.root)throw new Error("a11y tree has null root");n.allNodes=n.allNodes.filter(a=>{var c;return a.ignored?!((c=a.ignoredReasons)==null?void 0:c.find(m=>Er.includes(m.name))):!0});let t=new Map;for(let a of n.allNodes)t.set(parseInt(a.nodeId),a);let o=ko(n.root,null,t);if(o.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(o)}`);if(o.length===0)throw new ze;let r=new Map,s=new Map;return $o(o[0],r,s,e),new Rt(o[0],r,s)}var Le=(n,e)=>{e.id=n.id,e.content=n.content,e.name=n.name,e.role=n.role,e.numChildren=n.children.length,e.serializedForm=n.serialize({noID:!0,maxLevel:1,neighbors:1})},xt=(n,e)=>{var r;let t=1;n.role===e.role&&t++;let o=["name","content"];for(let s of o){if(!((r=n[s])!=null&&r.trim()))continue;let a=zo(n[s],e[s])/Math.min(n[s].length,e[s].length);a===0?t+=2:a<=.1&&t++}if(e.numChildren!==void 0&&(n.children.length===e.numChildren&&e.numChildren>0?t++:(e.numChildren>0&&n.children.length===0||Math.abs(n.children.length-e.numChildren)>2)&&t--),e.serializedForm){let s=n.serialize({noID:!0,maxLevel:1,neighbors:1}),a=zo(s,e.serializedForm)/Math.min(s.length,e.serializedForm.length);a===0?t+=2:a<=.1&&t++}return t};var ce={r:147,g:196,b:125,a:.55},Bo={showInfo:!1,showRulers:!1,showStyles:!1,showAccessibilityInfo:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:ce,paddingColor:ce,borderColor:ce,marginColor:ce,eventTargetColor:ce,shapeColor:ce,shapeMarginColor:ce};var X=(n=1e3)=>new Promise(e=>setTimeout(()=>e(),n));function jo(){cursor=document.createElement("img"),cursor.setAttribute("src","data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjMyIiB2aWV3Qm94PSIwIDAgMzIgMzIiIHdpZHRoPSIzMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDEwIDcpIj48cGF0aCBkPSJtNi4xNDggMTguNDczIDEuODYzLTEuMDAzIDEuNjE1LS44MzktMi41NjgtNC44MTZoNC4zMzJsLTExLjM3OS0xMS40MDh2MTYuMDE1bDMuMzE2LTMuMjIxeiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Im02LjQzMSAxNyAxLjc2NS0uOTQxLTIuNzc1LTUuMjAyaDMuNjA0bC04LjAyNS04LjA0M3YxMS4xODhsMi41My0yLjQ0MnoiIGZpbGw9IiMwMDAiLz48L2c+PC9zdmc+"),cursor.setAttribute("id","selenium_cursor"),cursor.setAttribute("style","position: absolute; z-index: 99999999999; pointer-events: none; left:0; top:0"),cursor.style.filter="invert(0%) sepia(6%) saturate(24%) hue-rotate(315deg) brightness(89%) contrast(110%)",document.body.appendChild(cursor),document.onmousemove=function(n){n=n||window.event,document.getElementById("selenium_cursor").style.left=n.pageX+"px",document.getElementById("selenium_cursor").style.top=n.pageY+"px"}}function Go(){window.globalHintManager||(window.globalHintManager=new window.HintManager),window.globalHintManager.capture()}function Vo(){window.globalHintManager&&window.globalHintManager.reset()}function Wo(){let n=document.body.getElementsByTagName("*"),e=1;for(let t=0;t<n.length;t++){let o=e.toString();for(;[6].some(s=>o.includes(s.toString()));)e++,o=e.toString();let r=n[t];r==null||r.setAttribute("data-momentic-id",`${e}`),r==null||r.setAttribute("aria-keyshortcuts",`${e}`),e++}}var Rr=new Set(["document","script","XMLHttpRequest","fetch","xhr"]),xr=new Set(["script","document"]),Ir=["intercom.io","googletagmanager.com","google-analytics.com","www.gstatic.com","gstatic.com","apis.google.com","sentry.io","newrelic.com","p.retool.com","m.stripe.com","m.stripe.network","js.stripe.com","assets.trybento.co","udon.trybento.co","cdn.lr-in-prod.com","r.lr-in-prod.com","content.product-usage.assembledhq.com","data.product-usage.assembledhq.com","static.zdassets.com","o.clarity.ms/collect"],Lr=["api.stripe.com","supabase.co"];function It(n){return`${n.resourceType()} ${n.method()} ${n.url()}`}function Ko(n){return n=n.replace(/^www\./,""),n}function Yo(n){return Lr.some(e=>n.includes(e))}function qo(n,e){if(!Rr.has(n.resourceType()))return!1;let t=new URL(e),o=new URL(n.url());return Ir.some(r=>o.hostname.includes(r))?!1:xr.has(n.resourceType())||n.method()!=="GET"?!0:Ko(o.hostname).includes(Ko(t.hostname))}var Lt=Hr($r);Lt.use(jr());Lt.use(Br({provider:{id:"2captcha",token:process.env.TWO_CAPTCHA_KEY},visualFeedback:!0}));var Z=class Z{constructor({browser:e,context:t,page:o,baseUrl:r,cdpClient:s,logger:a,localMode:i}){this.a11yIdToNodeMap=new Map;this.dataMomenticIdToNodeMap=new Map;this.browser=e,this.context=t,this.page=o,this.baseURL=r,this.cdpClient=s,this.logger=a,this.localMode=!!i}static init(c){return l(this,arguments,function*({baseUrl:e,logger:t,browserArgs:o,contextArgs:r,sendScreenshotsDuringLoad:s,localMode:a,timeout:i=8e3}){let m=yield Lt.launch(T({headless:!0,handleSIGTERM:!1},o!=null?o:{})),u=yield m.newContext(T({viewport:Z.VIEWPORT,deviceScaleFactor:process.platform==="darwin"?2:1,userAgent:en["Desktop Chrome"].userAgent,geolocation:{latitude:37.7749,longitude:-122.4194},locale:"en-US",timezoneId:"America/Los_Angeles"},r!=null?r:{})),h=yield u.newPage(),w=yield u.newCDPSession(h),S=new Z({browser:m,context:u,page:h,baseUrl:e,cdpClient:w,logger:t,localMode:a}),b=!1;l(this,null,function*(){try{yield S.navigate({url:e,wrapPossibleNavigation:!1,initialNavigation:!0})}catch(v){t.error({err:v},"Failed to initialize chrome browser")}finally{b=!0}});let p=()=>l(this,null,function*(){if(s)try{s({viewport:yield S.viewport(),buffer:yield S.screenshot()})}catch(v){t.error({err:v},"Failed to take screenshot")}});p();let d=setInterval(()=>{p()},250),E=Date.now();for(;!b&&Date.now()-E<i;)yield X(250);return clearInterval(d),b||t.warn("Timeout elapsed waiting for browser to initialize - are you sure this page is accessible?"),S})}getUserPageOrFrame(){return l(this,null,function*(){if(this.localMode&&this.activeFrame){let e=yield this.page.frame(this.activeFrame);if(!e)throw new Error(`Failed to get non-existent frame: ${this.activeFrame}`);return e}return this.page})}initCDPSession(e=2){return l(this,null,function*(){try{yield this.cdpClient.send("Accessibility.enable"),yield this.cdpClient.send("DOM.enable"),yield this.cdpClient.send("Overlay.enable")}catch(t){if(e>0)return this.logger.error({err:t},"Failed to initialize CDP session, re-creating CDP client"),this.cdpClient=yield this.context.newCDPSession(this.page),yield X(250),this.initCDPSession(e-1)}})}setLogger(e){this.logger=e}registerLocalRequestInterceptors(e){return l(this,null,function*(){yield e.route("**/*",t=>l(this,null,function*(){let o;try{o=yield t.fetch()}catch(s){this.closed||this.logger.warn({err:s},"Network request failed");return}let r=o.headers();delete r["content-security-policy"],delete r["x-frame-options"],delete r["x-xss-protection"],yield t.fulfill({headers:r,response:o})}))})}ping(){if(!this.browser.isConnected())throw new Error("Browser is not connected");if(this.closed)throw new Error("Page has been closed")}setActiveFrame(e){this.activeFrame=e}reset(e){return l(this,null,function*(){var o;this.a11yIdToNodeMap.clear(),this.dataMomenticIdToNodeMap.clear();let t=yield this.context.pages();this.page=t[0];for(let r=1;r<t.length;r++)yield t[r].close();e.clearCookies&&(yield this.context.clearCookies()),e.clearStorage&&(yield(yield this.getUserPageOrFrame()).evaluate(()=>{localStorage.clear()})),yield this.navigate({url:(o=e.url)!=null?o:this.baseURL,wrapPossibleNavigation:!1,initialNavigation:!0})})}pageSetup(){return l(this,null,function*(){try{this.localMode||(yield this.page.evaluate(jo))}catch(e){}})}wait(e){return l(this,null,function*(){yield X(e)})}toggleHints(e){return l(this,null,function*(){let t=yield this.getUserPageOrFrame();e.state==="on"?(yield t.addStyleTag({content:Tt.css}),yield t.addScriptTag({content:Tt.js}),yield t.evaluate(Go)):yield t.evaluate(Vo)})}showHints(){return l(this,null,function*(){yield this.toggleHints({state:"on"});let e=()=>l(this,null,function*(){try{yield this.toggleHints({state:"off"})}catch(t){this.logger.debug({err:t},"Failed to remove vision hints")}});setTimeout(()=>{e()},3e3)})}cleanup(){return l(this,null,function*(){yield this.page.close(),yield this.context.close(),yield this.browser.close()})}get closed(){return this.page.isClosed()||!this.browser.isConnected()}html(){return l(this,null,function*(){return(yield this.getUserPageOrFrame()).content()})}url(){return l(this,null,function*(){return(yield this.getUserPageOrFrame()).url()})}screenshotWithHints(e=100,t="device",o="/tmp/screenshots/test.jpg"){return l(this,null,function*(){let r=o==null?void 0:o.split("."),s=r==null?void 0:r.slice(0,-1).join("."),a=r==null?void 0:r.slice(-1)[0],i=yield this.screenshot(e,t,o?`${s}-before-hint.${a}`:void 0);yield this.showHints();let c=yield this.screenshot(e,t,o?`${s}-after-hint.${a}`:void 0);return{before:i,after:c}})}screenshot(e=100,t="device",o){return l(this,null,function*(){let r={fullPage:!1,quality:e,scale:t,type:"jpeg",caret:"initial",path:o};return!this.localMode||!this.activeFrame?this.page.screenshot(r):Buffer.from("")})}viewport(){return l(this,null,function*(){if(this.localMode&&this.activeFrame){let t=yield this.page.locator(`iframe[name="${this.activeFrame}"]`).boundingBox();if(!t)throw new Error(`Failed to get bounding box for frame: ${this.activeFrame}`);return t}let e=this.page.viewportSize();if(!e)throw new Error("failed to get viewport");return e})}navigate(r){return l(this,arguments,function*({url:e,wrapPossibleNavigation:t=!0,initialNavigation:o=!1}){this.logger.debug(`Navigating to ${e}`),o&&this.localMode&&(yield this.registerLocalRequestInterceptors(this.context));let s=Date.now(),a=()=>l(this,null,function*(){try{yield(yield this.getUserPageOrFrame()).goto(e,{waitUntil:"load",timeout:3e3}),this.logger.debug({url:e},`Got load event in ${Math.floor(Date.now()-s)}ms`)}catch(c){this.logger.warn({url:e},"Timeout elapsed waiting for page to fire load event, continuing anyways...")}finally{yield this.initCDPSession()}});t?yield this.wrapPossibleNavigation(a):yield a();let i=yield this.url();if(No.has(i)&&process.env.NODE_ENV==="production")throw new Error(`${e} took too long to load \u{1F61E}. Please ensure the site and your internet are working.`);yield this.pageSetup(),this.logger.info({url:e},"Navigation complete")})}fill(r,s){return l(this,arguments,function*(e,t,o={}){let a=yield this.click(e,{doubleClick:!1,rightClick:!1});return yield this.type(t,o),a})}type(o){return l(this,arguments,function*(e,t={}){let{clearContent:r=!0,pressKeysSequentially:s=!1}=t;r&&(process.platform==="darwin"?yield this.page.keyboard.press("Meta+A"):yield this.page.keyboard.press("Control+A"),yield this.page.keyboard.press("Backspace")),s?yield this.page.keyboard.type(e):yield this.page.keyboard.insertText(e)})}clickByA11yID(o){return l(this,arguments,function*(e,t={}){let r=this.a11yIdToNodeMap.get(e);if(!r)throw new Error(`Could not find DOM node during click: ${e}`);let s=yield this.clickUsingCDP(r,t);return yield this.highlightNode(s),r.serialize({noChildren:!0,noProperties:!0,noID:!0})})}selectOptionByA11yID(e,t){return l(this,null,function*(){let o=this.a11yIdToNodeMap.get(e);if(!o)throw new Error(`Could not find DOM node while selecting option: ${e}`);if(!o.backendNodeID)throw new Error(`Select target missing backend node id: ${o.getLogForm()}`);return yield(yield this.getLocatorFromBackendID(o.backendNodeID)).selectOption(t,{timeout:8e3}),yield this.highlightNode(o),o.serialize({noChildren:!0,noProperties:!0,noID:!0})})}scrollIntoView(e){return l(this,null,function*(){let t=yield this.resolveCachedTargetToID(e),o=this.a11yIdToNodeMap.get(t);if(!o)throw new Error(`Could not find node in DOM with a11y id: ${t}`);if(!o.backendNodeID)throw new Error(`Focus target missing backend node id: ${o.getLogForm()}`);yield(yield this.getLocatorFromBackendID(o.backendNodeID)).scrollIntoViewIfNeeded({timeout:8e3})})}highlight(e){return l(this,null,function*(){try{let t=yield this.resolveCachedTargetToID(e),o=this.a11yIdToNodeMap.get(t);if(!o)throw new Error(`Could not find DOM node during highlight: ${t}`);if(!o.backendNodeID)throw new Error(`Select target missing backend node id: ${o.getLogForm()}`);yield this.highlightNode(o)}catch(t){this.logger.warn({err:t,target:e},"Failed to highlight target")}})}highlightNode(e){return l(this,null,function*(){try{yield this.cdpClient.send("Overlay.highlightNode",{highlightConfig:Bo,backendNodeId:e.backendNodeID})}catch(o){this.logger.warn("Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests.")}let t=()=>l(this,null,function*(){try{yield this.cdpClient.send("Overlay.hideHighlight",{backendNodeId:e.backendNodeID})}catch(o){this.logger.debug({err:o},"Failed to remove node highlight")}});setTimeout(()=>{t()},3e3)})}wrapPossibleNavigation(r){return l(this,arguments,function*(e,t=8e3,o=!0){let s=Date.now(),a=yield this.url(),i=Date.now(),c=new Map,m=new Map,u=C=>{var J;let R=It(C.request());m.set(R,((J=m.get(R))!=null?J:0)+1);let U=C.status();U>=500&&this.logger.warn({request:R,status:U},"Received 500 level response")},h=C=>{var U;if(!qo(C,a))return;let R=It(C);c.set(R,((U=c.get(R))!=null?U:0)+1),i=Date.now()};this.page.on("response",u),this.page.on("request",h);let w=[];o&&(w=(yield this.context.pages()).map(C=>C.url()));let S=!1,b=e().catch(C=>(S=!0,C instanceof Error?C:new Error(`${C}`)));yield X(250);let f=C=>l(this,null,function*(){let R=yield C;if(R instanceof Error)throw R;return R}),p=new Set,d=!1,v=yield l(this,null,function*(){for(;!S&&!(!d&&Date.now()-s>t);){if(yield X(250),d=!1,p=new Set,Date.now()-i<=1250)continue;let C=!1;for(let R of c.keys())c.get(R)!==m.get(R)&&(Yo(R)&&(d=!0),C=!0,p.add(R));if(!C)return this.logger.debug({url:this.url,requests:JSON.stringify(Array.from(c.entries()))},`Network idle in ${Math.floor(Date.now()-s)}ms`),!0}return!S&&p.size>0&&this.logger.warn({url:this.url,unfinishedRequests:JSON.stringify(Array.from(p.entries()))},"Timeout elapsed waiting for network idle, continuing anyways..."),!1});if(this.page.off("response",u),this.page.off("request",h),!v)return f(b);let L=yield this.url();if(!S&&le(L,a)){this.logger.debug({startUrl:a,newUrl:L},"Detected url change in wrapPossibleNavigation, waiting for load state");let C=Math.max(t-(Date.now()-s),0);if(C>0)try{yield(yield this.getUserPageOrFrame()).waitForLoadState("load",{timeout:C})}catch(R){this.logger.warn({url:yield this.url()},"Timeout elapsed waiting for load state, continuing anyways...")}}if(o){let C=(yield this.context.pages()).map(R=>R.url());if(C.length>w.length)for(let R of C)R!==L&&(yield this.switchToPage(R))}return f(b)})}resolveCachedTargetToID(e){return l(this,null,function*(){if(!_e(e)){let i=this.a11yIdToNodeMap.get(e.id);if(!i)throw new Error(`Resolving target failed, fresh value did not exist in node map: ${e.id}`);return Le(i,e),e.id}let t=(yield this.getA11yTree()).serialize();this.logger.debug({tree:t},"Refreshed a11y tree before resolving target");let o=this.a11yIdToNodeMap.get(e.id);if(o){let i=xt(o,e);if(i>=5)return this.logger.debug({target:e,proposedNode:o.getLogForm(),comparisonScore:i},"Resolved cached a11y target to node with exact same id"),Le(o,e),e.id}let r=1/0,s=1/0,a;for(let i of this.a11yIdToNodeMap.values()){let c=xt(i,e);if(c>=5)return this.logger.debug({newNode:i.getLogForm(),target:e,comparisonScore:c},"Resolved cached a11y target to new node with field comparison"),Le(i,e),i.id;if(!e.serializedForm)continue;let m=i.serialize({noID:!0,maxLevel:1,neighbors:1});if(Math.abs(m.length-e.serializedForm.length)>15)continue;let u=kr(e.serializedForm,m),h=u/Math.min(e.serializedForm.length,m.length);u<r&&h<.2&&(r=u,s=h,a=i)}if(a&&r<15)return this.logger.debug({newNode:a.getLogForm(),target:e,distance:r,ratio:s},"Resolved cached a11y target to new node with pure levenshtein distance"),Le(a,e),a.id;throw new Error(`Could not find any relevant node given cached target: ${JSON.stringify(e)}`)})}click(o){return l(this,arguments,function*(e,t={}){let r=yield this.resolveCachedTargetToID(e);return yield this.wrapPossibleNavigation(()=>this.clickByA11yID(r,t))})}hover(e){return l(this,null,function*(){let t=yield this.resolveCachedTargetToID(e),o=this.a11yIdToNodeMap.get(t);if(!o)throw new Error(`Could not find DOM node for hover: ${t}`);if(!o.backendNodeID)throw new Error(`Hover target missing backend node id: ${o.getLogForm()}`);return yield(yield this.getLocatorFromBackendID(o.backendNodeID)).hover({timeout:8e3}),yield this.highlightNode(o),o.serialize({noChildren:!0,noProperties:!0,noID:!0})})}selectOption(e,t){return l(this,null,function*(){let o=yield this.resolveCachedTargetToID(e);return this.selectOptionByA11yID(o,t)})}press(e){return l(this,null,function*(){yield this.wrapPossibleNavigation(()=>this.page.keyboard.press(e))})}refresh(){return l(this,null,function*(){if(this.localMode&&this.activeFrame){let t=(yield this.getUserPageOrFrame()).url();yield this.navigate({url:t,wrapPossibleNavigation:!0})}else yield this.page.reload(),yield this.pageSetup()})}getA11yTree(){return l(this,null,function*(){yield this.initCDPSession();let e=null,t=0,o=this.url;for(;!e;)try{let r=yield this.getRawA11yTree();if(!r.root||r.allNodes.length===0)throw new Error("No a11y tree found on page");e=Ho(r,this.logger)}catch(r){if(this.logger.error({err:r,url:o},"Error fetching a11y tree"),t===0)yield X(1e3),t++;else throw new Error(`Max retries exceeded fetching a11y tree: ${r}`)}return e.root||this.logger.warn("A11y tree was pruned entirely"),this.a11yIdToNodeMap=e.a11yIdNodeMap,this.dataMomenticIdToNodeMap=e.dataMomenticIdMap,e})}getA11yIdFromDataMomenticId(e){var t;return(t=this.dataMomenticIdToNodeMap.get(e))==null?void 0:t.id}getRawA11yTree(){return l(this,null,function*(){let e=yield this.url(),t=Date.now(),o=()=>{t=Date.now()};this.cdpClient.addListener("Accessibility.nodesUpdated",o);let r=!1,s=()=>{this.logger.info({url:e},"Load event fired on page"),r=!0,t=Date.now()};this.cdpClient.addListener("Accessibility.loadComplete",s);let a=Date.now(),i=!0;for(;Date.now()-a<3e3;){if(yield X(250),!r&&Date.now()-a<1e3){process.env.NODE_ENV!=="production"&&this.logger.debug({url:e},"A11y tree not loaded yet, waiting...");continue}if(Date.now()-t>=1250){i=!1;break}this.logger.debug({url:e},"A11y tree not stable yet, waiting...")}this.logger.debug({duration:Date.now()-a,eventReceived:r,timeoutTriggered:i},"A11y wait phase completed"),yield(yield this.getUserPageOrFrame()).evaluate(Wo);let c;if(this.localMode&&this.activeFrame){let{result:{objectId:u}}=yield this.cdpClient.send("Runtime.evaluate",{expression:`document.querySelector("#${this.activeFrame}")`}),h=yield this.cdpClient.send("DOM.describeNode",{objectId:u}),{nodes:w}=yield this.cdpClient.send("Accessibility.getFullAXTree",{frameId:h.node.frameId}),S=w[0];if(!S)throw new Error("No contents found in main page viewer. Are you sure a page is loaded?");c=S}else({node:c}=yield this.cdpClient.send("Accessibility.getRootAXNode"));let{nodes:m}=yield this.cdpClient.send("Accessibility.queryAXTree",{backendNodeId:c.backendDOMNodeId});return this.cdpClient.removeListener("Accessibility.loadComplete",s),this.cdpClient.removeListener("Accessibility.nodesUpdated",o),{root:c,allNodes:m}})}clickUsingVisualCoordinates(e){return l(this,null,function*(){let t=yield this.getElementLocation(e);if(!t)throw new Error(`Could not find element location with backend node id: ${e}`);this.logger.debug({location:t},"Executing mouse click"),yield this.page.mouse.click(t.centerX,t.centerY)})}getIDAttributeUsingCDP(e){return l(this,null,function*(){yield this.cdpClient.send("DOM.getDocument",{depth:0});let t=yield this.cdpClient.send("DOM.requestNode",{objectId:e}),r=(yield this.cdpClient.send("DOM.getAttributes",{nodeId:t.nodeId})).attributes,s=r.findIndex(a=>a==="data-momentic-id");return s===-1?"":r[s+1]||""})}getLocatorFromBackendID(e){return l(this,null,function*(){let t=yield this.cdpClient.send("DOM.resolveNode",{backendNodeId:e});if(!t||!t.object.objectId)throw new Error(`Could not resolve backend node ${e}`);try{let o=yield this.getIDAttributeUsingCDP(t.object.objectId);if(!o)throw new Error("Failed getting data-momentic-id attribute using CDP");return(yield this.getUserPageOrFrame()).locator(`[data-momentic-id="${o}"]`)}catch(o){throw this.logger.error({err:o},"Failed to get ID attribute"),o}})}clickUsingCDP(o){return l(this,arguments,function*(e,t={}){let r=0,s=e;for(;r<Do;){if(!s||s.role==="RootWebArea")throw new Error(`Attempted to click node with no clickable surrounding elements: ${e.getLogForm()}`);if(s.role==="StaticText"){s=s.parent;continue}let a=s.backendNodeID;if(!a){this.logger.warn({node:s.getLogForm()},"Click candidate had no backend node ID"),s=s.parent;continue}try{let i=yield this.getLocatorFromBackendID(a);return t.doubleClick?yield i.dblclick({timeout:8e3}):yield i.click({timeout:8e3,button:t.rightClick?"right":"left"}),s.id!==e.id&&this.logger.info({oldNode:e.getLogForm(),newNode:s.getLogForm()},"Redirected click successfully to new element"),s}catch(i){this.logger.error({err:i,node:s.getLogForm()},"Failed click or click timed out"),r++,s=s.parent}}throw new Error(`Max click redirection attempts exhausted on original element: ${e.getLogForm()}`)})}getElementLocation(e){return l(this,null,function*(){let t=yield this.cdpClient.send("DOMSnapshot.captureSnapshot",{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0}),o=yield this.page.evaluate(()=>window.devicePixelRatio);process.platform==="darwin"&&o===1&&(o=2);let r=t.documents[0],s=r.layout,a=r.nodes,i=a.nodeName||[],c=a.backendNodeId||[],m=s.nodeIndex,u=s.bounds,h=-1;for(let E=0;E<i.length;E++)if(c[E]===e){h=m.indexOf(E);break}if(h===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[w=0,S=0,b=0,f=0]=u[h];w/=o,S/=o,b/=o,f/=o;let p=w+b/2,d=S+f/2;return{centerX:p,centerY:d}})}scrollUp(e){return l(this,null,function*(){yield this.page.mouse.wheel(0,-(e!=null?e:Z.VIEWPORT.height))})}scrollDown(e){return l(this,null,function*(){yield this.page.mouse.wheel(0,e!=null?e:Z.VIEWPORT.height)})}goForward(){return l(this,null,function*(){yield this.wrapPossibleNavigation(()=>l(this,null,function*(){return this.localMode&&this.activeFrame?(yield this.getUserPageOrFrame()).evaluate(e=>{let t=e().contentWindow;t?t.history.forward():console.error("Failed to get content window for frame")},()=>document.querySelector(`iframe[name="${this.activeFrame}"]`)):this.page.goForward({timeout:8e3})})),yield this.pageSetup()})}goBack(){return l(this,null,function*(){yield this.wrapPossibleNavigation(()=>l(this,null,function*(){return this.localMode&&this.activeFrame?(yield this.getUserPageOrFrame()).evaluate(e=>{let t=e().contentWindow;t?t.history.back():console.error("Failed to get content window for frame")},()=>document.querySelector(`iframe[name="${this.activeFrame}"]`)):this.page.goBack({timeout:8e3})})),yield this.pageSetup()})}switchToPage(e){return l(this,null,function*(){let t=yield this.context.pages();for(let o=0;o<t.length;o++){let r=t[o];if(r.url().includes(e)){this.logger.info(`Switching to tab ${o} with url ${r.url()}`),this.page=r;try{yield r.waitForLoadState("load",{timeout:3e3})}catch(s){this.logger.warn({url:yield this.url()},"Timeout elapsed waiting for load state during tab switch, continuing anyways...")}yield this.pageSetup(),yield this.initCDPSession();return}}throw new Error(`Could not find page with url containing ${e}`)})}setCookie(e){return l(this,null,function*(){let t=Ht(e);yield this.context.addCookies([t])})}solveCaptcha(){return l(this,null,function*(){yield this.getA11yTree();let e;for(let i of this.a11yIdToNodeMap.values())if(i.role==="image"&&i.name.toLowerCase().includes("captcha")){if(!i.backendNodeID)continue;e=yield this.getLocatorFromBackendID(i.backendNodeID);break}if(!e){let i=yield(yield this.getUserPageOrFrame()).solveRecaptchas();if(!i.captchas||!i.captchas.length)throw new Error("No captchas found on the page");return}let t=yield e.screenshot({type:"jpeg",animations:"allow",quality:100}),o=yield fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:process.env.TWO_CAPTCHA_KEY,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!o.ok){let i=`Captcha solver API returned error response: ${o.statusText}`;throw this.logger.error({text:yield o.text()},i),new Error(i)}let{taskId:r}=yield o.json(),s=Date.now(),a="";for(;Date.now()-s<6e4;){yield X(2500);let i=yield fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:process.env.TWO_CAPTCHA_KEY,taskId:r})});if(!i.ok){let m=`Captcha solution API returned error response: ${i.statusText}`;throw this.logger.error({text:yield i.text()},m),new Error(m)}let c=yield i.json();if(c.errorId){let m=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(m),new Error(m)}if(c.status==="ready"){a=c.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a})}};Z.USER_AGENT=en["Desktop Chrome"].userAgent,Z.VIEWPORT={width:1920,height:1080};var F=Z;var Xe=s=>l(void 0,null,function*(){var a=s,{controller:n,step:e,logger:t,advanced:o}=a,r=pe(a,["controller","step","logger","advanced"]);var c,m,u,h,w,S,b;(c=r.onStarted)==null||c.call(r),n.resetHistory();let i=M(T({},e),{startedAt:new Date,userAgent:F.USER_AGENT,finishedAt:new Date,results:[],status:"SUCCESS"});try{let f=0,p=e.commands&&e.commands.length>0;for(;;){if(f>20)throw new Error(`Exceeded max number of commands per step (${20})`);if(n.isClosed())throw new Error("Cancelling remaining steps in AI action because the controller is now closed");let d,E=new Date,v=yield n.browser.screenshot(),L=yield r.onSaveScreenshot(v);if(p){if(d=e.commands[f],!d)throw new Error(`Saved command at index ${f} is undefined.`)}else{t.info(`Executing sub-command ${f} within AI step`);let R=yield n.promptToCommand(e.type,e.text,o.disableAICaching);if(d=R.command,d.type==="FAILURE"){i.finishedAt=new Date,i.status="FAILED",i.message=d.thoughts;break}let U=f;l(void 0,null,function*(){var V;if("target"in d&&d.target){yield new Promise(be=>setTimeout(()=>be(),500));try{let be=yield Gr(n,R.context,d.target);d.target.elementDescriptor=be,(V=r.onCommandExecuted)==null||V.call(r,{commandIndex:U,command:d})}catch(be){t.error({err:be},"Failed to generate element description, continuing...")}}})}(m=r.onCommandGenerated)==null||m.call(r,{commandIndex:f,message:tt[d.type]||`Unknown command (${d.type})`});let C={beforeScreenshot:L,beforeUrl:yield n.browser.url(),startedAt:E,viewport:yield n.browser.viewport(),finishedAt:new Date,status:"SUCCESS"};t.info(`Executing sub-command ${f} within AI step: ${ye(d)}`);try{let R=yield n.executeCommand(d,o.disableAICaching,p);t.info(`AI sub-command ${f} completed successfully`),C.elementInteracted=R.elementInteracted;let U=yield n.browser.screenshot(),J=yield r.onSaveScreenshot(U);C.afterScreenshot=J,C.afterUrl=yield n.browser.url(),C.finishedAt=new Date;let V={status:"SUCCESS",startedAt:C.startedAt,finishedAt:C.finishedAt,type:"PRESET_ACTION",command:d,results:[C]};if(i.results.push(V),(u=r.onCommandExecuted)==null||u.call(r,{commandIndex:f,output:V,command:d}),d.type==="SUCCESS"){i.finishedAt=new Date,i.status="SUCCESS",i.message=(h=R.thoughts)!=null?h:"All commands completed.";break}if(R.succeedImmediately&&!p){i.finishedAt=new Date,i.status="SUCCESS",i.message=R.succeedImmediatelyReason,d={type:"SUCCESS"},(w=r.onCommandExecuted)==null||w.call(r,{commandIndex:f+1,output:V,command:d}),i.results.push(M(T({},V),{command:d}));break}}catch(R){if(p){p=!1,f=0,i.results=[];continue}let U=R instanceof Error?R.message:`${R}`;C.status="FAILED",C.message=U,C.finishedAt=new Date,C.afterUrl=yield n.browser.url();let J;try{J=yield n.browser.screenshot()}catch(V){t.warn({err:V},"Failed to take screenshot after error, skipping")}C.afterScreenshot=J,i.results.push({status:"FAILED",startedAt:C.startedAt,finishedAt:C.finishedAt,type:"PRESET_ACTION",command:d,results:[C],message:U}),i.status="FAILED",i.finishedAt=new Date,i.message=U;break}f++}}catch(f){i.message=f instanceof Error?f.message:`${f}`,i.finishedAt=new Date,i.status="FAILED"}return i.status==="SUCCESS"?(S=r.onSuccess)==null||S.call(r,{message:i.message||"AI step succeeded.",startedAt:i.startedAt.getTime(),durationMs:i.finishedAt.getTime()-i.startedAt.getTime(),output:i}):(b=r.onFailure)==null||b.call(r,{message:i.message||"AI step errored.",startedAt:i.startedAt.getTime(),durationMs:i.finishedAt.getTime()-i.startedAt.getTime(),output:i}),i});function Gr(n,e,t){return l(this,null,function*(){var r;let o=(r=t.a11yData)==null?void 0:r.id;if(!o)throw new Error("Attempted to get reverse mapping for command with no a11y id target");return n.getReverseMappedTarget(e,o,!0)})}var Je=r=>l(void 0,null,function*(){var s=r,{controller:n,step:e,advanced:t}=s,o=pe(s,["controller","step","advanced"]);var u,h,w,S;(u=o.onStarted)==null||u.call(o);let a=new Date,i=yield n.browser.url(),c=yield n.browser.screenshot(),m=yield o.onSaveScreenshot(c);try{let b=yield n.executePresetStep(e.command,t.disableAICaching),f=yield n.browser.screenshot(),p=yield o.onSaveScreenshot(f),d=new Date,E=M(T({},e),{startedAt:a,finishedAt:d,status:"SUCCESS",results:[]}),v="Successfully executed preset action.";e.command.type==="AI_ASSERTION"&&(v=b.thoughts||"Assertion passed.");let L={beforeUrl:i,beforeScreenshot:m,afterUrl:yield n.browser.url(),afterScreenshot:p,startedAt:a,finishedAt:d,viewport:yield n.browser.viewport(),status:"SUCCESS"};return E.status="SUCCESS",E.results=[L],E.message=v,(h=o.onSuccess)==null||h.call(o,{message:v,startedAt:a.getTime(),durationMs:d.getTime()-a.getTime(),command:e.command,output:E}),E}catch(b){o.logger.error({err:b},`Failed executing preset step ${e.command.type}`);let f=new Date,p=b instanceof Error?b.message:`${b}`,d=yield n.browser.screenshot();if(e.command.type==="AI_ASSERTION"&&e.command.cancelOnFailure){let v=M(T({},e),{startedAt:a,finishedAt:f,status:"CANCELLED",message:p,results:[{beforeUrl:i,beforeScreenshot:m,afterUrl:yield n.browser.url(),afterScreenshot:d,startedAt:a,finishedAt:f,viewport:yield n.browser.viewport(),status:"CANCELLED",message:p}]});return(w=o.onCancelled)==null||w.call(o,{message:p,startedAt:a.getTime(),durationMs:f.getTime()-a.getTime(),output:v}),v}let E=M(T({},e),{startedAt:a,finishedAt:f,status:"FAILED",message:p,results:[{beforeUrl:i,beforeScreenshot:m,afterUrl:yield n.browser.url(),afterScreenshot:d,startedAt:a,finishedAt:f,viewport:yield n.browser.viewport(),status:"FAILED",message:p}]});return(S=o.onFailure)==null||S.call(o,{message:p,startedAt:a.getTime(),durationMs:f.getTime()-a.getTime(),output:E}),E}});var on=s=>l(void 0,null,function*(){var a=s,{controller:n,step:e,advanced:t,logger:o}=a,r=pe(a,["controller","step","advanced","logger"]);var c,m,u,h;(c=r.onStarted)==null||c.call(r);let i={type:"MODULE",moduleId:e.moduleId,startedAt:new Date,userAgent:F.USER_AGENT,results:[],finishedAt:new Date,status:"SUCCESS"};for(let w=0;w<e.steps.length;w++){let S=e.steps[w];if(n.isClosed())throw i.status="CANCELLED",new Error("Cancelling remaining steps in module because the controller is now closed");o.debug({i:w,moduleStep:S},"Starting module step"),o.info(`Starting module sub-step ${w+1}/${e.steps.length}: ${Be(S)}`);let b;switch(S.type){case"PRESET_ACTION":b=yield Je({controller:n,step:S,advanced:t,logger:o,onSaveScreenshot:r.onSaveScreenshot,onStarted(){var p;(p=r.onStepStarted)==null||p.call(r,{index:w})},onSuccess({message:p,startedAt:d,durationMs:E,output:v}){var L;(L=r.onStepSuccess)==null||L.call(r,{index:w,message:p,startedAt:d,durationMs:E,output:v})},onFailure({message:p,startedAt:d,durationMs:E,output:v}){var L;(L=r.onStepFailure)==null||L.call(r,{index:w,message:p,startedAt:d,durationMs:E,output:v})},onCancelled({message:p,startedAt:d,durationMs:E,output:v}){var L;(L=r.onStepCancelled)==null||L.call(r,{index:w,message:p,startedAt:d,durationMs:E,output:v})}});break;case"AI_ACTION":b=yield Xe({controller:n,step:S,advanced:t,logger:o,onSaveScreenshot:r.onSaveScreenshot,onStarted(){var p;(p=r.onStepStarted)==null||p.call(r,{index:w})},onSuccess({message:p,startedAt:d,durationMs:E,output:v}){var L;(L=r.onStepSuccess)==null||L.call(r,{index:w,message:p,startedAt:d,durationMs:E,output:v})},onFailure({message:p,startedAt:d,durationMs:E,output:v}){var L;(L=r.onStepFailure)==null||L.call(r,{index:w,message:p,startedAt:d,durationMs:E,output:v})},onCommandGenerated({commandIndex:p,message:d}){var E;(E=r.onCommandGenerated)==null||E.call(r,{index:w,commandIndex:p,message:d})},onCommandExecuted({commandIndex:p,command:d,output:E}){var v;(v=r.onCommandExecuted)==null||v.call(r,{index:w,commandIndex:p,command:d,output:E})}});break;default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(S)}if(i.results.push(b),b.status==="FAILED"||b.status==="CANCELLED"){i.status=b.status,i.finishedAt=new Date,i.message=b.message;for(let f=w+1;f<e.steps.length;f++){let p=e.steps[f],d=M(T({},p),{status:"CANCELLED",startedAt:new Date,finishedAt:new Date,userAgent:F.USER_AGENT,results:[],message:"Cancelled due to previous failure."});i.results.push(d)}break}}return i.status==="SUCCESS"?(m=r.onSuccess)==null||m.call(r,{message:"Executed module step.",startedAt:i.startedAt.getTime(),durationMs:i.finishedAt.getTime()-i.startedAt.getTime(),output:i}):i.status==="FAILED"?(u=r.onFailure)==null||u.call(r,{message:"Failed to execute module step.",startedAt:i.startedAt.getTime(),durationMs:i.finishedAt.getTime()-i.startedAt.getTime(),output:i}):i.status==="CANCELLED"&&((h=r.onCancelled)==null||h.call(r,{message:"Module step cancelled.",startedAt:i.startedAt.getTime(),durationMs:i.finishedAt.getTime()-i.startedAt.getTime(),output:i})),i});import{v4 as lm}from"uuid";var cm=process.env.AWS_ACCESS_KEY_ID,dm=process.env.AWS_SECRET_ACCESS_KEY,mm=process.env.S3_REGION,um=process.env.S3_BUCKET;var nn=a=>l(void 0,[a],function*({test:n,runId:e,controller:t,logger:o,onUpdateRun:r,onSaveScreenshot:s}){try{let i=yield Vr({test:n,runId:e,controller:t,logger:o,onUpdateRun:r,onSaveScreenshot:s});if(i==="PASSED"||i==="CANCELLED")return i;throw new D("InternalPlatformError",i.message||"An unknown platform error occurred")}catch(i){throw i instanceof D||(i=new D("InternalPlatformError",i instanceof Error?i.message:`${i}`,{cause:i})),i}finally{yield t.browser.cleanup()}}),Vr=a=>l(void 0,[a],function*({test:n,runId:e,controller:t,logger:o,onUpdateRun:r,onSaveScreenshot:s}){var w;let i=$e.parse(n.advanced),c=o.child({runId:e,testId:n.id});c.info("Starting test run"),yield r({status:"RUNNING",startedAt:new Date});let m,u="PASSED",h=[];for(let S=0;S<n.steps.length;S++){let b=n.steps[S];c.info(`Starting step ${S+1}/${n.steps.length}: ${Be(b)}`);let f;switch(b.type){case"PRESET_ACTION":f=yield Je({controller:t,step:b,advanced:i,logger:c,onSaveScreenshot:s});break;case"AI_ACTION":f=yield Xe({controller:t,step:b,advanced:i,logger:c,onSaveScreenshot:s});break;case"RESOLVED_MODULE":f=yield on({controller:t,step:b,advanced:i,logger:c,onSaveScreenshot:s});break;default:return(d=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(b)}if(h.push(f),yield r({results:h}),f.status==="SUCCESS"){c.info(`Step ${S+1}/${n.steps.length} succeeded`);continue}if(f.status!=="FAILED"&&f.status!=="CANCELLED")throw new D("InternalPlatformError",`Received unexpected non-terminal status from step: ${f.status}`);c.info({message:(w=h[h.length-1])==null?void 0:w.message},`Step ${S+1}/${n.steps.length} ended with status: ${f.status}`),m=f,u=f.status;for(let p=S+1;p<n.steps.length;p++){let d=n.steps[p];if(d.type==="RESOLVED_MODULE"){let E={type:"MODULE",moduleId:d.moduleId,startedAt:new Date,userAgent:F.USER_AGENT,results:d.steps.map(v=>M(T({},v),{status:"CANCELLED",startedAt:new Date,finishedAt:new Date,userAgent:F.USER_AGENT,results:[]})),finishedAt:new Date,status:"CANCELLED"};h.push(E)}else{let E=M(T({},d),{status:"CANCELLED",startedAt:new Date,finishedAt:new Date,userAgent:F.USER_AGENT,results:[]});h.push(E)}}break}return yield r({status:u,finishedAt:new Date,results:h}),u==="FAILED"?m:u});import{existsSync as rn,readFileSync as Wr,readdirSync as Kr,statSync as sn}from"fs";import an from"path";function ln(n){return l(this,null,function*(){let e=cn(n.paths);A.info(`Found ${e.size} test(s) to push:`),e.forEach(r=>A.info(` - ${r}`)),A.info("Loading file contents and resolving dependent modules");let t=Array.from(e).map(r=>Ct(r,se)),o=new Set(t.flatMap(r=>Object.keys(r.modules)));if(A.info(`Resolved ${e.size} test(s) and ${o.size} module(s)`),!n.yes&&!(yield we("Pushing tests overwrites tests on production and will instantly affect scheduled runs. Continue?",!0))){A.error("Push cancelled");return}yield n.client.updateTestWithYAML(t),A.info("Update successful!")})}function Yr(n){if(!n.endsWith(".yaml"))return!1;let e=Wr(n,"utf8");return e.includes("momentic/test")?e.match(/localOnly:.*true/)?(A.warn(`Skipping local-only test: ${n}`),!1):!0:(A.warn(`Skipping YAML that is not a Momentic test: ${n}`),!1)}function cn(n,e=new Set){for(let t of n){let o=an.resolve(t);if(o&&rn(o)&&sn(o).isDirectory()){let r=Kr(o).map(s=>an.join(o,s));cn(r,e);continue}if(o.endsWith(".yaml")){if(!rn(o)||!sn(o).isFile())throw new Error(`File not found or unreadable: ${o}`);if(!Yr(o))continue;e.add(o)}}return e}import{existsSync as un,statSync as mi}from"fs";import ui from"wait-on";var qr={type:"a11y",version:"1.0.0",useHistory:"diff",useGoalSplitter:!0},Ot=qr;import Xr from"dedent";import Jr from"diff-lines";var Qr=1e4,Me=class{constructor({browser:e,config:t,generator:o,logger:r}){this.closed=!1;this.browser=e,this.generator=o,this.config=t,this.logger=r,this.pendingInstructions=[],this.commandHistory=[]}get history(){return this.commandHistory.filter(e=>e.state==="DONE")}get lastExecutedCommand(){let e=this.history;return e.length===0?null:e[e.length-1]}setOpen(){this.closed=!1}isClosed(){return this.closed}setLogger(e){this.logger=e}resetHistory(){this.commandHistory=[],this.pendingInstructions=[]}resetState(e){return l(this,null,function*(){this.resetHistory(),this.closed=!0,yield this.browser.reset(e)})}getBrowserState(){return l(this,null,function*(){let t=yield(yield this.browser.getA11yTree()).serialize();return this.logger.debug({tree:t},"Got a11y tree"),t})}getSerializedHistory(e,t){let o;return this.config.useHistory==="diff"?o=this.getDiffHistory(e,t):o=this.getListHistory(),o}splitUserGoal(e,t,o){return l(this,null,function*(){if(e==="AI_ACTION"&&t.match(/[,!;.]|(?:and)|(?:then)/)&&this.config.useGoalSplitter){let r=yield this.generator.getGranularGoals({goal:t,url:yield this.browser.url()},o);this.pendingInstructions=r.reverse()}else this.pendingInstructions=[t]})}promptToCommand(e,t,o){return l(this,null,function*(){try{return yield this.promptToCommandHelper(e,t,o)}catch(r){throw r instanceof D?r:new D("InternalWebAgentError",r instanceof Error?r.message:`${r}`,{cause:r})}})}promptToCommandHelper(e,t,o){return l(this,null,function*(){if(this.pendingInstructions.length===0){if(!t.trim())throw new Error("Cannot generate commands for empty goal");yield this.splitUserGoal(e,t,o)}let r=this.pendingInstructions[this.pendingInstructions.length-1];this.logger.info({goal:r},"Starting prompt translation");let s=Date.now(),a=yield this.browser.url(),i=yield this.getBrowserState();this.logger.info({duration:Date.now()-s,url:a},"Got browser state");let c=this.commandHistory.length;this.commandHistory.push({state:"PENDING",browserStateBeforeCommand:i,urlBeforeCommand:a,type:e});let m=this.getSerializedHistory(a,i),u={url:a,numPrevious:c,browserState:i,history:m,goal:r,lastCommand:this.lastExecutedCommand},h=yield this.generator.getProposedCommand(u,o);if(this.logger.info({type:h.type,thoughts:h.thoughts},"Got proposed command"),h.type==="SUCCESS"){let w=this.pendingInstructions.pop();if(this.logger.info({finishedInstruction:w,remainingInstructions:this.pendingInstructions},"Removing pending instruction due to SUCCESS"),this.pendingInstructions.length!==0)return this.commandHistory=[],this.promptToCommand(e,"",o)}else h.type==="FAILURE"&&(this.logger.info({remainingInstructions:this.pendingInstructions},"Removing pending instructions due to FAILURE"),this.pendingInstructions=[]);return{context:u,command:h}})}locateElement(e,t,o){return l(this,null,function*(){if(!e)throw new D("InternalWebAgentError","Cannot locate element with empty description");let r=yield this.getBrowserState(),s;if(t){let{before:a,after:i}=yield this.browser.screenshotWithHints();if(s=yield this.generator.getElementLocationWithVision({goal:e,screenshot:a,hintActivatedScreenshot:i},o),s.id>0){let c=this.browser.getA11yIdFromDataMomenticId(s.id);if(!c)throw new D("InternalWebAgentError",`Unable to find corresponding DOM node for id ${s.id}`);s.id=c}}else s=yield this.generator.getElementLocation({browserState:r,goal:e},o);if(s.id<0)throw new D("ActionFailureError",`Unable to locate element: ${s.thoughts?s.thoughts:"please ensure the element is visible and conforms to Accessibility guidelines"}`);return s})}getDiffHistory(e,t){let o=this.history.filter(s=>s.type==="AI_ACTION");if(o.length===0)return"<NONE/>";let r=[`
580
+ You have already executed the following commands successfully (most recent listed first)`,"-".repeat(10)];return o.reverse().forEach((s,a)=>{if(r.push(`COMMAND ${o.length-a}${a===0?" (command just executed)":""}: ${s.serializedCommand}`),a===0)if(le(s.urlBeforeCommand,e))r.push(` URL CHANGE: '${s.urlBeforeCommand}' -> '${e}'`);else{let i=Jr(s.browserStateBeforeCommand,t,{n_surrounding:1});i?i.length<Qr?(r.push("PAGE CONTENT CHANGE:"),i.split(`
581
581
  `).forEach(c=>r.push(` ${c}`))):r.push("PAGE CONTENT CHANGE: <TOO_LONG_TO_DISPLAY/>"):r.push("PAGE CONTENT CHANGE: <NONE/>")}r.push("-".repeat(10))}),r.push(`STARTING URL: ${this.browser.baseURL}`),r.join(`
582
- `)}getListHistory(){return Ur`Here are the commands that you have successfully executed:
582
+ `)}getListHistory(){return Xr`Here are the commands that you have successfully executed:
583
583
  ${this.commandHistory.filter(e=>e.type==="AI_ACTION").map(e=>`- ${e.serializedCommand}`).join(`
584
- `)}`}executeCommand(e,t,o=!1){return l(this,null,function*(){let r=this.commandHistory[this.commandHistory.length-1];if(!o&&(!r||r.state!=="PENDING"))throw new M("InternalWebAgentError","Executing command but there is no pending entry in the history");let s;try{let a=Date.now();s=yield this.executePresetStep(e,t);let i=Date.now()-a;this.logger.debug({result:s,duration:i},"Got execution result")}catch(a){throw a instanceof Error?new he(`Failed to execute command: ${a}`,{cause:a}):new he("Unexpected throw from executing command",{cause:new Error(`${a}`)})}return s.succeedImmediately&&!o&&(this.pendingInstructions.pop(),this.pendingInstructions.length>0&&(s.succeedImmediately=!1)),s.elementInteracted&&"target"in e&&e.target&&!e.target.elementDescriptor&&(e.target.elementDescriptor=s.elementInteracted.trim()),o||(r.generatedStep=e,r.serializedCommand=Y(e),r.state="DONE"),s})}executeAssertion(e,t){return l(this,null,function*(){let o;if(t.useVision)o={goal:t.assertion,url:e,screenshot:yield this.browser.screenshot(),browserState:"",history:"",numPrevious:-1,lastCommand:null};else{let s=yield this.getBrowserState(),a=this.getSerializedHistory(e,s);o={goal:t.assertion,url:e,browserState:s,history:a,lastCommand:this.lastExecutedCommand,numPrevious:this.commandHistory.length}}let r=yield this.generator.getAssertionResult(o,t.useVision,t.disableCache);if(r.relevantElements&&Promise.all(r.relevantElements.map(s=>this.browser.highlight({id:s}))),!r.result)throw new M("AssertionFailureError",r.thoughts);return{succeedImmediately:!1,thoughts:r.thoughts,urlAfterCommand:e}})}wrapElementTargetingCommand(e,t,o,r,s=!0){return l(this,null,function*(){if(!e.a11yData&&!e.elementDescriptor)throw new M("InternalWebAgentError","Cannot target element with no target data or element descriptor");let a=e.a11yData&&Le(e.a11yData);e.a11yData||(e.a11yData=Ie.parse(yield this.locateElement(e.elementDescriptor,t,o)),s=!1);try{let i=yield r(e.a11yData);return a?this.logger.debug({target:e},"Successfully used cached target to perform action"):this.logger.debug({target:e},"Successfully generated and used new a11y target information"),i}catch(i){if(s&&e.elementDescriptor)return this.logger.warn({err:i,target:e},"Failed to execute action with cached target, retrying with AI"),e.a11yData=void 0,this.wrapElementTargetingCommand(e,t,o,r,!0);if(i instanceof M)throw i;let c=`Failed to find '${e.elementDescriptor}': ${i instanceof Error?i.message:i}`;throw this.logger.error({err:i,target:e},c),new M("ActionFailureError",c,{cause:i})}})}executePresetStep(e,t){return l(this,null,function*(){try{return yield this.executePresetStepHelper(e,t)}catch(o){throw o instanceof M?o:new M("InternalWebAgentError",o instanceof Error?o.message:`${o}`,{cause:o})}})}executePresetStepHelper(e,t){return l(this,null,function*(){var r;let o=this.browser.url;switch(e.type){case"SUCCESS":return(r=e.condition)!=null&&r.assertion.trim()?this.executeAssertion(o,e.condition):{succeedImmediately:!1,urlAfterCommand:this.browser.url};case"AI_ASSERTION":return this.executeAssertion(o,e);case"NAVIGATE":yield this.browser.navigate(e.url);break;case"CAPTCHA":let s=yield this.browser.solveCaptcha();s&&(yield this.wrapElementTargetingCommand({elementDescriptor:"the captcha image solution input"},e.useVision,t,d=>this.browser.click(d)),yield this.browser.type(s,{clearContent:!0,pressKeysSequentially:!1}));break;case"GO_BACK":yield this.browser.goBack();break;case"GO_FORWARD":yield this.browser.goForward();break;case"SCROLL_DOWN":case"SCROLL_UP":let a;return e.target&&(e.target.elementDescriptor.trim()||e.target.a11yData)&&(a=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,d=>this.browser.hover(d))),e.type==="SCROLL_UP"?yield this.browser.scrollUp():yield this.browser.scrollDown(),{succeedImmediately:!1,urlAfterCommand:o,elementInteracted:a};case"WAIT":yield this.browser.wait(e.delay*1e3);break;case"REFRESH":yield this.browser.refresh();break;case"CLICK":{let d=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,p=>this.browser.click(p,{doubleClick:e.doubleClick,rightClick:e.rightClick})),h={urlAfterCommand:this.browser.url,succeedImmediately:!1,elementInteracted:d};return J(o,h.urlAfterCommand)&&(h.succeedImmediately=!0,h.succeedImmediatelyReason="URL changed"),h}case"SELECT_OPTION":{let d=yield this.wrapElementTargetingCommand(e.target,!1,t,h=>this.browser.selectOption(h,e.option));return{succeedImmediately:!1,urlAfterCommand:this.browser.url,elementInteracted:d}}case"TAB":yield this.browser.switchToPage(e.url);break;case"COOKIE":if(!e.value)break;yield this.browser.setCookie(e.value);break;case"TYPE":{let d=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,p=>this.browser.click(p));yield this.browser.type(e.value,{clearContent:e.clearContent,pressKeysSequentially:e.pressKeysSequentially}),e.pressEnter&&(yield this.browser.press("Enter"));let h={urlAfterCommand:this.browser.url,succeedImmediately:!1,elementInteracted:d};return J(o,h.urlAfterCommand)&&(h.succeedImmediately=!0,h.succeedImmediatelyReason="URL changed"),h}case"HOVER":{let d=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,h=>this.browser.hover(h));return{succeedImmediately:!1,urlAfterCommand:this.browser.url,elementInteracted:d}}case"PRESS":yield this.browser.press(e.value);let i={urlAfterCommand:this.browser.url,succeedImmediately:!1};return J(o,i.urlAfterCommand)&&(i.succeedImmediately=!0,i.succeedImmediatelyReason="URL changed"),i;default:return(d=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url}})}};import $r from"fetch-retry";var Hr=$r(global.fetch),ue="v1",ve=class{constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey}getElementLocation(e,t){return l(this,null,function*(){let o=yield this.sendRequest(`/${ue}/web-agent/locate-element`,{browserState:e.browserState,goal:e.goal,disableCache:t});return lt.parse(o)})}getElementLocationWithVision(e,t){return l(this,null,function*(){var r,s;let o=yield this.sendRequest(`/${ue}/web-agent/visual-locate`,{goal:e.goal,screenshot:(r=e.screenshot)==null?void 0:r.toString("base64"),hintActivatedScreenshot:(s=e.hintActivatedScreenshot)==null?void 0:s.toString("base64"),disableCache:t});return lt.parse(o)})}getAssertionResult(e,t,o){return l(this,null,function*(){var s;if(t){let a=yield this.sendRequest(`/${ue}/web-agent/assertion`,{url:e.url,goal:e.goal,screenshot:(s=e.screenshot)==null?void 0:s.toString("base64"),disableCache:o,vision:!0});return at.parse(a)}let r=yield this.sendRequest(`/${ue}/web-agent/assertion`,{url:e.url,browserState:e.browserState,goal:e.goal,history:e.history,numPrevious:e.numPrevious,lastCommand:e.lastCommand,disableCache:o,vision:!1});return at.parse(r)})}getProposedCommand(e,t){return l(this,null,function*(){let o=yield this.sendRequest(`/${ue}/web-agent/next-command`,{url:e.url,browserState:e.browserState,goal:e.goal,history:e.history,numPrevious:e.numPrevious,lastCommand:e.lastCommand,disableCache:t});return Qt.parse(o)})}getGranularGoals(e,t){return l(this,null,function*(){let o=yield this.sendRequest(`/${ue}/web-agent/split-goal`,{url:e.url,goal:e.goal,disableCache:t});return Zt.parse(o)})}sendRequest(e,t){return l(this,null,function*(){let o=yield Hr(`${this.baseURL}${e}`,{retries:1,retryDelay:1e3,method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!o.ok)throw new Error(`Request to ${e} failed with status ${o.status}: ${yield o.text()}`);return o.json()})}};import Br from"@actions/exec";import jr from"@actions/io";import{spawn as Gr}from"child_process";import Vr from"quote";import Wr from"string-argv";function Wo(n,e=!0){return l(this,null,function*(){let t=Wr(n),o=yield jr.which(t[0],!0),r=t.slice(1),s=Br.exec(Vr(o),r,{delay:100});if(e)return s})}function Ko(n){return l(this,null,function*(){return new Promise((e,t)=>{let o={stdio:"inherit",env:process.env,detached:!0},r=Gr("bash",["-c",n],o),s=!1;process.on("exit",()=>r.pid!==void 0&&!s&&process.kill(-r.pid)),r.on("close",a=>{if(s=!0,a===0){e();return}t(`command exited with code ${a}`)})})})}import Lt from"fs";import Yo from"path";var Kr=new Set(["modules","node_modules","dist","bin",".git","logs",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"]);function Ot(n){var r;let e=(r=n.split(Yo.sep).pop())!=null?r:"";if(Kr.has(e))return e!=="modules"&&S.warn(`Skipping directory '${n}' because it is likely an artifact folder.`),[];let t=Lt.readdirSync(n),o=[];return t.forEach(s=>{let a=Yo.join(n,s);Lt.statSync(a).isDirectory()?o=o.concat(Ot(a)):s.endsWith(".yaml")&&(Lt.readFileSync(a,"utf-8").includes("momentic/test")?o.push(a):S.warn(`Skipping file '${a}' because it does not appear to be a valid Momentic test.`))}),o}var Ve=s=>l(void 0,null,function*(){var a=s,{controller:n,step:e,logger:t,advanced:o}=a,r=ne(a,["controller","step","logger","advanced"]);var c,d,h,p,A,w,b;(c=r.onStarted)==null||c.call(r),n.resetHistory();let i=O(C({},e),{startedAt:new Date,userAgent:_.USER_AGENT,finishedAt:new Date,results:[],status:"SUCCESS"});try{let m=0,g=e.commands&&e.commands.length>0;for(;;){if(m>20)throw new Error(`Exceeded max number of commands per step (${20})`);let u,E=new Date,R=yield n.browser.screenshot(),j=yield r.onSaveScreenshot(R);if(g){if(u=e.commands[m],!u)throw new Error(`Saved command at index ${m} is undefined.`)}else u=yield n.promptToCommand(e.type,e.text,o.disableAICaching);if(u.type==="FAILURE"){i.finishedAt=new Date,i.status="FAILED",i.message=u.thoughts;break}(d=r.onCommandGenerated)==null||d.call(r,{commandIndex:m,message:Ze[u.type]||`Unknown command (${u.type})`});let T={beforeScreenshot:j,beforeUrl:n.browser.url,startedAt:E,viewport:n.browser.viewport,finishedAt:new Date,status:"SUCCESS"};t.info(`Starting sub-command ${m} within AI step: ${Y(u)}`);try{let x=yield n.executeCommand(u,o.disableAICaching,g);t.info(`AI sub-command ${m} completed successfully`),T.elementInteracted=x.elementInteracted,(h=r.onCommandExecuted)==null||h.call(r,{commandIndex:m,message:Y(u),command:u});let F=yield n.browser.screenshot(),xe=yield r.onSaveScreenshot(F);T.afterScreenshot=xe,T.afterUrl=n.browser.url,T.finishedAt=new Date;let Dt={status:"SUCCESS",startedAt:T.startedAt,finishedAt:T.finishedAt,type:"PRESET_ACTION",command:u,results:[T]};if(i.results.push(Dt),u.type==="SUCCESS"){i.finishedAt=new Date,i.status="SUCCESS",i.message=(p=x.thoughts)!=null?p:"All commands completed.";break}if(x.succeedImmediately&&!g){i.finishedAt=new Date,i.status="SUCCESS",i.message=x.succeedImmediatelyReason,u={type:"SUCCESS"},(A=r.onCommandExecuted)==null||A.call(r,{commandIndex:m+1,message:Y(u),command:u}),i.results.push(O(C({},Dt),{command:u}));break}}catch(x){if(g){g=!1,m=0,i.results=[];continue}let F=x instanceof Error?x.message:`${x}`;T.status="FAILED",T.message=F,T.finishedAt=new Date,T.afterScreenshot=void 0,T.afterUrl=n.browser.url,i.results.push({status:"FAILED",startedAt:T.startedAt,finishedAt:T.finishedAt,type:"PRESET_ACTION",command:u,results:[T],message:F}),i.status="FAILED",i.finishedAt=new Date,i.message=F;break}m++}}catch(m){i.message=m instanceof Error?m.message:`${m}`,i.finishedAt=new Date,i.status="FAILED"}return i.status==="SUCCESS"?(w=r.onSuccess)==null||w.call(r,{message:i.message||"AI step succeeded.",startedAt:i.startedAt.getTime(),durationMs:i.finishedAt.getTime()-i.startedAt.getTime(),output:i}):(b=r.onFailure)==null||b.call(r,{message:i.message||"AI step errored.",startedAt:i.startedAt.getTime(),durationMs:i.finishedAt.getTime()-i.startedAt.getTime(),output:i}),i});var We=r=>l(void 0,null,function*(){var s=r,{controller:n,step:e,advanced:t}=s,o=ne(s,["controller","step","advanced"]);var h,p,A,w;(h=o.onStarted)==null||h.call(o);let a=new Date,i=n.browser.url,c=yield n.browser.screenshot(),d=yield o.onSaveScreenshot(c);try{let b=yield n.executePresetStep(e.command,t.disableAICaching),m=yield n.browser.screenshot(),g=yield o.onSaveScreenshot(m),u=new Date,E=O(C({},e),{startedAt:a,finishedAt:u,status:"SUCCESS",results:[]}),R="Successfully executed preset action.";e.command.type==="AI_ASSERTION"&&(R=b.thoughts||"Assertion passed.");let j={beforeUrl:i,beforeScreenshot:d,afterUrl:n.browser.url,afterScreenshot:g,startedAt:a,finishedAt:u,viewport:n.browser.viewport,status:"SUCCESS"};return E.status="SUCCESS",E.results=[j],E.message=R,(p=o.onSuccess)==null||p.call(o,{message:R,startedAt:a.getTime(),durationMs:u.getTime()-a.getTime(),command:e.command,output:E}),E}catch(b){let m=new Date,g=b instanceof Error?b.message:`${b}`;if(e.command.type==="AI_ASSERTION"&&e.command.cancelOnFailure){let E=O(C({},e),{startedAt:a,finishedAt:m,status:"CANCELLED",message:g,results:[{beforeUrl:i,beforeScreenshot:d,afterUrl:n.browser.url,afterScreenshot:void 0,startedAt:a,finishedAt:m,viewport:n.browser.viewport,status:"CANCELLED",message:g}]});return(A=o.onCancelled)==null||A.call(o,{message:g,startedAt:a.getTime(),durationMs:m.getTime()-a.getTime(),output:E}),E}let u=O(C({},e),{startedAt:a,finishedAt:m,status:"FAILED",message:g,results:[{beforeUrl:i,beforeScreenshot:d,afterUrl:n.browser.url,afterScreenshot:void 0,startedAt:a,finishedAt:m,viewport:n.browser.viewport,status:"FAILED",message:g}]});return(w=o.onFailure)==null||w.call(o,{message:g,startedAt:a.getTime(),durationMs:m.getTime()-a.getTime(),output:u}),u}});var Xo=s=>l(void 0,null,function*(){var a=s,{controller:n,step:e,advanced:t,logger:o}=a,r=ne(a,["controller","step","advanced","logger"]);var c,d,h;(c=r.onStarted)==null||c.call(r);let i={type:"MODULE",moduleId:e.moduleId,startedAt:new Date,userAgent:_.USER_AGENT,results:[],finishedAt:new Date,status:"SUCCESS"};for(let p=0;p<e.steps.length;p++){let A=e.steps[p];o.debug({i:p,moduleStep:A},"Starting module step"),o.info(`Starting module sub-step ${p+1}/${e.steps.length}: ${ze(A)}`);let w;switch(A.type){case"PRESET_ACTION":w=yield We({controller:n,step:A,advanced:t,logger:o,onSaveScreenshot:r.onSaveScreenshot,onStarted(){var m;(m=r.onStepStarted)==null||m.call(r,{index:p})},onSuccess({message:m,startedAt:g,durationMs:u,output:E}){var R;(R=r.onStepSuccess)==null||R.call(r,{index:p,message:m,startedAt:g,durationMs:u,output:E})},onFailure({message:m,startedAt:g,durationMs:u,output:E}){var R;(R=r.onStepFailure)==null||R.call(r,{index:p,message:m,startedAt:g,durationMs:u,output:E})},onCancelled({message:m,startedAt:g,durationMs:u,output:E}){var R;(R=r.onStepCancelled)==null||R.call(r,{index:p,message:m,startedAt:g,durationMs:u,output:E})}});break;case"AI_ACTION":w=yield Ve({controller:n,step:A,advanced:t,logger:o,onSaveScreenshot:r.onSaveScreenshot,onStarted(){var m;(m=r.onStepStarted)==null||m.call(r,{index:p})},onSuccess({message:m,startedAt:g,durationMs:u,output:E}){var R;(R=r.onStepSuccess)==null||R.call(r,{index:p,message:m,startedAt:g,durationMs:u,output:E})},onFailure({message:m,startedAt:g,durationMs:u,output:E}){var R;(R=r.onStepFailure)==null||R.call(r,{index:p,message:m,startedAt:g,durationMs:u,output:E})},onCommandGenerated({commandIndex:m,message:g}){var u;(u=r.onCommandGenerated)==null||u.call(r,{index:p,commandIndex:m,message:g})},onCommandExecuted({commandIndex:m,message:g,command:u}){var E;(E=r.onCommandExecuted)==null||E.call(r,{index:p,commandIndex:m,message:g,command:u})}});break;default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(A)}if(i.results.push(w),w.status==="FAILED"){i.status="FAILED",i.finishedAt=new Date;for(let b=p+1;b<e.steps.length;b++){let m=e.steps[b],g=O(C({},m),{status:"CANCELLED",startedAt:new Date,finishedAt:new Date,userAgent:_.USER_AGENT,results:[],message:"Cancelled due to previous failure."});i.results.push(g)}break}}return i.status==="SUCCESS"?(d=r.onSuccess)==null||d.call(r,{message:"Executed module step.",startedAt:i.startedAt.getTime(),durationMs:i.finishedAt.getTime()-i.startedAt.getTime(),output:i}):(h=r.onFailure)==null||h.call(r,{message:"Failed to execute module step.",startedAt:i.startedAt.getTime(),durationMs:i.finishedAt.getTime()-i.startedAt.getTime(),output:i}),i});var Jo=a=>l(void 0,[a],function*({test:n,runId:e,controller:t,logger:o,onUpdateRun:r,onSaveScreenshot:s}){try{let i=yield Yr({test:n,runId:e,controller:t,logger:o,onUpdateRun:r,onSaveScreenshot:s});if(i==="PASSED"||i==="CANCELLED")return i;throw new M("InternalPlatformError",i.message||"")}catch(i){throw i instanceof M||(i=new M("InternalPlatformError",i instanceof Error?i.message:`${i}`,{cause:i})),i}finally{yield t.browser.cleanup()}}),Yr=a=>l(void 0,[a],function*({test:n,runId:e,controller:t,logger:o,onUpdateRun:r,onSaveScreenshot:s}){var A;let i=_e.parse(n.advanced),c=o.child({runId:e,testId:n.id});c.info("Starting test run"),yield r({status:"RUNNING",startedAt:new Date});let d,h="PASSED",p=[];for(let w=0;w<n.steps.length;w++){let b=n.steps[w];c.info(`Starting step ${w+1}/${n.steps.length}: ${ze(b)}`);let m;switch(b.type){case"PRESET_ACTION":m=yield We({controller:t,step:b,advanced:i,logger:c,onSaveScreenshot:s});break;case"AI_ACTION":m=yield Ve({controller:t,step:b,advanced:i,logger:c,onSaveScreenshot:s});break;case"RESOLVED_MODULE":m=yield Xo({controller:t,step:b,advanced:i,logger:c,onSaveScreenshot:s});break;default:return(u=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(b)}if(p.push(m),yield r({results:p}),m.status==="SUCCESS"){c.info(`Step ${w+1}/${n.steps.length} succeeded`);continue}if(m.status!=="FAILED"&&m.status!=="CANCELLED")throw new M("InternalPlatformError",`Received unexpected non-terminal status from step: ${m.status}`);c.info({message:(A=p[p.length-1])==null?void 0:A.message},`Step ${w+1}/${n.steps.length} ended with status: ${m.status}`),d=m,h=m.status;for(let g=w+1;g<n.steps.length;g++){let u=n.steps[g];if(u.type==="RESOLVED_MODULE"){let E={type:"MODULE",moduleId:u.moduleId,startedAt:new Date,userAgent:_.USER_AGENT,results:u.steps.map(R=>O(C({},R),{status:"CANCELLED",startedAt:new Date,finishedAt:new Date,userAgent:_.USER_AGENT,results:[]})),finishedAt:new Date,status:"CANCELLED"};p.push(E)}else{let E=O(C({},u),{status:"CANCELLED",startedAt:new Date,finishedAt:new Date,userAgent:_.USER_AGENT,results:[]});p.push(E)}}break}return yield r({status:h,finishedAt:new Date,results:p}),h==="FAILED"?d:h});import qr from"diff-lines";import Ye from"semver";var Qo={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:n=>l(void 0,null,function*(){return n=n.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),n=n.map(e=>{var t,o;return e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=(o=(t=e.commands)!=null?t:e.results)!=null?o:[]),e}),n})};var Zo={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:n=>l(void 0,null,function*(){return n.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,o=t[t.length-1];return o&&o.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})})};var en={name:"Migrate AI assertions to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:n=>l(void 0,null,function*(){return n.map(e=>{if(e.type!=="AI_ASSERTION")return e;let o={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},r=C(C({},e),o);return delete r.text,r})}),stopOnFailure:!0};var Ke=new Set(["CLICK","TYPE","SELECT_OPTION"]),tn={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:n=>l(void 0,null,function*(){return n.map(e=>{let t=e.command,o=t==null?void 0:t.type,r=t==null?void 0:t.elementDescriptor;return(r!==void 0||Ke.has(o))&&(t.target={elementDescriptor:r!=null?r:""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let i=a==null?void 0:a.elementDescriptor,c=a==null?void 0:a.type;(i!==void 0||Ke.has(c))&&(a.target={elementDescriptor:i!=null?i:""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let i=a.command,c=i==null?void 0:i.elementDescriptor,d=i==null?void 0:i.type;(c!==void 0||Ke.has(d))&&(i.target={elementDescriptor:c!=null?c:""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(p=>{let A=p==null?void 0:p.elementDescriptor,w=p==null?void 0:p.type;(A!==void 0||Ke.has(w))&&(p.target={elementDescriptor:A!=null?A:""})})}),e})}),stopOnFailure:!0};var on={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:n=>l(void 0,null,function*(){return n.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(o=>{if(o&&typeof o=="object"){let r=o;(r==null?void 0:r.status)==="FAILURE"&&(r.status="FAILED")}}),t})}),stopOnFailure:!0};var nn={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:n=>l(void 0,null,function*(){return n.map(e=>{let t=e.command,o=t==null?void 0:t.type;return o!=null&&o.startsWith("PRESET_")&&(t.type=o.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(s=>{let a=s.type;a!=null&&a.startsWith("PRESET_")&&(s.type=a.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(s=>{let a=s.command,i=a==null?void 0:a.type;i!=null&&i.startsWith("PRESET_")&&(a.type=i.slice(7)),s.commands&&Array.isArray(s.commands)&&s.commands.forEach(d=>{let h=d.type;h!=null&&h.startsWith("PRESET_")&&(d.type=h.slice(7))})}),e})}),stopOnFailure:!0};var ee=[en,on,nn,tn,Qo,Zo];if(K!==ee[ee.length-1].toVersion)throw new Error("Please bump LATEST_VERSION in types package after adding a migration");ee.forEach((n,e)=>{if(!Ye.valid(n.toVersion)||!Ye.valid(n.fromVersion))throw new Error(`Migration '${n.name}' has invalid version`);if(!Ye.gt(n.toVersion,n.fromVersion))throw new Error(`Migration '${n.name}' has toVersion <= fromVersion`);if(e===0)return;if(ee[e-1].toVersion!==n.fromVersion)throw new Error(`Migration '${n.name}' at index ${e} is not contiguous with previous migration`)});function Xr(n){return n.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var Nt=o=>l(void 0,[o],function*({metadata:n,steps:e,logger:t}){let r=e,{schemaVersion:s,id:a}=n,i=ee.findIndex(h=>Ye.gt(h.toVersion,s));if(i===-1)return t.debug({id:a},"Step migrations up to date"),{steps:r,newVersion:s};let c=s;for(let h=i;h<ee.length;h++){let p=ee[h],A={id:a,migration:p.name,toVersion:p.toVersion};t.debug(A,"Starting migration");try{r=yield rn(r,p),c=p.toVersion}catch(w){throw t.error(C({err:w},A),"Migration failed"),new Error(`Step migration ${p.name} failed: ${w}`)}}let d=qr(JSON.stringify(e,void 0,2),JSON.stringify(r,void 0,2),{n_surrounding:1});return t.debug({diffs:d,id:a},"Migration diffs"),{newVersion:c,steps:r}});function rn(n,e){return l(this,null,function*(){let t=yield e.execute(n);for(let o of t)for(let r of Object.keys(o)){if(!e.recursiveKeys.has(r))continue;let s=o[r];!s||!Array.isArray(s)||Xr(s)&&(o[r]=yield rn(s,e))}return t})}import{v4 as oi}from"uuid";import{parse as sn}from"yaml";import{existsSync as Jr,readFileSync as Qr}from"fs";import{join as Zr}from"path";import{parse as ei}from"yaml";function ti(n){let e=Zr(ut,`${n}.yaml`);if(!Jr(e))throw new Error(`Fixture '${n}' does not exist at expected path ${e}`);let t;try{t=ei(Qr(e,"utf-8").replace(/\r\n|\r/g,`
585
- `))}catch(r){throw new Error(`Fixture at path ${e} does not parse as valid YAML: ${r}`)}let o;try{o=Gt.parse(t)}catch(r){throw new Error(`Fixture at path ${e} does not conform to expected schema: ${r}`)}return o}function Mt(n,e){return l(this,null,function*(){let t=ti(n),o=e==="setup"?t.setup:t.teardown;if(!o){S.warn(`Fixture '${n}' does not have any steps in the ${e} phase, skipping...`);return}let r=o.timeout,s=function(){return l(this,null,function*(){for(let d=0;d<o.steps.length;d++){let h=o.steps[d],p=h.run,A=w=>l(this,null,function*(){try{yield Ko(`set -ex; ${p}`)}catch(b){if(w){let m=`Fixture '${n}' ${e} step ${d+1} errored in the background. The test will continue, but this may affect test execution and results: ${b}`;S.error(m)}else throw new Error(`Fixture '${n}' ${e} step ${d+1} errored: ${b}`)}});h.waitForCompletion===!1?A(!0):yield A(!1)}})};if(S.info(`Running ${e} phase of fixture '${n}'`),!r){yield s();return}let a,i,c=function(){return l(this,null,function*(){return new Promise((d,h)=>{i=d,a=setTimeout(()=>{i=void 0,h(`Fixture '${n}' ${e} phase timed out after ${r} seconds`)},r*1e3)})})};try{yield Promise.race([s(),c()])}catch(d){throw d}finally{i&&i(),clearTimeout(a)}})}function an(a){return l(this,arguments,function*({path:n,apiClient:e,generator:t,newBaseURL:o,useLocalFiles:r,noReport:s}){var m;let i;r?(S.info(`Reading ${n} from local filesystem`),i=yield ni(n)):(S.info(`Fetching ${n} from Momentic Cloud server (${e.baseURL})`),i=yield e.getTest(n)),i.schemaVersion>K&&S.warn(`Test ${n} has schema version ${i.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`);let c=(m=i.envSettings)==null?void 0:m.find(g=>g.name==="development");for(let g of(c==null?void 0:c.fixtures)||[])yield Mt(g,"setup");let d=new URL(i.baseUrl);if(o){let g=new URL(o);d.hostname=g.hostname,d.protocol=g.protocol,d.port=g.port}let h=yield _.init(d.toString(),S),p=new Ce({browser:h,generator:t,config:It,logger:S}),A,w;if(s)w=oi();else try{A=yield e.createRun({testId:i.id,trigger:"CLI"}),w=A.id}catch(g){throw S.error(g),new Error(`Are you sure test ${i.name} exists on the server?`)}let b="FAILED";try{b=yield Jo({test:i,runId:w,controller:p,logger:S,onSaveScreenshot:g=>l(this,null,function*(){if(s)return"";let{key:u}=yield e.uploadScreenshot({screenshot:g.toString("base64")});return u}),onUpdateRun:g=>l(this,null,function*(){s||(yield e.updateRun(w,g))})})}catch(g){throw s||(yield e.updateRun(w,{status:"FAILED",finishedAt:new Date})),g}finally{try{for(let g of(c==null?void 0:c.fixtures)||[])yield Mt(g,"teardown")}catch(g){S.error(`Failed to run teardown fixtures: ${g}`)}}return b})}function ni(n){return l(this,null,function*(){let{test:e,modules:t}=wt(n),o=sn(e);if(!o.steps||!Array.isArray(o.steps))throw new Error(`Test ${n} is missing steps`);if(!o.schemaVersion||!o.id)throw new Error(`Test ${n} is missing an ID or schema version`);let r;if(o.schemaVersion<K){S.warn(`Test ${n} has schema version ${o.schemaVersion}, which is lower than the version used by this SDK, ${K}. Your test will be migrated to the latest version before execution.`);let{steps:i}=yield Nt({metadata:o,steps:o.steps,logger:S});r=we.array().parse(i)}else r=we.array().parse(o.steps);let s={};for(let[i,c]of Object.entries(t)){let d=sn(c);if(!d.schemaVersion||!d.moduleId)throw new Error(`Module ${i} is missing an ID or schema version`);if(!d.steps||!Array.isArray(d.steps))throw new Error(`Module ${i} is missing steps`);if(d.schemaVersion<K){S.warn(`Module ${i} has schema version ${d.schemaVersion}, which is lower than the version used by this SDK, ${K}. Your module will be migrated to the latest version before execution.`);let{steps:h}=yield Nt({metadata:{id:d.moduleId,schemaVersion:d.schemaVersion},steps:d.steps,logger:S});s[i]=O(C({},d),{steps:Se.array().parse(h)})}else s[i]=d}let a=r.map(i=>{if(i.type!=="MODULE")return i;let c=s[i.moduleId];if(!c)throw new Error(`Could not resolve module ${i.moduleId} required in test ${n}`);return{type:"RESOLVED_MODULE",moduleId:i.moduleId,name:c.name,steps:c.steps}});return Jt.parse(O(C({},o),{steps:a}))})}function cn(c){return l(this,arguments,function*({tests:n,start:e,waitOn:t,waitOnTimeout:o,client:r,all:s,noReport:a,parallelization:i=1}){e&&(S.info(`Running start command: ${e}`),yield Wo(e,!1)),t&&(S.info(`Waiting for ${t} to be accessible (timeout: ${o}s)`),yield ii({resources:[t],timeout:o*1e3}));let d=new ve({baseURL:r.baseURL,apiKey:r.apiKey}),h=!1;(n.some(u=>u.endsWith(".yaml"))||n.some(u=>ln(u)))&&(h=!0);let p=new Set;if(h)S.info(n,"Reading tests from the following local file paths:"),n.forEach(u=>{if(!ln(u))throw new Error(`Path '${u}' does not exist.`);if(ri(u).isDirectory())Ot(u).forEach(R=>p.add(R));else if(u.endsWith(".yaml"))p.add(u);else throw new Error(`Path '${u}' is not a directory or a .yaml file.`)});else if(S.warn("The paths you specified are not files or directories that exist locally."),S.warn(`Fetching tests from Momentic Cloud (${r.baseURL}) instead...`),s)for(let u of yield r.getAllTestIds())p.add(u);else p=new Set(n);let A=Array.from(p);S.info(A,`Identified ${A.length} tests to run locally:`);let w=[];for(let u=0;u<A.length;u+=i){let E=yield Promise.all(A.slice(u,u+i).map(R=>l(this,null,function*(){let j="FAILED";try{j=yield an({useLocalFiles:h,path:R,apiClient:r,generator:d,newBaseURL:t,noReport:a})}catch(T){let x=T instanceof Error?T.message:`${T}`;S.error(`Test ${R} failed with error: ${x}`)}return{runStatus:j,path:R}})));w=w.concat(E)}let b=w.filter(u=>u.runStatus==="PASSED");b.length>0&&(S.info(`Passed ${b.length} out of ${w.length} tests:`),b.forEach(u=>{S.info(`- ${u.path}`)}));let m=w.filter(u=>u.runStatus==="CANCELLED");m.length>0&&(S.warn(`Cancelled ${m.length} out of ${w.length} tests:`),m.forEach(u=>{S.warn(`- ${u.path}`)}));let g=w.filter(u=>u.runStatus==="FAILED");g.length>0&&(S.error(`Failed ${g.length} out of ${w.length} tests:`),g.forEach(u=>{S.error(`- ${u.path}`)}),process.exit(1)),process.exit(0)})}function dn(o){return l(this,arguments,function*({tests:n,client:e,all:t}){let{queuedTests:r}=yield e.queueTests({testPaths:n,all:t});S.info(`Successfully queued ${r.length} tests!`)})}var oe=new si;oe.name("momentic").description("Momentic CLI").version(ao);oe.command("install-browsers").action(()=>l(void 0,null,function*(){yield co()}));oe.addOption(new te("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",n=>{S.setMinLevel(Wt[n.toUpperCase()])});oe.command("run").alias("run-tests").addOption($e).addOption(He).addOption(ft).addOption(new te("-r, --remote","Run tests remotely. The production version of this test will be queued for execution.").default(!0).conflicts(["start, waitOn, waitOnTimeout, local"]).implies({local:!1})).addOption(uo).addOption(new te("-l, --local","Run tests locally. Useful for accessing apps on localhost. This option does not control where tests are read from (see <tests> argument documentation).").implies({remote:!1,noReport:!0})).addOption(new te("--start <command>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new te("--wait-on <url>","URL to wait to become accessible before Momentic tests begin.")).addOption(new te("--wait-on-timeout <timeout>","Max time to wait for the --wait-on URL to become accessible.").default(60,"one minute")).addOption(new te("-p, --parallel <parallelization>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.").default(1)).addArgument(po).action((n,e)=>l(void 0,null,function*(){let{apiKey:t,server:o,remote:r,local:s,all:a}=e,i=new ce({baseURL:o,apiKey:t});if(s){try{yield cn(C({tests:n,client:i},e))}catch(c){S.error(c),process.exit(1)}return}if(r){for(let c of n)(c.endsWith(".yaml")||li(c))&&(S.error(ai`'${c}' looks like a local file or directory, but the --local flag was not supplied.
586
- Please supply the --local flag to run tests locally, or specify the test path without its file extension to queue tests remotely (e.g. 'hello-world').`),process.exit(1));yield dn({tests:n,client:i,all:a});return}S.error("One of --remote or --local must be specified"),process.exit(1)}));oe.command("pull").description("Fetch one or more tests from Momentic Cloud and save it in to local disk in YAML format.").addOption($e).addOption(He).addOption(ft).addOption(gt).addArgument(mo).action((n,e)=>l(void 0,null,function*(){let{apiKey:t,server:o,all:r,yes:s}=e;if(yield mt(s),!r&&!(n!=null&&n.length))throw new Error("At least one test name or --all must be provided");let a=new ce({baseURL:o,apiKey:t});yield wo({testsToFetch:n,client:a,all:r})}));oe.command("push").description("Save one or more tests in YAML format to Momentic Cloud.").addOption(gt).addOption($e).addOption(He).addArgument(ho).action((n,e)=>l(void 0,null,function*(){let{apiKey:t,server:o,yes:r}=e;yield mt(r);let s=new ce({baseURL:o,apiKey:t});yield Eo({paths:n,client:s,yes:r})}));function ci(){return l(this,null,function*(){yield oe.parseAsync(process.argv)})}ci();
584
+ `)}`}executeCommand(e,t,o=!1){return l(this,null,function*(){let r=this.commandHistory[this.commandHistory.length-1];if(!o&&(!r||r.state!=="PENDING"))throw new D("InternalWebAgentError","Executing command but there is no pending entry in the history");if(this.closed)throw new Error("Attempting to execute command on a closed controller");let s;try{let a=Date.now();s=yield this.executePresetStep(e,t);let i=Date.now()-a;this.logger.debug({result:s,duration:i},"Got execution result")}catch(a){throw a instanceof Error?new Ce(`Failed to execute command: ${a}`,{cause:a}):new Ce("Unexpected throw from executing command",{cause:new Error(`${a}`)})}return s.succeedImmediately&&!o&&(this.pendingInstructions.pop(),this.pendingInstructions.length>0&&(s.succeedImmediately=!1)),s.elementInteracted&&"target"in e&&e.target&&!e.target.elementDescriptor&&(e.target.elementDescriptor=s.elementInteracted.trim()),o||(r.generatedStep=e,r.serializedCommand=ye(e),r.state="DONE"),s})}executeAssertion(e){return l(this,null,function*(){let t=yield this.getBrowserState(),o=yield this.browser.url(),r;if(e.useVision)r={goal:e.assertion,url:o,screenshot:yield this.browser.screenshot(),browserState:"",history:"",numPrevious:-1,lastCommand:null};else{let a=this.getSerializedHistory(o,t);r={goal:e.assertion,url:o,browserState:t,history:a,lastCommand:this.lastExecutedCommand,numPrevious:this.commandHistory.length}}let s=yield this.generator.getAssertionResult(r,e.useVision,e.disableCache);if(s.relevantElements&&Promise.all(s.relevantElements.map(a=>this.browser.highlight({id:a}))),!s.result)throw new D("AssertionFailureError",s.thoughts);return{succeedImmediately:!1,thoughts:s.thoughts,urlAfterCommand:o}})}wrapElementTargetingCommand(e,t,o,r,s=!0){return l(this,null,function*(){if(!e.a11yData&&!e.elementDescriptor)throw new D("InternalWebAgentError","Cannot target element with no target data or element descriptor");let a=e.a11yData&&_e(e.a11yData);e.a11yData||(this.logger.debug("No cached locator data for target, prompting AI for fresh location"),e.a11yData=Pe.parse(yield this.locateElement(e.elementDescriptor,t,o)),s=!1);try{let i=yield r(e.a11yData);return a?this.logger.debug({target:e},"Successfully used cached target to perform action"):this.logger.debug({target:e},"Successfully generated and used new a11y target information"),i}catch(i){if(s&&e.elementDescriptor)return this.logger.warn({err:i,target:e},"Failed to execute action with cached target, retrying with AI"),e.a11yData=void 0,this.wrapElementTargetingCommand(e,t,o,r,!0);if(i instanceof D)throw i;let c=`Failed to find ${e.elementDescriptor?`${e.elementDescriptor}`:"element"}: ${i instanceof Error?i.message:i}`;throw this.logger.error({err:i,target:e},c),new D("ActionFailureError",c,{cause:i})}})}executePresetStep(e,t){return l(this,null,function*(){try{return yield this.executePresetStepHelper(e,t)}catch(o){throw o instanceof D?o:new D("InternalWebAgentError",o instanceof Error?o.message:`${o}`,{cause:o})}})}executePresetStepHelper(e,t){return l(this,null,function*(){var o;switch(e.type){case"SUCCESS":return(o=e.condition)!=null&&o.assertion.trim()?this.executeAssertion(e.condition):{succeedImmediately:!1,urlAfterCommand:yield this.browser.url()};case"AI_ASSERTION":return this.executeAssertion(e);case"NAVIGATE":yield this.browser.navigate({url:e.url});break;case"CAPTCHA":let r=yield this.browser.solveCaptcha();r&&(yield this.wrapElementTargetingCommand({elementDescriptor:"the captcha image solution input"},e.useVision,t,m=>this.browser.click(m)),yield this.browser.type(r,{clearContent:!0,pressKeysSequentially:!1}));break;case"GO_BACK":yield this.browser.goBack();break;case"GO_FORWARD":yield this.browser.goForward();break;case"SCROLL_DOWN":case"SCROLL_UP":let s;return e.target&&(e.target.elementDescriptor.trim()||e.target.a11yData)&&(s=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,m=>this.browser.hover(m))),e.type==="SCROLL_UP"?yield this.browser.scrollUp(e.deltaY):yield this.browser.scrollDown(e.deltaY),{succeedImmediately:!1,urlAfterCommand:yield this.browser.url(),elementInteracted:s};case"WAIT":yield this.browser.wait(e.delay*1e3);break;case"REFRESH":yield this.browser.refresh();break;case"CLICK":{let m=yield this.browser.url(),u=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,w=>this.browser.click(w,{doubleClick:e.doubleClick,rightClick:e.rightClick})),h={urlAfterCommand:yield this.browser.url(),succeedImmediately:!1,elementInteracted:u};return le(m,h.urlAfterCommand)&&(h.succeedImmediately=!0,h.succeedImmediatelyReason="URL changed"),h}case"SELECT_OPTION":{let m=yield this.wrapElementTargetingCommand(e.target,!1,t,u=>this.browser.selectOption(u,e.option));return{succeedImmediately:!1,urlAfterCommand:yield this.browser.url(),elementInteracted:m}}case"TAB":yield this.browser.switchToPage(e.url);break;case"COOKIE":if(!e.value)break;yield this.browser.setCookie(e.value);break;case"TYPE":{let m=yield this.browser.url(),u=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,w=>this.browser.click(w));yield this.browser.type(e.value,{clearContent:e.clearContent,pressKeysSequentially:e.pressKeysSequentially}),e.pressEnter&&(yield this.browser.press("Enter"));let h={urlAfterCommand:yield this.browser.url(),succeedImmediately:!1,elementInteracted:u};return le(m,h.urlAfterCommand)&&(h.succeedImmediately=!0,h.succeedImmediatelyReason="URL changed"),h}case"HOVER":{let m=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,u=>this.browser.hover(u));return{succeedImmediately:!1,urlAfterCommand:yield this.browser.url(),elementInteracted:m}}case"PRESS":let a=yield this.browser.url();yield this.browser.press(e.value);let i={urlAfterCommand:yield this.browser.url(),succeedImmediately:!1};return le(a,i.urlAfterCommand)&&(i.succeedImmediately=!0,i.succeedImmediatelyReason="URL changed"),i;default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{succeedImmediately:!1,urlAfterCommand:yield this.browser.url()}})}getReverseMappedTarget(e,t,o){return l(this,null,function*(){return(yield this.generator.getReverseMappedDescription({browserState:e.browserState,goal:`${t}`},o)).phrase})}};import Zr from"fetch-retry";var ei=Zr(global.fetch),de="v1",Ne=class{constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey}getElementLocation(e,t){return l(this,null,function*(){let o=yield this.sendRequest(`/${de}/web-agent/locate-element`,{browserState:e.browserState,goal:e.goal,disableCache:t});return mt.parse(o)})}getElementLocationWithVision(e,t){return l(this,null,function*(){var r,s;let o=yield this.sendRequest(`/${de}/web-agent/visual-locate`,{goal:e.goal,screenshot:(r=e.screenshot)==null?void 0:r.toString("base64"),hintActivatedScreenshot:(s=e.hintActivatedScreenshot)==null?void 0:s.toString("base64"),disableCache:t});return mt.parse(o)})}getAssertionResult(e,t,o){return l(this,null,function*(){var s;if(t){let a=yield this.sendRequest(`/${de}/web-agent/assertion`,{url:e.url,goal:e.goal,screenshot:(s=e.screenshot)==null?void 0:s.toString("base64"),disableCache:o,vision:!0});return dt.parse(a)}let r=yield this.sendRequest(`/${de}/web-agent/assertion`,{url:e.url,browserState:e.browserState,goal:e.goal,history:e.history,numPrevious:e.numPrevious,lastCommand:e.lastCommand,disableCache:o,vision:!1});return dt.parse(r)})}getProposedCommand(e,t){return l(this,null,function*(){let o=yield this.sendRequest(`/${de}/web-agent/next-command`,{url:e.url,browserState:e.browserState,goal:e.goal,history:e.history,numPrevious:e.numPrevious,lastCommand:e.lastCommand,disableCache:t});return Qt.parse(o)})}getGranularGoals(e,t){return l(this,null,function*(){let o=yield this.sendRequest(`/${de}/web-agent/split-goal`,{url:e.url,goal:e.goal,disableCache:t});return Zt.parse(o)})}getReverseMappedDescription(e,t){return l(this,null,function*(){let o=yield this.sendRequest(`/${de}/web-agent/reverse-mapped-description`,{goal:e.goal,browserState:e.browserState,disableCache:t});return eo.parse(o)})}sendRequest(e,t){return l(this,null,function*(){let o=yield ei(`${this.baseURL}${e}`,{retries:1,retryDelay:1e3,method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!o.ok)throw new Error(`Request to ${e} failed with status ${o.status}: ${yield o.text()}`);return o.json()})}};import ti from"@actions/exec";import oi from"@actions/io";import ni from"quote";import ri from"string-argv";function dn(n,e=!0){return l(this,null,function*(){let t=ri(n),o=yield oi.which(t[0],!0),r=t.slice(1),s=ti.exec(ni(o),r,{delay:100});if(e)return s})}import{v4 as di}from"uuid";import{existsSync as ii,readFileSync as si}from"fs";import{join as ai}from"path";import{parse as li}from"yaml";function ci(n){let e=ai(pt,`${n}.yaml`);if(!ii(e))throw new Error(`Fixture '${n}' does not exist at expected path ${e}`);let t;try{t=li(si(e,"utf-8").replace(/\r\n|\r/g,`
585
+ `))}catch(r){throw new Error(`Fixture at path ${e} does not parse as valid YAML: ${r}`)}let o;try{o=jt.parse(t)}catch(r){throw new Error(`Fixture at path ${e} does not conform to expected schema: ${r}`)}return o}function Mt(n,e){return l(this,null,function*(){let t=ci(n),o=e==="setup"?t.setup:t.teardown;if(!o){A.warn(`Fixture '${n}' does not have any steps in the ${e} phase, skipping...`);return}let r=o.timeout,s=function(){return l(this,null,function*(){for(let m=0;m<o.steps.length;m++){let u=o.steps[m],h=u.run,w=S=>l(this,null,function*(){try{yield Mo(`set -ex; ${h}`)}catch(b){if(S){let f=`Fixture '${n}' ${e} step ${m+1} errored in the background. The test will continue, but this may affect test execution and results: ${b}`;A.error(f)}else throw new Error(`Fixture '${n}' ${e} step ${m+1} errored: ${b}`)}});u.waitForCompletion===!1?w(!0):yield w(!1)}})};if(A.info(`Running ${e} phase of fixture '${n}'`),!r){yield s();return}let a,i,c=function(){return l(this,null,function*(){return new Promise((m,u)=>{i=m,a=setTimeout(()=>{i=void 0,u(`Fixture '${n}' ${e} phase timed out after ${r} seconds`)},r*1e3)})})};try{yield Promise.race([s(),c()])}catch(m){throw m}finally{i&&i(),clearTimeout(a)}})}function mn(a){return l(this,arguments,function*({path:n,apiClient:e,generator:t,newBaseURL:o,useLocalFiles:r,noReport:s}){var f;let i;r?(A.info(`Reading ${n} from local filesystem`),i=yield Oo(n,se)):(A.info(`Fetching ${n} from Momentic Cloud server (${e.baseURL})`),i=yield e.getTest(n)),i.schemaVersion>W&&A.warn(`Test ${n} has schema version ${i.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`);let c=(f=i.envSettings)==null?void 0:f.find(p=>p.name==="development");for(let p of(c==null?void 0:c.fixtures)||[])yield Mt(p,"setup");let m=new URL(i.baseUrl);if(o){let p=new URL(o);m.hostname=p.hostname,m.protocol=p.protocol,m.port=p.port}let u=yield F.init({baseUrl:m.toString(),logger:A}),h=new Me({browser:u,generator:t,config:Ot,logger:A}),w,S;if(s)S=di();else try{w=yield e.createRun({testId:i.id,trigger:"CLI"}),S=w.id}catch(p){throw A.error(p),new Error(`Are you sure test ${i.name} exists on the server?`)}let b="FAILED";try{b=yield nn({test:i,runId:S,controller:h,logger:A,onSaveScreenshot:p=>l(this,null,function*(){if(s)return"";let{key:d}=yield e.uploadScreenshot({screenshot:p.toString("base64")});return d}),onUpdateRun:p=>l(this,null,function*(){s||(yield e.updateRun(S,p))})})}catch(p){throw s||(yield e.updateRun(S,{status:"FAILED",finishedAt:new Date})),s||A.error(`Test '${i.name}' failed. You can view a playback of this run at ${e.baseURL}/runs/${S}`),p}finally{try{for(let p of(c==null?void 0:c.fixtures)||[])yield Mt(p,"teardown")}catch(p){A.error(`Failed to run teardown fixtures: ${p}`)}}return b})}function pn(c){return l(this,arguments,function*({tests:n,start:e,waitOn:t,waitOnTimeout:o,client:r,all:s,noReport:a,parallelization:i=1}){e&&(A.info(`Running start command: ${e}`),yield dn(e,!1)),t&&(A.info(`Waiting for ${t} to be accessible (timeout: ${o}s)`),yield ui({resources:[t],timeout:o*1e3}));let m=new Ne({baseURL:r.baseURL,apiKey:r.apiKey}),u=!1;(n.some(d=>d.endsWith(".yaml"))||n.some(d=>un(d)))&&(u=!0);let h=new Set;if(u)A.info(n,"Reading tests from the following local file paths:"),n.forEach(d=>{if(!un(d))throw new Error(`Path '${d}' does not exist.`);if(mi(d).isDirectory())Et(d).map(v=>v.path).forEach(v=>h.add(v));else if(d.endsWith(".yaml"))h.add(d);else throw new Error(`Path '${d}' is not a directory or a .yaml file.`)});else if(A.warn("The paths you specified are not files or directories that exist locally."),A.warn(`Fetching tests from Momentic Cloud (${r.baseURL}) instead...`),s)for(let d of yield r.getAllTestIds())h.add(d);else h=new Set(n);let w=Array.from(h);A.info(w,`Identified ${w.length} tests to run locally:`);let S=[];for(let d=0;d<w.length;d+=i){let E=yield Promise.all(w.slice(d,d+i).map(v=>l(this,null,function*(){let L="FAILED";try{L=yield mn({useLocalFiles:u,path:v,apiClient:r,generator:m,newBaseURL:t,noReport:a})}catch(C){let R=C instanceof Error?C.message:`${C}`;A.error(`Test ${v} failed with error: ${R}`)}return{runStatus:L,path:v}})));S=S.concat(E)}let b=S.filter(d=>d.runStatus==="PASSED");b.length>0&&(A.info(`Passed ${b.length} out of ${S.length} tests:`),b.forEach(d=>{A.info(`- ${d.path}`)}));let f=S.filter(d=>d.runStatus==="CANCELLED");f.length>0&&(A.warn(`Cancelled ${f.length} out of ${S.length} tests:`),f.forEach(d=>{A.warn(`- ${d.path}`)}));let p=S.filter(d=>d.runStatus==="FAILED");p.length>0&&(A.error(`Failed ${p.length} out of ${S.length} tests:`),p.forEach(d=>{A.error(`- ${d.path}`)}),process.exit(1)),process.exit(0)})}function hn(o){return l(this,arguments,function*({tests:n,client:e,all:t}){let{queuedTests:r}=yield e.queueTests({testPaths:n,all:t});A.info(`Successfully queued ${r.length} tests!`)})}var ue=new pi;ue.name("momentic").description("Momentic CLI").version(lo);ue.command("install-browsers").action(()=>l(void 0,null,function*(){yield mo()}));ue.addOption(new me("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",n=>{A.setMinLevel(Jt[n.toUpperCase()])});ue.command("run").alias("run-tests").addOption(Ge).addOption(Ve).addOption(St).addOption(new me("-r, --remote","Run tests remotely. The production version of this test will be queued for execution.").default(!0).conflicts(["start, waitOn, waitOnTimeout, local"]).implies({local:!1})).addOption(uo).addOption(new me("-l, --local","Run tests locally. Useful for accessing apps on localhost. This option does not control where tests are read from (see <tests> argument documentation).").implies({remote:!1,noReport:!0})).addOption(new me("--start <command>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new me("--wait-on <url>","URL to wait to become accessible before Momentic tests begin.")).addOption(new me("--wait-on-timeout <timeout>","Max time to wait for the --wait-on URL to become accessible.").default(60,"one minute")).addOption(new me("-p, --parallel <parallelization>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.").default(1)).addArgument(ho).action((n,e)=>l(void 0,null,function*(){let{apiKey:t,server:o,remote:r,local:s,all:a}=e,i=new Se({baseURL:o,apiKey:t});if(s){try{yield pn(T({tests:n,client:i},e))}catch(c){A.error(c),process.exit(1)}return}if(r){for(let c of n)(c.endsWith(".yaml")||fi(c))&&(A.error(hi`'${c}' looks like a local file or directory, but the --local flag was not supplied.
586
+ Please supply the --local flag to run tests locally, or specify the test path without its file extension to queue tests remotely (e.g. 'hello-world').`),process.exit(1));yield hn({tests:n,client:i,all:a});return}A.error("One of --remote or --local must be specified"),process.exit(1)}));ue.command("pull").description("Fetch one or more tests from Momentic Cloud and save it in to local disk in YAML format.").addOption(Ge).addOption(Ve).addOption(St).addOption(yt).addArgument(po).action((n,e)=>l(void 0,null,function*(){let{apiKey:t,server:o,all:r,yes:s}=e;if(yield ht(s),!r&&!(n!=null&&n.length))throw new Error("At least one test name or --all must be provided");let a=new Se({baseURL:o,apiKey:t});yield bo({testsToFetch:n,client:a,all:r})}));ue.command("push").description("Save one or more tests in YAML format to Momentic Cloud.").addOption(yt).addOption(Ge).addOption(Ve).addArgument(fo).action((n,e)=>l(void 0,null,function*(){let{apiKey:t,server:o,yes:r}=e;yield ht(r);let s=new Se({baseURL:o,apiKey:t});yield ln({paths:n,client:s,yes:r})}));function gi(){return l(this,null,function*(){yield ue.parseAsync(process.argv)})}gi();
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
- var Nt=Object.defineProperty,Lt=Object.defineProperties;var Ot=Object.getOwnPropertyDescriptors;var Be=Object.getOwnPropertySymbols;var Dt=Object.prototype.hasOwnProperty,Mt=Object.prototype.propertyIsEnumerable;var Ge=(o,e,t)=>e in o?Nt(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,L=(o,e)=>{for(var t in e||(e={}))Dt.call(e,t)&&Ge(o,t,e[t]);if(Be)for(var t of Be(e))Mt.call(e,t)&&Ge(o,t,e[t]);return o},B=(o,e)=>Lt(o,Ot(e));var c=(o,e,t)=>new Promise((n,r)=>{var i=d=>{try{s(t.next(d))}catch(p){r(p)}},a=d=>{try{s(t.throw(d))}catch(p){r(p)}},s=d=>d.done?n(d.value):Promise.resolve(d.value).then(i,a);s((t=t.apply(o,e)).next())});import zt from"dedent";import*as l from"zod";import*as M from"zod";var ie=M.object({id:M.number().int(),role:M.string().optional(),name:M.string().optional(),numChildren:M.number().optional(),content:M.string().optional(),pathFromRoot:M.string().optional(),serializedForm:M.string().optional()});function se(o){return o.name||o.role||o.content||o.serializedForm}var H=(y=>(y.AI_ASSERTION="AI_ASSERTION",y.CLICK="CLICK",y.SELECT_OPTION="SELECT_OPTION",y.TYPE="TYPE",y.PRESS="PRESS",y.NAVIGATE="NAVIGATE",y.SCROLL_UP="SCROLL_UP",y.SCROLL_DOWN="SCROLL_DOWN",y.GO_BACK="GO_BACK",y.GO_FORWARD="GO_FORWARD",y.WAIT="WAIT",y.REFRESH="REFRESH",y.TAB="TAB",y.COOKIE="COOKIE",y.HOVER="HOVER",y.CAPTCHA="CAPTCHA",y.SUCCESS="SUCCESS",y))(H||{}),W=l.object({elementDescriptor:l.string(),a11yData:ie.optional()}),T=l.object({thoughts:l.string().optional()}),kt=T.merge(l.object({type:l.literal("NAVIGATE"),url:l.string()})).describe("NAVIGATE <URL> - Go to the specified URL. Only navigate to URLs relevant to the user goal."),_t=T.merge(l.object({target:W.optional(),type:l.literal("SCROLL_UP"),useVision:l.boolean().default(!1)})).describe("SCROLL_UP [id] - Scroll up while hovering over the element with the specified id. If no id is provided, scroll the entire page."),Pt=T.merge(l.object({target:W.optional(),type:l.literal("SCROLL_DOWN"),useVision:l.boolean().default(!1)})).describe("SCROLL_DOWN [id] - Scroll down while hovering over the element with the specified id. If no id is provided, scroll the entire page."),Ut=T.merge(l.object({type:l.literal("WAIT"),delay:l.number()})),Ht=T.merge(l.object({type:l.literal("REFRESH")})),Ft=T.merge(l.object({type:l.literal("GO_BACK")})),Bt=T.merge(l.object({type:l.literal("GO_FORWARD")})),Gt=T.merge(l.object({type:l.literal("CAPTCHA"),useVision:l.boolean().default(!1)})),$t=T.merge(l.object({type:l.literal("CLICK"),target:W,doubleClick:l.boolean().default(!1),rightClick:l.boolean().default(!1),useVision:l.boolean().default(!1)})).describe(zt`CLICK <id> - click on the element that has the specified id.
1
+ var Ot=Object.defineProperty,Dt=Object.defineProperties;var Mt=Object.getOwnPropertyDescriptors;var Ge=Object.getOwnPropertySymbols;var zt=Object.prototype.hasOwnProperty,Pt=Object.prototype.propertyIsEnumerable;var $e=(r,e,t)=>e in r?Ot(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,L=(r,e)=>{for(var t in e||(e={}))zt.call(e,t)&&$e(r,t,e[t]);if(Ge)for(var t of Ge(e))Pt.call(e,t)&&$e(r,t,e[t]);return r},j=(r,e)=>Dt(r,Mt(e));var l=(r,e,t)=>new Promise((o,n)=>{var i=m=>{try{s(t.next(m))}catch(p){n(p)}},a=m=>{try{s(t.throw(m))}catch(p){n(p)}},s=m=>m.done?o(m.value):Promise.resolve(m.value).then(i,a);s((t=t.apply(r,e)).next())});import kt from"dedent";import*as c from"zod";import*as M from"zod";var de=M.object({id:M.number().int(),role:M.string().optional(),name:M.string().optional(),numChildren:M.number().optional(),content:M.string().optional(),pathFromRoot:M.string().optional(),serializedForm:M.string().optional()});function me(r){return r.name||r.role||r.content||r.serializedForm}var B=(y=>(y.AI_ASSERTION="AI_ASSERTION",y.CLICK="CLICK",y.SELECT_OPTION="SELECT_OPTION",y.TYPE="TYPE",y.PRESS="PRESS",y.NAVIGATE="NAVIGATE",y.SCROLL_UP="SCROLL_UP",y.SCROLL_DOWN="SCROLL_DOWN",y.GO_BACK="GO_BACK",y.GO_FORWARD="GO_FORWARD",y.WAIT="WAIT",y.REFRESH="REFRESH",y.TAB="TAB",y.COOKIE="COOKIE",y.HOVER="HOVER",y.CAPTCHA="CAPTCHA",y.SUCCESS="SUCCESS",y))(B||{}),Z=c.object({elementDescriptor:c.string(),a11yData:de.optional()}),I=c.object({thoughts:c.string().optional()}),_t=I.merge(c.object({type:c.literal("NAVIGATE"),url:c.string()})).describe("NAVIGATE <URL> - Go to the specified URL. Only navigate to URLs relevant to the user goal."),Ut=I.merge(c.object({target:Z.optional(),type:c.literal("SCROLL_UP"),useVision:c.boolean().default(!1),deltaY:c.number().optional()})).describe("SCROLL_UP [id] - Scroll up while hovering over the element with the specified id. If no id is provided, scroll the entire page."),Ft=I.merge(c.object({target:Z.optional(),type:c.literal("SCROLL_DOWN"),useVision:c.boolean().default(!1),deltaY:c.number().optional()})).describe("SCROLL_DOWN [id] - Scroll down while hovering over the element with the specified id. If no id is provided, scroll the entire page."),Ht=I.merge(c.object({type:c.literal("WAIT"),delay:c.number()})),Bt=I.merge(c.object({type:c.literal("REFRESH")})),Gt=I.merge(c.object({type:c.literal("GO_BACK")})),$t=I.merge(c.object({type:c.literal("GO_FORWARD")})),jt=I.merge(c.object({type:c.literal("CAPTCHA"),useVision:c.boolean().default(!1)})),Vt=I.merge(c.object({type:c.literal("CLICK"),target:Z,doubleClick:c.boolean().default(!1),rightClick:c.boolean().default(!1),useVision:c.boolean().default(!1)})).describe(kt`CLICK <id> - click on the element that has the specified id.
2
2
  You are NOT allowed to click on disabled, hidden or StaticText elements.
3
3
  Only click on elements on the Current Page.
4
4
  Only click on elements with the following tag names: button, input, link, image, generic.
5
5
  `.replaceAll(`
6
- `," ")),Vt=T.merge(l.object({type:l.literal("HOVER"),target:W,useVision:l.boolean().default(!1)})),jt=T.merge(l.object({type:l.literal("SELECT_OPTION"),target:W,option:l.string()})).describe('SELECT_OPTION <id> "<option>" - select an option from a combobox, listbox, or menu element on the page. Provide the id of the parent combobox, listbox, or menu element in <id>. Provide the name of the option in <option> enclosed by single quotes.'),$e=T.merge(l.object({type:l.literal("AI_ASSERTION"),assertion:l.string(),useVision:l.boolean().default(!1),disableCache:l.boolean().default(!1),cancelOnFailure:l.boolean().default(!1)})),Wt=l.object({clearContent:l.boolean().default(!0),pressKeysSequentially:l.boolean().default(!1)}),Kt=T.merge(l.object({type:l.literal("TYPE"),target:W,value:l.string(),pressEnter:l.boolean().default(!1),useVision:l.boolean().default(!1)})).merge(Wt).describe('TYPE <id> "<text>" - type the specified text into the input with the specified id. The text should be specified by the user - do not use text from the EXAMPLES or generate text yourself. Make sure to include quotes around the text.'),Xt=T.merge(l.object({type:l.literal("PRESS"),value:l.string()})).describe('PRESS <key> - press the specified key, such as "ArrowLeft", "Enter", or "a". You must specify at least one key.'),Yt=T.merge(l.object({type:l.literal("TAB"),url:l.string()})),qt=T.merge(l.object({type:l.literal("COOKIE"),value:l.string()})),Jt=T.merge(l.object({type:l.literal("SUCCESS"),condition:$e.optional()})).describe("SUCCESS - the user goal has been successfully achieved"),K=l.discriminatedUnion("type",[$t,Kt,Xt,jt,kt,Pt,_t,Jt]),Zt=l.discriminatedUnion("type",[Ft,Bt,Ht,$e,Ut,Yt,qt,Vt,Gt]),Ve=l.discriminatedUnion("type",[...K.options,...Zt.options]),Qt=T.merge(l.object({type:l.literal("FAILURE")})).describe("FAILURE - there are no commands to suggest that could make progress that have not already been tried before"),ge=l.discriminatedUnion("type",[...K.options,Qt]);import*as A from"zod";var _=(n=>(n.AI_ACTION="AI_ACTION",n.PRESET_ACTION="PRESET_ACTION",n.MODULE="MODULE",n))(_||{}),Z=A.object({type:A.literal("AI_ACTION"),text:A.string(),commands:A.array(K).optional()}),Q=A.object({type:A.literal("PRESET_ACTION"),command:Ve}),fe=A.object({type:A.literal("MODULE"),moduleId:A.string().uuid()}),ye=A.union([Z,Q]),be=A.object({type:A.literal("RESOLVED_MODULE"),moduleId:A.string().uuid(),name:A.string(),steps:ye.array()}),je=A.union([Z,Q,fe]),we=A.union([Z,Q,be]);import{distance as $n}from"fastest-levenshtein";import{chromium as Vn,devices as It}from"playwright";import{addExtra as jn}from"playwright-extra";import Wn from"puppeteer-extra-plugin-recaptcha";import Kn from"puppeteer-extra-plugin-stealth";import{z as ee}from"zod";var We=ee.object({thoughts:ee.string(),result:ee.boolean(),relevantElements:ee.array(ee.number()).optional()});import bo from"string-argv";import{z as ne}from"zod";var ae=(s=>(s.AI_PROVIDER="AIProviderError",s.AI_TIMEOUT="AITimeoutError",s.JOB_TIMEOUT="JobTimeoutError",s.ACTION_FAILURE="ActionFailureError",s.ASSERTION_FAILURE="AssertionFailureError",s.WEB_AGENT_PLATFORM="InternalWebAgentError",s.UNKNOWN_PLATFORM="InternalPlatformError",s))(ae||{});var te=class extends Error{constructor(e,t={}){super(e,t),this.name="BrowserExecutionError"}};var le=class extends Error{constructor(e={}){super("Got empty a11y tree",e),this.name="EmptyA11yTreeError"}};var N=class extends Error{constructor(e,t,n={}){var i;let r=!1;for(let a of Object.values(ae))if(t.startsWith(a)){r=!0,e=a;break}r?super(t,n):super(`${e}: ${t}`,n),this.name="TestFailureError",this.stack=(i=this.stack)==null?void 0:i.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}};var Eo=ne.object({command:ne.string(),thoughts:ne.string()}),vo=ne.string().pipe(ne.coerce.number());var Io=new Set(Object.values(H));var en={AI_ACTION:"AI action",MODULE:"Module",AI_ASSERTION:"AI check",CLICK:"Click",HOVER:"Hover",SELECT_OPTION:"Select",TYPE:"Type",PRESS:"Press",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",CAPTCHA:"Captcha",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",COOKIE:"Set cookie",SUCCESS:"Done"},Ro={AI_ACTION:"Ask AI to plan and execute something on the page.",MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI whether something is true on the page.",CLICK:"Click on an element on the page based on a description.",HOVER:"Hover over an element on the page based on a description.",SELECT_OPTION:"Select an option from a dropdown based on a description.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Ctrl+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up one page.",SCROLL_DOWN:"Scroll down one page.",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.",COOKIE:"Set a cookie that will persist throughout the browser session",CAPTCHA:"Solve captchas on the page. This may take 10-60 seconds.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."};import*as f from"zod";var Ke=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Ke||{}),Xe=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(Xe||{}),tn=f.object({beforeUrl:f.string(),beforeScreenshot:f.string().or(f.instanceof(Buffer)),afterUrl:f.string().optional(),afterScreenshot:f.string().or(f.instanceof(Buffer)).optional(),startedAt:f.coerce.date(),finishedAt:f.coerce.date(),viewport:f.object({height:f.number(),width:f.number()}),status:f.nativeEnum(Xe),message:f.string().optional(),elementInteracted:f.string().optional()}),Se=f.object({startedAt:f.coerce.date(),finishedAt:f.coerce.date(),status:f.nativeEnum(Ke),message:f.string().optional(),userAgent:f.string().optional()}),Ce=Q.merge(Se).merge(f.object({results:tn.array()})),Ye=Z.merge(Se).merge(f.object({results:Ce.array()})),nn=fe.merge(Se).merge(f.object({results:f.union([Ye,Ce]).array()})),ce=f.discriminatedUnion("type",[Ye,Ce,nn]);function on(o,e){return o.length<e?o:o.slice(0,e-3)+"[...]"}function Ee(o){var e,t,n;switch(o.type){case"SUCCESS":return(e=o.condition)!=null&&e.assertion?`Check success condition: ${o.condition.assertion}`:"All commands completed";case"NAVIGATE":return`Go to URL: ${on(o.url,30)}`;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 one page${o.target?` in the container of: ${o.target.elementDescriptor}`:""}`;case"SCROLL_UP":return`Scroll up one page${o.target?` in the container of: ${o.target.elementDescriptor}`:""}`;case"WAIT":return`Wait for ${o.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":return`Click on '${o.target.elementDescriptor}'`;case"TYPE":{let i="";return(t=o.target.a11yData)!=null&&t.serializedForm?i=`in element: ${o.target.a11yData.serializedForm}`:o.target.elementDescriptor.length>0&&(i=`in element: ${o.target.elementDescriptor}`),`Type '${o.value}' ${i}`}case"HOVER":{let i="";return(n=o.target.a11yData)!=null&&n.serializedForm?i=` over element: ${o.target.a11yData.serializedForm}`:o.target.elementDescriptor.length>0&&(i=` over element: ${o.target.elementDescriptor}`),`Hover${i}`}case"PRESS":return`Press '${o.value}'`;case"SELECT_OPTION":return`Select option '${o.option}' in '${o.target.elementDescriptor}'`;case"TAB":return`Switch to tab: ${o.url}`;case"COOKIE":return`Set cookie: ${o.value}`;case"AI_ASSERTION":return`${o.useVision?"Visual assertion":"Assertion"}: '${o.assertion}'`;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(o)}}import*as z from"zod";import*as G from"zod";var qe=G.object({type:G.nativeEnum(_),generatedStep:K.optional(),serializedCommand:G.string().optional(),elementInteracted:G.string().optional()});var X=z.object({goal:z.string(),url:z.string(),browserState:z.string(),history:z.string(),numPrevious:z.number(),lastCommand:qe.or(z.null())});import{parseString as rn}from"set-cookie-parser";function Je(o){let e=rn(o);if(!e.name)throw new Error("Name missing from cookie");if(!e.value)throw new Error("Value missing from cookie");let t;if(e.sameSite){let r=e.sameSite.trim().toLowerCase();if(r==="strict")t="Strict";else if(r==="lax")t="Lax";else if(r==="none")t="None";else throw new Error(`Invalid sameSite setting in cookie: ${r}`)}return!e.path&&e.domain&&(e.path="/"),B(L({},e),{expires:e.expires?e.expires.getTime()/1e3:void 0,sameSite:t})}import{z as O}from"zod";var an="1.0.0",Ze=O.object({run:O.string().describe("Run a single command in the shell. The working directory will be set to where the CLI was invoked from."),waitForCompletion:O.boolean().optional().describe("Defaults to true")}),jo=O.object({type:O.literal("momentic/fixture"),schemaVersion:O.string(),name:O.string(),description:O.string().optional(),setup:O.object({steps:Ze.array(),timeout:O.number().optional().describe("Timeout for all steps in seconds")}).optional(),teardown:O.object({steps:Ze.array(),timeout:O.number().optional().describe("Timeout for all steps in seconds")}).optional()}),Wo={type:"momentic/fixture",schemaVersion:an,name:"example",description:"An example fixture",setup:{steps:[{run:"./scripts/seed_db.sh",waitForCompletion:!0},{run:"npm run start",waitForCompletion:!1}],timeout:30},teardown:{steps:[{run:"./scripts/shutdown_db.sh"}]}};import{z as ln}from"zod";var Yo=ln.string().array();import*as P from"zod";var Qe=P.object({thoughts:P.string(),id:P.number().int(),options:P.array(P.string()).optional()});var cn={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},dn={0:"\x1B[90m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},ve=class o{constructor(e,t){this.minLogLevel=e,this.logBindings=t}log(e,...t){let n=cn[e],r;Array.isArray(t[0])?(r=t[0],t=t.slice(1)):typeof t[0]=="object"&&!(t[0]instanceof Error)&&(r=L(L({},t[0]),this.logBindings),t=t.slice(1));let i=dn[e],a=[`${i}[${new Date().toTimeString().slice(0,8)}][${n}]`];if(e!==0&&a.push("\x1B[39m"),a.push(...t),console.log(...a),r&&!Array.isArray(r))for(let[s,d]of Object.entries(r)){let p=d;typeof d=="object"&&(p=JSON.stringify(d,void 0,2),p=p.split(`
7
- `).map((u,h)=>h>0?` ${u}`:u).join(`
8
- `)),console.log(e===0?`${i} ${s}:`:` ${s}:`,p)}else if(r)for(let s of r){let d=s;typeof s=="object"&&(d=JSON.stringify(s,void 0,2),d=d.split(`
9
- `).map((p,u)=>u>0?` ${p}`:p).join(`
10
- `)),console.log(e===0?`${i} `:" ",d)}e===0&&process.stdout.write("\x1B[39m")}setMinLevel(e){this.minLogLevel=e}info(...e){1<this.minLogLevel||this.log(1,...e)}debug(...e){0<this.minLogLevel||this.log(0,...e)}warn(...e){2<this.minLogLevel||this.log(2,...e)}error(...e){3<this.minLogLevel||this.log(3,...e)}child(e){return new o(this.minLogLevel,L(L({},this.logBindings),e))}flush(){}bindings(){return this.logBindings}},Zo=new ve(1,{});import{z as U}from"zod";var mn=U.object({id:U.string(),createdAt:U.coerce.date(),createdBy:U.string(),organizationId:U.string(),name:U.string(),schemaVersion:U.string(),numSteps:U.number()}),or=U.object({steps:ye.array()}).merge(mn.omit({numSteps:!0}));import*as m from"zod";import{z as b}from"zod";var Ae={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},Te={PENDING:"PENDING",RUNNING:"RUNNING",PASSED:"PASSED",FAILED:"FAILED",CANCELLED:"CANCELLED"},pn={PASSED:"PASSED",FAILED:"FAILED"},de=b.string().pipe(b.coerce.date()).or(b.date()),un=b.object({id:b.string(),createdAt:de,createdBy:b.string(),organizationId:b.string(),scheduledAt:de.or(b.null()),startedAt:de.or(b.null()),finishedAt:de.or(b.null()),testId:b.string().or(b.null()),status:b.nativeEnum(Te),expectedStatus:b.nativeEnum(pn).or(b.null()),runKey:b.string(),trigger:b.nativeEnum(Ae),attempts:b.number(),test:b.object({name:b.string(),id:b.string()}).or(b.null())}),hn=un.merge(b.object({results:ce.array(),test:b.object({name:b.string(),id:b.string(),baseUrl:b.string()}).or(b.null())}));import{z as I}from"zod";import{z as me}from"zod";var et=me.object({name:me.string(),fixtures:me.array(me.string().describe("Name of the fixture (must be available locally in the fixtures directory).")).optional()});import{isValidCron as gn}from"cron-validator";import{z as k}from"zod";var tt=k.object({availableAsModule:k.boolean().default(!1),disableAICaching:k.boolean().default(!1)}),nt=k.object({cron:k.string().refine(o=>gn(o),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:k.boolean().default(!1),timeZone:k.string().default("America/Los_Angeles"),jobKey:k.string().optional()}),ot=k.object({onSuccess:k.boolean().default(!1),onFailure:k.boolean().default(!0)});var fn=I.string().min(1).max(255).superRefine((o,e)=>{try{Cn(o)}catch(t){return e.addIssue({code:I.ZodIssueCode.custom,message:t.message,fatal:!0}),I.NEVER}}),Y=I.object({id:I.string(),name:fn,baseUrl:I.string(),schemaVersion:I.string(),advanced:tt,retries:I.number(),envSettings:et.array().optional()}),yr=Y.pick({name:!0,baseUrl:!0,retries:!0,advanced:!0}),yn=I.object({createdAt:I.coerce.date(),updatedAt:I.coerce.date(),schedule:nt,notification:ot,createdBy:I.string(),organizationId:I.string()}),bn=Y.merge(yn).merge(I.object({steps:I.array(we)})),br=Y.merge(I.object({steps:I.array(we)}));var wn=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Sn=["modules","fixtures"];function Cn(o){if(o=o.toLowerCase().trim(),o.length===0||o.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"\/\\|?*\x00]/.test(o))throw new Error("Name can only contain alphanumeric characters, dashes, and underscores.");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(o))throw new Error(`"${o}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(o)||/^\s|\s$/.test(o))throw new Error("Name cannot start or end with a space or dot.");if(o.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(Sn.includes(o))throw new Error("'modules' is a reserved folder name in Momentic. Please choose a different name.");if(o.match(wn))throw new Error("Name cannot be a UUID. Please choose a different name.")}var oe=m.object({disableCache:m.boolean()}),Ir=m.object({error:m.boolean(),reason:m.string(),message:m.string()}),Rr=X.merge(oe),rt=ge,Nr=m.discriminatedUnion("vision",[X.merge(oe).merge(m.object({vision:m.literal(!1)})),X.pick({goal:!0,url:!0}).merge(oe).merge(m.object({screenshot:m.string(),vision:m.literal(!0)}))]),xe=We,Lr=X.pick({browserState:!0,goal:!0}).merge(oe),Ie=Qe,Or=X.pick({goal:!0,url:!0}).merge(oe),it=m.string().array(),Dr=m.object({testPaths:m.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),all:m.boolean().optional()}),Mr=m.object({message:m.string(),queuedTests:m.object({name:m.string(),id:m.string()}).array()});var zr=m.string().array(),kr=m.union([m.object({paths:m.string().array().describe("run specific test paths (e.g. todo-test)")}),m.object({path:m.string().describe("deprecated; present for backcompat")}),m.object({all:m.boolean().describe("run all tests")})]),_r=m.object({tests:m.record(m.string().describe("Test name"),m.string().describe("Test YAML")),modules:m.record(m.string().describe("Module name"),m.string().describe("Module YAML"))}),En=m.object({test:m.string().describe("test YAML"),modules:m.record(m.string().describe("moduleId"),m.string().describe("module YAML"))}),Pr=En.array();var Ur=m.object({testPath:m.string(),testId:m.string()}).partial().merge(m.object({trigger:m.nativeEnum(Ae)}));var Hr=m.object({startedAt:m.coerce.date(),finishedAt:m.coerce.date(),results:ce.array(),status:m.nativeEnum(Te)}).partial(),Fr=m.object({screenshot:m.string()}),Br=m.object({key:m.string()});import{stringify as Yr}from"yaml";import{z as C}from"zod";var ni=C.object({test:C.string().describe("YAML for the test, including metadata and steps"),modules:C.record(C.string(),C.string()).describe("Map of module name to YAML for the module")}),oi=Y.merge(C.object({steps:je.array(),fileType:C.literal("momentic/test")})),ri=be.omit({type:!0}).merge(C.object({schemaVersion:C.string(),fileType:C.literal("momentic/module")})),ii=Y.merge(C.object({steps:C.array(C.record(C.string(),C.unknown()))})),si=C.object({moduleId:C.string().uuid(),name:C.string(),schemaVersion:C.string(),steps:C.array(C.record(C.string(),C.unknown()))});var Re={js:'var K=Object.defineProperty;var P=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var H=(t,e,n)=>e in t?K(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e)=>{for(var n in e||(e={}))z.call(e,n)&&H(t,n,e[n]);if(P)for(var n of P(e))B.call(e,n)&&H(t,n,e[n]);return t};var g=(t,e,n)=>(H(t,typeof e!="symbol"?e+"":e,n),n);var _=(t,e,n)=>new Promise((o,r)=>{var i=s=>{try{d(n.next(s))}catch(l){r(l)}},a=s=>{try{d(n.throw(s))}catch(l){r(l)}},d=s=>s.done?o(s.value):Promise.resolve(s.value).then(i,a);d((n=n.apply(t,e)).next())});var E=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=E);var k={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?[k.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 N={_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=E(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=E(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(k.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),a=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>a,a};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let a of Array.from(t.children)){i=window.getComputedStyle(a,null);let d=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(d)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(a,!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=k.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,a,d,s=o.coords.split(",").map(p=>parseInt(p,10)),l=o.shape.toLowerCase();if(["rect","rectangle"].includes(l))s.length==4&&([r,a,i,d]=s);else if(["circle","circ"].includes(l)){if(s.length==3){let[p,w,v]=s,u=v/Math.sqrt(2);r=p-u,i=p+u,a=w-u,d=w+u}}else l==="default"?s.length==2&&([r,a,i,d]=[0,0,t.width,t.height]):s.length>=4&&([r,a,i,d]=s);let c=k.translate(k.create(r,a,i,d),t.left,t.top);c=this.cropRectToVisible(c),c&&!isNaN(c.top)&&!isNaN(c.left)&&!isNaN(c.width)&&!isNaN(c.height)&&n.push({element:o,rect:c})}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(e){}},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:a}=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&&a===!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 N.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!=null?n.parentNode:void 0),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 O={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){var r,i;let e={};this.addAttributes(t,this.commonAttributes,e);let n=((i=(r=t.tagName).toLowerCase)==null?void 0:i.call(r))||"";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,D({tag:n,attributes:e},o&&{content:o}))},getContent(t){var n,o;let e=((o=(n=t.tagName).toLowerCase)==null?void 0:o.call(n))||"";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){var o,r;if((((r=(o=t.tagName).toLowerCase)==null?void 0:r.call(o))||"")=="label"&&t.hasAttribute("for")){let i=t.getAttribute("for"),a=document.getElementById(i);a&&(e.target=this.describe(a))}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 x=null,C=()=>G()||document.scrollingElement||document.body,W=function(t){return t?t<0?-1:1:0},U={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},X=function(t,e,n){if(N.isString(n)){let o=n;return o==="viewSize"&&t===C()?e==="x"?window.innerWidth:window.innerHeight:t[U[e][o]]}else return n},V=function(t,e,n){let o=U[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},q=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},T=function(t,e,n,o){let r=o*X(t,e,n)||-1;return r=W(r),V(t,e,r)&&V(t,e,-r)},$=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),T(t,e,n,o)&&q(t,e)},j=function(t=null){let e;if(!t){let n=C();if(T(n,"y",1,1)||T(n,"y",-1,1))return n;t=document.body||C()}if(T(t,"y",1,1)||T(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=j(e.element);if(o)return o}return null}},L={init(){x=null},isScrollableElement(t){return x||(x=C()&&j()||C()),t!==x&&$(t)}},G=function(){let t=J[window.location.host];if(t)return document.querySelector(t)},J={"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=L;var A=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",E(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",E(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:A});var R=class{constructor(e){g(this,"element");g(this,"image");g(this,"rect");g(this,"linkText");g(this,"showLinkText");g(this,"reason");g(this,"secondClassCitizen");g(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},M={getLocalHintsForElement(t){var p,w,v;let e=((w=(p=t.tagName).toLowerCase)==null?void 0:w.call(p))||"",n=!1,o=!1,r=!1,i=[],a=[],d=null;if(e==="img"){let u=t.getAttribute("usemap");if(u){let h=t.getClientRects();u=u.replace(/^#/,"").replace(\'"\',\'\\\\"\');let m=document.querySelector(`map[name="${u}"]`);if(m&&h.length>0){n=!0;let y=m.getElementsByTagName("area"),S=f.getClientRectsForAreas(h[0],y);S=S.map(F=>Object.assign(F,{image:t})),a.push(...S)}}}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 h=[];for(let m of["","data-","x-"])for(let y of["-",":","_"])h.push(`${m}ng${y}click`);return function(m){for(let y of h)if(m.hasAttribute(y))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let u=t.getAttribute("role"),h=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(u!=null&&h.includes(u.toLowerCase()))n=!0;else{let m=t.getAttribute("contentEditable");m!=null&&["","contenteditable","true","plaintext-only"].includes(m.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let u=t.getAttribute("jsaction").split(";");for(let h of u){let m=h.trim().split(":");if(m.length>=1&&m.length<=2){let[y,S,F]=m.length===1?["click",...m[0].trim().split("."),"_"]:[m[0],...m[1].trim().split("."),"_"];n||(n=y==="click"&&S!=="none"&&F!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||(n=!t.disabled&&!t.readOnly);break;case"input":n||(n=!(((v=t.getAttribute("type"))==null?void 0:v.toLowerCase())=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t)));break;case"button":case"select":n||(n=!t.disabled);break;case"object":case"embed":n=!0;break;case"label":n||(n=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0);break;case"body":n||(n=t===document.body&&!A()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?d="Frame.":void 0),n||(n=t===document.body&&A()&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"img":n||(n=["zoom-in","zoom-out"].includes(t.style.cursor));break;case"div":case"ol":case"ul":n||(n=t.clientHeight<t.scrollHeight&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"details":n=!0,d="Open.";break}let l=t.getAttribute("class");!n&&(l!=null&&l.toLowerCase().includes("button"))&&(n=!0,r=!0);let c=t.getAttribute("tabindex"),b=c?parseInt(c):-1;if(!n&&!(b<0)&&!isNaN(b)&&(n=!0,o=!0),n)if(a.length>0){let u=a.map(h=>new R({element:h.element,image:t,rect:h.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:d}));i.push(...u)}else{let u=f.getVisibleClientRect(t,!0);if(u!==null){let h=new R({element:t,rect:u,secondClassCitizen:o,possibleFalsePositive:r,reason:d});i.push(h)}}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?M.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,l)=>{l==null&&(l=[]);for(let c of Array.from(s.querySelectorAll("*")))l.push(c),c.shadowRoot&&e(c.shadowRoot,l);return l},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let l=this.getLocalHintsForElement(s);o.push(...l)}o=o.reverse();let r=[1,2,3];o=o.filter((s,l)=>{if(!s.possibleFalsePositive)return!0;let b=Math.max(0,l-6);for(;b<l;){let p=o[b].element;for(let w of r)if(p=p==null?void 0:p.parentElement,p===s.element)return!1;b+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let l=s.rect,c=M.getElementFromPoint(l.left+l.width*.5,l.top+l.height*.5);if(c&&(s.element.contains(c)||c.contains(s.element))||s.element.localName=="area"&&c==s.image)return!0;let p=[l.top+.1,l.bottom-.1],w=[l.left+.1,l.right-.1];for(let v of p)for(let u of w){let h=M.getElementFromPoint(u,v);if(h&&(s.element.contains(h)||h.contains(s.element)))return!0}});i.reverse();let{top:a,left:d}=f.getViewportTopLeft();for(let s of i)s.rect.top+=a,s.rect.left+=d;return i}};var I=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}capture(){return _(this,null,function*(){this.reset(),this.createMarkers(),this.displayMarkers()})}createMarkers(){this.hints=M.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{var i,a;let o=f.createElement("div"),r=(a=(i=e.element.attributes["data-momentic-id"])==null?void 0:i.value)!=null?a: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(O.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=I;\n',css:`/* Reproduced from https://github.com/philc/vimium/blob/master/content_scripts/vimium.css */
6
+ `," ")),Wt=I.merge(c.object({type:c.literal("HOVER"),target:Z,useVision:c.boolean().default(!1)})),Kt=I.merge(c.object({type:c.literal("SELECT_OPTION"),target:Z,option:c.string()})).describe('SELECT_OPTION <id> "<option>" - select an option from a combobox, listbox, or menu element on the page. Provide the id of the parent combobox, listbox, or menu element in <id>. Do NOT provide the id of the option: instead, provide the name of the option in <option> enclosed by single quotes.'),je=I.merge(c.object({type:c.literal("AI_ASSERTION"),assertion:c.string(),useVision:c.boolean().default(!1),disableCache:c.boolean().default(!1),cancelOnFailure:c.boolean().default(!1)})),Xt=c.object({clearContent:c.boolean().default(!0),pressKeysSequentially:c.boolean().default(!1)}),qt=I.merge(c.object({type:c.literal("TYPE"),target:Z,value:c.string(),pressEnter:c.boolean().default(!1),useVision:c.boolean().default(!1)})).merge(Xt).describe('TYPE <id> "<text>" - type the specified text into the input with the specified id. The text should be specified by the user - do not use text from the EXAMPLES or generate text yourself. Make sure to include quotes around the text.'),Yt=I.merge(c.object({type:c.literal("PRESS"),value:c.string()})).describe('PRESS <key> - press the specified key, such as "ArrowLeft", "Enter", or "a". You must specify at least one key.'),Jt=I.merge(c.object({type:c.literal("TAB"),url:c.string()})),Zt=I.merge(c.object({type:c.literal("COOKIE"),value:c.string()})),Qt=I.merge(c.object({type:c.literal("SUCCESS"),condition:je.optional()})).describe("SUCCESS - the user goal has been successfully achieved"),Q=c.discriminatedUnion("type",[Vt,qt,Yt,Kt,_t,Ft,Ut,Qt]),eo=c.discriminatedUnion("type",[Gt,$t,Bt,je,Ht,Jt,Zt,Wt,jt]),Ve=c.discriminatedUnion("type",[...Q.options,...eo.options]),to=I.merge(c.object({type:c.literal("FAILURE")})).describe("FAILURE - there are no commands to suggest that could make progress that have not already been tried before"),ve=c.discriminatedUnion("type",[...Q.options,to]);import*as A from"zod";var _=(o=>(o.AI_ACTION="AI_ACTION",o.PRESET_ACTION="PRESET_ACTION",o.MODULE="MODULE",o))(_||{}),oe=A.object({type:A.literal("AI_ACTION"),text:A.string(),commands:A.array(Q).optional()}),ne=A.object({type:A.literal("PRESET_ACTION"),command:Ve}),Ce=A.object({type:A.literal("MODULE"),moduleId:A.string().uuid()}),re=A.union([oe,ne]),Ee=A.object({type:A.literal("RESOLVED_MODULE"),moduleId:A.string().uuid(),name:A.string(),steps:re.array()}),pe=A.union([oe,ne,Ce]),ie=A.union([oe,ne,Ee]);import{distance as Ko}from"fastest-levenshtein";import{chromium as Xo,devices as Lt}from"playwright";import{addExtra as qo}from"playwright-extra";import Yo from"puppeteer-extra-plugin-recaptcha";import Jo from"puppeteer-extra-plugin-stealth";import{z as se}from"zod";var We=se.object({thoughts:se.string(),result:se.boolean(),relevantElements:se.array(se.number()).optional()});import Cn from"string-argv";import{z as V}from"zod";var ue=(s=>(s.AI_PROVIDER="AIProviderError",s.AI_TIMEOUT="AITimeoutError",s.JOB_TIMEOUT="JobTimeoutError",s.ACTION_FAILURE="ActionFailureError",s.ASSERTION_FAILURE="AssertionFailureError",s.WEB_AGENT_PLATFORM="InternalWebAgentError",s.UNKNOWN_PLATFORM="InternalPlatformError",s))(ue||{});var ae=class extends Error{constructor(e,t={}){super(e,t),this.name="BrowserExecutionError"}};var he=class extends Error{constructor(e={}){super("Got empty a11y tree",e),this.name="EmptyA11yTreeError"}};var O=class extends Error{constructor(e,t,o={}){var i;let n=!1;for(let a of Object.values(ue))if(t.startsWith(a)){n=!0,e=a;break}n?super(t,o):super(`${e}: ${t}`,o),this.name="TestFailureError",this.stack=(i=this.stack)==null?void 0:i.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}};var xn=V.object({command:V.string(),thoughts:V.string()}),In=V.string().pipe(V.coerce.number());var Ke=V.object({phrase:V.string()});var On=new Set(Object.values(B));var oo={AI_ACTION:"AI action",MODULE:"Module",AI_ASSERTION:"AI check",CLICK:"Click",HOVER:"Hover",SELECT_OPTION:"Select",TYPE:"Type",PRESS:"Press",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",CAPTCHA:"Captcha",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",COOKIE:"Set cookie",SUCCESS:"Done"},Dn={AI_ACTION:"Ask AI to plan and execute something on the page.",MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI whether something is true on the page.",CLICK:"Click on an element on the page based on a description.",HOVER:"Hover over an element on the page based on a description.",SELECT_OPTION:"Select an option from a dropdown based on a description.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Ctrl+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up one page.",SCROLL_DOWN:"Scroll down one page.",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.",COOKIE:"Set a cookie that will persist throughout the browser session",CAPTCHA:"Solve captchas on the page. This may take 10-60 seconds.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."};import*as g from"zod";var Xe=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Xe||{}),qe=(o=>(o.SUCCESS="SUCCESS",o.FAILED="FAILED",o.CANCELLED="CANCELLED",o))(qe||{}),no=g.object({beforeUrl:g.string(),beforeScreenshot:g.string().or(g.instanceof(Buffer)),afterUrl:g.string().optional(),afterScreenshot:g.string().or(g.instanceof(Buffer)).optional(),startedAt:g.coerce.date(),finishedAt:g.coerce.date(),viewport:g.object({height:g.number(),width:g.number()}),status:g.nativeEnum(qe),message:g.string().optional(),elementInteracted:g.string().optional()}),Te=g.object({startedAt:g.coerce.date(),finishedAt:g.coerce.date(),status:g.nativeEnum(Xe),message:g.string().optional(),userAgent:g.string().optional()}),Ae=ne.merge(Te).merge(g.object({results:no.array()})),Ye=oe.merge(Te).merge(g.object({results:Ae.array()})),ro=Ce.merge(Te).merge(g.object({results:g.union([Ye,Ae]).array()})),ge=g.discriminatedUnion("type",[Ye,Ae,ro]);function io(r,e){return r.length<e?r:r.slice(0,e-3)+"[...]"}function xe(r){var e,t,o;switch(r.type){case"SUCCESS":return(e=r.condition)!=null&&e.assertion?`Check success condition: ${r.condition.assertion}`:"All commands completed";case"NAVIGATE":return`Go to URL: ${io(r.url,30)}`;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 one page${r.target?` in the container of: ${r.target.elementDescriptor}`:""}`;case"SCROLL_UP":return`Scroll up one page${r.target?` in the container of: ${r.target.elementDescriptor}`:""}`;case"WAIT":return`Wait for ${r.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":return`Click on '${r.target.elementDescriptor}'`;case"TYPE":{let i="";return(t=r.target.a11yData)!=null&&t.serializedForm?i=`in element: ${r.target.a11yData.serializedForm}`:r.target.elementDescriptor.length>0&&(i=`in element: ${r.target.elementDescriptor}`),`Type '${r.value}' ${i}`}case"HOVER":{let i="";return(o=r.target.a11yData)!=null&&o.serializedForm?i=` over element: ${r.target.a11yData.serializedForm}`:r.target.elementDescriptor.length>0&&(i=` over element: ${r.target.elementDescriptor}`),`Hover${i}`}case"PRESS":return`Press '${r.value}'`;case"SELECT_OPTION":return`Select option '${r.option}' in '${r.target.elementDescriptor}'`;case"TAB":return`Switch to tab: ${r.url}`;case"COOKIE":return`Set cookie: ${r.value}`;case"AI_ASSERTION":return`${r.useVision?"Visual assertion":"Assertion"}: '${r.assertion}'`;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import*as z from"zod";import*as W from"zod";var Je=W.object({type:W.nativeEnum(_),generatedStep:Q.optional(),serializedCommand:W.string().optional(),elementInteracted:W.string().optional()});var G=z.object({goal:z.string(),url:z.string(),browserState:z.string(),history:z.string(),numPrevious:z.number(),lastCommand:Je.or(z.null())});import{parseString as so}from"set-cookie-parser";function Ze(r){let e=so(r);if(!e.name)throw new Error("Name missing from cookie");if(!e.value)throw new Error("Value missing from cookie");let t;if(e.sameSite){let n=e.sameSite.trim().toLowerCase();if(n==="strict")t="Strict";else if(n==="lax")t="Lax";else if(n==="none")t="None";else throw new Error(`Invalid sameSite setting in cookie: ${n}`)}return!e.path&&e.domain&&(e.path="/"),j(L({},e),{expires:e.expires?e.expires.getTime()/1e3:void 0,sameSite:t})}import{z as D}from"zod";var lo="1.0.0",Qe=D.object({run:D.string().describe("Run a single command in the shell. The working directory will be set to where the CLI was invoked from."),waitForCompletion:D.boolean().optional().describe("Defaults to true")}),qn=D.object({type:D.literal("momentic/fixture"),schemaVersion:D.string(),name:D.string(),description:D.string().optional(),setup:D.object({steps:Qe.array(),timeout:D.number().optional().describe("Timeout for all steps in seconds")}).optional(),teardown:D.object({steps:Qe.array(),timeout:D.number().optional().describe("Timeout for all steps in seconds")}).optional()}),Yn={type:"momentic/fixture",schemaVersion:lo,name:"example",description:"An example fixture",setup:{steps:[{run:"./scripts/seed_db.sh",waitForCompletion:!0},{run:"npm run start",waitForCompletion:!1}],timeout:30},teardown:{steps:[{run:"./scripts/shutdown_db.sh"}]}};import{z as co}from"zod";var Qn=co.string().array();import{z as N}from"zod";import{z as R}from"zod";import{z as fe}from"zod";var et=fe.object({name:fe.string(),fixtures:fe.array(fe.string().describe("Name of the fixture (must be available locally in the fixtures directory).")).optional()});import{isValidCron as mo}from"cron-validator";import{z as P}from"zod";var tt=P.object({availableAsModule:P.boolean().default(!1),disableAICaching:P.boolean().default(!1)}),ot=P.object({cron:P.string().refine(r=>mo(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:P.boolean().default(!1),timeZone:P.string().default("America/Los_Angeles"),jobKey:P.string().optional()}),nt=P.object({onSuccess:P.boolean().default(!1),onFailure:P.boolean().default(!0)});var po=R.string().min(1).max(255).superRefine((r,e)=>{try{bo(r)}catch(t){return e.addIssue({code:R.ZodIssueCode.custom,message:t.message,fatal:!0}),R.NEVER}}),K=R.object({id:R.string(),name:po,baseUrl:R.string(),schemaVersion:R.string(),advanced:tt,retries:R.number(),envSettings:et.array().optional()}),dr=K.pick({name:!0,baseUrl:!0,retries:!0,advanced:!0}),uo=R.object({createdAt:R.coerce.date(),updatedAt:R.coerce.date(),schedule:ot,notification:nt,createdBy:R.string(),organizationId:R.string()}),ho=K.merge(uo).merge(R.object({steps:R.array(ie)})),go=K.merge(R.object({steps:R.array(ie)})),mr=K.merge(R.object({steps:pe.array()}));var fo=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,yo=["modules","fixtures"];function bo(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(/[<>:"\/\\|?*\x00]/.test(r))throw new Error("Name can only contain alphanumeric characters, dashes, and underscores.");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(yo.includes(r))throw new Error("'modules' is a reserved folder name in Momentic. Please choose a different name.");if(r.match(fo))throw new Error("Name cannot be a UUID. Please choose a different name.")}var wo="momentic-frame",fr=`${wo}-0`,yr=N.array(N.object({path:N.string(),lastModified:N.date(),createdAt:N.date()})),br=N.object({name:N.string(),steps:ie.array()}),wr=N.object({name:N.string(),baseUrl:N.string().url()});var Sr=N.object({name:N.string(),steps:re.array()}),vr=N.array(N.object({name:N.string(),moduleId:N.string().uuid(),numSteps:N.number()}));import*as U from"zod";var rt=U.object({thoughts:U.string(),id:U.number().int(),options:U.array(U.string()).optional()});var So={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},vo={0:"\x1B[90m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},Ie=class r{constructor(e,t){this.minLogLevel=e,this.logBindings=t}log(e,...t){let o=So[e],n;Array.isArray(t[0])?(n=t[0],t=t.slice(1)):typeof t[0]=="object"&&!(t[0]instanceof Error)&&(n=L(L({},t[0]),this.logBindings),t=t.slice(1));let i=vo[e],a=[`${i}[${new Date().toTimeString().slice(0,8)}][${o}]`];if(e!==0&&a.push("\x1B[39m"),a.push(...t),console.log(...a),n&&!Array.isArray(n))for(let[s,m]of Object.entries(n)){let p=m;m instanceof Error?p=m.message:typeof m=="object"&&(p=JSON.stringify(m,void 0,2),p=p.split(`
7
+ `).map((h,u)=>u>0?` ${h}`:h).join(`
8
+ `)),console.log(e===0?`${i} ${s}:`:` ${s}:`,p)}else if(n)for(let s of n){let m=s;typeof s=="object"&&(m=JSON.stringify(s,void 0,2),m=m.split(`
9
+ `).map((p,h)=>h>0?` ${p}`:p).join(`
10
+ `)),console.log(e===0?`${i} `:" ",m)}e===0&&process.stdout.write("\x1B[39m")}setMinLevel(e){this.minLogLevel=e}info(...e){1<this.minLogLevel||this.log(1,...e)}debug(...e){0<this.minLogLevel||this.log(0,...e)}warn(...e){2<this.minLogLevel||this.log(2,...e)}error(...e){3<this.minLogLevel||this.log(3,...e)}child(e){return new r(this.minLogLevel,L(L({},this.logBindings),e))}flush(){}bindings(){return this.logBindings}},Tr=new Ie(1,{});import{z as F}from"zod";var Co=F.object({id:F.string(),createdAt:F.coerce.date(),createdBy:F.string(),organizationId:F.string(),name:F.string(),schemaVersion:F.string(),numSteps:F.number()}),Nr=F.object({steps:re.array()}).merge(Co.omit({numSteps:!0}));import*as d from"zod";import{z as w}from"zod";var Re={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},Ne={PENDING:"PENDING",RUNNING:"RUNNING",PASSED:"PASSED",FAILED:"FAILED",CANCELLED:"CANCELLED"},Eo={PASSED:"PASSED",FAILED:"FAILED"},ye=w.string().pipe(w.coerce.date()).or(w.date()),To=w.object({id:w.string(),createdAt:ye,createdBy:w.string(),organizationId:w.string(),scheduledAt:ye.or(w.null()),startedAt:ye.or(w.null()),finishedAt:ye.or(w.null()),testId:w.string().or(w.null()),status:w.nativeEnum(Ne),expectedStatus:w.nativeEnum(Eo).or(w.null()),runKey:w.string(),trigger:w.nativeEnum(Re),attempts:w.number(),test:w.object({name:w.string(),id:w.string()}).or(w.null())}),Ao=To.merge(w.object({results:ge.array(),test:w.object({name:w.string(),id:w.string(),baseUrl:w.string()}).or(w.null())}));var X=d.object({disableCache:d.boolean()}),Gr=d.object({error:d.boolean(),reason:d.string(),message:d.string()}),$r=G.merge(X),it=ve,jr=d.discriminatedUnion("vision",[G.merge(X).merge(d.object({vision:d.literal(!1)})),G.pick({goal:!0,url:!0}).merge(X).merge(d.object({screenshot:d.string(),vision:d.literal(!0)}))]),Le=We,Vr=G.pick({browserState:!0,goal:!0}).merge(X),Wr=G.pick({goal:!0}).merge(X).merge(d.object({screenshot:d.string().describe("base64 encoded image"),hintActivatedScreenshot:d.string().describe("base64 encoded image")})),Oe=rt,Kr=G.pick({goal:!0,url:!0}).merge(X),st=d.string().array(),Xr=G.pick({goal:!0,browserState:!0}).merge(X),at=Ke,qr=d.object({testPaths:d.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),all:d.boolean().optional()}),Yr=d.object({message:d.string(),queuedTests:d.object({name:d.string(),id:d.string()}).array()});var Jr=d.string().array(),Zr=d.union([d.object({paths:d.string().array().describe("run specific test paths (e.g. todo-test)")}),d.object({path:d.string().describe("deprecated; present for backcompat")}),d.object({all:d.boolean().describe("run all tests")})]),Qr=d.object({tests:d.record(d.string().describe("Test name"),d.string().describe("Test YAML")),modules:d.record(d.string().describe("Module name"),d.string().describe("Module YAML"))}),xo=d.object({test:d.string().describe("test YAML"),modules:d.record(d.string().describe("moduleId"),d.string().describe("module YAML"))}),ei=xo.array();var ti=d.object({testPath:d.string(),testId:d.string()}).partial().merge(d.object({trigger:d.nativeEnum(Re)}));var oi=d.object({startedAt:d.coerce.date(),finishedAt:d.coerce.date(),results:ge.array(),status:d.nativeEnum(Ne)}).partial(),ni=d.object({screenshot:d.string()}),ri=d.object({key:d.string()}),ii=d.object({orgId:d.string()});import{stringify as ui}from"yaml";import{z as v}from"zod";var Si=v.object({test:v.string().describe("YAML for the test, including metadata and steps"),modules:v.record(v.string(),v.string()).describe("Map of module name to YAML for the module")}),vi=K.merge(v.object({steps:pe.array(),fileType:v.literal("momentic/test")})),Ci=Ee.omit({type:!0}).merge(v.object({schemaVersion:v.string(),fileType:v.literal("momentic/module")})),Ei=K.merge(v.object({steps:v.array(v.record(v.string(),v.unknown()))})),Ti=v.object({moduleId:v.string().uuid(),name:v.string(),schemaVersion:v.string(),steps:v.array(v.record(v.string(),v.unknown()))});var De={js:'var K=Object.defineProperty;var P=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var H=(t,e,n)=>e in t?K(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e)=>{for(var n in e||(e={}))z.call(e,n)&&H(t,n,e[n]);if(P)for(var n of P(e))B.call(e,n)&&H(t,n,e[n]);return t};var g=(t,e,n)=>(H(t,typeof e!="symbol"?e+"":e,n),n);var _=(t,e,n)=>new Promise((o,r)=>{var i=s=>{try{d(n.next(s))}catch(l){r(l)}},a=s=>{try{d(n.throw(s))}catch(l){r(l)}},d=s=>s.done?o(s.value):Promise.resolve(s.value).then(i,a);d((n=n.apply(t,e)).next())});var E=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=E);var k={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?[k.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 N={_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=E(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=E(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(k.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),a=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>a,a};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let a of Array.from(t.children)){i=window.getComputedStyle(a,null);let d=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(d)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(a,!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=k.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,a,d,s=o.coords.split(",").map(p=>parseInt(p,10)),l=o.shape.toLowerCase();if(["rect","rectangle"].includes(l))s.length==4&&([r,a,i,d]=s);else if(["circle","circ"].includes(l)){if(s.length==3){let[p,w,v]=s,u=v/Math.sqrt(2);r=p-u,i=p+u,a=w-u,d=w+u}}else l==="default"?s.length==2&&([r,a,i,d]=[0,0,t.width,t.height]):s.length>=4&&([r,a,i,d]=s);let c=k.translate(k.create(r,a,i,d),t.left,t.top);c=this.cropRectToVisible(c),c&&!isNaN(c.top)&&!isNaN(c.left)&&!isNaN(c.width)&&!isNaN(c.height)&&n.push({element:o,rect:c})}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(e){}},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:a}=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&&a===!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 N.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!=null?n.parentNode:void 0),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 O={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){var r,i;let e={};this.addAttributes(t,this.commonAttributes,e);let n=((i=(r=t.tagName).toLowerCase)==null?void 0:i.call(r))||"";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,D({tag:n,attributes:e},o&&{content:o}))},getContent(t){var n,o;let e=((o=(n=t.tagName).toLowerCase)==null?void 0:o.call(n))||"";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){var o,r;if((((r=(o=t.tagName).toLowerCase)==null?void 0:r.call(o))||"")=="label"&&t.hasAttribute("for")){let i=t.getAttribute("for"),a=document.getElementById(i);a&&(e.target=this.describe(a))}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 x=null,C=()=>G()||document.scrollingElement||document.body,W=function(t){return t?t<0?-1:1:0},U={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},X=function(t,e,n){if(N.isString(n)){let o=n;return o==="viewSize"&&t===C()?e==="x"?window.innerWidth:window.innerHeight:t[U[e][o]]}else return n},V=function(t,e,n){let o=U[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},q=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},T=function(t,e,n,o){let r=o*X(t,e,n)||-1;return r=W(r),V(t,e,r)&&V(t,e,-r)},$=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),T(t,e,n,o)&&q(t,e)},j=function(t=null){let e;if(!t){let n=C();if(T(n,"y",1,1)||T(n,"y",-1,1))return n;t=document.body||C()}if(T(t,"y",1,1)||T(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=j(e.element);if(o)return o}return null}},L={init(){x=null},isScrollableElement(t){return x||(x=C()&&j()||C()),t!==x&&$(t)}},G=function(){let t=J[window.location.host];if(t)return document.querySelector(t)},J={"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=L;var A=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",E(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",E(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:A});var R=class{constructor(e){g(this,"element");g(this,"image");g(this,"rect");g(this,"linkText");g(this,"showLinkText");g(this,"reason");g(this,"secondClassCitizen");g(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},M={getLocalHintsForElement(t){var p,w,v;let e=((w=(p=t.tagName).toLowerCase)==null?void 0:w.call(p))||"",n=!1,o=!1,r=!1,i=[],a=[],d=null;if(e==="img"){let u=t.getAttribute("usemap");if(u){let h=t.getClientRects();u=u.replace(/^#/,"").replace(\'"\',\'\\\\"\');let m=document.querySelector(`map[name="${u}"]`);if(m&&h.length>0){n=!0;let y=m.getElementsByTagName("area"),S=f.getClientRectsForAreas(h[0],y);S=S.map(F=>Object.assign(F,{image:t})),a.push(...S)}}}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 h=[];for(let m of["","data-","x-"])for(let y of["-",":","_"])h.push(`${m}ng${y}click`);return function(m){for(let y of h)if(m.hasAttribute(y))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let u=t.getAttribute("role"),h=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(u!=null&&h.includes(u.toLowerCase()))n=!0;else{let m=t.getAttribute("contentEditable");m!=null&&["","contenteditable","true","plaintext-only"].includes(m.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let u=t.getAttribute("jsaction").split(";");for(let h of u){let m=h.trim().split(":");if(m.length>=1&&m.length<=2){let[y,S,F]=m.length===1?["click",...m[0].trim().split("."),"_"]:[m[0],...m[1].trim().split("."),"_"];n||(n=y==="click"&&S!=="none"&&F!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||(n=!t.disabled&&!t.readOnly);break;case"input":n||(n=!(((v=t.getAttribute("type"))==null?void 0:v.toLowerCase())=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t)));break;case"button":case"select":n||(n=!t.disabled);break;case"object":case"embed":n=!0;break;case"label":n||(n=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0);break;case"body":n||(n=t===document.body&&!A()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?d="Frame.":void 0),n||(n=t===document.body&&A()&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"img":n||(n=["zoom-in","zoom-out"].includes(t.style.cursor));break;case"div":case"ol":case"ul":n||(n=t.clientHeight<t.scrollHeight&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"details":n=!0,d="Open.";break}let l=t.getAttribute("class");!n&&(l!=null&&l.toLowerCase().includes("button"))&&(n=!0,r=!0);let c=t.getAttribute("tabindex"),b=c?parseInt(c):-1;if(!n&&!(b<0)&&!isNaN(b)&&(n=!0,o=!0),n)if(a.length>0){let u=a.map(h=>new R({element:h.element,image:t,rect:h.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:d}));i.push(...u)}else{let u=f.getVisibleClientRect(t,!0);if(u!==null){let h=new R({element:t,rect:u,secondClassCitizen:o,possibleFalsePositive:r,reason:d});i.push(h)}}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?M.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,l)=>{l==null&&(l=[]);for(let c of Array.from(s.querySelectorAll("*")))l.push(c),c.shadowRoot&&e(c.shadowRoot,l);return l},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let l=this.getLocalHintsForElement(s);o.push(...l)}o=o.reverse();let r=[1,2,3];o=o.filter((s,l)=>{if(!s.possibleFalsePositive)return!0;let b=Math.max(0,l-6);for(;b<l;){let p=o[b].element;for(let w of r)if(p=p==null?void 0:p.parentElement,p===s.element)return!1;b+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let l=s.rect,c=M.getElementFromPoint(l.left+l.width*.5,l.top+l.height*.5);if(c&&(s.element.contains(c)||c.contains(s.element))||s.element.localName=="area"&&c==s.image)return!0;let p=[l.top+.1,l.bottom-.1],w=[l.left+.1,l.right-.1];for(let v of p)for(let u of w){let h=M.getElementFromPoint(u,v);if(h&&(s.element.contains(h)||h.contains(s.element)))return!0}});i.reverse();let{top:a,left:d}=f.getViewportTopLeft();for(let s of i)s.rect.top+=a,s.rect.left+=d;return i}};var I=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}capture(){return _(this,null,function*(){this.reset(),this.createMarkers(),this.displayMarkers()})}createMarkers(){this.hints=M.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{var i,a;let o=f.createElement("div"),r=(a=(i=e.element.attributes["data-momentic-id"])==null?void 0:i.value)!=null?a: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(O.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=I;\n',css:`/* Reproduced from https://github.com/philc/vimium/blob/master/content_scripts/vimium.css */
11
11
 
12
12
  /*
13
13
  * Many CSS class names in this file use the verbose "vimiumXYZ" as the class name. This is so we
@@ -560,17 +560,17 @@ var Nt=Object.defineProperty,Lt=Object.defineProperties;var Ot=Object.getOwnProp
560
560
  color: white;
561
561
  }
562
562
  }
563
- `};var $=(o,e)=>{let{hostname:t,pathname:n}=new URL(o),{hostname:r,pathname:i}=new URL(e);return t!==r||n!==i};import{distance as dt}from"fastest-levenshtein";var st=new Set(["about:blank","chrome-error://chromewebdata/"]),at=2;var An=["focusable","keyshortcuts","controls"],Tn=["textbox","checkbox","combobox","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch"],xn=["notRendered","notVisible","ariaHiddenSubtree","ariaHiddenElement"],In=80,Rn={paragraph:"p",searchbox:"input"},pt=["paragraph","option","StaticText"],mt={indentLevel:0,noID:!1,noChildren:!1,noProperties:!1,maxLevel:void 0,neighbors:void 0},Ne=class{constructor(e){this.id=e.id,this.role=e.role,this.name=e.name,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeID=e.backendNodeID,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value})}getLogForm(){var e,t;return JSON.stringify({id:this.id,name:(e=this.name)!=null?e:"",role:(t=this.role)!=null?t:"",backendNodeId:this.backendNodeID})}isInteresting(){return Tn.includes(this.role)||this.children.some(e=>e.role==="StaticText")?!0:!!this.name.trim()||!!this.content}serialize(e=mt){var x,w;let{indentLevel:t,noChildren:n,noProperties:r,noID:i}=Object.assign({},mt,e),a=" ".repeat(t),s=Rn[this.role]||this.role,d=this.name,p=L({},this.properties);s==="heading"&&(p.level&&(s=`h${p.level}`,delete p.level),d==="heading"&&(d=""));let u=!pt.includes(this.role);if(this.role==="StaticText")return`${a}${d}
564
- `;let h=`${a}<${s}`;!i&&u&&(h+=` id="${this.id}"`),d&&(h+=` name="${d}"`),this.content&&(h+=` content="${this.content}"`),Object.keys(this.properties).length>0&&!r&&Object.entries(this.properties).forEach(([g,S])=>{An.includes(g)||(typeof S=="string"?h+=` ${g}="${S}"`:typeof S=="boolean"?S?h+=` ${g}`:h+=` ${g}={false}`:typeof S!="undefined"&&(h+=` ${g}={${JSON.stringify(S)}}`))});let R=e.maxLevel!==void 0&&t/2>=e.maxLevel;if(this.children.length===0||n||R)return h+=` />
565
- `,h;{let g="";for(let y of this.children)g+=y.serialize(B(L({},e),{indentLevel:t+2}));let S=g.trim();S.length<=In&&!S.includes(`
566
- `)?h+=`>${S}</${s}>
567
- `:h+=`>
568
- ${g}${a}</${s}>
569
- `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let g=this.parent.children.findIndex(D=>D.id===this.id),S=g>0?(x=this.parent.children[g-1])==null?void 0:x.serialize(B(L({},e),{neighbors:0})):"",y=g<this.parent.children.length-1?(w=this.parent.children[g+1])==null?void 0:w.serialize(B(L({},e),{neighbors:0})):"";return`${S||""}
570
- ${h}
571
- ${y||""}`}return h}},Le=class{constructor(e,t,n){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n}serialize(){return this.root?this.root.serialize():""}};function Nn(o){var e,t;return(e=o.name)!=null&&e.value?`"${o.name.value}"`:(t=o.role)!=null&&t.value&&o.role.value!=="none"&&o.role.value!=="generic"?`"${o.role.value}"`:`"${o.nodeId}"`}function ut(o,e,t){var s,d,p,u,h,R,x;if(!e&&o.parentId)throw new Error(`Got no parent for accessibility node ${o.nodeId}: ${JSON.stringify(o)}`);let n=new Ne({id:parseInt(o.nodeId),role:((s=o.role)==null?void 0:s.value)||"",name:((d=o.name)==null?void 0:d.value)||"",content:((p=o.value)==null?void 0:p.value)||"",properties:o.properties,children:[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+Nn(o),backendNodeID:o.backendDOMNodeId});(u=o.value)!=null&&u.value&&(n.content=`${(h=o.value)==null?void 0:h.value}`);let r=(R=o.childIds)!=null?R:[];for(let w of r){if(!w)continue;let g=t.get(parseInt(w));if(!g)continue;let S=ut(g,n,t);S.length&&(n.children=n.children.concat(S))}if(n.role==="StaticText"&&(n.children=[]),n.children.length===1&&n.children[0].role==="StaticText"){let w=n.name,g=(x=n.children[0])==null?void 0:x.name;(w===g||!g)&&(n.children=[])}let i=[];for(let w=n.children.length-1;w>=0;w--){let g=n.children[w];if(g.role!=="StaticText"){i.push(g);continue}if(w===0||n.children[w-1].role!=="StaticText"){i.push(g);continue}n.children[w-1].name+=` ${g.name}`}if(n.children=i.reverse(),n.role==="generic"&&n.children.length===1){let w=n.children[0];if(!pt.includes(w.role)&&n.name===w.name)return n.children}if(!n.isInteresting()&&o.parentId)return n.children;for(let w of n.children)w.parent=n;return[n]}function ht(o,e,t,n,r=1){o.id=r,r+=1,e.set(o.id,o),o.dataMomenticId?t.set(o.dataMomenticId,o):o.role!=="StaticText"&&o.role!=="RootWebArea"&&o.role!=="paragraph"&&n.debug({node:o.serialize({neighbors:1,maxLevel:1})},"Node has no data-momentic-id");for(let i of o.children)r=ht(i,e,t,n,r);return r}function gt(o,e){if(!o.root)throw new Error("a11y tree has null root");o.allNodes=o.allNodes.filter(a=>{var d;return a.ignored?!((d=a.ignoredReasons)==null?void 0:d.find(p=>xn.includes(p.name))):!0});let t=new Map;for(let a of o.allNodes)t.set(parseInt(a.nodeId),a);let n=ut(o.root,null,t);if(n.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(n)}`);if(n.length===0)throw new le;let r=new Map,i=new Map;return ht(n[0],r,i,e),new Le(n[0],r,i)}var re=(o,e)=>{e.id=o.id,e.content=o.content,e.name=o.name,e.role=o.role,e.numChildren=o.children.length,e.serializedForm=o.serialize({noID:!0,maxLevel:1,neighbors:1})},Oe=(o,e)=>{var r;let t=1;o.role===e.role&&t++;let n=["name","content"];for(let i of n){if(!((r=o[i])!=null&&r.trim()))continue;let a=dt(o[i],e[i])/Math.min(o[i].length,e[i].length);a===0?t+=2:a<=.1&&t++}if(e.numChildren!==void 0&&(o.children.length===e.numChildren&&e.numChildren>0?t++:(e.numChildren>0&&o.children.length===0||Math.abs(o.children.length-e.numChildren)>2)&&t--),e.serializedForm){let i=o.serialize({noID:!0,maxLevel:1,neighbors:1}),a=dt(i,e.serializedForm)/Math.min(i.length,e.serializedForm.length);a===0?t+=2:a<=.1&&t++}return t};var V={r:147,g:196,b:125,a:.55},ft={showInfo:!1,showRulers:!1,showStyles:!1,showAccessibilityInfo:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:V,paddingColor:V,borderColor:V,marginColor:V,eventTargetColor:V,shapeColor:V,shapeMarginColor:V};var j=(o=1e3)=>new Promise(e=>setTimeout(()=>e(),o));function yt(){cursor=document.createElement("img"),cursor.setAttribute("src","data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjMyIiB2aWV3Qm94PSIwIDAgMzIgMzIiIHdpZHRoPSIzMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDEwIDcpIj48cGF0aCBkPSJtNi4xNDggMTguNDczIDEuODYzLTEuMDAzIDEuNjE1LS44MzktMi41NjgtNC44MTZoNC4zMzJsLTExLjM3OS0xMS40MDh2MTYuMDE1bDMuMzE2LTMuMjIxeiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Im02LjQzMSAxNyAxLjc2NS0uOTQxLTIuNzc1LTUuMjAyaDMuNjA0bC04LjAyNS04LjA0M3YxMS4xODhsMi41My0yLjQ0MnoiIGZpbGw9IiMwMDAiLz48L2c+PC9zdmc+"),cursor.setAttribute("id","selenium_cursor"),cursor.setAttribute("style","position: absolute; z-index: 99999999999; pointer-events: none; left:0; top:0"),cursor.style.filter="invert(0%) sepia(6%) saturate(24%) hue-rotate(315deg) brightness(89%) contrast(110%)",document.body.appendChild(cursor),document.onmousemove=function(o){o=o||window.event,document.getElementById("selenium_cursor").style.left=o.pageX+"px",document.getElementById("selenium_cursor").style.top=o.pageY+"px"}}function bt(){window.globalHintManager||(window.globalHintManager=new window.HintManager),window.globalHintManager.capture()}function wt(){window.globalHintManager&&window.globalHintManager.reset()}function St(){let o=document.body.getElementsByTagName("*"),e=1;for(let t=0;t<o.length;t++){let n=e.toString();for(;[6].some(i=>n.includes(i.toString()));)e++,n=e.toString();let r=o[t];r==null||r.setAttribute("data-momentic-id",`${e}`),r==null||r.setAttribute("aria-keyshortcuts",`${e}`),e++}}var Ln=new Set(["document","script","XMLHttpRequest","fetch","xhr"]),On=new Set(["script","document"]),Dn=["intercom.io","googletagmanager.com","google-analytics.com","www.gstatic.com","gstatic.com","apis.google.com","sentry.io","newrelic.com","p.retool.com","m.stripe.com","m.stripe.network","js.stripe.com","assets.trybento.co","udon.trybento.co","cdn.lr-in-prod.com","r.lr-in-prod.com","content.product-usage.assembledhq.com","data.product-usage.assembledhq.com","static.zdassets.com","o.clarity.ms/collect"],Mn=["api.stripe.com","supabase.co"];function De(o){return`${o.resourceType()} ${o.method()} ${o.url()}`}function Ct(o){return o=o.replace(/^www\./,""),o}function Et(o){return Mn.some(e=>o.includes(e))}function vt(o,e){if(!Ln.has(o.resourceType()))return!1;let t=new URL(e),n=new URL(o.url());return Dn.some(r=>n.hostname.includes(r))?!1:On.has(o.resourceType())||o.method()!=="GET"?!0:Ct(n.hostname).includes(Ct(t.hostname))}var _e=jn(Vn);_e.use(Kn());_e.use(Wn({provider:{id:"2captcha",token:process.env.TWO_CAPTCHA_KEY},visualFeedback:!0}));function ze(o){return c(this,null,function*(){yield o.send("Accessibility.enable"),yield o.send("DOM.enable"),yield o.send("Overlay.enable")})}var F=class F{constructor({browser:e,context:t,page:n,baseURL:r,cdpClient:i,logger:a}){this.a11yIdToNodeMap=new Map;this.dataMomenticIdToNodeMap=new Map;this.browser=e,this.context=t,this.page=n,this.baseURL=r,this.cdpClient=i,this.logger=a}static init(i,a,s){return c(this,arguments,function*(e,t,n,r=8e3){let d=yield _e.launch({headless:!0,handleSIGTERM:!1}),p=yield d.newContext({viewport:F.VIEWPORT,deviceScaleFactor:process.platform==="darwin"?2:1,userAgent:It["Desktop Chrome"].userAgent,geolocation:{latitude:37.7749,longitude:-122.4194},locale:"en-US",timezoneId:"America/Los_Angeles"}),u=yield p.newPage(),h=yield p.newCDPSession(u),R=new F({browser:d,context:p,page:u,baseURL:e,cdpClient:h,logger:t}),x=!1;c(this,null,function*(){try{yield R.navigate(e,!1),yield ze(h)}catch(D){t.error({err:D},"Failed to initialize chrome browser")}finally{x=!0}});let g=()=>c(this,null,function*(){if(n)try{n({viewport:R.viewport,buffer:yield R.screenshot()})}catch(D){t.error({err:D},"Failed to take screenshot")}});g();let S=setInterval(()=>{g()},250),y=Date.now();for(;!x&&Date.now()-y<r;)yield j(250);return clearInterval(S),x||t.warn("Timeout elapsed waiting for browser to initialize - are you sure this page is accessible?"),R})}reset(e){return c(this,null,function*(){this.a11yIdToNodeMap.clear(),this.dataMomenticIdToNodeMap.clear();let t=yield this.context.pages();this.page=t[0];for(let n=1;n<t.length;n++)yield t[n].close();e.clearCookies&&(yield this.context.clearCookies()),e.clearStorage&&(yield this.page.evaluate(()=>{localStorage.clear()})),yield this.page.goto(this.baseURL,{waitUntil:"load",timeout:3e3})})}pageSetup(){return c(this,null,function*(){try{yield this.page.evaluate(yt)}catch(e){}})}wait(e){return c(this,null,function*(){yield this.page.waitForTimeout(e)})}toggleHints(e){return c(this,null,function*(){e.state==="on"?(yield this.page.addStyleTag({content:Re.css}),yield this.page.addScriptTag({content:Re.js}),yield this.page.evaluate(bt)):yield this.page.evaluate(wt)})}showHints(){return c(this,null,function*(){yield this.toggleHints({state:"on"});let e=()=>c(this,null,function*(){try{yield this.toggleHints({state:"off"})}catch(t){this.logger.debug({err:t},"Failed to remove vision hints")}});setTimeout(()=>{e()},3e3)})}cleanup(){return c(this,null,function*(){yield this.page.close(),yield this.context.close(),yield this.browser.close()})}get closed(){return this.page.isClosed()||!this.browser.isConnected()}html(){return c(this,null,function*(){return yield this.page.content()})}get url(){return this.page.url()}screenshotWithHints(e=100,t="device",n="/tmp/screenshots/test.jpg"){return c(this,null,function*(){let r=n==null?void 0:n.split("."),i=r==null?void 0:r.slice(0,-1).join("."),a=r==null?void 0:r.slice(-1)[0],s=yield this.screenshot(e,t,n?`${i}-before-hint.${a}`:void 0);yield this.showHints();let d=yield this.screenshot(e,t,n?`${i}-after-hint.${a}`:void 0);return{before:s,after:d}})}screenshot(e=100,t="device",n){return c(this,null,function*(){return this.page.screenshot({fullPage:!1,quality:e,scale:t,type:"jpeg",caret:"initial",path:n})})}get viewport(){let e=this.page.viewportSize();if(!e)throw new Error("failed to get viewport");return e}navigate(e,t=!0){return c(this,null,function*(){this.logger.debug(`Navigating to ${e}`);let n=Date.now(),r=()=>c(this,null,function*(){try{yield this.page.goto(e,{waitUntil:"load",timeout:3e3}),this.logger.debug({url:e},`Got load event in ${Math.floor(Date.now()-n)}ms`)}catch(i){this.logger.warn({url:e},"Timeout elapsed waiting for page to fire load event, continuing anyways...")}});if(t?yield this.wrapPossibleNavigation(r):yield r(),st.has(this.url)&&process.env.NODE_ENV==="production")throw new Error(`${e} took too long to load \u{1F61E}. Please ensure the site and your internet are working.`);this.logger.debug({url:e},"Navigation complete")})}fill(r,i){return c(this,arguments,function*(e,t,n={}){let a=yield this.click(e,{doubleClick:!1,rightClick:!1});return yield this.type(t,n),a})}type(n){return c(this,arguments,function*(e,t={}){let{clearContent:r=!0,pressKeysSequentially:i=!1}=t;r&&(process.platform==="darwin"?yield this.page.keyboard.press("Meta+A"):yield this.page.keyboard.press("Control+A"),yield this.page.keyboard.press("Backspace")),i?yield this.page.keyboard.type(e):yield this.page.keyboard.insertText(e)})}clickByA11yID(n){return c(this,arguments,function*(e,t={}){let r=this.a11yIdToNodeMap.get(e);if(!r)throw new Error(`Could not find DOM node during click: ${e}`);let i=yield this.clickUsingCDP(r,t);return yield this.highlightNode(i),r.serialize({noChildren:!0,noProperties:!0,noID:!0})})}selectOptionByA11yID(e,t){return c(this,null,function*(){let n=this.a11yIdToNodeMap.get(e);if(!n)throw new Error(`Could not find DOM node while selecting option: ${e}`);if(!n.backendNodeID)throw new Error(`Select target missing backend node id: ${n.getLogForm()}`);return yield(yield this.getLocatorFromBackendID(n.backendNodeID)).selectOption(t,{timeout:8e3}),yield this.highlightNode(n),n.serialize({noChildren:!0,noProperties:!0,noID:!0})})}scrollIntoView(e){return c(this,null,function*(){let t=yield this.resolveCachedTargetToID(e),n=this.a11yIdToNodeMap.get(t);if(!n)throw new Error(`Could not find node in DOM with a11y id: ${t}`);if(!n.backendNodeID)throw new Error(`Focus target missing backend node id: ${n.getLogForm()}`);yield(yield this.getLocatorFromBackendID(n.backendNodeID)).scrollIntoViewIfNeeded({timeout:8e3})})}highlight(e){return c(this,null,function*(){try{let t=yield this.resolveCachedTargetToID(e),n=this.a11yIdToNodeMap.get(t);if(!n)throw new Error(`Could not find DOM node during highlight: ${t}`);if(!n.backendNodeID)throw new Error(`Select target missing backend node id: ${n.getLogForm()}`);yield this.highlightNode(n)}catch(t){this.logger.warn({err:t,target:e},"Failed to highlight target")}})}highlightNode(e){return c(this,null,function*(){try{yield this.cdpClient.send("Overlay.highlightNode",{highlightConfig:ft,backendNodeId:e.backendNodeID})}catch(n){this.logger.warn("Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests.")}let t=()=>c(this,null,function*(){try{yield this.cdpClient.send("Overlay.hideHighlight",{backendNodeId:e.backendNodeID})}catch(n){this.logger.debug({err:n},"Failed to remove node highlight")}});setTimeout(()=>{t()},3e3)})}wrapPossibleNavigation(r){return c(this,arguments,function*(e,t=8e3,n=!0){let i=Date.now(),a=this.url,s=Date.now(),d=new Map,p=new Map,u=E=>{var Fe;let v=De(E.request());p.set(v,((Fe=p.get(v))!=null?Fe:0)+1);let J=E.status();J>=500&&this.logger.warn({request:v,status:J},"Received 500 level response")},h=E=>{var J;if(!vt(E,this.url))return;let v=De(E);d.set(v,((J=d.get(v))!=null?J:0)+1),s=Date.now()};this.page.on("response",u),this.page.on("request",h);let R=[];n&&(R=(yield this.context.pages()).map(E=>E.url()));let x=!1,w=e().catch(E=>(x=!0,E instanceof Error?E:new Error(`${E}`)));yield j(250);let g=E=>c(this,null,function*(){let v=yield E;if(v instanceof Error)throw v;return v}),S=new Set,y=!1,Rt=yield c(this,null,function*(){for(;!x&&!(!y&&Date.now()-i>t);){if(yield j(250),y=!1,S=new Set,Date.now()-s<=1250)continue;let E=!1;for(let v of d.keys())d.get(v)!==p.get(v)&&(Et(v)&&(y=!0),E=!0,S.add(v));if(!E)return this.logger.debug({url:this.url,requests:JSON.stringify(Array.from(d.entries()))},`Network idle in ${Math.floor(Date.now()-i)}ms`),!0}return!x&&S.size>0&&this.logger.warn({url:this.url,unfinishedRequests:JSON.stringify(Array.from(S.entries()))},"Timeout elapsed waiting for network idle, continuing anyways..."),!1});if(this.page.off("response",u),this.page.off("request",h),!Rt)return g(w);let He=this.url;if(!x&&$(He,a)){this.logger.debug({startURL:a,newURL:this.url},"Detected url change in wrapPossibleNavigation, waiting for load state");let E=Math.max(t-(Date.now()-i),0);if(E>0)try{yield this.page.waitForLoadState("load",{timeout:E})}catch(v){this.logger.warn({url:this.url},"Timeout elapsed waiting for load state to fire, continuing anyways...")}}if(n){let E=(yield this.context.pages()).map(v=>v.url());if(E.length>R.length)for(let v of E)v!==He&&(yield this.switchToPage(v))}return g(w)})}resolveCachedTargetToID(e){return c(this,null,function*(){if(!se(e)){let s=this.a11yIdToNodeMap.get(e.id);if(!s)throw new Error(`Resolving target failed, fresh value did not exist in node map: ${e.id}`);return re(s,e),e.id}let t=(yield this.getA11yTree()).serialize();this.logger.debug({tree:t},"Refreshed a11y tree before resolving target");let n=this.a11yIdToNodeMap.get(e.id);if(n){let s=Oe(n,e);if(s>=5)return this.logger.debug({target:e,proposedNode:n.getLogForm(),comparisonScore:s},"Resolved cached a11y target to node with exact same id"),re(n,e),e.id}let r=1/0,i=1/0,a;for(let s of this.a11yIdToNodeMap.values()){let d=Oe(s,e);if(d>=5)return this.logger.debug({newNode:s.getLogForm(),target:e,comparisonScore:d},"Resolved cached a11y target to new node with field comparison"),re(s,e),s.id;if(!e.serializedForm)continue;let p=s.serialize({noID:!0,maxLevel:1,neighbors:1});if(Math.abs(p.length-e.serializedForm.length)>15)continue;let u=$n(e.serializedForm,p),h=u/Math.min(e.serializedForm.length,p.length);u<r&&h<.2&&(r=u,i=h,a=s)}if(a&&r<15)return this.logger.debug({newNode:a.getLogForm(),target:e,distance:r,ratio:i},"Resolved cached a11y target to new node with pure levenshtein distance"),re(a,e),a.id;throw new Error(`Could not find any relevant node given cached target: ${JSON.stringify(e)}`)})}click(n){return c(this,arguments,function*(e,t={}){let r=yield this.resolveCachedTargetToID(e);return yield this.wrapPossibleNavigation(()=>this.clickByA11yID(r,t))})}hover(e){return c(this,null,function*(){let t=yield this.resolveCachedTargetToID(e),n=this.a11yIdToNodeMap.get(t);if(!n)throw new Error(`Could not find DOM node for hover: ${t}`);if(!n.backendNodeID)throw new Error(`Hover target missing backend node id: ${n.getLogForm()}`);return yield(yield this.getLocatorFromBackendID(n.backendNodeID)).hover({timeout:8e3}),yield this.highlightNode(n),n.serialize({noChildren:!0,noProperties:!0,noID:!0})})}selectOption(e,t){return c(this,null,function*(){let n=yield this.resolveCachedTargetToID(e);return this.selectOptionByA11yID(n,t)})}press(e){return c(this,null,function*(){yield this.wrapPossibleNavigation(()=>this.page.keyboard.press(e))})}refresh(){return c(this,null,function*(){yield this.page.reload(),yield this.pageSetup()})}getA11yTree(){return c(this,null,function*(){yield ze(this.cdpClient),yield this.page.evaluate(St);let e=null,t=0,n=this.url;for(;!e;)try{let r=yield this.getRawA11yTree();if(!r.root||r.allNodes.length===0)throw new Error("No a11y tree found on page");e=gt(r,this.logger)}catch(r){if(this.logger.error({err:r,url:n},"Error fetching a11y tree"),t===0)yield j(1e3),t++;else throw new Error(`Max retries exceeded fetching a11y tree: ${r}`)}return e.root||this.logger.warn("A11y tree was pruned entirely"),this.a11yIdToNodeMap=e.a11yIdNodeMap,this.dataMomenticIdToNodeMap=e.dataMomenticIdMap,e})}getA11yIdFromDataMomenticId(e){var t;return(t=this.dataMomenticIdToNodeMap.get(e))==null?void 0:t.id}getRawA11yTree(){return c(this,null,function*(){let e=this.page.url(),t=Date.now(),n=()=>{t=Date.now()};this.cdpClient.addListener("Accessibility.nodesUpdated",n);let r=!1,i=()=>{this.logger.info({url:e},"Load event fired on page"),r=!0,t=Date.now()};this.cdpClient.addListener("Accessibility.loadComplete",i);let a=Date.now(),s=!0;for(;Date.now()-a<3e3;){if(yield j(250),!r&&Date.now()-a<1e3){process.env.NODE_ENV!=="production"&&this.logger.debug({url:e},"A11y tree not loaded yet, waiting...");continue}if(Date.now()-t>=1250){s=!1;break}this.logger.debug({url:e},"A11y tree not stable yet, waiting...")}this.logger.debug({duration:Date.now()-a,eventReceived:r,timeoutTriggered:s},"A11y wait phase completed");let{node:d}=yield this.cdpClient.send("Accessibility.getRootAXNode"),{nodes:p}=yield this.cdpClient.send("Accessibility.queryAXTree",{backendNodeId:d.backendDOMNodeId});return this.cdpClient.removeListener("Accessibility.loadComplete",i),this.cdpClient.removeListener("Accessibility.nodesUpdated",n),{root:d,allNodes:p}})}clickUsingVisualCoordinates(e){return c(this,null,function*(){let t=yield this.getElementLocation(e);if(!t)throw new Error(`Could not find element location with backend node id: ${e}`);this.logger.debug({location:t},"Executing mouse click"),yield this.page.mouse.click(t.centerX,t.centerY)})}getIDAttributeUsingCDP(e){return c(this,null,function*(){yield this.cdpClient.send("DOM.getDocument",{depth:0});let t=yield this.cdpClient.send("DOM.requestNode",{objectId:e}),r=(yield this.cdpClient.send("DOM.getAttributes",{nodeId:t.nodeId})).attributes,i=r.findIndex(a=>a==="data-momentic-id");return i===-1?"":r[i+1]||""})}getLocatorFromBackendID(e){return c(this,null,function*(){let t=yield this.cdpClient.send("DOM.resolveNode",{backendNodeId:e});if(!t||!t.object.objectId)throw new Error(`Could not resolve backend node ${e}`);try{let n=yield this.getIDAttributeUsingCDP(t.object.objectId);if(!n)throw new Error("Failed getting data-momentic-id attribute using CDP");return this.page.locator(`[data-momentic-id="${n}"]`)}catch(n){throw this.logger.error({err:n},"Failed to get ID attribute"),n}})}clickUsingCDP(n){return c(this,arguments,function*(e,t={}){let r=0,i=e;for(;r<at;){if(!i||i.role==="RootWebArea")throw new Error(`Attempted to click node with no clickable surrounding elements: ${e.getLogForm()}`);if(i.role==="StaticText"){i=i.parent;continue}let a=i.backendNodeID;if(!a){this.logger.warn({node:i.getLogForm()},"Click candidate had no backend node ID"),i=i.parent;continue}try{let s=yield this.getLocatorFromBackendID(a);return t.doubleClick?yield s.dblclick({timeout:8e3}):yield s.click({timeout:8e3,button:t.rightClick?"right":"left"}),i.id!==e.id&&this.logger.info({oldNode:e.getLogForm(),newNode:i.getLogForm()},"Redirected click successfully to new element"),i}catch(s){this.logger.error({err:s,node:i.getLogForm()},"Failed click or click timed out"),r++,i=i.parent}}throw new Error(`Max click redirection attempts exhausted on original element: ${e.getLogForm()}`)})}getElementLocation(e){return c(this,null,function*(){let t=yield this.cdpClient.send("DOMSnapshot.captureSnapshot",{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0}),n=yield this.page.evaluate(()=>window.devicePixelRatio);process.platform==="darwin"&&n===1&&(n=2);let r=t.documents[0],i=r.layout,a=r.nodes,s=a.nodeName||[],d=a.backendNodeId||[],p=i.nodeIndex,u=i.bounds,h=-1;for(let D=0;D<s.length;D++)if(d[D]===e){h=p.indexOf(D);break}if(h===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[R=0,x=0,w=0,g=0]=u[h];R/=n,x/=n,w/=n,g/=n;let S=R+w/2,y=x+g/2;return{centerX:S,centerY:y}})}scrollUp(){return c(this,null,function*(){yield this.page.mouse.wheel(0,-F.VIEWPORT.height)})}scrollDown(){return c(this,null,function*(){yield this.page.mouse.wheel(0,F.VIEWPORT.height)})}goForward(){return c(this,null,function*(){yield this.wrapPossibleNavigation(()=>this.page.goForward({timeout:8e3})),yield this.pageSetup()})}goBack(){return c(this,null,function*(){yield this.wrapPossibleNavigation(()=>this.page.goBack({timeout:8e3})),yield this.pageSetup()})}switchToPage(e){return c(this,null,function*(){let t=yield this.context.pages();for(let n=0;n<t.length;n++){let r=t[n];if(r.url().includes(e)){this.logger.info(`Switching to tab ${n} with url ${r.url()}`),this.page=r,yield r.waitForLoadState("load",{timeout:3e3}),yield this.pageSetup(),this.cdpClient=yield this.context.newCDPSession(r),yield ze(this.cdpClient);return}}throw new Error(`Could not find page with url containing ${e}`)})}setCookie(e){return c(this,null,function*(){let t=Je(e);yield this.context.addCookies([t])})}solveCaptcha(){return c(this,null,function*(){yield this.getA11yTree();let e;for(let s of this.a11yIdToNodeMap.values())if(s.role==="image"&&s.name.toLowerCase().includes("captcha")){if(!s.backendNodeID)continue;e=yield this.getLocatorFromBackendID(s.backendNodeID);break}if(!e){let s=yield this.page.solveRecaptchas();if(!s.captchas||!s.captchas.length)throw new Error("No captchas found on the page");return}let t=yield e.screenshot({type:"jpeg",animations:"allow",quality:100}),n=yield fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:process.env.TWO_CAPTCHA_KEY,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let s=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:yield n.text()},s),new Error(s)}let{taskId:r}=yield n.json(),i=Date.now(),a="";for(;Date.now()-i<6e4;){yield j(2500);let s=yield fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:process.env.TWO_CAPTCHA_KEY,taskId:r})});if(!s.ok){let p=`Captcha solution API returned error response: ${s.statusText}`;throw this.logger.error({text:yield s.text()},p),new Error(p)}let d=yield s.json();if(d.errorId){let p=`Captcha solution API returned error ID ${d.errorId}`;throw this.logger.error(p),new Error(p)}if(d.status==="ready"){a=d.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a})}};F.USER_AGENT=It["Desktop Chrome"].userAgent,F.VIEWPORT={width:1920,height:1080};var ke=F;var Xn={type:"a11y",version:"1.0.0",useHistory:"diff",useGoalSplitter:!0},Yn=Xn;import qn from"dedent";import Jn from"diff-lines";var Zn=1e4,Pe=class{constructor({browser:e,config:t,generator:n,logger:r}){this.browser=e,this.generator=n,this.config=t,this.logger=r,this.pendingInstructions=[],this.commandHistory=[]}get history(){return this.commandHistory.filter(e=>e.state==="DONE")}get lastExecutedCommand(){let e=this.history;return e.length===0?null:e[e.length-1]}resetHistory(){this.commandHistory=[],this.pendingInstructions=[]}resetState(){return c(this,null,function*(){this.resetHistory(),yield this.browser.navigate(this.browser.baseURL)})}getBrowserState(){return c(this,null,function*(){let t=yield(yield this.browser.getA11yTree()).serialize();return this.logger.debug({tree:t},"Got a11y tree"),t})}getSerializedHistory(e,t){let n;return this.config.useHistory==="diff"?n=this.getDiffHistory(e,t):n=this.getListHistory(),n}splitUserGoal(e,t,n){return c(this,null,function*(){if(e==="AI_ACTION"&&t.match(/[,!;.]|(?:and)|(?:then)/)&&this.config.useGoalSplitter){let r=yield this.generator.getGranularGoals({goal:t,url:this.browser.url},n);this.pendingInstructions=r.reverse()}else this.pendingInstructions=[t]})}promptToCommand(e,t,n){return c(this,null,function*(){try{return yield this.promptToCommandHelper(e,t,n)}catch(r){throw r instanceof N?r:new N("InternalWebAgentError",r instanceof Error?r.message:`${r}`,{cause:r})}})}promptToCommandHelper(e,t,n){return c(this,null,function*(){if(this.pendingInstructions.length===0){if(!t.trim())throw new Error("Cannot generate commands for empty goal");yield this.splitUserGoal(e,t,n)}let r=this.pendingInstructions[this.pendingInstructions.length-1];this.logger.info({goal:r},"Starting prompt translation");let i=Date.now(),a=this.browser.url,s=yield this.getBrowserState();this.logger.info({duration:Date.now()-i,url:a},"Got browser state");let d=this.commandHistory.length;this.commandHistory.push({state:"PENDING",browserStateBeforeCommand:s,urlBeforeCommand:a,type:e});let p=this.getSerializedHistory(a,s),u=yield this.generator.getProposedCommand({url:a,numPrevious:d,browserState:s,history:p,goal:r,lastCommand:this.lastExecutedCommand},n);if(this.logger.info({type:u.type,thoughts:u.thoughts},"Got proposed command"),u.type==="SUCCESS"){let h=this.pendingInstructions.pop();if(this.logger.info({finishedInstruction:h,remainingInstructions:this.pendingInstructions},"Removing pending instruction due to SUCCESS"),this.pendingInstructions.length!==0)return this.commandHistory=[],this.promptToCommand(e,"",n)}else u.type==="FAILURE"&&(this.logger.info({remainingInstructions:this.pendingInstructions},"Removing pending instructions due to FAILURE"),this.pendingInstructions=[]);return u})}locateElement(e,t,n){return c(this,null,function*(){if(!e)throw new N("InternalWebAgentError","Cannot locate element with empty description");let r=yield this.getBrowserState(),i;if(t){let{before:a,after:s}=yield this.browser.screenshotWithHints();if(i=yield this.generator.getElementLocationWithVision({goal:e,screenshot:a,hintActivatedScreenshot:s},n),i.id>0){let d=this.browser.getA11yIdFromDataMomenticId(i.id);if(!d)throw new N("InternalWebAgentError",`Unable to find corresponding DOM node for id ${i.id}`);i.id=d}}else i=yield this.generator.getElementLocation({browserState:r,goal:e},n);if(i.id<0)throw new N("ActionFailureError",`Unable to locate element: ${i.thoughts?i.thoughts:"please ensure the element is visible and conforms to Accessibility guidelines"}`);return i})}getDiffHistory(e,t){let n=this.history.filter(i=>i.type==="AI_ACTION");if(n.length===0)return"<NONE/>";let r=[`
572
- You have already executed the following commands successfully (most recent listed first)`,"-".repeat(10)];return n.reverse().forEach((i,a)=>{if(r.push(`COMMAND ${n.length-a}${a===0?" (command just executed)":""}: ${i.serializedCommand}`),a===0)if($(i.urlBeforeCommand,e))r.push(` URL CHANGE: '${i.urlBeforeCommand}' -> '${e}'`);else{let s=Jn(i.browserStateBeforeCommand,t,{n_surrounding:1});s?s.length<Zn?(r.push("PAGE CONTENT CHANGE:"),s.split(`
573
- `).forEach(d=>r.push(` ${d}`))):r.push("PAGE CONTENT CHANGE: <TOO_LONG_TO_DISPLAY/>"):r.push("PAGE CONTENT CHANGE: <NONE/>")}r.push("-".repeat(10))}),r.push(`STARTING URL: ${this.browser.baseURL}`),r.join(`
574
- `)}getListHistory(){return qn`Here are the commands that you have successfully executed:
563
+ `};var q=(r,e)=>{let{hostname:t,pathname:o}=new URL(r),{hostname:n,pathname:i}=new URL(e);return t!==n||o!==i};import{distance as pt}from"fastest-levenshtein";var lt=new Set(["about:blank","chrome-error://chromewebdata/"]),ct=2;var Ro=["focusable","keyshortcuts","controls"],No=["textbox","checkbox","combobox","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch"],Lo=["notRendered","notVisible","ariaHiddenSubtree","ariaHiddenElement"],Oo=80,Do={paragraph:"p",searchbox:"input"},ht=["paragraph","option","StaticText"],ut={indentLevel:0,noID:!1,noChildren:!1,noProperties:!1,maxLevel:void 0,neighbors:void 0},Me=class{constructor(e){this.id=e.id,this.role=e.role,this.name=e.name,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeID=e.backendNodeID,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value})}getLogForm(){var e,t;return JSON.stringify({id:this.id,name:(e=this.name)!=null?e:"",role:(t=this.role)!=null?t:"",backendNodeId:this.backendNodeID})}isInteresting(){return No.includes(this.role)||this.children.some(e=>e.role==="StaticText")?!0:!!this.name.trim()||!!this.content}serialize(e=ut){var E,b;let{indentLevel:t,noChildren:o,noProperties:n,noID:i}=Object.assign({},ut,e),a=" ".repeat(t),s=Do[this.role]||this.role,m=this.name,p=L({},this.properties);s==="heading"&&(p.level&&(s=`h${p.level}`,delete p.level),m==="heading"&&(m=""));let h=!ht.includes(this.role);if(this.role==="StaticText")return`${a}${m}
564
+ `;let u=`${a}<${s}`;!i&&h&&(u+=` id="${this.id}"`),m&&(u+=` name="${m}"`),this.content&&(u+=` content="${this.content}"`),Object.keys(this.properties).length>0&&!n&&Object.entries(this.properties).forEach(([f,S])=>{Ro.includes(f)||(typeof S=="string"?u+=` ${f}="${S}"`:typeof S=="boolean"?S?u+=` ${f}`:u+=` ${f}={false}`:typeof S!="undefined"&&(u+=` ${f}={${JSON.stringify(S)}}`))});let x=e.maxLevel!==void 0&&t/2>=e.maxLevel;if(this.children.length===0||o||x)u+=` />
565
+ `;else{let f="";for(let y of this.children)f+=y.serialize(j(L({},e),{indentLevel:t+2}));let S=f.trim();S.length<=Oo&&!S.includes(`
566
+ `)?u+=`>${S}</${s}>
567
+ `:u+=`>
568
+ ${f}${a}</${s}>
569
+ `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let f=this.parent.children.findIndex(k=>k.id===this.id),S=f>0?(E=this.parent.children[f-1])==null?void 0:E.serialize(j(L({},e),{neighbors:0})):"",y=f<this.parent.children.length-1?(b=this.parent.children[f+1])==null?void 0:b.serialize(j(L({},e),{neighbors:0})):"";return`${S||""}
570
+ ${u}
571
+ ${y||""}`}return u}},ze=class{constructor(e,t,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=o}serialize(){return this.root?this.root.serialize():""}};function Mo(r){var e,t;return(e=r.name)!=null&&e.value?`"${r.name.value}"`:(t=r.role)!=null&&t.value&&r.role.value!=="none"&&r.role.value!=="generic"?`"${r.role.value}"`:`"${r.nodeId}"`}function gt(r,e,t){var s,m,p,h,u,x,E;if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let o=new Me({id:parseInt(r.nodeId),role:((s=r.role)==null?void 0:s.value)||"",name:((m=r.name)==null?void 0:m.value)||"",content:((p=r.value)==null?void 0:p.value)||"",properties:r.properties,children:[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+Mo(r),backendNodeID:r.backendDOMNodeId});(h=r.value)!=null&&h.value&&(o.content=`${(u=r.value)==null?void 0:u.value}`);let n=(x=r.childIds)!=null?x:[];for(let b of n){if(!b)continue;let f=t.get(parseInt(b));if(!f)continue;let S=gt(f,o,t);S.length&&(o.children=o.children.concat(S))}if(o.role==="StaticText"&&(o.children=[]),o.children.length===1&&o.children[0].role==="StaticText"){let b=o.name,f=(E=o.children[0])==null?void 0:E.name;(b===f||!f)&&(o.children=[])}let i=[];for(let b=o.children.length-1;b>=0;b--){let f=o.children[b];if(f.role!=="StaticText"){i.push(f);continue}if(b===0||o.children[b-1].role!=="StaticText"){i.push(f);continue}o.children[b-1].name+=` ${f.name}`}if(o.children=i.reverse(),o.role==="generic"&&o.children.length===1){let b=o.children[0];if(!ht.includes(b.role)&&o.name===b.name)return o.children}if(!o.isInteresting()&&r.parentId)return o.children;for(let b of o.children)b.parent=o;return[o]}function ft(r,e,t,o,n=1){r.id=n,n+=1,e.set(r.id,r),r.dataMomenticId?t.set(r.dataMomenticId,r):r.role!=="StaticText"&&r.role!=="RootWebArea"&&r.role!=="paragraph"&&o.debug({node:r.serialize({neighbors:1,maxLevel:1})},"Node has no data-momentic-id");for(let i of r.children)n=ft(i,e,t,o,n);return n}function yt(r,e){if(!r.root)throw new Error("a11y tree has null root");r.allNodes=r.allNodes.filter(a=>{var m;return a.ignored?!((m=a.ignoredReasons)==null?void 0:m.find(p=>Lo.includes(p.name))):!0});let t=new Map;for(let a of r.allNodes)t.set(parseInt(a.nodeId),a);let o=gt(r.root,null,t);if(o.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(o)}`);if(o.length===0)throw new he;let n=new Map,i=new Map;return ft(o[0],n,i,e),new ze(o[0],n,i)}var le=(r,e)=>{e.id=r.id,e.content=r.content,e.name=r.name,e.role=r.role,e.numChildren=r.children.length,e.serializedForm=r.serialize({noID:!0,maxLevel:1,neighbors:1})},Pe=(r,e)=>{var n;let t=1;r.role===e.role&&t++;let o=["name","content"];for(let i of o){if(!((n=r[i])!=null&&n.trim()))continue;let a=pt(r[i],e[i])/Math.min(r[i].length,e[i].length);a===0?t+=2:a<=.1&&t++}if(e.numChildren!==void 0&&(r.children.length===e.numChildren&&e.numChildren>0?t++:(e.numChildren>0&&r.children.length===0||Math.abs(r.children.length-e.numChildren)>2)&&t--),e.serializedForm){let i=r.serialize({noID:!0,maxLevel:1,neighbors:1}),a=pt(i,e.serializedForm)/Math.min(i.length,e.serializedForm.length);a===0?t+=2:a<=.1&&t++}return t};var Y={r:147,g:196,b:125,a:.55},bt={showInfo:!1,showRulers:!1,showStyles:!1,showAccessibilityInfo:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:Y,paddingColor:Y,borderColor:Y,marginColor:Y,eventTargetColor:Y,shapeColor:Y,shapeMarginColor:Y};var H=(r=1e3)=>new Promise(e=>setTimeout(()=>e(),r));function wt(){cursor=document.createElement("img"),cursor.setAttribute("src","data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjMyIiB2aWV3Qm94PSIwIDAgMzIgMzIiIHdpZHRoPSIzMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDEwIDcpIj48cGF0aCBkPSJtNi4xNDggMTguNDczIDEuODYzLTEuMDAzIDEuNjE1LS44MzktMi41NjgtNC44MTZoNC4zMzJsLTExLjM3OS0xMS40MDh2MTYuMDE1bDMuMzE2LTMuMjIxeiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Im02LjQzMSAxNyAxLjc2NS0uOTQxLTIuNzc1LTUuMjAyaDMuNjA0bC04LjAyNS04LjA0M3YxMS4xODhsMi41My0yLjQ0MnoiIGZpbGw9IiMwMDAiLz48L2c+PC9zdmc+"),cursor.setAttribute("id","selenium_cursor"),cursor.setAttribute("style","position: absolute; z-index: 99999999999; pointer-events: none; left:0; top:0"),cursor.style.filter="invert(0%) sepia(6%) saturate(24%) hue-rotate(315deg) brightness(89%) contrast(110%)",document.body.appendChild(cursor),document.onmousemove=function(r){r=r||window.event,document.getElementById("selenium_cursor").style.left=r.pageX+"px",document.getElementById("selenium_cursor").style.top=r.pageY+"px"}}function St(){window.globalHintManager||(window.globalHintManager=new window.HintManager),window.globalHintManager.capture()}function vt(){window.globalHintManager&&window.globalHintManager.reset()}function Ct(){let r=document.body.getElementsByTagName("*"),e=1;for(let t=0;t<r.length;t++){let o=e.toString();for(;[6].some(i=>o.includes(i.toString()));)e++,o=e.toString();let n=r[t];n==null||n.setAttribute("data-momentic-id",`${e}`),n==null||n.setAttribute("aria-keyshortcuts",`${e}`),e++}}var zo=new Set(["document","script","XMLHttpRequest","fetch","xhr"]),Po=new Set(["script","document"]),ko=["intercom.io","googletagmanager.com","google-analytics.com","www.gstatic.com","gstatic.com","apis.google.com","sentry.io","newrelic.com","p.retool.com","m.stripe.com","m.stripe.network","js.stripe.com","assets.trybento.co","udon.trybento.co","cdn.lr-in-prod.com","r.lr-in-prod.com","content.product-usage.assembledhq.com","data.product-usage.assembledhq.com","static.zdassets.com","o.clarity.ms/collect"],_o=["api.stripe.com","supabase.co"];function ke(r){return`${r.resourceType()} ${r.method()} ${r.url()}`}function Et(r){return r=r.replace(/^www\./,""),r}function Tt(r){return _o.some(e=>r.includes(e))}function At(r,e){if(!zo.has(r.resourceType()))return!1;let t=new URL(e),o=new URL(r.url());return ko.some(n=>o.hostname.includes(n))?!1:Po.has(r.resourceType())||r.method()!=="GET"?!0:Et(o.hostname).includes(Et(t.hostname))}var Ue=qo(Xo);Ue.use(Jo());Ue.use(Yo({provider:{id:"2captcha",token:process.env.TWO_CAPTCHA_KEY},visualFeedback:!0}));var $=class ${constructor({browser:e,context:t,page:o,baseUrl:n,cdpClient:i,logger:a,localMode:s}){this.a11yIdToNodeMap=new Map;this.dataMomenticIdToNodeMap=new Map;this.browser=e,this.context=t,this.page=o,this.baseURL=n,this.cdpClient=i,this.logger=a,this.localMode=!!s}static init(m){return l(this,arguments,function*({baseUrl:e,logger:t,browserArgs:o,contextArgs:n,sendScreenshotsDuringLoad:i,localMode:a,timeout:s=8e3}){let p=yield Ue.launch(L({headless:!0,handleSIGTERM:!1},o!=null?o:{})),h=yield p.newContext(L({viewport:$.VIEWPORT,deviceScaleFactor:process.platform==="darwin"?2:1,userAgent:Lt["Desktop Chrome"].userAgent,geolocation:{latitude:37.7749,longitude:-122.4194},locale:"en-US",timezoneId:"America/Los_Angeles"},n!=null?n:{})),u=yield h.newPage(),x=yield h.newCDPSession(u),E=new $({browser:p,context:h,page:u,baseUrl:e,cdpClient:x,logger:t,localMode:a}),b=!1;l(this,null,function*(){try{yield E.navigate({url:e,wrapPossibleNavigation:!1,initialNavigation:!0})}catch(ee){t.error({err:ee},"Failed to initialize chrome browser")}finally{b=!0}});let S=()=>l(this,null,function*(){if(i)try{i({viewport:yield E.viewport(),buffer:yield E.screenshot()})}catch(ee){t.error({err:ee},"Failed to take screenshot")}});S();let y=setInterval(()=>{S()},250),k=Date.now();for(;!b&&Date.now()-k<s;)yield H(250);return clearInterval(y),b||t.warn("Timeout elapsed waiting for browser to initialize - are you sure this page is accessible?"),E})}getUserPageOrFrame(){return l(this,null,function*(){if(this.localMode&&this.activeFrame){let e=yield this.page.frame(this.activeFrame);if(!e)throw new Error(`Failed to get non-existent frame: ${this.activeFrame}`);return e}return this.page})}initCDPSession(e=2){return l(this,null,function*(){try{yield this.cdpClient.send("Accessibility.enable"),yield this.cdpClient.send("DOM.enable"),yield this.cdpClient.send("Overlay.enable")}catch(t){if(e>0)return this.logger.error({err:t},"Failed to initialize CDP session, re-creating CDP client"),this.cdpClient=yield this.context.newCDPSession(this.page),yield H(250),this.initCDPSession(e-1)}})}setLogger(e){this.logger=e}registerLocalRequestInterceptors(e){return l(this,null,function*(){yield e.route("**/*",t=>l(this,null,function*(){let o;try{o=yield t.fetch()}catch(i){this.closed||this.logger.warn({err:i},"Network request failed");return}let n=o.headers();delete n["content-security-policy"],delete n["x-frame-options"],delete n["x-xss-protection"],yield t.fulfill({headers:n,response:o})}))})}ping(){if(!this.browser.isConnected())throw new Error("Browser is not connected");if(this.closed)throw new Error("Page has been closed")}setActiveFrame(e){this.activeFrame=e}reset(e){return l(this,null,function*(){var o;this.a11yIdToNodeMap.clear(),this.dataMomenticIdToNodeMap.clear();let t=yield this.context.pages();this.page=t[0];for(let n=1;n<t.length;n++)yield t[n].close();e.clearCookies&&(yield this.context.clearCookies()),e.clearStorage&&(yield(yield this.getUserPageOrFrame()).evaluate(()=>{localStorage.clear()})),yield this.navigate({url:(o=e.url)!=null?o:this.baseURL,wrapPossibleNavigation:!1,initialNavigation:!0})})}pageSetup(){return l(this,null,function*(){try{this.localMode||(yield this.page.evaluate(wt))}catch(e){}})}wait(e){return l(this,null,function*(){yield H(e)})}toggleHints(e){return l(this,null,function*(){let t=yield this.getUserPageOrFrame();e.state==="on"?(yield t.addStyleTag({content:De.css}),yield t.addScriptTag({content:De.js}),yield t.evaluate(St)):yield t.evaluate(vt)})}showHints(){return l(this,null,function*(){yield this.toggleHints({state:"on"});let e=()=>l(this,null,function*(){try{yield this.toggleHints({state:"off"})}catch(t){this.logger.debug({err:t},"Failed to remove vision hints")}});setTimeout(()=>{e()},3e3)})}cleanup(){return l(this,null,function*(){yield this.page.close(),yield this.context.close(),yield this.browser.close()})}get closed(){return this.page.isClosed()||!this.browser.isConnected()}html(){return l(this,null,function*(){return(yield this.getUserPageOrFrame()).content()})}url(){return l(this,null,function*(){return(yield this.getUserPageOrFrame()).url()})}screenshotWithHints(e=100,t="device",o="/tmp/screenshots/test.jpg"){return l(this,null,function*(){let n=o==null?void 0:o.split("."),i=n==null?void 0:n.slice(0,-1).join("."),a=n==null?void 0:n.slice(-1)[0],s=yield this.screenshot(e,t,o?`${i}-before-hint.${a}`:void 0);yield this.showHints();let m=yield this.screenshot(e,t,o?`${i}-after-hint.${a}`:void 0);return{before:s,after:m}})}screenshot(e=100,t="device",o){return l(this,null,function*(){let n={fullPage:!1,quality:e,scale:t,type:"jpeg",caret:"initial",path:o};return!this.localMode||!this.activeFrame?this.page.screenshot(n):Buffer.from("")})}viewport(){return l(this,null,function*(){if(this.localMode&&this.activeFrame){let t=yield this.page.locator(`iframe[name="${this.activeFrame}"]`).boundingBox();if(!t)throw new Error(`Failed to get bounding box for frame: ${this.activeFrame}`);return t}let e=this.page.viewportSize();if(!e)throw new Error("failed to get viewport");return e})}navigate(n){return l(this,arguments,function*({url:e,wrapPossibleNavigation:t=!0,initialNavigation:o=!1}){this.logger.debug(`Navigating to ${e}`),o&&this.localMode&&(yield this.registerLocalRequestInterceptors(this.context));let i=Date.now(),a=()=>l(this,null,function*(){try{yield(yield this.getUserPageOrFrame()).goto(e,{waitUntil:"load",timeout:3e3}),this.logger.debug({url:e},`Got load event in ${Math.floor(Date.now()-i)}ms`)}catch(m){this.logger.warn({url:e},"Timeout elapsed waiting for page to fire load event, continuing anyways...")}finally{yield this.initCDPSession()}});t?yield this.wrapPossibleNavigation(a):yield a();let s=yield this.url();if(lt.has(s)&&process.env.NODE_ENV==="production")throw new Error(`${e} took too long to load \u{1F61E}. Please ensure the site and your internet are working.`);yield this.pageSetup(),this.logger.info({url:e},"Navigation complete")})}fill(n,i){return l(this,arguments,function*(e,t,o={}){let a=yield this.click(e,{doubleClick:!1,rightClick:!1});return yield this.type(t,o),a})}type(o){return l(this,arguments,function*(e,t={}){let{clearContent:n=!0,pressKeysSequentially:i=!1}=t;n&&(process.platform==="darwin"?yield this.page.keyboard.press("Meta+A"):yield this.page.keyboard.press("Control+A"),yield this.page.keyboard.press("Backspace")),i?yield this.page.keyboard.type(e):yield this.page.keyboard.insertText(e)})}clickByA11yID(o){return l(this,arguments,function*(e,t={}){let n=this.a11yIdToNodeMap.get(e);if(!n)throw new Error(`Could not find DOM node during click: ${e}`);let i=yield this.clickUsingCDP(n,t);return yield this.highlightNode(i),n.serialize({noChildren:!0,noProperties:!0,noID:!0})})}selectOptionByA11yID(e,t){return l(this,null,function*(){let o=this.a11yIdToNodeMap.get(e);if(!o)throw new Error(`Could not find DOM node while selecting option: ${e}`);if(!o.backendNodeID)throw new Error(`Select target missing backend node id: ${o.getLogForm()}`);return yield(yield this.getLocatorFromBackendID(o.backendNodeID)).selectOption(t,{timeout:8e3}),yield this.highlightNode(o),o.serialize({noChildren:!0,noProperties:!0,noID:!0})})}scrollIntoView(e){return l(this,null,function*(){let t=yield this.resolveCachedTargetToID(e),o=this.a11yIdToNodeMap.get(t);if(!o)throw new Error(`Could not find node in DOM with a11y id: ${t}`);if(!o.backendNodeID)throw new Error(`Focus target missing backend node id: ${o.getLogForm()}`);yield(yield this.getLocatorFromBackendID(o.backendNodeID)).scrollIntoViewIfNeeded({timeout:8e3})})}highlight(e){return l(this,null,function*(){try{let t=yield this.resolveCachedTargetToID(e),o=this.a11yIdToNodeMap.get(t);if(!o)throw new Error(`Could not find DOM node during highlight: ${t}`);if(!o.backendNodeID)throw new Error(`Select target missing backend node id: ${o.getLogForm()}`);yield this.highlightNode(o)}catch(t){this.logger.warn({err:t,target:e},"Failed to highlight target")}})}highlightNode(e){return l(this,null,function*(){try{yield this.cdpClient.send("Overlay.highlightNode",{highlightConfig:bt,backendNodeId:e.backendNodeID})}catch(o){this.logger.warn("Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests.")}let t=()=>l(this,null,function*(){try{yield this.cdpClient.send("Overlay.hideHighlight",{backendNodeId:e.backendNodeID})}catch(o){this.logger.debug({err:o},"Failed to remove node highlight")}});setTimeout(()=>{t()},3e3)})}wrapPossibleNavigation(n){return l(this,arguments,function*(e,t=8e3,o=!0){let i=Date.now(),a=yield this.url(),s=Date.now(),m=new Map,p=new Map,h=C=>{var Be;let T=ke(C.request());p.set(T,((Be=p.get(T))!=null?Be:0)+1);let te=C.status();te>=500&&this.logger.warn({request:T,status:te},"Received 500 level response")},u=C=>{var te;if(!At(C,a))return;let T=ke(C);m.set(T,((te=m.get(T))!=null?te:0)+1),s=Date.now()};this.page.on("response",h),this.page.on("request",u);let x=[];o&&(x=(yield this.context.pages()).map(C=>C.url()));let E=!1,b=e().catch(C=>(E=!0,C instanceof Error?C:new Error(`${C}`)));yield H(250);let f=C=>l(this,null,function*(){let T=yield C;if(T instanceof Error)throw T;return T}),S=new Set,y=!1,ee=yield l(this,null,function*(){for(;!E&&!(!y&&Date.now()-i>t);){if(yield H(250),y=!1,S=new Set,Date.now()-s<=1250)continue;let C=!1;for(let T of m.keys())m.get(T)!==p.get(T)&&(Tt(T)&&(y=!0),C=!0,S.add(T));if(!C)return this.logger.debug({url:this.url,requests:JSON.stringify(Array.from(m.entries()))},`Network idle in ${Math.floor(Date.now()-i)}ms`),!0}return!E&&S.size>0&&this.logger.warn({url:this.url,unfinishedRequests:JSON.stringify(Array.from(S.entries()))},"Timeout elapsed waiting for network idle, continuing anyways..."),!1});if(this.page.off("response",h),this.page.off("request",u),!ee)return f(b);let Se=yield this.url();if(!E&&q(Se,a)){this.logger.debug({startUrl:a,newUrl:Se},"Detected url change in wrapPossibleNavigation, waiting for load state");let C=Math.max(t-(Date.now()-i),0);if(C>0)try{yield(yield this.getUserPageOrFrame()).waitForLoadState("load",{timeout:C})}catch(T){this.logger.warn({url:yield this.url()},"Timeout elapsed waiting for load state, continuing anyways...")}}if(o){let C=(yield this.context.pages()).map(T=>T.url());if(C.length>x.length)for(let T of C)T!==Se&&(yield this.switchToPage(T))}return f(b)})}resolveCachedTargetToID(e){return l(this,null,function*(){if(!me(e)){let s=this.a11yIdToNodeMap.get(e.id);if(!s)throw new Error(`Resolving target failed, fresh value did not exist in node map: ${e.id}`);return le(s,e),e.id}let t=(yield this.getA11yTree()).serialize();this.logger.debug({tree:t},"Refreshed a11y tree before resolving target");let o=this.a11yIdToNodeMap.get(e.id);if(o){let s=Pe(o,e);if(s>=5)return this.logger.debug({target:e,proposedNode:o.getLogForm(),comparisonScore:s},"Resolved cached a11y target to node with exact same id"),le(o,e),e.id}let n=1/0,i=1/0,a;for(let s of this.a11yIdToNodeMap.values()){let m=Pe(s,e);if(m>=5)return this.logger.debug({newNode:s.getLogForm(),target:e,comparisonScore:m},"Resolved cached a11y target to new node with field comparison"),le(s,e),s.id;if(!e.serializedForm)continue;let p=s.serialize({noID:!0,maxLevel:1,neighbors:1});if(Math.abs(p.length-e.serializedForm.length)>15)continue;let h=Ko(e.serializedForm,p),u=h/Math.min(e.serializedForm.length,p.length);h<n&&u<.2&&(n=h,i=u,a=s)}if(a&&n<15)return this.logger.debug({newNode:a.getLogForm(),target:e,distance:n,ratio:i},"Resolved cached a11y target to new node with pure levenshtein distance"),le(a,e),a.id;throw new Error(`Could not find any relevant node given cached target: ${JSON.stringify(e)}`)})}click(o){return l(this,arguments,function*(e,t={}){let n=yield this.resolveCachedTargetToID(e);return yield this.wrapPossibleNavigation(()=>this.clickByA11yID(n,t))})}hover(e){return l(this,null,function*(){let t=yield this.resolveCachedTargetToID(e),o=this.a11yIdToNodeMap.get(t);if(!o)throw new Error(`Could not find DOM node for hover: ${t}`);if(!o.backendNodeID)throw new Error(`Hover target missing backend node id: ${o.getLogForm()}`);return yield(yield this.getLocatorFromBackendID(o.backendNodeID)).hover({timeout:8e3}),yield this.highlightNode(o),o.serialize({noChildren:!0,noProperties:!0,noID:!0})})}selectOption(e,t){return l(this,null,function*(){let o=yield this.resolveCachedTargetToID(e);return this.selectOptionByA11yID(o,t)})}press(e){return l(this,null,function*(){yield this.wrapPossibleNavigation(()=>this.page.keyboard.press(e))})}refresh(){return l(this,null,function*(){if(this.localMode&&this.activeFrame){let t=(yield this.getUserPageOrFrame()).url();yield this.navigate({url:t,wrapPossibleNavigation:!0})}else yield this.page.reload(),yield this.pageSetup()})}getA11yTree(){return l(this,null,function*(){yield this.initCDPSession();let e=null,t=0,o=this.url;for(;!e;)try{let n=yield this.getRawA11yTree();if(!n.root||n.allNodes.length===0)throw new Error("No a11y tree found on page");e=yt(n,this.logger)}catch(n){if(this.logger.error({err:n,url:o},"Error fetching a11y tree"),t===0)yield H(1e3),t++;else throw new Error(`Max retries exceeded fetching a11y tree: ${n}`)}return e.root||this.logger.warn("A11y tree was pruned entirely"),this.a11yIdToNodeMap=e.a11yIdNodeMap,this.dataMomenticIdToNodeMap=e.dataMomenticIdMap,e})}getA11yIdFromDataMomenticId(e){var t;return(t=this.dataMomenticIdToNodeMap.get(e))==null?void 0:t.id}getRawA11yTree(){return l(this,null,function*(){let e=yield this.url(),t=Date.now(),o=()=>{t=Date.now()};this.cdpClient.addListener("Accessibility.nodesUpdated",o);let n=!1,i=()=>{this.logger.info({url:e},"Load event fired on page"),n=!0,t=Date.now()};this.cdpClient.addListener("Accessibility.loadComplete",i);let a=Date.now(),s=!0;for(;Date.now()-a<3e3;){if(yield H(250),!n&&Date.now()-a<1e3){process.env.NODE_ENV!=="production"&&this.logger.debug({url:e},"A11y tree not loaded yet, waiting...");continue}if(Date.now()-t>=1250){s=!1;break}this.logger.debug({url:e},"A11y tree not stable yet, waiting...")}this.logger.debug({duration:Date.now()-a,eventReceived:n,timeoutTriggered:s},"A11y wait phase completed"),yield(yield this.getUserPageOrFrame()).evaluate(Ct);let m;if(this.localMode&&this.activeFrame){let{result:{objectId:h}}=yield this.cdpClient.send("Runtime.evaluate",{expression:`document.querySelector("#${this.activeFrame}")`}),u=yield this.cdpClient.send("DOM.describeNode",{objectId:h}),{nodes:x}=yield this.cdpClient.send("Accessibility.getFullAXTree",{frameId:u.node.frameId}),E=x[0];if(!E)throw new Error("No contents found in main page viewer. Are you sure a page is loaded?");m=E}else({node:m}=yield this.cdpClient.send("Accessibility.getRootAXNode"));let{nodes:p}=yield this.cdpClient.send("Accessibility.queryAXTree",{backendNodeId:m.backendDOMNodeId});return this.cdpClient.removeListener("Accessibility.loadComplete",i),this.cdpClient.removeListener("Accessibility.nodesUpdated",o),{root:m,allNodes:p}})}clickUsingVisualCoordinates(e){return l(this,null,function*(){let t=yield this.getElementLocation(e);if(!t)throw new Error(`Could not find element location with backend node id: ${e}`);this.logger.debug({location:t},"Executing mouse click"),yield this.page.mouse.click(t.centerX,t.centerY)})}getIDAttributeUsingCDP(e){return l(this,null,function*(){yield this.cdpClient.send("DOM.getDocument",{depth:0});let t=yield this.cdpClient.send("DOM.requestNode",{objectId:e}),n=(yield this.cdpClient.send("DOM.getAttributes",{nodeId:t.nodeId})).attributes,i=n.findIndex(a=>a==="data-momentic-id");return i===-1?"":n[i+1]||""})}getLocatorFromBackendID(e){return l(this,null,function*(){let t=yield this.cdpClient.send("DOM.resolveNode",{backendNodeId:e});if(!t||!t.object.objectId)throw new Error(`Could not resolve backend node ${e}`);try{let o=yield this.getIDAttributeUsingCDP(t.object.objectId);if(!o)throw new Error("Failed getting data-momentic-id attribute using CDP");return(yield this.getUserPageOrFrame()).locator(`[data-momentic-id="${o}"]`)}catch(o){throw this.logger.error({err:o},"Failed to get ID attribute"),o}})}clickUsingCDP(o){return l(this,arguments,function*(e,t={}){let n=0,i=e;for(;n<ct;){if(!i||i.role==="RootWebArea")throw new Error(`Attempted to click node with no clickable surrounding elements: ${e.getLogForm()}`);if(i.role==="StaticText"){i=i.parent;continue}let a=i.backendNodeID;if(!a){this.logger.warn({node:i.getLogForm()},"Click candidate had no backend node ID"),i=i.parent;continue}try{let s=yield this.getLocatorFromBackendID(a);return t.doubleClick?yield s.dblclick({timeout:8e3}):yield s.click({timeout:8e3,button:t.rightClick?"right":"left"}),i.id!==e.id&&this.logger.info({oldNode:e.getLogForm(),newNode:i.getLogForm()},"Redirected click successfully to new element"),i}catch(s){this.logger.error({err:s,node:i.getLogForm()},"Failed click or click timed out"),n++,i=i.parent}}throw new Error(`Max click redirection attempts exhausted on original element: ${e.getLogForm()}`)})}getElementLocation(e){return l(this,null,function*(){let t=yield this.cdpClient.send("DOMSnapshot.captureSnapshot",{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0}),o=yield this.page.evaluate(()=>window.devicePixelRatio);process.platform==="darwin"&&o===1&&(o=2);let n=t.documents[0],i=n.layout,a=n.nodes,s=a.nodeName||[],m=a.backendNodeId||[],p=i.nodeIndex,h=i.bounds,u=-1;for(let k=0;k<s.length;k++)if(m[k]===e){u=p.indexOf(k);break}if(u===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[x=0,E=0,b=0,f=0]=h[u];x/=o,E/=o,b/=o,f/=o;let S=x+b/2,y=E+f/2;return{centerX:S,centerY:y}})}scrollUp(e){return l(this,null,function*(){yield this.page.mouse.wheel(0,-(e!=null?e:$.VIEWPORT.height))})}scrollDown(e){return l(this,null,function*(){yield this.page.mouse.wheel(0,e!=null?e:$.VIEWPORT.height)})}goForward(){return l(this,null,function*(){yield this.wrapPossibleNavigation(()=>l(this,null,function*(){return this.localMode&&this.activeFrame?(yield this.getUserPageOrFrame()).evaluate(e=>{let t=e().contentWindow;t?t.history.forward():console.error("Failed to get content window for frame")},()=>document.querySelector(`iframe[name="${this.activeFrame}"]`)):this.page.goForward({timeout:8e3})})),yield this.pageSetup()})}goBack(){return l(this,null,function*(){yield this.wrapPossibleNavigation(()=>l(this,null,function*(){return this.localMode&&this.activeFrame?(yield this.getUserPageOrFrame()).evaluate(e=>{let t=e().contentWindow;t?t.history.back():console.error("Failed to get content window for frame")},()=>document.querySelector(`iframe[name="${this.activeFrame}"]`)):this.page.goBack({timeout:8e3})})),yield this.pageSetup()})}switchToPage(e){return l(this,null,function*(){let t=yield this.context.pages();for(let o=0;o<t.length;o++){let n=t[o];if(n.url().includes(e)){this.logger.info(`Switching to tab ${o} with url ${n.url()}`),this.page=n;try{yield n.waitForLoadState("load",{timeout:3e3})}catch(i){this.logger.warn({url:yield this.url()},"Timeout elapsed waiting for load state during tab switch, continuing anyways...")}yield this.pageSetup(),yield this.initCDPSession();return}}throw new Error(`Could not find page with url containing ${e}`)})}setCookie(e){return l(this,null,function*(){let t=Ze(e);yield this.context.addCookies([t])})}solveCaptcha(){return l(this,null,function*(){yield this.getA11yTree();let e;for(let s of this.a11yIdToNodeMap.values())if(s.role==="image"&&s.name.toLowerCase().includes("captcha")){if(!s.backendNodeID)continue;e=yield this.getLocatorFromBackendID(s.backendNodeID);break}if(!e){let s=yield(yield this.getUserPageOrFrame()).solveRecaptchas();if(!s.captchas||!s.captchas.length)throw new Error("No captchas found on the page");return}let t=yield e.screenshot({type:"jpeg",animations:"allow",quality:100}),o=yield fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:process.env.TWO_CAPTCHA_KEY,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!o.ok){let s=`Captcha solver API returned error response: ${o.statusText}`;throw this.logger.error({text:yield o.text()},s),new Error(s)}let{taskId:n}=yield o.json(),i=Date.now(),a="";for(;Date.now()-i<6e4;){yield H(2500);let s=yield fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:process.env.TWO_CAPTCHA_KEY,taskId:n})});if(!s.ok){let p=`Captcha solution API returned error response: ${s.statusText}`;throw this.logger.error({text:yield s.text()},p),new Error(p)}let m=yield s.json();if(m.errorId){let p=`Captcha solution API returned error ID ${m.errorId}`;throw this.logger.error(p),new Error(p)}if(m.status==="ready"){a=m.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a})}};$.USER_AGENT=Lt["Desktop Chrome"].userAgent,$.VIEWPORT={width:1920,height:1080};var _e=$;var Zo={type:"a11y",version:"1.0.0",useHistory:"diff",useGoalSplitter:!0},Qo=Zo;import en from"dedent";import tn from"diff-lines";var on=1e4,Fe=class{constructor({browser:e,config:t,generator:o,logger:n}){this.closed=!1;this.browser=e,this.generator=o,this.config=t,this.logger=n,this.pendingInstructions=[],this.commandHistory=[]}get history(){return this.commandHistory.filter(e=>e.state==="DONE")}get lastExecutedCommand(){let e=this.history;return e.length===0?null:e[e.length-1]}setOpen(){this.closed=!1}isClosed(){return this.closed}setLogger(e){this.logger=e}resetHistory(){this.commandHistory=[],this.pendingInstructions=[]}resetState(e){return l(this,null,function*(){this.resetHistory(),this.closed=!0,yield this.browser.reset(e)})}getBrowserState(){return l(this,null,function*(){let t=yield(yield this.browser.getA11yTree()).serialize();return this.logger.debug({tree:t},"Got a11y tree"),t})}getSerializedHistory(e,t){let o;return this.config.useHistory==="diff"?o=this.getDiffHistory(e,t):o=this.getListHistory(),o}splitUserGoal(e,t,o){return l(this,null,function*(){if(e==="AI_ACTION"&&t.match(/[,!;.]|(?:and)|(?:then)/)&&this.config.useGoalSplitter){let n=yield this.generator.getGranularGoals({goal:t,url:yield this.browser.url()},o);this.pendingInstructions=n.reverse()}else this.pendingInstructions=[t]})}promptToCommand(e,t,o){return l(this,null,function*(){try{return yield this.promptToCommandHelper(e,t,o)}catch(n){throw n instanceof O?n:new O("InternalWebAgentError",n instanceof Error?n.message:`${n}`,{cause:n})}})}promptToCommandHelper(e,t,o){return l(this,null,function*(){if(this.pendingInstructions.length===0){if(!t.trim())throw new Error("Cannot generate commands for empty goal");yield this.splitUserGoal(e,t,o)}let n=this.pendingInstructions[this.pendingInstructions.length-1];this.logger.info({goal:n},"Starting prompt translation");let i=Date.now(),a=yield this.browser.url(),s=yield this.getBrowserState();this.logger.info({duration:Date.now()-i,url:a},"Got browser state");let m=this.commandHistory.length;this.commandHistory.push({state:"PENDING",browserStateBeforeCommand:s,urlBeforeCommand:a,type:e});let p=this.getSerializedHistory(a,s),h={url:a,numPrevious:m,browserState:s,history:p,goal:n,lastCommand:this.lastExecutedCommand},u=yield this.generator.getProposedCommand(h,o);if(this.logger.info({type:u.type,thoughts:u.thoughts},"Got proposed command"),u.type==="SUCCESS"){let x=this.pendingInstructions.pop();if(this.logger.info({finishedInstruction:x,remainingInstructions:this.pendingInstructions},"Removing pending instruction due to SUCCESS"),this.pendingInstructions.length!==0)return this.commandHistory=[],this.promptToCommand(e,"",o)}else u.type==="FAILURE"&&(this.logger.info({remainingInstructions:this.pendingInstructions},"Removing pending instructions due to FAILURE"),this.pendingInstructions=[]);return{context:h,command:u}})}locateElement(e,t,o){return l(this,null,function*(){if(!e)throw new O("InternalWebAgentError","Cannot locate element with empty description");let n=yield this.getBrowserState(),i;if(t){let{before:a,after:s}=yield this.browser.screenshotWithHints();if(i=yield this.generator.getElementLocationWithVision({goal:e,screenshot:a,hintActivatedScreenshot:s},o),i.id>0){let m=this.browser.getA11yIdFromDataMomenticId(i.id);if(!m)throw new O("InternalWebAgentError",`Unable to find corresponding DOM node for id ${i.id}`);i.id=m}}else i=yield this.generator.getElementLocation({browserState:n,goal:e},o);if(i.id<0)throw new O("ActionFailureError",`Unable to locate element: ${i.thoughts?i.thoughts:"please ensure the element is visible and conforms to Accessibility guidelines"}`);return i})}getDiffHistory(e,t){let o=this.history.filter(i=>i.type==="AI_ACTION");if(o.length===0)return"<NONE/>";let n=[`
572
+ You have already executed the following commands successfully (most recent listed first)`,"-".repeat(10)];return o.reverse().forEach((i,a)=>{if(n.push(`COMMAND ${o.length-a}${a===0?" (command just executed)":""}: ${i.serializedCommand}`),a===0)if(q(i.urlBeforeCommand,e))n.push(` URL CHANGE: '${i.urlBeforeCommand}' -> '${e}'`);else{let s=tn(i.browserStateBeforeCommand,t,{n_surrounding:1});s?s.length<on?(n.push("PAGE CONTENT CHANGE:"),s.split(`
573
+ `).forEach(m=>n.push(` ${m}`))):n.push("PAGE CONTENT CHANGE: <TOO_LONG_TO_DISPLAY/>"):n.push("PAGE CONTENT CHANGE: <NONE/>")}n.push("-".repeat(10))}),n.push(`STARTING URL: ${this.browser.baseURL}`),n.join(`
574
+ `)}getListHistory(){return en`Here are the commands that you have successfully executed:
575
575
  ${this.commandHistory.filter(e=>e.type==="AI_ACTION").map(e=>`- ${e.serializedCommand}`).join(`
576
- `)}`}executeCommand(e,t,n=!1){return c(this,null,function*(){let r=this.commandHistory[this.commandHistory.length-1];if(!n&&(!r||r.state!=="PENDING"))throw new N("InternalWebAgentError","Executing command but there is no pending entry in the history");let i;try{let a=Date.now();i=yield this.executePresetStep(e,t);let s=Date.now()-a;this.logger.debug({result:i,duration:s},"Got execution result")}catch(a){throw a instanceof Error?new te(`Failed to execute command: ${a}`,{cause:a}):new te("Unexpected throw from executing command",{cause:new Error(`${a}`)})}return i.succeedImmediately&&!n&&(this.pendingInstructions.pop(),this.pendingInstructions.length>0&&(i.succeedImmediately=!1)),i.elementInteracted&&"target"in e&&e.target&&!e.target.elementDescriptor&&(e.target.elementDescriptor=i.elementInteracted.trim()),n||(r.generatedStep=e,r.serializedCommand=Ee(e),r.state="DONE"),i})}executeAssertion(e,t){return c(this,null,function*(){let n;if(t.useVision)n={goal:t.assertion,url:e,screenshot:yield this.browser.screenshot(),browserState:"",history:"",numPrevious:-1,lastCommand:null};else{let i=yield this.getBrowserState(),a=this.getSerializedHistory(e,i);n={goal:t.assertion,url:e,browserState:i,history:a,lastCommand:this.lastExecutedCommand,numPrevious:this.commandHistory.length}}let r=yield this.generator.getAssertionResult(n,t.useVision,t.disableCache);if(r.relevantElements&&Promise.all(r.relevantElements.map(i=>this.browser.highlight({id:i}))),!r.result)throw new N("AssertionFailureError",r.thoughts);return{succeedImmediately:!1,thoughts:r.thoughts,urlAfterCommand:e}})}wrapElementTargetingCommand(e,t,n,r,i=!0){return c(this,null,function*(){if(!e.a11yData&&!e.elementDescriptor)throw new N("InternalWebAgentError","Cannot target element with no target data or element descriptor");let a=e.a11yData&&se(e.a11yData);e.a11yData||(e.a11yData=ie.parse(yield this.locateElement(e.elementDescriptor,t,n)),i=!1);try{let s=yield r(e.a11yData);return a?this.logger.debug({target:e},"Successfully used cached target to perform action"):this.logger.debug({target:e},"Successfully generated and used new a11y target information"),s}catch(s){if(i&&e.elementDescriptor)return this.logger.warn({err:s,target:e},"Failed to execute action with cached target, retrying with AI"),e.a11yData=void 0,this.wrapElementTargetingCommand(e,t,n,r,!0);if(s instanceof N)throw s;let d=`Failed to find '${e.elementDescriptor}': ${s instanceof Error?s.message:s}`;throw this.logger.error({err:s,target:e},d),new N("ActionFailureError",d,{cause:s})}})}executePresetStep(e,t){return c(this,null,function*(){try{return yield this.executePresetStepHelper(e,t)}catch(n){throw n instanceof N?n:new N("InternalWebAgentError",n instanceof Error?n.message:`${n}`,{cause:n})}})}executePresetStepHelper(e,t){return c(this,null,function*(){var r;let n=this.browser.url;switch(e.type){case"SUCCESS":return(r=e.condition)!=null&&r.assertion.trim()?this.executeAssertion(n,e.condition):{succeedImmediately:!1,urlAfterCommand:this.browser.url};case"AI_ASSERTION":return this.executeAssertion(n,e);case"NAVIGATE":yield this.browser.navigate(e.url);break;case"CAPTCHA":let i=yield this.browser.solveCaptcha();i&&(yield this.wrapElementTargetingCommand({elementDescriptor:"the captcha image solution input"},e.useVision,t,p=>this.browser.click(p)),yield this.browser.type(i,{clearContent:!0,pressKeysSequentially:!1}));break;case"GO_BACK":yield this.browser.goBack();break;case"GO_FORWARD":yield this.browser.goForward();break;case"SCROLL_DOWN":case"SCROLL_UP":let a;return e.target&&(e.target.elementDescriptor.trim()||e.target.a11yData)&&(a=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,p=>this.browser.hover(p))),e.type==="SCROLL_UP"?yield this.browser.scrollUp():yield this.browser.scrollDown(),{succeedImmediately:!1,urlAfterCommand:n,elementInteracted:a};case"WAIT":yield this.browser.wait(e.delay*1e3);break;case"REFRESH":yield this.browser.refresh();break;case"CLICK":{let p=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,h=>this.browser.click(h,{doubleClick:e.doubleClick,rightClick:e.rightClick})),u={urlAfterCommand:this.browser.url,succeedImmediately:!1,elementInteracted:p};return $(n,u.urlAfterCommand)&&(u.succeedImmediately=!0,u.succeedImmediatelyReason="URL changed"),u}case"SELECT_OPTION":{let p=yield this.wrapElementTargetingCommand(e.target,!1,t,u=>this.browser.selectOption(u,e.option));return{succeedImmediately:!1,urlAfterCommand:this.browser.url,elementInteracted:p}}case"TAB":yield this.browser.switchToPage(e.url);break;case"COOKIE":if(!e.value)break;yield this.browser.setCookie(e.value);break;case"TYPE":{let p=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,h=>this.browser.click(h));yield this.browser.type(e.value,{clearContent:e.clearContent,pressKeysSequentially:e.pressKeysSequentially}),e.pressEnter&&(yield this.browser.press("Enter"));let u={urlAfterCommand:this.browser.url,succeedImmediately:!1,elementInteracted:p};return $(n,u.urlAfterCommand)&&(u.succeedImmediately=!0,u.succeedImmediatelyReason="URL changed"),u}case"HOVER":{let p=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,u=>this.browser.hover(u));return{succeedImmediately:!1,urlAfterCommand:this.browser.url,elementInteracted:p}}case"PRESS":yield this.browser.press(e.value);let s={urlAfterCommand:this.browser.url,succeedImmediately:!1};return $(n,s.urlAfterCommand)&&(s.succeedImmediately=!0,s.succeedImmediatelyReason="URL changed"),s;default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url}})}};import Qn from"fetch-retry";var eo=Qn(global.fetch),q="v1",Ue=class{constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey}getElementLocation(e,t){return c(this,null,function*(){let n=yield this.sendRequest(`/${q}/web-agent/locate-element`,{browserState:e.browserState,goal:e.goal,disableCache:t});return Ie.parse(n)})}getElementLocationWithVision(e,t){return c(this,null,function*(){var r,i;let n=yield this.sendRequest(`/${q}/web-agent/visual-locate`,{goal:e.goal,screenshot:(r=e.screenshot)==null?void 0:r.toString("base64"),hintActivatedScreenshot:(i=e.hintActivatedScreenshot)==null?void 0:i.toString("base64"),disableCache:t});return Ie.parse(n)})}getAssertionResult(e,t,n){return c(this,null,function*(){var i;if(t){let a=yield this.sendRequest(`/${q}/web-agent/assertion`,{url:e.url,goal:e.goal,screenshot:(i=e.screenshot)==null?void 0:i.toString("base64"),disableCache:n,vision:!0});return xe.parse(a)}let r=yield this.sendRequest(`/${q}/web-agent/assertion`,{url:e.url,browserState:e.browserState,goal:e.goal,history:e.history,numPrevious:e.numPrevious,lastCommand:e.lastCommand,disableCache:n,vision:!1});return xe.parse(r)})}getProposedCommand(e,t){return c(this,null,function*(){let n=yield this.sendRequest(`/${q}/web-agent/next-command`,{url:e.url,browserState:e.browserState,goal:e.goal,history:e.history,numPrevious:e.numPrevious,lastCommand:e.lastCommand,disableCache:t});return rt.parse(n)})}getGranularGoals(e,t){return c(this,null,function*(){let n=yield this.sendRequest(`/${q}/web-agent/split-goal`,{url:e.url,goal:e.goal,disableCache:t});return it.parse(n)})}sendRequest(e,t){return c(this,null,function*(){let n=yield eo(`${this.baseURL}${e}`,{retries:1,retryDelay:1e3,method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!n.ok)throw new Error(`Request to ${e} failed with status ${n.status}: ${yield n.text()}`);return n.json()})}};export{Ue as APIGenerator,Pe as AgentController,ke as ChromeBrowser,H as CommandType,Yn as DEFAULT_CONTROLLER_CONFIG,_ as StepType};
576
+ `)}`}executeCommand(e,t,o=!1){return l(this,null,function*(){let n=this.commandHistory[this.commandHistory.length-1];if(!o&&(!n||n.state!=="PENDING"))throw new O("InternalWebAgentError","Executing command but there is no pending entry in the history");if(this.closed)throw new Error("Attempting to execute command on a closed controller");let i;try{let a=Date.now();i=yield this.executePresetStep(e,t);let s=Date.now()-a;this.logger.debug({result:i,duration:s},"Got execution result")}catch(a){throw a instanceof Error?new ae(`Failed to execute command: ${a}`,{cause:a}):new ae("Unexpected throw from executing command",{cause:new Error(`${a}`)})}return i.succeedImmediately&&!o&&(this.pendingInstructions.pop(),this.pendingInstructions.length>0&&(i.succeedImmediately=!1)),i.elementInteracted&&"target"in e&&e.target&&!e.target.elementDescriptor&&(e.target.elementDescriptor=i.elementInteracted.trim()),o||(n.generatedStep=e,n.serializedCommand=xe(e),n.state="DONE"),i})}executeAssertion(e){return l(this,null,function*(){let t=yield this.getBrowserState(),o=yield this.browser.url(),n;if(e.useVision)n={goal:e.assertion,url:o,screenshot:yield this.browser.screenshot(),browserState:"",history:"",numPrevious:-1,lastCommand:null};else{let a=this.getSerializedHistory(o,t);n={goal:e.assertion,url:o,browserState:t,history:a,lastCommand:this.lastExecutedCommand,numPrevious:this.commandHistory.length}}let i=yield this.generator.getAssertionResult(n,e.useVision,e.disableCache);if(i.relevantElements&&Promise.all(i.relevantElements.map(a=>this.browser.highlight({id:a}))),!i.result)throw new O("AssertionFailureError",i.thoughts);return{succeedImmediately:!1,thoughts:i.thoughts,urlAfterCommand:o}})}wrapElementTargetingCommand(e,t,o,n,i=!0){return l(this,null,function*(){if(!e.a11yData&&!e.elementDescriptor)throw new O("InternalWebAgentError","Cannot target element with no target data or element descriptor");let a=e.a11yData&&me(e.a11yData);e.a11yData||(this.logger.debug("No cached locator data for target, prompting AI for fresh location"),e.a11yData=de.parse(yield this.locateElement(e.elementDescriptor,t,o)),i=!1);try{let s=yield n(e.a11yData);return a?this.logger.debug({target:e},"Successfully used cached target to perform action"):this.logger.debug({target:e},"Successfully generated and used new a11y target information"),s}catch(s){if(i&&e.elementDescriptor)return this.logger.warn({err:s,target:e},"Failed to execute action with cached target, retrying with AI"),e.a11yData=void 0,this.wrapElementTargetingCommand(e,t,o,n,!0);if(s instanceof O)throw s;let m=`Failed to find ${e.elementDescriptor?`${e.elementDescriptor}`:"element"}: ${s instanceof Error?s.message:s}`;throw this.logger.error({err:s,target:e},m),new O("ActionFailureError",m,{cause:s})}})}executePresetStep(e,t){return l(this,null,function*(){try{return yield this.executePresetStepHelper(e,t)}catch(o){throw o instanceof O?o:new O("InternalWebAgentError",o instanceof Error?o.message:`${o}`,{cause:o})}})}executePresetStepHelper(e,t){return l(this,null,function*(){var o;switch(e.type){case"SUCCESS":return(o=e.condition)!=null&&o.assertion.trim()?this.executeAssertion(e.condition):{succeedImmediately:!1,urlAfterCommand:yield this.browser.url()};case"AI_ASSERTION":return this.executeAssertion(e);case"NAVIGATE":yield this.browser.navigate({url:e.url});break;case"CAPTCHA":let n=yield this.browser.solveCaptcha();n&&(yield this.wrapElementTargetingCommand({elementDescriptor:"the captcha image solution input"},e.useVision,t,p=>this.browser.click(p)),yield this.browser.type(n,{clearContent:!0,pressKeysSequentially:!1}));break;case"GO_BACK":yield this.browser.goBack();break;case"GO_FORWARD":yield this.browser.goForward();break;case"SCROLL_DOWN":case"SCROLL_UP":let i;return e.target&&(e.target.elementDescriptor.trim()||e.target.a11yData)&&(i=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,p=>this.browser.hover(p))),e.type==="SCROLL_UP"?yield this.browser.scrollUp(e.deltaY):yield this.browser.scrollDown(e.deltaY),{succeedImmediately:!1,urlAfterCommand:yield this.browser.url(),elementInteracted:i};case"WAIT":yield this.browser.wait(e.delay*1e3);break;case"REFRESH":yield this.browser.refresh();break;case"CLICK":{let p=yield this.browser.url(),h=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,x=>this.browser.click(x,{doubleClick:e.doubleClick,rightClick:e.rightClick})),u={urlAfterCommand:yield this.browser.url(),succeedImmediately:!1,elementInteracted:h};return q(p,u.urlAfterCommand)&&(u.succeedImmediately=!0,u.succeedImmediatelyReason="URL changed"),u}case"SELECT_OPTION":{let p=yield this.wrapElementTargetingCommand(e.target,!1,t,h=>this.browser.selectOption(h,e.option));return{succeedImmediately:!1,urlAfterCommand:yield this.browser.url(),elementInteracted:p}}case"TAB":yield this.browser.switchToPage(e.url);break;case"COOKIE":if(!e.value)break;yield this.browser.setCookie(e.value);break;case"TYPE":{let p=yield this.browser.url(),h=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,x=>this.browser.click(x));yield this.browser.type(e.value,{clearContent:e.clearContent,pressKeysSequentially:e.pressKeysSequentially}),e.pressEnter&&(yield this.browser.press("Enter"));let u={urlAfterCommand:yield this.browser.url(),succeedImmediately:!1,elementInteracted:h};return q(p,u.urlAfterCommand)&&(u.succeedImmediately=!0,u.succeedImmediatelyReason="URL changed"),u}case"HOVER":{let p=yield this.wrapElementTargetingCommand(e.target,e.useVision,t,h=>this.browser.hover(h));return{succeedImmediately:!1,urlAfterCommand:yield this.browser.url(),elementInteracted:p}}case"PRESS":let a=yield this.browser.url();yield this.browser.press(e.value);let s={urlAfterCommand:yield this.browser.url(),succeedImmediately:!1};return q(a,s.urlAfterCommand)&&(s.succeedImmediately=!0,s.succeedImmediatelyReason="URL changed"),s;default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{succeedImmediately:!1,urlAfterCommand:yield this.browser.url()}})}getReverseMappedTarget(e,t,o){return l(this,null,function*(){return(yield this.generator.getReverseMappedDescription({browserState:e.browserState,goal:`${t}`},o)).phrase})}};import nn from"fetch-retry";var rn=nn(global.fetch),J="v1",He=class{constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey}getElementLocation(e,t){return l(this,null,function*(){let o=yield this.sendRequest(`/${J}/web-agent/locate-element`,{browserState:e.browserState,goal:e.goal,disableCache:t});return Oe.parse(o)})}getElementLocationWithVision(e,t){return l(this,null,function*(){var n,i;let o=yield this.sendRequest(`/${J}/web-agent/visual-locate`,{goal:e.goal,screenshot:(n=e.screenshot)==null?void 0:n.toString("base64"),hintActivatedScreenshot:(i=e.hintActivatedScreenshot)==null?void 0:i.toString("base64"),disableCache:t});return Oe.parse(o)})}getAssertionResult(e,t,o){return l(this,null,function*(){var i;if(t){let a=yield this.sendRequest(`/${J}/web-agent/assertion`,{url:e.url,goal:e.goal,screenshot:(i=e.screenshot)==null?void 0:i.toString("base64"),disableCache:o,vision:!0});return Le.parse(a)}let n=yield this.sendRequest(`/${J}/web-agent/assertion`,{url:e.url,browserState:e.browserState,goal:e.goal,history:e.history,numPrevious:e.numPrevious,lastCommand:e.lastCommand,disableCache:o,vision:!1});return Le.parse(n)})}getProposedCommand(e,t){return l(this,null,function*(){let o=yield this.sendRequest(`/${J}/web-agent/next-command`,{url:e.url,browserState:e.browserState,goal:e.goal,history:e.history,numPrevious:e.numPrevious,lastCommand:e.lastCommand,disableCache:t});return it.parse(o)})}getGranularGoals(e,t){return l(this,null,function*(){let o=yield this.sendRequest(`/${J}/web-agent/split-goal`,{url:e.url,goal:e.goal,disableCache:t});return st.parse(o)})}getReverseMappedDescription(e,t){return l(this,null,function*(){let o=yield this.sendRequest(`/${J}/web-agent/reverse-mapped-description`,{goal:e.goal,browserState:e.browserState,disableCache:t});return at.parse(o)})}sendRequest(e,t){return l(this,null,function*(){let o=yield rn(`${this.baseURL}${e}`,{retries:1,retryDelay:1e3,method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!o.ok)throw new Error(`Request to ${e} failed with status ${o.status}: ${yield o.text()}`);return o.json()})}};export{He as APIGenerator,Fe as AgentController,_e as ChromeBrowser,B as CommandType,Qo as DEFAULT_CONTROLLER_CONFIG,_ as StepType};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "momentic",
3
- "version": "0.0.19",
3
+ "version": "0.0.20",
4
4
  "description": "The Momentic SDK for Node.js",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",