momentic 1.1.10 → 1.1.12-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b9a19da0-3de9-5151-a7c3-c7bbfbbf1a85")}catch(e){}}();
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f34cad2a-8e48-5044-a601-5f7a2dec8aab")}catch(e){}}();
4
4
  var ax=Object.create;var Iu=Object.defineProperty;var lx=Object.getOwnPropertyDescriptor;var cx=Object.getOwnPropertyNames;var dx=Object.getPrototypeOf,px=Object.prototype.hasOwnProperty;var rn=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ux=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of cx(e))!px.call(n,o)&&o!==t&&Iu(n,o,{get:()=>e[o],enumerable:!(r=lx(e,o))||r.enumerable});return n};var Pu=(n,e,t)=>(t=n!=null?ax(dx(n)):{},ux(e||!n||!n.__esModule?Iu(t,"default",{value:n,enumerable:!0}):t,n));var dy=rn((Xa,$d)=>{"use strict";(function(n){typeof define=="function"&&define.amd?define([],n):typeof Xa=="object"?(Xa=n(),typeof $d=="object"&&($d.exports=Xa)):window?window.JClass=n():typeof console=="object"&&console.error instanceof Function&&console.error("cannot determine environment")})(function(){var n=function(i){return i instanceof Function},e=function(i){var s=Array.prototype.slice.call(arguments,1);for(var a in s){var l=s[a];if(typeof l=="object")for(var c in l)i[c]=l[c]}return i},t={_isClassObject:!1},r=!1,o=function(){};return o._subClasses=[],o.prototype.init=function(){},o._extend=function(i,s,a){i===void 0&&(i={}),s===void 0&&(s={}),a===void 0&&(a={}),a=e({},t,a);var l=function(){r||(this._class=l,this.init instanceof Function&&this.init.apply(this,arguments))},c=this;r=!0;var p=new c;r=!1;var d=c.prototype;l.prototype=p,l.prototype.constructor=l,l._superClass=c,l._subClasses=[],c._subClasses.push(l),l._extend=c._extend,l._extends=function(b){return this._superClass==o?!1:b==this._superClass||b==o?!0:this._superClass._extends(b)};for(var u in i){var m=Object.getOwnPropertyDescriptor(i,u),h=m.value;if(h!==null&&typeof h=="object"&&h.descriptor)Object.defineProperty(p,u,h);else if(!("value"in m)&&("set"in m||"get"in m))Object.defineProperty(p,u,m);else{p[u]=h;var g=d[u];n(h)&&n(g)&&h!==g&&(h._super=g)}}if(!a._isClassObject){var f=c._members===void 0?o:c._members._class,S=e({},a,{_isClassObject:!0}),v=f._extend(s,{},S);v._instanceClass=l,l._members=new v}return l},o._convert=function(i,s){var a=i.prototype;return a.init=function(){var l=this._origin=o._construct(i,arguments);Object.keys(l).forEach(function(c){l.hasOwnProperty(c)&&Object.defineProperty(this,c,{get:function(){return l[c]}})},this)},o._extend(a,{},s)},o._construct=function(i,s){s===void 0&&(s=[]);var a=function(){return i.apply(this,s)};return a.prototype=i.prototype,new a},o._superDescriptor=function(i,s){if("_class"in i&&i instanceof i._class&&(i=i._class),"_extends"in i&&i._extends instanceof Function&&i._extends(this))return Object.getOwnPropertyDescriptor(i._superClass.prototype,s)},o})});var uy=rn((B7,py)=>{"use strict";var hP=dy(),Wr=hP._extend({init:function(n,e,t){n=n instanceof Array?n:[n],this._map={},this._list=[],this.callback=e,this.keyFields=n,this.isHashArray=!0,this.options=t||{ignoreDuplicates:!1},e&&e("construct")},addOne:function(n){var e=!1;for(var t in this.keyFields){t=this.keyFields[t];var r=this.objectAt(n,t);if(r)if(this.has(r)){if(this.options.ignoreDuplicates)return;if(this._map[r].indexOf(n)!=-1){e=!0;continue}this._map[r].push(n)}else this._map[r]=[n]}(!e||this._list.indexOf(n)==-1)&&this._list.push(n)},add:function(){for(var n=0;n<arguments.length;n++)this.addOne(arguments[n]);return this.callback&&this.callback("add",Array.prototype.slice.call(arguments,0)),this},addAll:function(n){if(n.length<100)this.add.apply(this,n);else for(var e=0;e<n.length;e++)this.add(n[e]);return this},addMap:function(n,e){return this._map[n]=e,this.callback&&this.callback("addMap",{key:n,obj:e}),this},intersection:function(n){var e=this;if(!n||!n.isHashArray)throw Error("Cannot HashArray.intersection() on a non-hasharray object. You passed in: ",n);var t=this.clone(null,!0),r=this.clone(null,!0).addAll(this.all.concat(n.all));return r.all.forEach(function(o){e.collides(o)&&n.collides(o)&&t.add(o)}),t},complement:function(n){var e=this;if(!n||!n.isHashArray)throw Error("Cannot HashArray.complement() on a non-hasharray object. You passed in: ",n);var t=this.clone(null,!0);return this.all.forEach(function(r){n.collides(r)||t.add(r)}),t},get:function(n){if(this.has(n))return!(this._map[n]instanceof Array)||this._map[n].length!=1?this._map[n]:this._map[n][0]},getAll:function(n){if(n=n instanceof Array?n:[n],n[0]=="*")return this.all;var e=new Wr(this.keyFields);for(var t in n)e.add.apply(e,this.getAsArray(n[t]));return e.all},getAsArray:function(n){return this._map[n]||[]},getUniqueRandomIntegers:function(n,e,t){var r=[],o={};for(n=Math.min(Math.max(t-e,1),n);r.length<n;){var i=Math.floor(e+Math.random()*(t+1));o[i]||(o[i]=!0,r.push(i))}return r},sample:function(n,e){var t=this.all,r={},o=[];e&&(t=this.getAll(e));for(var i=this.getUniqueRandomIntegers(n,0,t.length-1),s=0;s<i.length;s++)o.push(t[i[s]]);return o},has:function(n){return this._map.hasOwnProperty(n)},collides:function(n){for(var e in this.keyFields)if(this.has(this.objectAt(n,this.keyFields[e])))return!0;return!1},hasMultiple:function(n){return this._map[n]instanceof Array},removeByKey:function(){for(var n=[],e=0;e<arguments.length;e++){var t=arguments[e],r=this._map[t].concat();if(r){n=n.concat(r);for(var o in r){var i=r[o];for(var s in this.keyFields){var a=this.objectAt(i,this.keyFields[s]);if(a&&this.has(a)){var s=this._map[a].indexOf(i);s!=-1&&this._map[a].splice(s,1),this._map[a].length==0&&delete this._map[a]}}this._list.splice(this._list.indexOf(i),1)}}delete this._map[t]}return this.callback&&this.callback("removeByKey",n),this},remove:function(){for(var n=0;n<arguments.length;n++){var e=arguments[n];for(var r in this.keyFields){var t=this.objectAt(e,this.keyFields[r]);if(t){var r=this._map[t].indexOf(e);if(r!=-1)this._map[t].splice(r,1);else throw new Error("HashArray: attempting to remove an object that was never added!"+t);this._map[t].length==0&&delete this._map[t]}}var r=this._list.indexOf(e);if(r!=-1)this._list.splice(r,1);else throw new Error("HashArray: attempting to remove an object that was never added!"+t)}return this.callback&&this.callback("remove",arguments),this},removeAll:function(){var n=this._list.concat();return this._map={},this._list=[],this.callback&&this.callback("remove",n),this},objectAt:function(n,e){if(typeof e=="string")return n[e];for(var t=e.concat();t.length&&n;)n=n[t.shift()];return n},forEach:function(n,e){n=n instanceof Array?n:[n];var t=this.getAll(n);return t.forEach(e),this},forEachDeep:function(n,e,t){n=n instanceof Array?n:[n];var r=this,o=this.getAll(n);return o.forEach(function(i){t(r.objectAt(i,e),i)}),this},clone:function(n,e){var t=new Wr(this.keyFields.concat(),n||this.callback);return e||t.add.apply(t,this.all.concat()),t},sum:function(n,e,t){var r=this,o=0;return this.forEachDeep(n,e,function(i,s){t!==void 0&&(i*=r.objectAt(s,t)),o+=i}),o},average:function(n,e,t){var r=0,o=0,i=0,s=this;return t!==void 0&&this.forEachDeep(n,t,function(a){i+=a}),this.forEachDeep(n,e,function(a,l){t!==void 0&&(a*=s.objectAt(l,t)/i),r+=a,o++}),t!==void 0?r:r/o},filter:function(n,e){var t=this,r=typeof e=="function"?e:i,o=new Wr(this.keyFields);return o.addAll(this.getAll(n).filter(r)),o;function i(s){var a=t.objectAt(s,e);return a!==void 0&&a!==!1}}});Object.defineProperty(Wr.prototype,"all",{get:function(){return this._list}});Object.defineProperty(Wr.prototype,"map",{get:function(){return this._map}});py.exports=Wr;typeof window<"u"&&(window.HashArray=Wr)});var hy=rn((z7,my)=>{"use strict";my.exports=uy()});var fy=rn((j7,gy)=>{"use strict";(function(){var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e={rotl:function(t,r){return t<<r|t>>>32-r},rotr:function(t,r){return t<<32-r|t>>>r},endian:function(t){if(t.constructor==Number)return e.rotl(t,8)&16711935|e.rotl(t,24)&4278255360;for(var r=0;r<t.length;r++)t[r]=e.endian(t[r]);return t},randomBytes:function(t){for(var r=[];t>0;t--)r.push(Math.floor(Math.random()*256));return r},bytesToWords:function(t){for(var r=[],o=0,i=0;o<t.length;o++,i+=8)r[i>>>5]|=t[o]<<24-i%32;return r},wordsToBytes:function(t){for(var r=[],o=0;o<t.length*32;o+=8)r.push(t[o>>>5]>>>24-o%32&255);return r},bytesToHex:function(t){for(var r=[],o=0;o<t.length;o++)r.push((t[o]>>>4).toString(16)),r.push((t[o]&15).toString(16));return r.join("")},hexToBytes:function(t){for(var r=[],o=0;o<t.length;o+=2)r.push(parseInt(t.substr(o,2),16));return r},bytesToBase64:function(t){for(var r=[],o=0;o<t.length;o+=3)for(var i=t[o]<<16|t[o+1]<<8|t[o+2],s=0;s<4;s++)o*8+s*6<=t.length*8?r.push(n.charAt(i>>>6*(3-s)&63)):r.push("=");return r.join("")},base64ToBytes:function(t){t=t.replace(/[^A-Z0-9+\/]/ig,"");for(var r=[],o=0,i=0;o<t.length;i=++o%4)i!=0&&r.push((n.indexOf(t.charAt(o-1))&Math.pow(2,-2*i+8)-1)<<i*2|n.indexOf(t.charAt(o))>>>6-i*2);return r}};gy.exports=e})()});var Gd=rn((H7,Sy)=>{"use strict";var Wd={utf8:{stringToBytes:function(n){return Wd.bin.stringToBytes(unescape(encodeURIComponent(n)))},bytesToString:function(n){return decodeURIComponent(escape(Wd.bin.bytesToString(n)))}},bin:{stringToBytes:function(n){for(var e=[],t=0;t<n.length;t++)e.push(n.charCodeAt(t)&255);return e},bytesToString:function(n){for(var e=[],t=0;t<n.length;t++)e.push(String.fromCharCode(n[t]));return e.join("")}}};Sy.exports=Wd});var wy=rn(($7,by)=>{"use strict";by.exports=function(n){return n!=null&&(yy(n)||gP(n)||!!n._isBuffer)};function yy(n){return!!n.constructor&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}function gP(n){return typeof n.readFloatLE=="function"&&typeof n.slice=="function"&&yy(n.slice(0,0))}});var xy=rn((W7,vy)=>{"use strict";(function(){var n=fy(),e=Gd().utf8,t=wy(),r=Gd().bin,o=function(i,s){i.constructor==String?s&&s.encoding==="binary"?i=r.stringToBytes(i):i=e.stringToBytes(i):t(i)?i=Array.prototype.slice.call(i,0):!Array.isArray(i)&&i.constructor!==Uint8Array&&(i=i.toString());for(var a=n.bytesToWords(i),l=i.length*8,c=1732584193,p=-271733879,d=-1732584194,u=271733878,m=0;m<a.length;m++)a[m]=(a[m]<<8|a[m]>>>24)&16711935|(a[m]<<24|a[m]>>>8)&4278255360;a[l>>>5]|=128<<l%32,a[(l+64>>>9<<4)+14]=l;for(var h=o._ff,g=o._gg,f=o._hh,S=o._ii,m=0;m<a.length;m+=16){var v=c,b=p,x=d,C=u;c=h(c,p,d,u,a[m+0],7,-680876936),u=h(u,c,p,d,a[m+1],12,-389564586),d=h(d,u,c,p,a[m+2],17,606105819),p=h(p,d,u,c,a[m+3],22,-1044525330),c=h(c,p,d,u,a[m+4],7,-176418897),u=h(u,c,p,d,a[m+5],12,1200080426),d=h(d,u,c,p,a[m+6],17,-1473231341),p=h(p,d,u,c,a[m+7],22,-45705983),c=h(c,p,d,u,a[m+8],7,1770035416),u=h(u,c,p,d,a[m+9],12,-1958414417),d=h(d,u,c,p,a[m+10],17,-42063),p=h(p,d,u,c,a[m+11],22,-1990404162),c=h(c,p,d,u,a[m+12],7,1804603682),u=h(u,c,p,d,a[m+13],12,-40341101),d=h(d,u,c,p,a[m+14],17,-1502002290),p=h(p,d,u,c,a[m+15],22,1236535329),c=g(c,p,d,u,a[m+1],5,-165796510),u=g(u,c,p,d,a[m+6],9,-1069501632),d=g(d,u,c,p,a[m+11],14,643717713),p=g(p,d,u,c,a[m+0],20,-373897302),c=g(c,p,d,u,a[m+5],5,-701558691),u=g(u,c,p,d,a[m+10],9,38016083),d=g(d,u,c,p,a[m+15],14,-660478335),p=g(p,d,u,c,a[m+4],20,-405537848),c=g(c,p,d,u,a[m+9],5,568446438),u=g(u,c,p,d,a[m+14],9,-1019803690),d=g(d,u,c,p,a[m+3],14,-187363961),p=g(p,d,u,c,a[m+8],20,1163531501),c=g(c,p,d,u,a[m+13],5,-1444681467),u=g(u,c,p,d,a[m+2],9,-51403784),d=g(d,u,c,p,a[m+7],14,1735328473),p=g(p,d,u,c,a[m+12],20,-1926607734),c=f(c,p,d,u,a[m+5],4,-378558),u=f(u,c,p,d,a[m+8],11,-2022574463),d=f(d,u,c,p,a[m+11],16,1839030562),p=f(p,d,u,c,a[m+14],23,-35309556),c=f(c,p,d,u,a[m+1],4,-1530992060),u=f(u,c,p,d,a[m+4],11,1272893353),d=f(d,u,c,p,a[m+7],16,-155497632),p=f(p,d,u,c,a[m+10],23,-1094730640),c=f(c,p,d,u,a[m+13],4,681279174),u=f(u,c,p,d,a[m+0],11,-358537222),d=f(d,u,c,p,a[m+3],16,-722521979),p=f(p,d,u,c,a[m+6],23,76029189),c=f(c,p,d,u,a[m+9],4,-640364487),u=f(u,c,p,d,a[m+12],11,-421815835),d=f(d,u,c,p,a[m+15],16,530742520),p=f(p,d,u,c,a[m+2],23,-995338651),c=S(c,p,d,u,a[m+0],6,-198630844),u=S(u,c,p,d,a[m+7],10,1126891415),d=S(d,u,c,p,a[m+14],15,-1416354905),p=S(p,d,u,c,a[m+5],21,-57434055),c=S(c,p,d,u,a[m+12],6,1700485571),u=S(u,c,p,d,a[m+3],10,-1894986606),d=S(d,u,c,p,a[m+10],15,-1051523),p=S(p,d,u,c,a[m+1],21,-2054922799),c=S(c,p,d,u,a[m+8],6,1873313359),u=S(u,c,p,d,a[m+15],10,-30611744),d=S(d,u,c,p,a[m+6],15,-1560198380),p=S(p,d,u,c,a[m+13],21,1309151649),c=S(c,p,d,u,a[m+4],6,-145523070),u=S(u,c,p,d,a[m+11],10,-1120210379),d=S(d,u,c,p,a[m+2],15,718787259),p=S(p,d,u,c,a[m+9],21,-343485551),c=c+v>>>0,p=p+b>>>0,d=d+x>>>0,u=u+C>>>0}return n.endian([c,p,d,u])};o._ff=function(i,s,a,l,c,p,d){var u=i+(s&a|~s&l)+(c>>>0)+d;return(u<<p|u>>>32-p)+s},o._gg=function(i,s,a,l,c,p,d){var u=i+(s&l|a&~l)+(c>>>0)+d;return(u<<p|u>>>32-p)+s},o._hh=function(i,s,a,l,c,p,d){var u=i+(s^a^l)+(c>>>0)+d;return(u<<p|u>>>32-p)+s},o._ii=function(i,s,a,l,c,p,d){var u=i+(a^(s|~l))+(c>>>0)+d;return(u<<p|u>>>32-p)+s},o._blocksize=16,o._digestsize=16,vy.exports=function(i,s){if(i==null)throw new Error("Illegal argument "+i);var a=n.wordsToBytes(o(i,s));return s&&s.asBytes?a:s&&s.asString?r.bytesToString(a):n.bytesToHex(a)}})()});var Ey=rn((G7,Kd)=>{"use strict";var Vd=hy(),fP=xy(),SP=1024,Ty=/^[\s]*$/,yP=[{regex:/[åäàáâãæ]/ig,alternate:"a"},{regex:/[èéêë]/ig,alternate:"e"},{regex:/[ìíîï]/ig,alternate:"i"},{regex:/[òóôõö]/ig,alternate:"o"},{regex:/[ùúûü]/ig,alternate:"u"},{regex:/[æ]/ig,alternate:"ae"}];String.prototype.replaceCharAt=function(n,e){return this.substring(0,n)+e+this.substr(n+e.length)};var Zi=function(n,e){this.options=e||{},this.options.ignoreCase=this.options.ignoreCase===void 0?!0:this.options.ignoreCase,this.options.maxCacheSize=this.options.maxCacheSize||SP,this.options.cache=this.options.hasOwnProperty("cache")?this.options.cache:!0,this.options.splitOnRegEx=this.options.hasOwnProperty("splitOnRegEx")?this.options.splitOnRegEx:/[\s.,\/#!$%\^&\*;:{}=\-_`~()]/g,this.options.splitOnGetRegEx=this.options.hasOwnProperty("splitOnGetRegEx")?this.options.splitOnGetRegEx:this.options.splitOnRegEx,this.options.min=this.options.min||1,this.options.keepAll=this.options.hasOwnProperty("keepAll")?this.options.keepAll:!1,this.options.keepAllKey=this.options.hasOwnProperty("keepAllKey")?this.options.keepAllKey:"id",this.options.idFieldOrFunction=this.options.hasOwnProperty("idFieldOrFunction")?this.options.idFieldOrFunction:void 0,this.options.expandRegexes=this.options.expandRegexes||yP,this.options.insertFullUnsplitKey=this.options.hasOwnProperty("insertFullUnsplitKey")?this.options.insertFullUnsplitKey:!1,this.options.defaultReducer=this.options.hasOwnProperty("defaultReducer")?this.options.defaultReducer:Zi.UNION_REDUCER,this.keyFields=n?n instanceof Array?n:[n]:[],this.root={},this.size=0,this.options.cache&&(this.getCache=new Vd("key"))};function qd(n,e){return e.length===1?n[e[0]]:qd(n[e[0]],e.slice(1,e.length))}Zi.prototype={add:function(n,e){this.options.cache&&this.clearCache(),typeof e=="number"&&(e=void 0);var t=e||this.keyFields;for(var r in t){var o=t[r],i=o instanceof Array,s=i?qd(n,o):n[o];if(s){s=s.toString(),this.options.ignoreCase&&(s=s.toLowerCase());for(var a=this.expandString(s),l=0;l<a.length;l++){var c=a[l];this.map(c,n,e)}}}},remove:function(n,e){if(n){n=n.toString(),n=this.options.ignoreCase?n.toLowerCase():n,e=e||this.keyFields,e=e instanceof Array?e:[e],this.options.cache&&this.clearCache();var t=this.expandString(n);for(var r of t){var o=this.options.splitOnRegEx?r.split(this.options.splitOnRegEx):[r];for(var i of o)this.removeNode(this.root,e,n,i)}}},removeNode:function(n,e,t,r){if(!n)return null;if(!r.length){n.value&&(n.value=n.value.filter(i=>!e.some(s=>{var a=i[s]||"";return a=this.options.ignoreCase?a.toLowerCase():a,a.indexOf(t)>-1})),n.value.length||delete n.value);return}var o=r[0];n[o]&&(this.removeNode(n[o],e,t,r.slice(1)),this.deleteNodeIfEmpty(n,o))},deleteNodeIfEmpty:function(n,e){Object.keys(n[e]).length===0&&(delete n[e],this.size--)},expandString:function(n){var e=[n];if(this.options.expandRegexes&&this.options.expandRegexes.length)for(var t=0;t<this.options.expandRegexes.length;t++)for(var r=this.options.expandRegexes[t],o;(o=r.regex.exec(n))!==null;){var i=n.replaceCharAt(o.index,r.alternate);e.push(i)}return e},addAll:function(n,e){for(var t=0;t<n.length;t++)this.add(n[t],e)},reset:function(){this.root={},this.size=0},clearCache:function(){this.getCache=new Vd("key")},cleanCache:function(){for(;this.getCache.all.length>this.options.maxCacheSize;)this.getCache.remove(this.getCache.all[0])},addFromObject:function(n,e){this.options.cache&&this.clearCache(),e=e||"value",this.keyFields.indexOf("_key_")==-1&&this.keyFields.push("_key_");for(var t in n){var r={_key_:t};r[e]=n[t],this.add(r)}},map:function(n,e,t){if(this.options.splitOnRegEx&&this.options.splitOnRegEx.test(n)){var r=n.split(this.options.splitOnRegEx),o=r.filter(function(u){return Ty.test(u)}),i=r.filter(function(u){return u===n}),s=i.length+o.length===r.length;if(!s){for(var a=0,l=r.length;a<l;a++)Ty.test(r[a])||this.map(r[a],e,t);if(!this.options.insertFullUnsplitKey)return}}this.options.cache&&this.clearCache(),this.options.keepAll&&(this.indexed=this.indexed||new Vd([this.options.keepAllKey]),this.indexed.add(e)),this.options.ignoreCase&&(n=n.toLowerCase());var c=this.keyToArr(n),p=this;d(c,e,this.root);try{e.$tsid=this.getId(e,t)}catch(u){throw console.warn("TrieSearch: since version 2.2 you cannot insert primitives as items, you must wrap them in an Object. This was done for performance."),u}function d(u,m,h){if(u.length==0){h.value=h.value||[],h.value.push(m);return}var g=u.shift();h[g]||p.size++,h[g]=h[g]||{},d(u,m,h[g])}},keyToArr:function(n){var e;if(this.options.min&&this.options.min>1){if(n.length<this.options.min)return[];e=[n.substring(0,this.options.min)],e=e.concat(n.substring(this.options.min).split(""))}else e=n.split("");return e},findNode:function(n){return e(this.keyToArr(n),this.root);function e(t,r){if(r){if(t.length===0)return r;var o=t.shift();return e(t,r[o])}}},_getCacheKey:function(n,e){var t=n;return e&&(t=n+"_"+e),t},_get:function(n,e){var t=this;n=this.options.ignoreCase?n.toLowerCase():n;var r,o,i=[],s={};if(this.options.cache&&(r=this.getCache.get(this._getCacheKey(n,e))))return r.value;if(o=this.findNode(n),o&&l(o),this.options.cache){var a=this._getCacheKey(n,e);this.getCache.add({key:a,value:i}),this.cleanCache()}return i;function l(c){if(i.length!==e){if(c.value&&c.value.length)for(let u=0;u<c.value.length;u++){var p=c.value[u];if(!e||i.length<e){let m=t.getId(p);if(s[m])continue;i.push(p),s[m]=p}}if(i.length!==e)for(var d in c)d!=="value"&&l(c[d])}}},get:function(n,e,t){var r=void 0;e=e||this.options.defaultReducer,typeof n=="string"&&(n=this.options.splitOnGetRegEx?n.split(this.options.splitOnGetRegEx):[n]),n=n.filter(l=>!this.options.min||l.length>=this.options.min);for(var o=0,i=n.length;o<i;o++){var s=n[o],a=this._get(s,t);r=e(r,s,a,this)}return r||[]},search:function(n,e,t){return this.get(n,e,t)},getId:function(n,e){if(n.$tsid)return n.$tsid;if(!this.options.idFieldOrFunction){var t="",r=e||this.keyFields;for(let s=0;s<r.length;s++){var o=r[s],i=typeof o=="string"?n[o]:qd(n,o);if(i==null)throw new Error(`Since 2.2.0 of TrieSearch, if you have undefined/null keyFields (or customKeys) on your items you must specify an idFieldOrFunction. item.${o} === ${i}`);t+=i.toString()}return fP(t)}return typeof this.options.idFieldOrFunction=="function"?this.options.idFieldOrFunction(n):n[this.options.idFieldOrFunction]}};Zi.UNION_REDUCER=function(n,e,t,r){if(n===void 0)return t;var o={},i=[];return n.forEach(function(s){o[r.getId(s)]=!0}),t.forEach(function(s){var a=r.getId(s);o[a]&&i.push(s)}),i};Kd.exports=Zi;Kd.exports.default=Zi});var Ry=rn((V7,Cy)=>{"use strict";Cy.exports=Ey()});var yb=rn((xie,Sb)=>{"use strict";Sb.exports=gb;function gb(n,e,t){n instanceof RegExp&&(n=hb(n,t)),e instanceof RegExp&&(e=hb(e,t));var r=fb(n,e,t);return r&&{start:r[0],end:r[1],pre:t.slice(0,r[0]),body:t.slice(r[0]+n.length,r[1]),post:t.slice(r[1]+e.length)}}function hb(n,e){var t=e.match(n);return t?t[0]:null}gb.range=fb;function fb(n,e,t){var r,o,i,s,a,l=t.indexOf(n),c=t.indexOf(e,l+1),p=l;if(l>=0&&c>0){if(n===e)return[l,c];for(r=[],i=t.length;p>=0&&!a;)p==l?(r.push(p),l=t.indexOf(n,p+1)):r.length==1?a=[r.pop(),c]:(o=r.pop(),o<i&&(i=o,s=c),c=t.indexOf(e,p+1)),p=l<c&&l>=0?l:c;r.length&&(a=[i,s])}return a}});var Rb=rn((Tie,Cb)=>{"use strict";var bb=yb();Cb.exports=_L;var wb="\0SLASH"+Math.random()+"\0",vb="\0OPEN"+Math.random()+"\0",mp="\0CLOSE"+Math.random()+"\0",xb="\0COMMA"+Math.random()+"\0",Tb="\0PERIOD"+Math.random()+"\0";function up(n){return parseInt(n,10)==n?parseInt(n,10):n.charCodeAt(0)}function kL(n){return n.split("\\\\").join(wb).split("\\{").join(vb).split("\\}").join(mp).split("\\,").join(xb).split("\\.").join(Tb)}function NL(n){return n.split(wb).join("\\").split(vb).join("{").split(mp).join("}").split(xb).join(",").split(Tb).join(".")}function Eb(n){if(!n)return[""];var e=[],t=bb("{","}",n);if(!t)return n.split(",");var r=t.pre,o=t.body,i=t.post,s=r.split(",");s[s.length-1]+="{"+o+"}";var a=Eb(i);return i.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),e.push.apply(e,s),e}function _L(n){return n?(n.substr(0,2)==="{}"&&(n="\\{\\}"+n.substr(2)),ss(kL(n),!0).map(NL)):[]}function ML(n){return"{"+n+"}"}function FL(n){return/^-?0\d/.test(n)}function DL(n,e){return n<=e}function UL(n,e){return n>=e}function ss(n,e){var t=[],r=bb("{","}",n);if(!r)return[n];var o=r.pre,i=r.post.length?ss(r.post,!1):[""];if(/\$$/.test(r.pre))for(var s=0;s<i.length;s++){var a=o+"{"+r.body+"}"+i[s];t.push(a)}else{var l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(r.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(r.body),p=l||c,d=r.body.indexOf(",")>=0;if(!p&&!d)return r.post.match(/,.*\}/)?(n=r.pre+"{"+r.body+mp+r.post,ss(n)):[n];var u;if(p)u=r.body.split(/\.\./);else if(u=Eb(r.body),u.length===1&&(u=ss(u[0],!1).map(ML),u.length===1))return i.map(function(U){return r.pre+u[0]+U});var m;if(p){var h=up(u[0]),g=up(u[1]),f=Math.max(u[0].length,u[1].length),S=u.length==3?Math.abs(up(u[2])):1,v=DL,b=g<h;b&&(S*=-1,v=UL);var x=u.some(FL);m=[];for(var C=h;v(C,g);C+=S){var E;if(c)E=String.fromCharCode(C),E==="\\"&&(E="");else if(E=String(C),x){var I=f-E.length;if(I>0){var N=new Array(I+1).join("0");C<0?E="-"+N+E.slice(1):E=N+E}}m.push(E)}}else{m=[];for(var P=0;P<u.length;P++)m.push.apply(m,ss(u[P],!1))}for(var P=0;P<m.length;P++)for(var s=0;s<i.length;s++){var a=o+m[P]+i[s];(!e||p||a)&&t.push(a)}}return t}});var rc=(n,e)=>{},mi=()=>{},oc=!1;try{let n=await import("@sentry/node"),{nodeProfilingIntegration:e}=await import("@sentry/profiling-node");rc=n.captureException,mi=n.profiler.stopProfiler,n.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",integrations:[e()],environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:1}),n.profiler.startProfiler(),oc=!0}catch{}import{Command as d_,Option as tn}from"@commander-js/extra-typings";import{execSync as p_}from"child_process";import Bw from"body-parser";import Bk from"cors";import zk from"dedent";import jk from"events";import zw,{Router as Hk}from"express";import $k from"http";import{z as Lu}from"zod";var E_=Lu.object({input:Lu.string()});import{z as je}from"zod";var A_=je.object({srcs:je.array(je.string()),urls:je.array(je.string()),desiredSrc:je.string().optional(),desiredUrl:je.string().optional()}),Ou=je.object({srcRegex:je.string().optional(),urlRegex:je.string().optional()}),ku=je.object({x:je.number(),y:je.number(),correlation:je.number()}),I_=je.object({searchImageBase64String:je.string(),pageImageBase64String:je.string(),id:je.string().uuid(),timeoutMs:je.number().max(1e4).min(0).optional()});import{z as k}from"zod";import{v4 as Ie}from"uuid";import*as w from"zod";function ye(n){if(typeof n.ZodType.prototype.openapi<"u")return;n.ZodType.prototype.openapi=function(o){return new this.constructor({...this._def,openapi:o})};let e=n.ZodObject.prototype.extend;n.ZodObject.prototype.extend=function(...o){let i=e.apply(this,o);return i._def.extendMetadata={extends:this},delete i._def.openapi,i};let t=n.ZodObject.prototype.omit;n.ZodObject.prototype.omit=function(...o){let i=t.apply(this,o);return delete i._def.extendMetadata,delete i._def.openapi,i};let r=n.ZodObject.prototype.pick;n.ZodObject.prototype.pick=function(...o){let i=r.apply(this,o);return delete i._def.extendMetadata,delete i._def.openapi,i}}import{z as pe}from"zod";ye(pe);var Nu=pe.object({plan:pe.string().optional(),evidence:pe.string().optional(),thoughts:pe.string(),result:pe.boolean(),relevantElements:pe.array(pe.number()).optional()}),io=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(io||{});var mx=pe.object({type:pe.literal("ELEMENT_CONTENT"),negated:pe.boolean().optional(),operation:pe.nativeEnum(io),value:pe.string()}).openapi({ref:"ElementContentAssertion"}),hx=pe.object({type:pe.literal("ELEMENT_ATTRIBUTE"),negated:pe.boolean().optional(),operation:pe.nativeEnum(io),attr:pe.string(),value:pe.string()}).openapi({ref:"ElementAttributeValueAssertion"}),hi=(o=>(o.EXISTS="EXISTS",o.VISIBLE="VISIBLE",o.ENABLED="ENABLED",o.EDITABLE="EDITABLE",o))(hi||{}),gx=pe.object({type:pe.literal("ELEMENT_EXISTENCE"),negated:pe.boolean().optional(),condition:pe.nativeEnum(hi).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),_u=pe.discriminatedUnion("type",[mx,hx,gx]).openapi({ref:"ManualElementAssertion"});var fx=pe.object({type:pe.literal("CONTENT"),negated:pe.boolean().optional(),value:pe.string()}).openapi({ref:"PageContentAssertion"}),Mu=pe.discriminatedUnion("type",[fx]).openapi({ref:"ManualPageAssertion"});import*as K from"zod";ye(K);var Gn=(a=>(a.AI="AI",a.AI_HEALED="AI_HEALED",a.CLICK_TO_FIND="CLICK_TO_FIND",a.XY_PERCENT="XY_PERCENT",a.RECORDING="RECORDING",a.USER_CSS_SELECTOR="USER_CSS_SELECTOR",a.HEURISTIC_HEALED="HEURISTIC_HEALED",a))(Gn||{}),Sx=K.object({mPathSelectorTokens:K.string().array(),frameSrcRegex:K.string().optional(),frameUrlRegex:K.string().optional(),indices:K.number().array()}),br=K.object({id:K.number().int(),dataMomenticId:K.number().int().optional(),selector:K.string().optional(),generatedSelectors:K.string().array().optional(),role:K.string().optional(),name:K.string().optional(),numChildren:K.number().optional(),content:K.string().optional(),pathFromRoot:K.string().optional(),serializedForm:K.string().optional(),nodeOnlySerializedForm:K.string().optional(),serializedHtml:K.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:K.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:K.string().url().optional(),boundingBox:K.object({x:K.number().optional(),y:K.number().optional(),width:K.number(),height:K.number()}).describe("css pixel bounding box").optional(),frameCache:Sx.optional(),inputDescription:K.string().optional().describe("the description that generated this cache"),targetSource:K.nativeEnum(Gn).optional(),targetUpdateTime:K.string().optional()}).openapi({ref:"A11yTargetWithCache"});function Fu(n){return!!(n.name||n.role||n.content||n.serializedForm||n.serializedHtml||n.screenshotUrl)}var yx=K.object({type:K.literal("description"),elementDescriptor:K.string(),a11yData:br.optional().describe("DEPRECATED: new a11y cache is stored in DB and resolved into the 'cache' field")}).openapi({ref:"DescriptionTarget"}),bx=K.object({x:K.number(),y:K.number()}),wx=K.object({type:K.literal("coordinates"),pixels:bx}).openapi({ref:"CoordinatesTarget"});function Vn(n){return n.type==="description"}function Sn(n){return n.type==="coordinates"}var dt=K.discriminatedUnion("type",[yx,wx]).openapi({ref:"ElementTarget"});function ic(n){if(!n)return!1;switch(n.type){case"description":return!!n.elementDescriptor}return!0}function pt(n){if(!n)return"";switch(n.type){case"description":return n.elementDescriptor;case"coordinates":return`x: ${n.pixels.x}, y: ${n.pixels.y}`}}import{z as oe}from"zod";var Ls=oe.object({url:oe.string(),method:oe.union([oe.literal("GET"),oe.literal("POST"),oe.literal("PUT"),oe.literal("DELETE"),oe.literal("PATCH")]),headers:oe.record(oe.string(),oe.string()).optional(),params:oe.record(oe.string(),oe.string()).optional(),body:oe.string().optional(),timeout:oe.number().int().optional().describe("Max seconds to wait for the request to complete")}),Du=oe.object({url:oe.string(),headers:oe.record(oe.string(),oe.string()).optional(),query:oe.string(),variables:oe.record(oe.string(),oe.string()).optional(),timeout:oe.number().int().optional().describe("Max seconds to wait for the request to complete")}),Os=oe.object({code:oe.string(),fragment:oe.boolean().optional(),environment:oe.union([oe.literal("NODE"),oe.literal("BROWSER")]).optional().describe("default NODE"),timeout:oe.number().int().max(60).optional().describe("Max seconds for the code to complete")});var Be=(G=>(G.AI_EXTRACT="AI_EXTRACT",G.AI_ASSERTION="AI_ASSERTION",G.AI_WAIT="AI_WAIT",G.AUTH_LOAD="AUTH_LOAD",G.AUTH_SAVE="AUTH_SAVE",G.BLUR="BLUR",G.CAPTCHA="CAPTCHA",G.CLICK="CLICK",G.COOKIE="COOKIE",G.COPY="COPY",G.DIALOG="DIALOG",G.DRAG="DRAG",G.ELEMENT_CHECK="ELEMENT_CHECK",G.FILE_UPLOAD="FILE_UPLOAD",G.FOCUS="FOCUS",G.GO_BACK="GO_BACK",G.GO_FORWARD="GO_FORWARD",G.HOVER="HOVER",G.JAVASCRIPT="JAVASCRIPT",G.LOCAL_STORAGE="LOCAL_STORAGE",G.MOUSE_DRAG="MOUSE_DRAG",G.NAVIGATE="NAVIGATE",G.NEW_TAB="NEW_TAB",G.PAGE_CHECK="PAGE_CHECK",G.PASTE="PASTE",G.PRESS="PRESS",G.REFRESH="REFRESH",G.REQUEST="REQUEST",G.GRAPHQL_REQUEST="GRAPHQL_REQUEST",G.SCROLL_DOWN="SCROLL_DOWN",G.SCROLL_UP="SCROLL_UP",G.SCROLL_LEFT="SCROLL_LEFT",G.SCROLL_RIGHT="SCROLL_RIGHT",G.SELECT_OPTION="SELECT_OPTION",G.SWITCH_TAB="TAB",G.TYPE="TYPE",G.VISUAL_DIFF="VISUAL_DIFF",G.WAIT="WAIT",G.WAIT_FOR_URL="WAIT_FOR_URL",G.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",G.AWAIT_LISTENER="AWAIT_LISTENER",G.SUCCESS="SUCCESS",G))(Be||{});ye(w);var Y=w.object({thoughts:w.string().optional(),id:w.string().uuid().describe("unique identifier to this step, used for step cache")}),Wt=w.object({useSelector:w.boolean().optional(),force:w.boolean().optional(),disableCache:w.boolean().optional().describe("disable element caching for this step"),iframeUrl:w.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),yn=w.object({target:br}).optional().openapi({ref:"SingleTargetCache"}),Ns=w.object({loadTimeout:w.number().int().max(60).optional().describe("Max seconds for the page to load")}),vx=Y.merge(Ns).merge(w.object({type:w.literal("NAVIGATE"),url:w.string()})).openapi({ref:"NavigateCommand"}),_s=Wt.merge(w.object({cache:yn})),so=Y.merge(_s.merge(w.object({target:dt.optional(),type:w.literal("SCROLL_UP"),deltaY:w.number().optional()}))).openapi({ref:"ScrollUpCommand"}),ao=Y.merge(_s.merge(w.object({target:dt.optional(),type:w.literal("SCROLL_DOWN"),deltaY:w.number().optional()}))).openapi({ref:"ScrollDownCommand"}),lo=Y.merge(_s.merge(w.object({target:dt.optional(),type:w.literal("SCROLL_LEFT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),co=Y.merge(_s.merge(w.object({target:dt.optional(),type:w.literal("SCROLL_RIGHT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollRightCommand"}),G_=w.discriminatedUnion("type",[so,ao,lo,co]).openapi({ref:"AllScrollCommands"}),xx=Y.merge(w.object({type:w.literal("DIALOG"),action:w.union([w.literal("ACCEPT"),w.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),Tx=Y.merge(w.object({type:w.literal("WAIT"),delay:w.number()})).openapi({ref:"WaitCommand"}),Ex=w.discriminatedUnion("type",[w.object({type:w.literal("SUBSTRING"),url:w.string()}),w.object({type:w.literal("GLOB"),glob:w.string()}),w.object({type:w.literal("REGEX"),regex:w.string()})]),Cx=w.object({caseInsensitive:w.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:w.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:w.number().int().optional().describe("Max seconds to wait for the URL to match")}),Rx=Y.extend({type:w.literal("WAIT_FOR_URL"),url:w.string().optional().describe("Deprecated: url or glob to wait for. New commands should use the discriminated matcher field."),matcher:Ex.optional()}).merge(Cx).openapi({ref:"WaitUrlCommand"}),Ax=Y.merge(Ns).merge(w.object({type:w.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),Ix=Y.merge(w.object({type:w.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),Px=Y.merge(w.object({type:w.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),Lx=Y.extend({type:w.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),Ox=Y.extend({type:w.literal("AUTH_LOAD"),storageState:w.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),ac=Y.merge(Wt).extend({type:w.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),kx=Y.extend({type:w.literal("COPY"),value:w.string()}).openapi({ref:"CopyCommand"}),Nx=Y.extend({type:w.literal("PASTE")}).openapi({ref:"PasteCommand"}),_x=Y.merge(Os).extend({type:w.literal("JAVASCRIPT"),envKey:w.string().optional()}).openapi({ref:"JavaScriptCommand"}),gi=Y.merge(Wt).merge(w.object({type:w.literal("CLICK"),target:dt,doubleClick:w.boolean().optional(),rightClick:w.boolean().optional(),waitForUrl:w.string().optional().describe("Deprecated: wait for the click to trigger a page load or new tab that matches the provided URL or URL glob (e.g. https://google.com/**/*)."),waitForDownload:w.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:w.number().optional(),downloadTimeoutMs:w.number().optional(),cache:yn,relativePosition:w.object({x:w.number(),y:w.number()}).optional()})).openapi({ref:"ClickCommand"}),fi=Y.merge(Wt).merge(w.object({type:w.literal("DRAG"),fromTarget:dt,toTarget:dt,steps:w.number().optional(),hoverSeconds:w.number().optional().describe("Seconds to hover the object before dropping"),cache:w.object({fromTarget:br.optional(),toTarget:br.optional()}).optional()})).openapi({ref:"DragCommand"}),Si=Y.merge(Wt).merge(w.object({type:w.literal("MOUSE_DRAG"),target:dt.optional(),deltaX:w.string().describe("pixels to move horizontally, can be template"),deltaY:w.string().describe("pixels to move vertically, can be template"),steps:w.number().optional(),cache:yn})).openapi({ref:"MouseDragCommand"}),yi=Y.merge(Wt).merge(w.object({type:w.literal("HOVER"),target:dt,cache:yn})).openapi({ref:"HoverCommand"}),bi=Y.merge(Wt).merge(w.object({type:w.literal("FOCUS"),target:dt,cache:yn})).openapi({ref:"FocusCommand"}),wi=Y.merge(Wt).extend({type:w.literal("BLUR"),target:dt.optional(),cache:yn}).openapi({ref:"BlurCommand"}),Mx=w.object({type:w.literal("URL"),url:w.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),Fx=w.object({type:w.literal("USER_FILE"),name:w.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),Dx=Y.extend({type:w.literal("FILE_UPLOAD"),fileSource:w.discriminatedUnion("type",[Mx,Fx]),filename:w.string().optional()}).openapi({ref:"FileUploadCommand"}),Ux=w.discriminatedUnion("type",[w.object({type:w.literal("VALUE"),value:w.string()}),w.object({type:w.literal("LABEL"),label:w.string()}),w.object({type:w.literal("INDEX"),index:w.number().int()})]),vi=Y.merge(Wt).extend({type:w.literal("SELECT_OPTION"),target:dt,cache:yn,option:w.string().describe("option value, deprecated old field").optional(),choice:Ux.optional().describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),lc=w.union([w.literal("MULTIMODAL"),w.literal("VISION_ONLY")]),cc=Y.merge(w.object({type:w.literal("AI_ASSERTION"),assertion:w.string(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional(),contextChoice:lc.optional(),timeout:w.number().int().optional().describe("Max seconds to wait for assertion to be true")})).openapi({ref:"AIAssertionCommand"}),Bx=cc.extend({type:w.literal("AI_WAIT")}).openapi({ref:"AIWaitCommand"}),bn=5,dc=600,xi=Y.merge(Wt).extend({type:w.literal("ELEMENT_CHECK"),target:dt,assertion:_u,cache:yn,timeout:w.number().int().min(0).max(dc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),zx=Y.extend({type:w.literal("PAGE_CHECK"),assertion:Mu,iframeUrl:w.string().optional().describe("url or url regex for the iframe"),timeout:w.number().int().min(0).max(dc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),jx=Y.merge(w.object({type:w.literal("AI_EXTRACT"),goal:w.string(),schema:w.string().optional(),envKey:w.string().optional(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional()})).openapi({ref:"AIExtractCommand"}),Hx=w.object({clearContent:w.boolean().optional(),forceClearContent:w.boolean().optional(),pressKeysSequentially:w.boolean().optional().describe("Deprecated: this is now the default. Please set delay to zero if you wish to achieve instant typing behavior."),delay:w.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:w.boolean().optional(),pressEnter:w.boolean().optional()}),Uu=25,Ti=Y.merge(Wt).merge(Hx).extend({type:w.literal("TYPE"),target:dt.optional(),value:w.string(),cache:yn}).openapi({ref:"TypeCommand"}),$x=Y.merge(w.object({type:w.literal("PRESS"),value:w.string(),repeat:w.number().optional(),convertMeta:w.boolean().optional(),delayMs:w.number().optional()})).openapi({ref:"PressCommand"}),Wx=w.object({type:w.literal("SUBSTRING"),substring:w.string()}),Gx=w.object({type:w.literal("REGEX"),pattern:w.string()}),Vx=w.object({type:w.literal("INDEX"),index:w.coerce.string()}),qx=w.discriminatedUnion("type",[Wx,Gx,Vx]),Kx=Y.merge(Ns).merge(w.object({type:w.literal("TAB"),url:w.string().optional().describe("deprecated field - new instances should use the discriminated union"),action:qx.optional()})).openapi({ref:"TabCommand"}),Yx=Y.merge(Ns).merge(w.object({type:w.literal("NEW_TAB"),url:w.string()})).openapi({ref:"NewTabCommand"}),Jx=Y.merge(w.object({type:w.literal("COOKIE"),value:w.string()})).openapi({ref:"CookieCommand"}),Xx=Y.merge(w.object({type:w.literal("LOCAL_STORAGE"),key:w.string(),value:w.string()})).openapi({ref:"LocalStorageCommand"}),Zx=Y.extend({type:w.literal("REQUEST")}).merge(Ls).openapi({ref:"RequestCommand"}),Qx=Y.extend({type:w.literal("GRAPHQL_REQUEST")}).merge(Du).openapi({ref:"GraphQLRequestCommand"}),eT=Y.merge(w.object({type:w.literal("SUCCESS"),condition:cc.optional()})).openapi({ref:"SuccessCommand"}),tT=Y.merge(w.object({type:w.literal("FAILURE")})).openapi({ref:"FailureCommand"}),nT=w.object({data:w.string().describe("location at which to find a jpg"),width:w.number(),height:w.number()}),Ei=Y.merge(Wt).merge(w.object({type:w.literal("VISUAL_DIFF"),threshold:w.number().optional().describe("default 0.1"),target:dt.optional(),screenshot:nT.optional(),cache:yn})).openapi({ref:"VisualDiffCommand"}),rT=Y.merge(w.object({type:w.literal("REGISTER_REQUEST_LISTENER"),pattern:w.string(),key:w.string()})).openapi({ref:"RegisterRequestListenerCommand"}),oT=Y.merge(w.object({type:w.literal("AWAIT_LISTENER"),key:w.string(),timeout:w.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),Bu=w.discriminatedUnion("type",[gi,Ti,$x,vi,vx,ao,so,cc,yi,Tx,eT]),iT=w.discriminatedUnion("type",[Bx,jx,Ox,Lx,ac,Jx,kx,xx,fi,xi,Dx,Ix,Px,_x,Xx,Si,Yx,zx,Nx,Ax,Zx,Qx,lo,co,Kx,Ei,bi,wi,Rx,rT,oT]),po=w.discriminatedUnion("type",[...Bu.options,...iT.options]).openapi({ref:"Command"}),Ms=w.discriminatedUnion("type",[...Bu.options,tT]);function On(n){let e;switch(n){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:Ie(),type:n};break;case"AUTH_LOAD":{e={id:Ie(),type:n,storageState:""};break}case"AI_EXTRACT":e={id:Ie(),type:n,goal:""};break;case"DIALOG":e={id:Ie(),type:n,action:"DISMISS"};break;case"DRAG":e={id:Ie(),type:n,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Ie(),type:n,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Ie(),type:n,url:""};break;case"WAIT":e={id:Ie(),type:n,delay:1};break;case"BLUR":e={id:Ie(),type:n};break;case"HOVER":case"FOCUS":case"CLICK":e={id:Ie(),type:n,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:Ie(),type:n,value:"",clearContent:!0};break;case"SELECT_OPTION":e={id:Ie(),type:n,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":case"TAB":e={id:Ie(),type:n,url:""};break;case"REQUEST":e={id:Ie(),type:n,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:Ie(),type:n,url:"",query:""};break;case"LOCAL_STORAGE":e={id:Ie(),type:n,key:"",value:""};break;case"JAVASCRIPT":e={id:Ie(),type:n,code:""};break;case"AI_WAIT":case"AI_ASSERTION":e={id:Ie(),type:n,assertion:""};break;case"FILE_UPLOAD":{e={id:Ie(),type:n,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Ie(),type:n,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Ie(),type:n,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:Ie(),type:n,pattern:"",key:""};break}case"AWAIT_LISTENER":{e={id:Ie(),type:n,key:""};break}default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return e}function zu(n){switch(n.type){case"BLUR":case"CLICK":case"DRAG":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"PRESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"TYPE":return!0;case"AUTH_LOAD":case"AUTH_SAVE":case"AWAIT_LISTENER":case"SUCCESS":case"AI_ASSERTION":case"AI_WAIT":case"AI_EXTRACT":case"CAPTCHA":case"COOKIE":case"COPY":case"DIALOG":case"ELEMENT_CHECK":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"GRAPHQL_REQUEST":case"JAVASCRIPT":case"LOCAL_STORAGE":case"NAVIGATE":case"NEW_TAB":case"PASTE":case"PAGE_CHECK":case"REGISTER_REQUEST_LISTENER":case"REFRESH":case"REQUEST":case"SELECT_OPTION":case"TAB":case"VISUAL_DIFF":case"WAIT":case"WAIT_FOR_URL":return!1;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}import{z as sT}from"zod";var J_=sT.discriminatedUnion("type",[wi,ac,gi,fi,bi,yi,Si,so,ao,lo,co,vi,Ti,Ei,xi]);function ju(n){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(n)}import{z as aT}from"zod";var Ct={type:!0,cache:!0},wr=aT.discriminatedUnion("type",[wi.pick(Ct),gi.pick(Ct),fi.pick(Ct),xi.pick(Ct),bi.pick(Ct),yi.pick(Ct),Si.pick(Ct),so.pick(Ct),ao.pick(Ct),lo.pick(Ct),co.pick(Ct),vi.pick(Ct),Ti.pick(Ct),Ei.pick(Ct)]),pc=Object.values(Be).filter(n=>wr.options.some(e=>e.shape.type.safeParse(n).success));po.options.forEach(n=>{if("target"in n.shape&&!pc.includes(n.shape.type.value))throw new Error(`Command ${n.shape.type.value} has a target but no cache`)});import{z as mc}from"zod";import{z as uc}from"zod";import{z as uo}from"zod";var Rt=uo.object({index:uo.number().optional().describe("global index within a test (in-order traversal)"),id:uo.string(),skipped:uo.boolean().optional(),envKey:uo.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:uo.boolean().optional()});ye(uc);var At=Rt.extend({type:uc.literal("PRESET_ACTION"),command:po,skipped:uc.boolean().optional()}).openapi({ref:"PresetAction"});ye(mc);var vr=Rt.extend({type:mc.literal("AI_ACTION"),text:mc.string(),steps:At.array().optional()}).openapi({ref:"AIAction"});import{z as se}from"zod";var lT=se.object({cacheKey:se.string(),cacheExpiryMs:se.number()}),hc=Rt.extend({id:se.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:se.record(se.string()).optional(),cacheConfig:lT.optional()}),kn=hc.extend({type:se.literal("MODULE"),moduleId:se.string().uuid()}),cT=se.union([kn.pick({type:!0,moduleId:!0}),se.record(se.unknown())]),dT=se.object({type:se.literal("URL_REGEX"),regex:se.string()}),pT=se.object({type:se.literal("PAGE_CHECK"),substring:se.string()}),gc=se.object({cacheInvalidation:se.discriminatedUnion("type",[pT,dT]).optional()}),It=se.object({moduleId:se.string().uuid(),name:se.string(),description:se.string().nullish(),enabled:se.boolean().nullish(),parameters:se.string().array().nullish(),defaultParameters:se.record(se.string(),se.string()).nullish(),defaultCacheKey:se.string().nullish(),defaultCacheTtl:se.number().nullish(),defaultCacheAllInvocations:se.boolean().nullish(),autoAuth:se.boolean().nullish(),advanced:gc.nullish()});import{z as ot}from"zod";import{z as fc}from"zod";ye(fc);var mo=Rt.extend({type:fc.literal("AI_ACTION_DYNAMIC"),text:fc.string()}).openapi({ref:"AIActionDynamic"});import{z as Hu}from"zod";var Sc=Rt.extend({type:Hu.literal("CONDITIONAL"),skipped:Hu.boolean().optional()});import{z as Fs}from"zod";var uT=Fs.object({type:Fs.literal("url"),url:Fs.string()}),Ci=Rt.extend({type:Fs.literal("IFRAME"),identifier:uT});import{z as Gt}from"zod";var yc=(r=>(r.ALWAYS="ALWAYS",r.ON_FAILURE="ON_FAILURE",r.ON_ACTION_FAILURE="ON_ACTION_FAILURE",r))(yc||{});var mT=Gt.discriminatedUnion("type",[Gt.object({type:Gt.literal("NAVIGATE_URL"),url:Gt.string().url()}),Gt.object({type:Gt.literal("GO_TO_SECTION_START")})]),hT=Gt.object({trigger:Gt.nativeEnum(yc).optional(),attempts:Gt.number().int().optional(),restartBehavior:mT}),Ri=Rt.extend({type:Gt.literal("SECTION"),description:Gt.string().describe("user provided goal of what the section should accomplish"),plan:Gt.string().array().optional(),autohealingConfig:hT.optional()});var $u=It.merge(hc).extend({type:ot.literal("RESOLVED_MODULE"),steps:ot.lazy(()=>ve.array())}),bc=It.extend({steps:ot.lazy(()=>ve.array())}),wc=Ci.extend({steps:ot.lazy(()=>Ke.array())}),gT=Ci.extend({steps:ot.lazy(()=>ve.array())}),vc=Ri.extend({steps:ot.lazy(()=>Ke.array())}),fT=Ri.extend({steps:ot.lazy(()=>ve.array())}),xr=Sc.extend({blocks:ot.object({assertion:ot.lazy(()=>At),steps:ot.lazy(()=>Ke.array())}).array(),elseSteps:ot.lazy(()=>Ke.array().optional())}),ST=Sc.extend({blocks:ot.object({assertion:ot.lazy(()=>At),steps:ot.lazy(()=>ve.array())}).array(),elseSteps:ot.lazy(()=>ve.array().optional())}),Ke=ot.discriminatedUnion("type",[At,vr,mo,kn,xr,wc,vc]),ve=ot.discriminatedUnion("type",[At,vr,mo,$u,ST,gT,fT]);import{z as Vt}from"zod";var yT=Vt.object({steps:Ke.array(),beforeSteps:Ke.array().nullish(),afterSteps:Ke.array().nullish()}),ho=Vt.object({steps:ve.array(),beforeSteps:ve.array().nullish(),afterSteps:ve.array().nullish()}),Tr=Vt.object({steps:Vt.record(Vt.string(),Vt.unknown()).array(),beforeSteps:Vt.record(Vt.string(),Vt.unknown()).array().nullish(),afterSteps:Vt.record(Vt.string(),Vt.unknown()).array().nullish()});var He="1.0.19";import{z as Er}from"zod";var xc=Er.object({key:Er.string(),testId:Er.string().optional(),moduleId:Er.string().optional(),organizationId:Er.string(),value:wr}),Wu=Er.record(Er.string(),xc);var Gu=k.object({phrase:k.string()}),Tc=k.object({thoughts:k.string().optional(),result:k.union([k.literal("NOT_FOUND"),k.string(),k.number(),k.array(k.unknown()),k.record(k.unknown(),k.unknown()),k.unknown()])}),YF=k.object({text:k.string()}),Vu=k.object({thoughts:k.string(),review:k.string().optional(),id:k.number().int()}),Ds=(u=>(u.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",u.FEW_WORDS="FEW_WORDS",u.STYLE_TAG="STYLE_TAG",u.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",u.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",u.NONE="NONE",u.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",u.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",u.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",u.PREFER_ASSERTION="PREFER_ASSERTION",u.HTML_ELEMENTS="HTML_ELEMENTS",u.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",u))(Ds||{});var qu=k.object({thoughts:k.string(),category:k.nativeEnum(Ds)}),bT=k.discriminatedUnion("op",[k.object({op:k.literal("replace"),path:k.string(),value:k.string()}),k.object({op:k.literal("add"),path:k.string(),value:k.string()}),k.object({op:k.literal("remove"),path:k.string()})]),JF=k.object({thoughts:k.string(),patches:bT.array()}),Ku=[k.literal("add"),k.literal("replace"),k.literal("remove")],wT=k.object({op:k.union(Ku),path:k.string(),value:ve.optional()}),Yu=k.object({patches:wT.array(),thoughts:k.string()});var vT=k.object({thoughts:k.string(),op:k.union(Ku),value:k.union([k.null(),ve])}),Ju=k.object({reasoning:k.string(),scenario:k.string(),patch:vT.or(k.null())}),XF=k.object({thoughts:k.string(),evaluation:k.number().min(1).max(10)}),ZF=k.object({observations:k.string(),reasoning:k.string(),command:Ms});var Ec=k.object({summary:k.string(),reasoning:k.string(),evaluation:k.discriminatedUnion("type",[k.object({type:k.literal("DONE")}),k.object({type:k.literal("RIGHT_TRACK")}),k.object({type:k.literal("WRONG_TRACK"),feedback:k.string()}),k.object({type:k.literal("IMPOSSIBLE")})])});import{z as F}from"zod";import*as te from"zod";var oD=te.object({thoughts:te.string().optional().describe("only provided if a description was provided"),target:br.optional().describe("only provided if a description was provided"),pageState:te.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:te.object({label:te.string(),value:te.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:te.object({data:te.string(),height:te.number().int(),width:te.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Xu=te.union([te.literal("NEGATED_CHECK"),te.literal("SELECT_OPTION"),te.literal("TYPE")]);function Ai(n){if(!("useSelector"in n&&n.useSelector)){if(n.type==="SELECT_OPTION")return"SELECT_OPTION";if(n.type==="TYPE")return"TYPE";if(n.type==="ELEMENT_CHECK"&&n.assertion.type==="ELEMENT_EXISTENCE"&&n.assertion.negated)return"NEGATED_CHECK"}}var Ii=(s=>(s.A11Y_ID="A11Y_ID",s.USER_SELECTOR="USER_SELECTOR",s.CSS_SELECTOR="CSS_SELECTOR",s.HTML_DISTANCE="HTML_DISTANCE",s.TEMPLATE_MATCHING="TEMPLATE_MATCHING",s.AUTO_FRAME="AUTO_FRAME",s))(Ii||{}),go=te.object({matched:te.boolean(),reason:te.string().optional().describe("Human understandable description"),logs:te.string().array().optional().describe("Logs for debugging")}),xT=go.extend({type:te.literal("A11Y_ID")}),TT=go.extend({type:te.literal("USER_SELECTOR")}),ET=go.extend({type:te.literal("CSS_SELECTOR"),selectors:te.string().array()}),CT=go.extend({type:te.literal("HTML_DISTANCE"),distance:te.number().optional(),closestElement:te.string().optional(),savedElement:te.string().optional()}),RT=go.extend({type:te.literal("TEMPLATE_MATCHING"),elementImageUrl:te.string().url()}),AT=go.extend({type:te.literal("AUTO_FRAME"),logs:te.string().array().optional()}),Zu=te.discriminatedUnion("type",[xT,TT,ET,CT,RT,AT]);import{z as _i}from"zod";import{z as YE}from"zod";import*as J from"zod";import{cloneDeep as Oi}from"lodash-es";var IT=n=>{let e=Qu(n,0);if(e===void 0||!LT(n[e]))return;let t=Qu(n,e+1);if(t!==void 0)return OT(n,e,t)},em=IT,Qu=(n,e)=>{for(let t=e;t<n.length;t+=1){let r=n[t];if(!PT(r))return t}},PT=n=>n===" "||n===" "||n===`
5
5
  `||n==="\r",LT=n=>n==="{"||n==="[",OT=(n,e,t)=>{let r;for(let o=t-1;o>e;o-=1){let i=n[o];if(i==="\r")return;if(i===`
6
6
  `)return kT(r);if(r===void 0)r=i;else if(r[0]===i)r+=i;else return}},kT=n=>n===void 0?0:n[0]===" "?n.length:n;var tm=(n,e)=>{let t=Cc(n,"toPrecision",e,e);return t===void 0?Cc(n,"toExponential",e,e):t},Cc=(n,e,t,r)=>{let i=n[e](r).replace(NT,"$1").replace(_T,"$1");return i.length<=t?i:r===1?void 0:Cc(n,e,t,r-1)},NT=/(e)\+/iu,_T=/\.?0*($|e)/iu;var rm=(n,e)=>{if(typeof n!="string")throw new TypeError(`Input must be a JSON string: ${n}`);MT(e)},MT=n=>{if(FT(n),n<0)throw new TypeError(`"maxSize" argument must be positive: ${n}`);if(n<nm)throw new TypeError(`"maxSize" argument must be at least ${nm}: ${n}`)},FT=n=>{if(n===void 0)throw new TypeError('"maxSize" argument must be defined');if(!Number.isInteger(n))throw new TypeError(`"maxSize" argument must be an integer: ${n}`)},nm=7;var Us=(n,e,t)=>{let r=im(e,t);return om(n,e,r)},om=(n,e,t)=>{if(t>=e)return t;let r=n[t];return r>=GT&&r<=VT?om(n,e,t+1):t},Bs=(n,e,t)=>{if(t===void 0)return t;let r=im(e,t);return DT(n,r)},DT=(n,e)=>UT(n,e)?e-3:BT(n,e)?e-2:zT(n,e)?e-1:e,UT=(n,e)=>e>=3&&n[e-3]>=jT&&n[e-3]<=HT,BT=(n,e)=>e>=2&&n[e-2]>=$T,zT=(n,e)=>e>=1&&n[e-1]>=WT,im=(n,e)=>e<0||Object.is(e,-0)?Math.max(n+e,0):e,jT=240,HT=244,$T=224,WT=194,GT=128,VT=191;var sm=(n,e,t)=>{let r=globalThis.Buffer.from(n),o=Us(r,r.length,e),i=Bs(r,r.length,t);return o===0&&i>=r.length?r.toString():r.toString("utf8",o,i)};var am=/[\uD800-\uDFFF]/gu,lm="\uFFFD";var zs=n=>qT(n)?n.replace(am,lm):n,qT=n=>{for(let e=0;e<n.length;e+=1){let t=n.codePointAt(e);if(t>=55296&&t<=57343)return!0}return!1};var Ic=({input:n,targetByteCount:e,firstStartSurrogate:t,lastStartSurrogate:r,firstEndSurrogate:o,lastEndSurrogate:i,increment:s,canBacktrack:a,shift:l,charIndexInit:c})=>{let p=c,d=p,u=0;for(;u<e;p+=s){d=p;let h=n.charCodeAt(p);if(Number.isNaN(h))break;if(h<=127){u+=1;continue}if(h<=2047){u+=2;continue}if(u+=3,h<t||h>r)continue;let g=n.charCodeAt(p+s);Number.isNaN(g)||g<o||g>i||(u+=1,p+=s)}return(a&&u>e?d:p)+l};var Pc=(n,e,t)=>e<0||Object.is(e,-0)?QT(n,e,t):ZT(n,e,t),ZT=(n,e,t)=>Ic({input:n,targetByteCount:e,firstStartSurrogate:55296,lastStartSurrogate:56319,firstEndSurrogate:56320,lastEndSurrogate:57343,increment:1,canBacktrack:t,shift:0,charIndexInit:0}),QT=(n,e,t)=>Ic({input:n,targetByteCount:-e,firstStartSurrogate:56320,lastStartSurrogate:57343,firstEndSurrogate:55296,lastEndSurrogate:56319,increment:-1,canBacktrack:!t,shift:1,charIndexInit:n.length-1});var js=(n,e,t)=>{let r=Pc(n,e,!1),o=eE(n,t),i=r===0&&o===void 0?n:n.slice(r,o);return zs(i)},eE=(n,e)=>{if(e===void 0)return e;let t=Pc(n,e,!0);return t===n.length?void 0:t};var dm=(n,e,t)=>{let{textEncoder:r,textDecoder:o}=tE(),i=nE(n),{written:s}=r.encodeInto(n,i),a=Us(i,s,e),l=Bs(i,s,t),c=l===void 0?s:Math.min(l,s),p=i.subarray(a,c);return o.decode(p)},tE=()=>(Lc===void 0&&(Lc=new globalThis.TextEncoder,cm=new globalThis.TextDecoder("utf8",{fatal:!1})),{textEncoder:Lc,textDecoder:cm}),Lc,cm,nE=n=>{let e=n.length*3;return e>rE?new Uint8Array(e):((Hs===void 0||Hs.length<e)&&(Hs=new Uint8Array(e)),Hs)},rE=1e5,Hs;var pm=(n,e)=>{if(e===void 0)return e;let t=Oc(n,e);return t>=n.length*um?void 0:t},Oc=(n,e)=>e<=n.length*-um?0:e,um=4;var mm=(n,e,t)=>{if(typeof n!="string")throw new TypeError(`First argument must be a string: ${n}`);oE(e),iE(t)},oE=n=>{if(n===void 0)throw new TypeError("Second argument is required.");hm("Second",n)},iE=n=>{n!==void 0&&hm("Third",n)},hm=(n,e)=>{if(!Number.isInteger(e))throw new TypeError(`${n} argument must be an integer: ${e}`)};var gm=n=>{let e=!0,t=0;for(let r=0;r<kc;r+=1){let o=sE(n,r);o<=127||(e&&(e=!1),o>2047&&(t+=1))}return{asciiOnly:e,longCharsPercentage:t/kc}},sE=(n,e)=>{let t=kc-1,r=1-(t-e)/t,o=Math.round(r*(n.length-1));return n.charCodeAt(o)},kc=50;var aE=(n,e,t)=>{if(mm(n,e,t),n==="")return n;let r=Oc(n,e),o=pm(n,t);return o===void 0&&Object.is(r,0)?zs(n):lE(n,r,o)},fm=aE,lE=(n,e,t)=>{if(n.length<=cE)return js(n,e,t);let{asciiOnly:r,longCharsPercentage:o}=gm(n);return r?pE(n,e,t):o>=dE?js(n,e,t):Sm(n,e,t)},cE=200,dE=.4,pE=(n,e,t)=>"Buffer"in globalThis&&"from"in globalThis.Buffer?sm(n,e,t):Sm(n,e,t),Sm=(n,e,t)=>"TextEncoder"in globalThis?dm(n,e,t):js(n,e,t);var bm=(n,e)=>{let t=JSON.stringify(n),r=hE(t),o=fm(r,0,e-ym.length-Pi.length*2),s=`${uE(o)}${ym}`;return gE(s)},uE=n=>n.replace(mE,""),mE=/(\\|\\u[0-9a-fA-F]{0,3})$/u,hE=n=>n.slice(Pi.length,-Pi.length),gE=n=>`${Pi}${n}${Pi}`,Pi='"',ym="...";var wm=n=>globalThis.Buffer.byteLength(n);var Nc=n=>{let e=n.length,t=e;for(let r=0;r<e;r+=1){let o=n.charCodeAt(r);if(o<=fE)continue;if(o<=SE){t+=1;continue}if(t+=2,o<yE||o>bE)continue;let i=n.charCodeAt(r+1);i<wE||i>vE||(r+=1)}return t},fE=127,SE=2047,yE=55296,bE=56319,wE=56320,vE=57343;var vm=()=>xE.bind(void 0,new TextEncoder),xE=(n,e)=>{let t=TE(e);return n.encodeInto(e,t).written},TE=n=>{let e=n.length*3;return e>EE?new Uint8Array(e):(($s===void 0||$s.length<e)&&($s=new Uint8Array(e)),$s)},EE=1e5,$s;var RE=()=>"Buffer"in globalThis&&"byteLength"in globalThis.Buffer?wm:"TextEncoder"in globalThis?AE.bind(void 0,vm()):Nc,AE=(n,e)=>e.length<100?Nc(e):n(e),xm=RE();var Tm=n=>{if(n===null)return IE;if(n===!0)return PE;if(n===!1)return LE;let e=typeof n;return e==="object"?OE:e==="number"?JSON.stringify(n).length:_c(n)},IE=4,PE=4,LE=5,OE=2,_c=n=>xm(JSON.stringify(n));var Ws=({size:n,increment:e,maxSize:t,truncatedProps:r,path:o,value:i})=>{let s=n+e,a=s>t;return a?{size:n,stop:a,truncatedProps:[...r,{path:o,value:i}]}:{size:s,stop:a,truncatedProps:r}},Cm=n=>Tm(n),Rm=(n,e,t)=>{let r=Im({empty:n,indent:e,depth:t,keySpaceSize:0}),o=Pm(n);return r+o},Am=({key:n,empty:e,indent:t,depth:r})=>{let o=Im({empty:e,indent:t,depth:r,keySpaceSize:1}),i=_c(n),s=Pm(e);return o+i+kE+s},kE=1,Im=({empty:n,indent:e,depth:t,keySpaceSize:r})=>{if(e===void 0)return 0;let o=Em+e*(t+1),i=n?Em+e*t:0;return r+o+i},Em=1,Pm=n=>n?0:NE,NE=1;var Gs=({parent:n,truncatedProps:e,path:t,increment:r,maxSize:o,key:i,empty:s,size:a,truncateValue:l,indent:c,depth:p})=>{let d=n[i],u=[...t,i],{size:m,stop:h,truncatedProps:g}=Ws({size:a,increment:r,maxSize:o,truncatedProps:e,path:u,value:d});return h?{empty:s,size:m,truncatedProps:g}:_E({value:d,truncatedProps:e,path:u,maxSize:o,empty:s,size:a,newSize:m,truncateValue:l,indent:c,depth:p})},_E=({value:n,truncatedProps:e,path:t,maxSize:r,empty:o,size:i,newSize:s,truncateValue:a,indent:l,depth:c})=>{let{value:p,size:d,truncatedProps:u}=a({value:n,truncatedProps:e,path:t,size:s,maxSize:r,indent:l,depth:c+1});return p===void 0?{empty:o,size:i,truncatedProps:u}:{empty:!1,size:d,value:p,truncatedProps:u}};var Lm=({array:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:i,indent:s,depth:a})=>{let l=[],c={empty:!0,size:r,truncatedProps:e};for(let p=0;p<n.length;p+=1){let d=Rm(c.empty,s,a);c=Gs({parent:n,truncatedProps:c.truncatedProps,path:t,increment:d,maxSize:o,key:p,empty:c.empty,size:c.size,truncateValue:i,indent:s,depth:a}),c.value!==void 0&&l.push(c.value)}return{value:l,size:c.size,truncatedProps:c.truncatedProps}};var Om=({object:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:i,indent:s,depth:a})=>{let l={},c={empty:!0,size:r,truncatedProps:e};for(let p in n){let d=Am({key:p,empty:c.empty,indent:s,depth:a});c=Gs({parent:n,truncatedProps:c.truncatedProps,path:t,increment:d,maxSize:o,key:p,empty:c.empty,size:c.size,truncateValue:i,indent:s,depth:a}),c.value!==void 0&&(l[p]=c.value)}return{value:l,size:c.size,truncatedProps:c.truncatedProps}};var Vs=({value:n,truncatedProps:e,path:t,size:r,maxSize:o,indent:i,depth:s})=>{let a=Cm(n),{size:l,stop:c,truncatedProps:p}=Ws({size:r,increment:a,maxSize:o,truncatedProps:e,path:t,value:n});return c?{value:void 0,size:l,truncatedProps:p}:ME({value:n,truncatedProps:p,path:t,size:l,maxSize:o,indent:i,depth:s})},ME=({value:n,truncatedProps:e,path:t,size:r,maxSize:o,indent:i,depth:s})=>typeof n!="object"||n===null?{value:n,size:r,truncatedProps:e}:Array.isArray(n)?Lm({array:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:Vs,indent:i,depth:s}):Om({object:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:Vs,indent:i,depth:s});var FE=(n,e)=>{rm(n,e);let t=DE(n),r=UE(n),{value:o,truncatedProps:i}=Vs({value:r,truncatedProps:[],path:[],size:0,maxSize:e,indent:t,depth:0});return{jsonString:BE({newValue:o,value:r,maxSize:e,indent:t}),truncatedProps:i}},Li=FE,DE=n=>{let e=em(n);return typeof e=="string"?e.length:e},UE=n=>{try{return JSON.parse(n)}catch(e){throw new TypeError(`Invalid JSON string: "${n}"
@@ -11,7 +11,7 @@ ${this.decisions.map(e=>e.toString()).join(`
11
11
  `).map((p,d)=>d>0?` ${p}`:p).join(`
12
12
  `)),console.log(t(` ${a}:`,c))}}else if(o)for(let s of o){let a=s;typeof s=="object"&&(a=JSON.stringify(s,void 0,2),a=a.split(`
13
13
  `).map((l,c)=>c>0?` ${l}`:l).join(`
14
- `)),console.log(" ",t(a))}}setMinLevel(e){this.minLogLevel=e}log(...e){this.logWithLevel(1,wn.reset,...e)}info(...e){this.logWithLevel(1,wn.blue,...e)}debug(...e){this.logWithLevel(0,wn.dim,...e)}warn(...e){this.logWithLevel(2,wn.yellow,...e)}error(...e){this.logWithLevel(3,wn.red,...e)}success(...e){this.logWithLevel(4,wn.green,...e)}dimmed(...e){this.logWithLevel(1,wn.dim,...e)}underline(...e){this.logWithLevel(2,wn.underline,...e)}bold(...e){this.logWithLevel(2,wn.bold,...e)}grey(...e){this.logWithLevel(0,wn.grey,...e)}child(e){return new n(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},y=new Qc(1,{}),kr={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>kr,flush:()=>{},bindings:()=>({})},wa={},Nr=({logger:n,logKey:e,maxCount:t,intervalMs:r},o,i,...s)=>{let a=wa[e];a?clearTimeout(a.timer):(a={count:0,totalCount:0},wa[e]=a),a.totalCount++,a.count<t&&(a.count++,n.debug(o,i,...s)),a.timer=setTimeout(()=>{let l=wa[e];l?.totalCount!==l?.count&&n.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete wa[e]},r)};import{z as Je}from"zod";var Mh=Je.object({id:Je.string(),createdAt:Je.coerce.date(),createdBy:Je.string(),organizationId:Je.string(),name:Je.string(),description:Je.string().nullish(),enabled:Je.boolean(),schemaVersion:Je.string().describe("Schema version for steps"),parameters:Je.string().array().nullish().describe("Parameter list"),defaultParameters:Je.record(Je.string(),Je.string()).nullish(),defaultCacheKey:Je.string().nullish(),defaultCacheTtl:Je.number().nullish(),defaultCacheAllInvocations:Je.boolean().nullish(),autoAuth:Je.boolean().nullish(),advanced:gc.nullish()}),zz=Mh.extend({steps:Je.lazy(()=>Ke.array())}),Fh=5*60*1e3,ed=It.merge(Mh.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as $z}from"date-fns-tz";import{z as _n}from"zod";var td=_n.object({failureRecovery:_n.boolean().optional(),aiAction:_n.boolean().optional()}),Vz=_n.object({ai:td.optional(),githubAppInstallationId:_n.number().nullish(),githubReleaseAppInstallationId:_n.number().nullish(),gitlabAppAccessToken:_n.string().nullish().optional(),gitlabAppBaseUrl:_n.string().nullish().optional(),qaseAccessToken:_n.string().nullish().optional()});import*as T from"zod";var lj=T.object({error:T.boolean(),reason:T.string(),message:T.string()}),cj=qt.merge(Hc),Dh=Ms,dj=qt.merge(Hc);var pj=qt.merge(Xm).extend({useConsensus:T.boolean().optional(),attemptNumber:T.number().optional()}),nd=Nu,uj=qt.merge(Zm),Uh=qu,mj=qt.merge(Km),Bh=Vu,hj=qt.merge(Ym),zh=Gu,gj=qt.merge(Jm);var fj=T.object({testPaths:T.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:T.string().optional(),all:T.boolean().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional(),testInputMatrix:T.record(T.string(),T.string()).array().optional()}),jh=T.object({queuedTests:T.unknown().array(),runIds:T.string().uuid().array(),runGroupId:T.string().optional()}),Hh=Hi,$h=T.string().array(),Sj=T.union([T.object({paths:T.string().array().describe("run specific test paths (e.g. todo-test)"),all:T.boolean().describe("run all tests").optional()}),T.object({path:T.string().describe("deprecated; present for backcompat")})]),Wh=T.object({tests:T.record(T.string().describe("Test name"),T.string().describe("Test YAML")),modules:T.record(T.string().describe("Module name"),T.string().describe("Module YAML"))}),eR=T.object({test:T.string().describe("test YAML"),modules:T.record(T.string().describe("moduleId"),T.string().describe("module YAML"))}),yj=eR.array(),bj=T.object({testId:T.string(),schemaVersion:T.string()}).merge(Tr),wj=T.object({entries:T.array(xc),testId:T.string()}),vj=T.object({steps:T.array(T.record(T.unknown())),testId:T.string(),schemaVersion:T.string(),organizationId:T.string()}),Gh=Wu,Vh=T.object({trigger:T.nativeEnum(Lt),status:T.nativeEnum(re),startedAt:T.coerce.date().optional(),gitCommitSha:T.string().optional(),gitCommitShaShort:T.string().optional(),gitCommitTimestamp:T.coerce.date().optional(),gitBranchName:T.string().optional(),gitOriginUrl:T.string().optional(),gitCommitMessage:T.string().optional(),gitCommitAuthorName:T.string().optional(),githubRepository:T.string().optional(),gitlabProjectPath:T.string().optional(),pipelineId:T.string().optional(),cliVersion:T.string().optional()}),qh=T.object({id:T.string()}),Kh=T.object({status:T.nativeEnum(re),updatedAt:T.coerce.date().optional(),finishedAt:T.coerce.date().optional()}),Yh=T.object({stepsSnapshot:T.array(T.record(T.unknown())).optional(),runGroupId:T.string().optional(),testId:T.string(),testName:T.string(),resolvedBaseUrl:T.string().optional(),environmentName:T.string().optional(),labels:T.array(T.string()).optional(),cliVersion:T.string().optional(),trigger:T.nativeEnum(Lt),schemaVersion:T.string().optional(),section:T.nativeEnum(ca).optional()}),Jh=T.object({id:T.string()}),tR=jc.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Xh=tR.array(),Zh=jc.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),Qh=T.object({id:T.string()}),eg=T.object({status:T.nativeEnum(re),finishedAt:T.coerce.date().optional()}).merge(na),xj=T.object({screenshot:T.string()}),tg=T.object({key:T.string()}),ng=T.object({orgId:T.string(),userId:T.string()}),rg=T.array(Ks),og=T.record(T.string(),T.union([T.string(),T.boolean()])),Tj=T.object({paths:T.string().array(),env:T.string().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional()}),ig=T.object({suiteRunIds:T.string().array(),runGroupIds:T.string().array()}),Ej=T.object({suiteRunIds:T.string().array()}),sg=qm.array(),Cj=T.object({runGroupIds:T.string().array()}),To=T.object({uploadUrl:T.string()}),Rj=qt.merge(Qm),Aj=qt.merge(th),Ij=qt.merge(eh),nR=T.object({testId:T.string().optional().default(""),testName:T.string().optional().default(""),suiteId:T.string().optional().default(""),suiteName:T.string().optional().default(""),creditsUsed:T.number().optional(),usedBy:T.string().optional()}),rR=T.object({transactionId:T.string(),timestamp:T.string(),event:T.nativeEnum(Lr),properties:nR}),Pj=rR.array(),ag=Mm.omit({steps:!0}).extend({steps:T.array(T.record(T.string(),T.unknown())).describe("unparsed ResolvedStep[]")}),Lj=T.object({limit:T.number().max(10).optional(),afterTime:T.number().optional()}),lg=Hm.array(),Oj=T.object({applied:T.boolean().optional(),appliedAt:T.coerce.date().optional()}),kj=qt.extend({chunks:$c.array(),description:T.string().describe("Input to pass to AI"),type:T.union([T.literal("locator"),T.literal("assertion"),T.literal("ai-action")]),softTokenLimit:T.number(),hardTokenLimit:T.number()}),cg=To.extend({id:T.string()}),dg=T.object({runGroupId:T.string()}),pg=T.object({featureFlags:T.record(T.string(),T.boolean().or(T.string())),featureFlagPayloads:T.record(T.string(),ba)});import{z as Te}from"zod";var ug=Te.object({orgId:Te.string(),cacheKeys:Te.string().array()}),Mj=Te.object({keyParams:ug,clientMetadata:Te.string(),lockAcquisitionTimeoutMs:Te.number().optional()}),mg=Te.object({acquired:Te.boolean(),acquiredByMetadata:Te.string(),keyPrefix:Te.string()}),Fj=Te.object({keyPrefix:Te.string(),result:Te.string(),ttlMs:Te.number()}),Dj=Te.union([Te.object({keyPrefix:Te.string()}),ug]),oR=Te.object({remainingTtlMs:Te.number(),value:Te.string().nullish()}),Uj=Te.object({results:Te.record(Te.string(),oR),activeLocks:Te.string().array()}),hg=0,gg=5*60*1e3;import{z as sn}from"zod";var fg="test",Sg="module",_t=(t=>(t.TEST=`${fg}.yaml`,t.MODULE=`${Sg}.yaml`,t))(_t||{}),he=(o=>(o.TEST=`momentic/${fg}`,o.MODULE=`momentic/${Sg}`,o.FIXTURE="momentic/fixture",o.ENVIRONMENT="momentic/environment",o))(he||{}),Vj=Nt.merge(Tr),rd=It.extend({steps:sn.array(sn.record(sn.string(),sn.unknown())),schemaVersion:sn.string()}),qj=rd.extend({fileType:sn.literal(he.MODULE)}),Kj=sn.object({test:sn.string().describe("YAML for the test, including metadata and steps"),modules:sn.record(sn.string(),sn.string()).describe("Map of module name to YAML for the module")});import{z as it}from"zod";var iR=it.object({version:it.string(),json:it.record(it.unknown()),hash:it.string()}),yg=it.record(it.unknown()),Zj=it.object({newSvgs:it.array(iR),metadata:yg.optional()}),sR=it.object({version:it.string(),json:it.record(it.unknown()).nullish(),hash:it.string(),description:it.string().nullish(),metadata:yg.nullish()}),bg=it.record(it.string().describe("icon hash"),sR);import{validator as rH}from"@exodus/schemasafe";var wg=n=>{n.extraHeaders&&(n.extraHeaders=Object.fromEntries(Object.entries(n.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as gH}from"zod";import{z as Xn}from"zod";var yH=Xn.object({repositoriesIndexed:Xn.boolean(),indexingInProgress:Xn.boolean(),indexesOutdated:Xn.boolean()}),vg=(s=>(s.Queued="queued",s.InProgress="in_progress",s.Completed="completed",s.Waiting="waiting",s.Requested="requested",s.Pending="pending",s))(vg||{}),xg=(a=>(a.Success="success",a.Failure="failure",a.Neutral="neutral",a.Cancelled="cancelled",a.Skipped="skipped",a.TimedOut="timed_out",a.ActionRequired="action_required",a))(xg||{}),bH=Xn.object({name:Xn.string(),status:Xn.nativeEnum(vg),conclusion:Xn.nativeEnum(xg).nullable()});import{z as Oe}from"zod";var od=Oe.object({assertion:Oe.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),aR=Oe.object({instruction:Oe.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:od.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),Tg=aR.extend({subSteps:Oe.lazy(()=>Tg.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Eg=Oe.object({name:Oe.string().describe("Short name describing the test plan"),description:Oe.string().nullish().transform(n=>n??void 0).describe("Longer form description of the high level goal of the test plan")}),Cg=Eg.extend({id:Oe.string(),createdAt:Oe.coerce.date(),updatedAt:Oe.coerce.date(),updatedBy:Oe.string(),createdBy:Oe.string(),test:Oe.object({id:Oe.string(),name:Oe.string()}).nullish().transform(n=>n??void 0)}),TH=Cg.extend({testGenRuns:Oe.tuple([]).or(Oe.tuple([Oe.object({id:Oe.string(),startedAt:Oe.coerce.date(),status:Oe.nativeEnum(re)})]))}),Rg=Oe.object({preConditions:od.array().nullish().transform(n=>n??[]),postConditions:od.array().nullish().transform(n=>n??[]),steps:Tg.array().nullish().transform(n=>n??[])}),EH=Cg.extend({plan:Rg.nullish().transform(n=>n??{preConditions:[],postConditions:[],steps:[]})}),lR=Eg.extend({plan:Rg.nullish().transform(n=>n??{preConditions:[],postConditions:[],steps:[]})}),CH=lR.array().nullish().transform(n=>n??[]);import{z as Ee}from"zod";var cR=Ee.object({step:ve,status:Ee.nativeEnum(re),startedAt:Ee.coerce.date(),finishedAt:Ee.coerce.date().optional(),healMetadata:Ee.object({healType:Ee.nativeEnum(Ii).or(Ee.literal("AI")),healedAt:Ee.coerce.date()}).optional(),beforeSnapshotId:Ee.string().uuid().optional(),afterSnapshotId:Ee.string().uuid().optional(),message:Ee.string().optional()}),_H=cR.extend({status:Ee.nativeEnum(xe),finishedAt:Ee.coerce.date()}),dR=Ee.object({startedAt:Ee.coerce.date()}).merge(eg),MH=dR.extend({finishedAt:Ee.coerce.date()}),pR=Zh.merge(Yh).extend({startedAt:Ee.coerce.date(),attempts:Ee.number()}),FH=pR.extend({status:Ee.nativeEnum(re),finishedAt:Ee.coerce.date()}),uR=Vh.merge(Kh).extend({startedAt:Ee.coerce.date(),cliVersion:Ee.string()}),id=uR.extend({updatedAt:Ee.coerce.date(),finishedAt:Ee.coerce.date()});var M="v1",Wi="1.1.10";var mR=9e4,hR=15e3,an=class extends Error{status;rawError;constructor(e,t,r,o={}){super(r,o),this.status=e,this.rawError=t}};async function gR(n){return n.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var sd=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Wi&&(e["X-MOMENTIC-CLI-VERSION"]=Wi),e}async sendRequest(e,t,r=3,o=mR){let i=r,s,a={path:e,baseUrl:this.baseUrl,method:t.method};for(;r>0;)try{return r--,await this.sendSingleRequestHelper(e,t,o)}catch(l){if(s=l,this.logger&&this.logger.warn({...a,err:l},`Got error response from Momentic server${r>0?", retrying":""}`),l instanceof an&&l.status>=400&&l.status<500||r===0)throw l;let c=1500,p=i-r,d=Math.min(c*Math.pow(2,p-1),hR);await new Promise(u=>setTimeout(u,d))}throw s}async sendSingleRequestHelper(e,t,r){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,s=setTimeout(()=>i.abort(),r),a=()=>i.abort();t.signal&&t.signal.addEventListener("abort",a);let l=this.getHeaders();try{let c=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!c.ok){let d=await gR(c);throw new an(c.status,d,`Request to ${e} failed with status ${c.status}: ${d}`)}let p;if(c.status===204)p={};else{let d=await c.text();try{p=JSON.parse(d)}catch{p=d}}return this.logger&&!t.noLog&&p&&this.logger.debug({result:p,status:c.status,...o},"Got response from Momentic server"),p}finally{clearTimeout(s),t.signal&&t.signal.removeEventListener("abort",a)}}},Mt=class extends sd{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var st=class extends Mt{constructor(e){super(e)}getAppUrl(){return this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${M}/auth/check`,{method:"GET",noLog:!0},10,5e3),{orgId:t,userId:r}=ng.parse(e);return{orgId:t,userId:r}}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${M}/runs/status`,{method:"POST",body:e,noLog:!0});return Xh.parse(t)}async createRunGroup(e){let t=await this.sendRequest(`/${M}/run-groups`,{method:"POST",body:e,noLog:!0},10);return qh.parse(t)}async updateRunGroup(e,t){await this.sendRequest(`/${M}/run-groups/${e}`,{method:"PATCH",body:t,noLog:!0},5)}async createRun(e){let t=await this.sendRequest(`/${M}/runs`,{method:"POST",body:e,noLog:!0},10);return Jh.parse(t)}async updateRun(e,t){await this.sendRequest(`/${M}/runs/${e}`,{method:"PATCH",body:t,noLog:!0},5)}async createRunAttempt(e){let t=await this.sendRequest(`/${M}/runs/${e}/attempts`,{method:"POST",noLog:!0},10);return Qh.parse(t)}async updateRunAttempt(e,t,r){await this.sendRequest(`/${M}/runs/${e}/attempts/${t}`,{method:"PATCH",body:r,noLog:!0},5)}async getTest(e){let t=await this.sendRequest(`/${M}/tests/${e}`,{method:"GET"});return Hh.parse(t)}async getAllTestIds(){let e=await this.sendRequest(`/${M}/tests`,{method:"GET"});return $h.parse(e)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${M}/tests/export`,{method:"POST",body:e});return Wh.parse(t)}async updateTestWithYAML(e){await this.sendRequest(`/${M}/tests/update`,{method:"POST",body:e})}async updateStepCaches(e){await this.sendRequest(`/${M}/cache`,{method:"PATCH",body:e})}async getStepCacheForTest(e){let t=await this.sendRequest(`/${M}/cache`,{method:"POST",body:e},10);return Gh.parse(t)}async queueTests(e){let t=await this.sendRequest(`/${M}/tests/queue`,{method:"POST",body:e});return jh.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${M}/screenshots`,{method:"POST",body:e,noLog:!0},3,5e3);return tg.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${M}/environments`,{method:"GET"});return rg.parse(e)}async getEnvironment(e){let t=await this.sendRequest(`/${M}/environments/${e}`,{method:"GET"});return Ks.parse(t)}async getAllFeatureFlags(){let e=await this.sendRequest(`/${M}/auth/flags`,{method:"GET",noLog:!0},10);return og.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${M}/result-cache/lock`,{method:"POST",body:e,signal:t});return mg.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${M}/result-cache/lock`,{method:"DELETE",body:{key:e}})}async deleteCacheResult(e){await this.sendRequest(`/${M}/result-cache/entry`,{method:"DELETE",body:e})}async setCacheResult(e){await this.sendRequest(`/${M}/result-cache/entry`,{method:"PATCH",body:e})}async getCacheResult(e){try{return await this.sendRequest(`/${M}/result-cache/entry`,{method:"POST",body:e})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${M}/suites/queue`,{method:"POST",body:e});return ig.parse(t)}async bulkGetSuiteStatus(e){let t={suiteRunIds:e},r=await this.sendRequest(`/${M}/suites/status`,{method:"POST",body:t,noLog:!0});return sg.parse(r)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${M}/run-groups/status`,{method:"POST",body:t,noLog:!0});return Wm.array().parse(r)}async updateCacheLastUsedDate(e,t){try{await this.sendRequest(`/${M}/cache/lastUsedAt`,{method:"PATCH",body:e,noLog:!0})}catch(r){t.error({err:r},"Failed to update cache last used date")}}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${M}/test-fragments/`,{method:"POST",body:e})}catch(r){t.error({err:r},"Failed to upload proposed steps")}}async uploadSnapshotScreenshot(e,t,r){try{await this.sendRequest(`/${M}/snapshots/${t}/screenshot`,{method:"POST",body:r,noLog:!0})}catch(o){e.error({err:o},"Failed to upload screenshot")}}async generateConsoleLogsForRunAttemptUploadUrl(e,t,r){let o=await this.sendRequest(`/${M}/runs/${t}/attempts/${r}/console-logs`,{method:"POST",noLog:!0});return To.parse(o)}async generateNetworkLogsForRunAttemptUploadUrl(e,t,r){let o=await this.sendRequest(`/${M}/runs/${t}/attempts/${r}/network-logs`,{method:"POST",noLog:!0});return To.parse(o)}async generateHtmlSnapshotUploadUrl(e,t){let r=await this.sendRequest(`/${M}/snapshots/${t}/html`,{method:"POST",noLog:!0});return To.parse(r)}async generateA11yTreeSnapshotUploadUrl(e,t){let r=await this.sendRequest(`/${M}/snapshots/${t}/a11y`,{method:"POST",noLog:!0});return To.parse(r)}async reportBillableEvents(e,t){try{await this.sendRequest(`/${M}/billing/events`,{method:"POST",body:t,noLog:!0},10,5e3)}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${M}/test-fragments/${e}`,{method:"GET",noLog:!0});return ag.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${M}/test-fragments/${e}`,{method:"PATCH",body:t})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${M}/results/tests/${e}`,{method:"POST",body:t});return lg.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${M}/results/uploads`,{method:"POST",noLog:!0});return cg.parse(e)}async startProcessingResultsUpload(e){let t=await this.sendRequest(`/${M}/results/uploads/${e}/process`,{method:"POST",noLog:!0});return dg.parse(t)}async fetchIconKnowledgeBase(e,t){try{let r=await this.sendRequest(`/${M}/knowledge-base/icons`,{method:"GET",noLog:!0});return bg.parse(r)}catch(r){return t.error({err:r},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t,r){try{await this.sendRequest(`/${M}/icon-knowledge-base/icons`,{method:"POST",body:t,noLog:!0},3,5e3)}catch(o){r.error({err:o},"Failed to save new icons to icon knowledge base")}}async getAllFlagsAndPayloads(){let e=await this.sendRequest(`/${M}/feature-flags`,{method:"GET",noLog:!0},3,5e3);return pg.parse(e)}};import{randomUUID as Ag}from"crypto";var va=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvent(e,t,r){try{return await this.apiClient.reportBillableEvents(e,[{event:t,timestamp:new Date().toISOString(),transactionId:r?.eventId??Ag(),properties:qc({},r)}])}catch(o){e.error({err:o},"Failed to report billable event")}}async reportCreditsUsed(e,t,r,o){if(r)try{return await this.apiClient.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:o?.eventId??Ag(),properties:qc({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};function Eo(n,e,t){return fetch(n,{method:"PUT",body:t,headers:{"Content-Type":e}})}var xa=class{constructor(e){this.client=e}async storeConsoleLogsForRunAttempt(e,t,r,o){try{let i=JSON.stringify(o),{uploadUrl:s}=await this.client.generateConsoleLogsForRunAttemptUploadUrl(e,t,r),a=await Eo(s,"application/json",i);if(!a.ok)throw new Error(`Failed to upload network logs: ${a.statusText}`)}catch(i){e.error({err:i},"Failed to upload console logs")}}async storeNetworkLogsForRunAttempt(e,t,r,o){let i=JSON.stringify(o);try{let{uploadUrl:s}=await this.client.generateNetworkLogsForRunAttemptUploadUrl(e,t,r),a=await Eo(s,"application/json",i);if(!a.ok)throw new Error(`Failed to upload network logs: ${a.statusText}`)}catch(s){e.error({err:s},"Failed to upload network logs")}}async storeHtmlSnapshot(e,t,r){try{let{uploadUrl:o}=await this.client.generateHtmlSnapshotUploadUrl(e,t),i=await Eo(o,"text/html",r);if(!i.ok)throw new Error(`Failed to upload network logs: ${i.statusText}`)}catch(o){e.error({err:o},"Failed to upload html snapshot")}}async storeScreenshot(e,t,r){try{await this.client.uploadSnapshotScreenshot(e,t,{screenshot:r.toString("base64")})}catch(o){e.error({err:o},"Failed to upload screenshot")}}async storeA11yTreeSnapshot(e,t,r){return Promise.resolve()}async getConsoleLogsForRunAttempt(e,t,r){}async getNetworkLogsForRunAttempt(e,t,r){}async getHtmlSnapshot(e,t){}async getA11yTreeSnapshot(e,t){}async getScreenshot(e,t){}};function ad(n){let e={parentChain:[]};return Ta(n,e),e}function Ta(n,e){let{onPresetAction:t,onSimpleStepContainer:r,onConditional:o,earlyStop:i}=n;for(let s of n.steps)switch(s.type){case"PRESET_ACTION":if(t(s,e)&&i)return!0;break;case"CONDITIONAL":if(o?.(s,e)&&i)return!0;e.parentChain.push(s);for(let l of s.blocks)if(t(l.assertion,e)&&i||Ta({...n,steps:l.steps},e)&&i)return!0;if(Ta({...n,steps:s.elseSteps??[]},e)&&i)return!0;e.parentChain.pop();break;case"RESOLVED_MODULE":case"IFRAME":case"SECTION":case"AI_ACTION":if(r?.(s,e)&&i)return!0;if(s.steps){if(e.parentChain.push(s),Ta({...n,steps:s.steps},e)&&i)return!0;e.parentChain.pop()}break;case"AI_ACTION_DYNAMIC":{if(r?.(s,e)&&i)return!0;break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(s)}}function Ig(n,e,t,r){let o=Array.from(e),i=Array.from(r);for(let a=0;a<o.length;a++){if(o[a]!==i[a])return!1;i.shift()}return!!fR([n],t,i).result}function fR(n,e,t=[]){let r,o=[],i=(s,a)=>{let l=JSON.stringify(a.parentChain.map(p=>p.id)),c=t.length===0?!0:JSON.stringify(t)===l;return s.id===e&&c?(r=s,o=a.parentChain,!0):!1};return ad({steps:n,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:r,parentChain:o}}function Pg(n,e){e(n);for(let t in n){let r=n[t];r&&(Array.isArray(r)?Ea(r,e):typeof r=="object"&&Pg(r,e))}}function Ea(n,e){for(let t of n)t&&(Array.isArray(t)?Ea(t,e):typeof t=="object"&&Pg(t,e))}function Co({steps:n,topLevel:e=!0,...t}){let{stepCacheEntries:r,logger:o,keyPrefix:i}=t,s=[],a=[],l=0,c=(d,u)=>{try{let m=wr.parse(u.value);if(m.type!==d.type){o.warn({parsedCacheEntry:m,command:d},"Not using step cache due to type mismatch"),a.push(u.key);return}d.cache=m.cache,s.push(u.key)}catch(m){a.push(u.key),o.error({err:m,cacheEntry:u},"Not using step cache due to parsing error")}},p=(d,u)=>{let m=SR(d.id,u),h=m.find(g=>!!r[g]);h?c(d,r[h]):a.push(m[0])};for(let d of n)switch(d.type){case"RESOLVED_MODULE":{l+=d.steps.length;let{hits:m,misses:h}=Co({...t,steps:d.steps,keyPrefix:i?`${i}:${d.id}`:d.id,topLevel:!1});s=s.concat(m),a=a.concat(h);break}case"IFRAME":case"SECTION":case"AI_ACTION":{if(l+=d.steps?.length??0,!d.steps?.length)break;let{hits:m,misses:h}=Co({...t,steps:d.steps,topLevel:!1});s=s.concat(m),a=a.concat(h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!pc.includes(d.command.type)||(d.command.type==="TYPE"||d.command.type==="MOUSE_DRAG"||d.command.type==="VISUAL_DIFF"||d.command.type==="SCROLL_DOWN"||d.command.type==="SCROLL_UP"||d.command.type==="SCROLL_LEFT"||d.command.type==="SCROLL_RIGHT")&&!d.command.target||"cache"in d.command&&d.command.cache)continue;l++,p(d.command,i);break}case"CONDITIONAL":{for(let m of d.blocks){l++,p(m.assertion.command,i),l+=m.steps.length;let{hits:h,misses:g}=Co({...t,steps:m.steps,topLevel:!1});s=s.concat(h),a=a.concat(g);break}if(d.elseSteps){l+=d.elseSteps.length;let{hits:m,misses:h}=Co({...t,steps:d.elseSteps,topLevel:!1});s=s.concat(m),a=a.concat(h)}break}default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(d)}return e&&l&&a.length>0&&o.warn({totalSteps:l,cacheMisses:a,cacheHits:s,cacheEntries:r.length},"Step cache did not fully resolve"),{hits:s,misses:a}}function Lg(n,e){return e?`${e}:${n}`:n}function SR(n,e){let t=[],r=e?.split(":")??[];for(let o=r.length;o>=0;o--){let i=[...r.slice(o),n];t.push(i.join(":"))}return t.reverse(),t}function Og(n){let{moduleStepParents:e=[],moduleIdParents:t=[]}=n;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
14
+ `)),console.log(" ",t(a))}}setMinLevel(e){this.minLogLevel=e}log(...e){this.logWithLevel(1,wn.reset,...e)}info(...e){this.logWithLevel(1,wn.blue,...e)}debug(...e){this.logWithLevel(0,wn.dim,...e)}warn(...e){this.logWithLevel(2,wn.yellow,...e)}error(...e){this.logWithLevel(3,wn.red,...e)}success(...e){this.logWithLevel(4,wn.green,...e)}dimmed(...e){this.logWithLevel(1,wn.dim,...e)}underline(...e){this.logWithLevel(2,wn.underline,...e)}bold(...e){this.logWithLevel(2,wn.bold,...e)}grey(...e){this.logWithLevel(0,wn.grey,...e)}child(e){return new n(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},y=new Qc(1,{}),kr={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>kr,flush:()=>{},bindings:()=>({})},wa={},Nr=({logger:n,logKey:e,maxCount:t,intervalMs:r},o,i,...s)=>{let a=wa[e];a?clearTimeout(a.timer):(a={count:0,totalCount:0},wa[e]=a),a.totalCount++,a.count<t&&(a.count++,n.debug(o,i,...s)),a.timer=setTimeout(()=>{let l=wa[e];l?.totalCount!==l?.count&&n.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete wa[e]},r)};import{z as Je}from"zod";var Mh=Je.object({id:Je.string(),createdAt:Je.coerce.date(),createdBy:Je.string(),organizationId:Je.string(),name:Je.string(),description:Je.string().nullish(),enabled:Je.boolean(),schemaVersion:Je.string().describe("Schema version for steps"),parameters:Je.string().array().nullish().describe("Parameter list"),defaultParameters:Je.record(Je.string(),Je.string()).nullish(),defaultCacheKey:Je.string().nullish(),defaultCacheTtl:Je.number().nullish(),defaultCacheAllInvocations:Je.boolean().nullish(),autoAuth:Je.boolean().nullish(),advanced:gc.nullish()}),zz=Mh.extend({steps:Je.lazy(()=>Ke.array())}),Fh=5*60*1e3,ed=It.merge(Mh.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as $z}from"date-fns-tz";import{z as _n}from"zod";var td=_n.object({failureRecovery:_n.boolean().optional(),aiAction:_n.boolean().optional()}),Vz=_n.object({ai:td.optional(),githubAppInstallationId:_n.number().nullish(),githubReleaseAppInstallationId:_n.number().nullish(),gitlabAppAccessToken:_n.string().nullish().optional(),gitlabAppBaseUrl:_n.string().nullish().optional(),qaseAccessToken:_n.string().nullish().optional()});import*as T from"zod";var lj=T.object({error:T.boolean(),reason:T.string(),message:T.string()}),cj=qt.merge(Hc),Dh=Ms,dj=qt.merge(Hc);var pj=qt.merge(Xm).extend({useConsensus:T.boolean().optional(),attemptNumber:T.number().optional()}),nd=Nu,uj=qt.merge(Zm),Uh=qu,mj=qt.merge(Km),Bh=Vu,hj=qt.merge(Ym),zh=Gu,gj=qt.merge(Jm);var fj=T.object({testPaths:T.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:T.string().optional(),all:T.boolean().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional(),testInputMatrix:T.record(T.string(),T.string()).array().optional()}),jh=T.object({queuedTests:T.unknown().array(),runIds:T.string().uuid().array(),runGroupId:T.string().optional()}),Hh=Hi,$h=T.string().array(),Sj=T.union([T.object({paths:T.string().array().describe("run specific test paths (e.g. todo-test)"),all:T.boolean().describe("run all tests").optional()}),T.object({path:T.string().describe("deprecated; present for backcompat")})]),Wh=T.object({tests:T.record(T.string().describe("Test name"),T.string().describe("Test YAML")),modules:T.record(T.string().describe("Module name"),T.string().describe("Module YAML"))}),eR=T.object({test:T.string().describe("test YAML"),modules:T.record(T.string().describe("moduleId"),T.string().describe("module YAML"))}),yj=eR.array(),bj=T.object({testId:T.string(),schemaVersion:T.string()}).merge(Tr),wj=T.object({entries:T.array(xc),testId:T.string()}),vj=T.object({steps:T.array(T.record(T.unknown())),testId:T.string(),schemaVersion:T.string(),organizationId:T.string()}),Gh=Wu,Vh=T.object({trigger:T.nativeEnum(Lt),status:T.nativeEnum(re),startedAt:T.coerce.date().optional(),gitCommitSha:T.string().optional(),gitCommitShaShort:T.string().optional(),gitCommitTimestamp:T.coerce.date().optional(),gitBranchName:T.string().optional(),gitOriginUrl:T.string().optional(),gitCommitMessage:T.string().optional(),gitCommitAuthorName:T.string().optional(),githubRepository:T.string().optional(),gitlabProjectPath:T.string().optional(),pipelineId:T.string().optional(),cliVersion:T.string().optional()}),qh=T.object({id:T.string()}),Kh=T.object({status:T.nativeEnum(re),updatedAt:T.coerce.date().optional(),finishedAt:T.coerce.date().optional()}),Yh=T.object({stepsSnapshot:T.array(T.record(T.unknown())).optional(),runGroupId:T.string().optional(),testId:T.string(),testName:T.string(),resolvedBaseUrl:T.string().optional(),environmentName:T.string().optional(),labels:T.array(T.string()).optional(),cliVersion:T.string().optional(),trigger:T.nativeEnum(Lt),schemaVersion:T.string().optional(),section:T.nativeEnum(ca).optional()}),Jh=T.object({id:T.string()}),tR=jc.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Xh=tR.array(),Zh=jc.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),Qh=T.object({id:T.string()}),eg=T.object({status:T.nativeEnum(re),finishedAt:T.coerce.date().optional()}).merge(na),xj=T.object({screenshot:T.string()}),tg=T.object({key:T.string()}),ng=T.object({orgId:T.string(),userId:T.string()}),rg=T.array(Ks),og=T.record(T.string(),T.union([T.string(),T.boolean()])),Tj=T.object({paths:T.string().array(),env:T.string().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional()}),ig=T.object({suiteRunIds:T.string().array(),runGroupIds:T.string().array()}),Ej=T.object({suiteRunIds:T.string().array()}),sg=qm.array(),Cj=T.object({runGroupIds:T.string().array()}),To=T.object({uploadUrl:T.string()}),Rj=qt.merge(Qm),Aj=qt.merge(th),Ij=qt.merge(eh),nR=T.object({testId:T.string().optional().default(""),testName:T.string().optional().default(""),suiteId:T.string().optional().default(""),suiteName:T.string().optional().default(""),creditsUsed:T.number().optional(),usedBy:T.string().optional()}),rR=T.object({transactionId:T.string(),timestamp:T.string(),event:T.nativeEnum(Lr),properties:nR}),Pj=rR.array(),ag=Mm.omit({steps:!0}).extend({steps:T.array(T.record(T.string(),T.unknown())).describe("unparsed ResolvedStep[]")}),Lj=T.object({limit:T.number().max(10).optional(),afterTime:T.number().optional()}),lg=Hm.array(),Oj=T.object({applied:T.boolean().optional(),appliedAt:T.coerce.date().optional()}),kj=qt.extend({chunks:$c.array(),description:T.string().describe("Input to pass to AI"),type:T.union([T.literal("locator"),T.literal("assertion"),T.literal("ai-action")]),softTokenLimit:T.number(),hardTokenLimit:T.number()}),cg=To.extend({id:T.string()}),dg=T.object({runGroupId:T.string()}),pg=T.object({featureFlags:T.record(T.string(),T.boolean().or(T.string())).optional(),featureFlagPayloads:T.record(T.string(),ba).optional()});import{z as Te}from"zod";var ug=Te.object({orgId:Te.string(),cacheKeys:Te.string().array()}),Mj=Te.object({keyParams:ug,clientMetadata:Te.string(),lockAcquisitionTimeoutMs:Te.number().optional()}),mg=Te.object({acquired:Te.boolean(),acquiredByMetadata:Te.string(),keyPrefix:Te.string()}),Fj=Te.object({keyPrefix:Te.string(),result:Te.string(),ttlMs:Te.number()}),Dj=Te.union([Te.object({keyPrefix:Te.string()}),ug]),oR=Te.object({remainingTtlMs:Te.number(),value:Te.string().nullish()}),Uj=Te.object({results:Te.record(Te.string(),oR),activeLocks:Te.string().array()}),hg=0,gg=5*60*1e3;import{z as sn}from"zod";var fg="test",Sg="module",_t=(t=>(t.TEST=`${fg}.yaml`,t.MODULE=`${Sg}.yaml`,t))(_t||{}),he=(o=>(o.TEST=`momentic/${fg}`,o.MODULE=`momentic/${Sg}`,o.FIXTURE="momentic/fixture",o.ENVIRONMENT="momentic/environment",o))(he||{}),Vj=Nt.merge(Tr),rd=It.extend({steps:sn.array(sn.record(sn.string(),sn.unknown())),schemaVersion:sn.string()}),qj=rd.extend({fileType:sn.literal(he.MODULE)}),Kj=sn.object({test:sn.string().describe("YAML for the test, including metadata and steps"),modules:sn.record(sn.string(),sn.string()).describe("Map of module name to YAML for the module")});import{z as it}from"zod";var iR=it.object({version:it.string(),json:it.record(it.unknown()),hash:it.string()}),yg=it.record(it.unknown()),Zj=it.object({newSvgs:it.array(iR),metadata:yg.optional()}),sR=it.object({version:it.string(),json:it.record(it.unknown()).nullish(),hash:it.string(),description:it.string().nullish(),metadata:yg.nullish()}),bg=it.record(it.string().describe("icon hash"),sR);import{validator as rH}from"@exodus/schemasafe";var wg=n=>{n.extraHeaders&&(n.extraHeaders=Object.fromEntries(Object.entries(n.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as gH}from"zod";import{z as Xn}from"zod";var yH=Xn.object({repositoriesIndexed:Xn.boolean(),indexingInProgress:Xn.boolean(),indexesOutdated:Xn.boolean()}),vg=(s=>(s.Queued="queued",s.InProgress="in_progress",s.Completed="completed",s.Waiting="waiting",s.Requested="requested",s.Pending="pending",s))(vg||{}),xg=(a=>(a.Success="success",a.Failure="failure",a.Neutral="neutral",a.Cancelled="cancelled",a.Skipped="skipped",a.TimedOut="timed_out",a.ActionRequired="action_required",a))(xg||{}),bH=Xn.object({name:Xn.string(),status:Xn.nativeEnum(vg),conclusion:Xn.nativeEnum(xg).nullable()});import{z as Oe}from"zod";var od=Oe.object({assertion:Oe.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),aR=Oe.object({instruction:Oe.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:od.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),Tg=aR.extend({subSteps:Oe.lazy(()=>Tg.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Eg=Oe.object({name:Oe.string().describe("Short name describing the test plan"),description:Oe.string().nullish().transform(n=>n??void 0).describe("Longer form description of the high level goal of the test plan")}),Cg=Eg.extend({id:Oe.string(),createdAt:Oe.coerce.date(),updatedAt:Oe.coerce.date(),updatedBy:Oe.string(),createdBy:Oe.string(),test:Oe.object({id:Oe.string(),name:Oe.string()}).nullish().transform(n=>n??void 0)}),TH=Cg.extend({testGenRuns:Oe.tuple([]).or(Oe.tuple([Oe.object({id:Oe.string(),startedAt:Oe.coerce.date(),status:Oe.nativeEnum(re)})]))}),Rg=Oe.object({preConditions:od.array().nullish().transform(n=>n??[]),postConditions:od.array().nullish().transform(n=>n??[]),steps:Tg.array().nullish().transform(n=>n??[])}),EH=Cg.extend({plan:Rg.nullish().transform(n=>n??{preConditions:[],postConditions:[],steps:[]})}),lR=Eg.extend({plan:Rg.nullish().transform(n=>n??{preConditions:[],postConditions:[],steps:[]})}),CH=lR.array().nullish().transform(n=>n??[]);import{z as Ee}from"zod";var cR=Ee.object({step:ve,status:Ee.nativeEnum(re),startedAt:Ee.coerce.date(),finishedAt:Ee.coerce.date().optional(),healMetadata:Ee.object({healType:Ee.nativeEnum(Ii).or(Ee.literal("AI")),healedAt:Ee.coerce.date()}).optional(),beforeSnapshotId:Ee.string().uuid().optional(),afterSnapshotId:Ee.string().uuid().optional(),message:Ee.string().optional()}),_H=cR.extend({status:Ee.nativeEnum(xe),finishedAt:Ee.coerce.date()}),dR=Ee.object({startedAt:Ee.coerce.date()}).merge(eg),MH=dR.extend({finishedAt:Ee.coerce.date()}),pR=Zh.merge(Yh).extend({startedAt:Ee.coerce.date(),attempts:Ee.number()}),FH=pR.extend({status:Ee.nativeEnum(re),finishedAt:Ee.coerce.date()}),uR=Vh.merge(Kh).extend({startedAt:Ee.coerce.date(),cliVersion:Ee.string()}),id=uR.extend({updatedAt:Ee.coerce.date(),finishedAt:Ee.coerce.date()});var M="v1",Wi="1.1.11";var mR=9e4,hR=15e3,an=class extends Error{status;rawError;constructor(e,t,r,o={}){super(r,o),this.status=e,this.rawError=t}};async function gR(n){return n.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var sd=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Wi&&(e["X-MOMENTIC-CLI-VERSION"]=Wi),e}async sendRequest(e,t,r=3,o=mR){let i=r,s,a={path:e,baseUrl:this.baseUrl,method:t.method};for(;r>0;)try{return r--,await this.sendSingleRequestHelper(e,t,o)}catch(l){if(s=l,this.logger&&this.logger.warn({...a,err:l},`Got error response from Momentic server${r>0?", retrying":""}`),l instanceof an&&l.status>=400&&l.status<500||r===0)throw l;let c=1500,p=i-r,d=Math.min(c*Math.pow(2,p-1),hR);await new Promise(u=>setTimeout(u,d))}throw s}async sendSingleRequestHelper(e,t,r){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,s=setTimeout(()=>i.abort(),r),a=()=>i.abort();t.signal&&t.signal.addEventListener("abort",a);let l=this.getHeaders();try{let c=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!c.ok){let d=await gR(c);throw new an(c.status,d,`Request to ${e} failed with status ${c.status}: ${d}`)}let p;if(c.status===204)p={};else{let d=await c.text();try{p=JSON.parse(d)}catch{p=d}}return this.logger&&!t.noLog&&p&&this.logger.debug({result:p,status:c.status,...o},"Got response from Momentic server"),p}finally{clearTimeout(s),t.signal&&t.signal.removeEventListener("abort",a)}}},Mt=class extends sd{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var st=class extends Mt{constructor(e){super(e)}getAppUrl(){return this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${M}/auth/check`,{method:"GET",noLog:!0},10,5e3),{orgId:t,userId:r}=ng.parse(e);return{orgId:t,userId:r}}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${M}/runs/status`,{method:"POST",body:e,noLog:!0});return Xh.parse(t)}async createRunGroup(e){let t=await this.sendRequest(`/${M}/run-groups`,{method:"POST",body:e,noLog:!0},10);return qh.parse(t)}async updateRunGroup(e,t){await this.sendRequest(`/${M}/run-groups/${e}`,{method:"PATCH",body:t,noLog:!0},5)}async createRun(e){let t=await this.sendRequest(`/${M}/runs`,{method:"POST",body:e,noLog:!0},10);return Jh.parse(t)}async updateRun(e,t){await this.sendRequest(`/${M}/runs/${e}`,{method:"PATCH",body:t,noLog:!0},5)}async createRunAttempt(e){let t=await this.sendRequest(`/${M}/runs/${e}/attempts`,{method:"POST",noLog:!0},10);return Qh.parse(t)}async updateRunAttempt(e,t,r){await this.sendRequest(`/${M}/runs/${e}/attempts/${t}`,{method:"PATCH",body:r,noLog:!0},5)}async getTest(e){let t=await this.sendRequest(`/${M}/tests/${e}`,{method:"GET"});return Hh.parse(t)}async getAllTestIds(){let e=await this.sendRequest(`/${M}/tests`,{method:"GET"});return $h.parse(e)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${M}/tests/export`,{method:"POST",body:e});return Wh.parse(t)}async updateTestWithYAML(e){await this.sendRequest(`/${M}/tests/update`,{method:"POST",body:e})}async updateStepCaches(e){await this.sendRequest(`/${M}/cache`,{method:"PATCH",body:e})}async getStepCacheForTest(e){let t=await this.sendRequest(`/${M}/cache`,{method:"POST",body:e},10);return Gh.parse(t)}async queueTests(e){let t=await this.sendRequest(`/${M}/tests/queue`,{method:"POST",body:e});return jh.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${M}/screenshots`,{method:"POST",body:e,noLog:!0},3,5e3);return tg.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${M}/environments`,{method:"GET"});return rg.parse(e)}async getEnvironment(e){let t=await this.sendRequest(`/${M}/environments/${e}`,{method:"GET"});return Ks.parse(t)}async getAllFeatureFlags(){let e=await this.sendRequest(`/${M}/auth/flags`,{method:"GET",noLog:!0},10);return og.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${M}/result-cache/lock`,{method:"POST",body:e,signal:t});return mg.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${M}/result-cache/lock`,{method:"DELETE",body:{key:e}})}async deleteCacheResult(e){await this.sendRequest(`/${M}/result-cache/entry`,{method:"DELETE",body:e})}async setCacheResult(e){await this.sendRequest(`/${M}/result-cache/entry`,{method:"PATCH",body:e})}async getCacheResult(e){try{return await this.sendRequest(`/${M}/result-cache/entry`,{method:"POST",body:e})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${M}/suites/queue`,{method:"POST",body:e});return ig.parse(t)}async bulkGetSuiteStatus(e){let t={suiteRunIds:e},r=await this.sendRequest(`/${M}/suites/status`,{method:"POST",body:t,noLog:!0});return sg.parse(r)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${M}/run-groups/status`,{method:"POST",body:t,noLog:!0});return Wm.array().parse(r)}async updateCacheLastUsedDate(e,t){try{await this.sendRequest(`/${M}/cache/lastUsedAt`,{method:"PATCH",body:e,noLog:!0})}catch(r){t.error({err:r},"Failed to update cache last used date")}}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${M}/test-fragments/`,{method:"POST",body:e})}catch(r){t.error({err:r},"Failed to upload proposed steps")}}async uploadSnapshotScreenshot(e,t,r){try{await this.sendRequest(`/${M}/snapshots/${t}/screenshot`,{method:"POST",body:r,noLog:!0})}catch(o){e.error({err:o},"Failed to upload screenshot")}}async generateConsoleLogsForRunAttemptUploadUrl(e,t,r){let o=await this.sendRequest(`/${M}/runs/${t}/attempts/${r}/console-logs`,{method:"POST",noLog:!0});return To.parse(o)}async generateNetworkLogsForRunAttemptUploadUrl(e,t,r){let o=await this.sendRequest(`/${M}/runs/${t}/attempts/${r}/network-logs`,{method:"POST",noLog:!0});return To.parse(o)}async generateHtmlSnapshotUploadUrl(e,t){let r=await this.sendRequest(`/${M}/snapshots/${t}/html`,{method:"POST",noLog:!0});return To.parse(r)}async generateA11yTreeSnapshotUploadUrl(e,t){let r=await this.sendRequest(`/${M}/snapshots/${t}/a11y`,{method:"POST",noLog:!0});return To.parse(r)}async reportBillableEvents(e,t){try{await this.sendRequest(`/${M}/billing/events`,{method:"POST",body:t,noLog:!0},10,5e3)}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${M}/test-fragments/${e}`,{method:"GET",noLog:!0});return ag.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${M}/test-fragments/${e}`,{method:"PATCH",body:t})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${M}/results/tests/${e}`,{method:"POST",body:t});return lg.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${M}/results/uploads`,{method:"POST",noLog:!0});return cg.parse(e)}async startProcessingResultsUpload(e){let t=await this.sendRequest(`/${M}/results/uploads/${e}/process`,{method:"POST",noLog:!0});return dg.parse(t)}async fetchIconKnowledgeBase(e,t){try{let r=await this.sendRequest(`/${M}/knowledge-base/icons`,{method:"GET",noLog:!0});return bg.parse(r)}catch(r){return t.error({err:r},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t,r){try{await this.sendRequest(`/${M}/icon-knowledge-base/icons`,{method:"POST",body:t,noLog:!0},3,5e3)}catch(o){r.error({err:o},"Failed to save new icons to icon knowledge base")}}async getAllFlagsAndPayloads(){let e=await this.sendRequest(`/${M}/feature-flags`,{method:"GET",noLog:!0},3,5e3);return pg.parse(e)}};import{randomUUID as Ag}from"crypto";var va=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvent(e,t,r){try{return await this.apiClient.reportBillableEvents(e,[{event:t,timestamp:new Date().toISOString(),transactionId:r?.eventId??Ag(),properties:qc({},r)}])}catch(o){e.error({err:o},"Failed to report billable event")}}async reportCreditsUsed(e,t,r,o){if(r)try{return await this.apiClient.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:o?.eventId??Ag(),properties:qc({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};function Eo(n,e,t){return fetch(n,{method:"PUT",body:t,headers:{"Content-Type":e}})}var xa=class{constructor(e){this.client=e}async storeConsoleLogsForRunAttempt(e,t,r,o){try{let i=JSON.stringify(o),{uploadUrl:s}=await this.client.generateConsoleLogsForRunAttemptUploadUrl(e,t,r),a=await Eo(s,"application/json",i);if(!a.ok)throw new Error(`Failed to upload network logs: ${a.statusText}`)}catch(i){e.error({err:i},"Failed to upload console logs")}}async storeNetworkLogsForRunAttempt(e,t,r,o){let i=JSON.stringify(o);try{let{uploadUrl:s}=await this.client.generateNetworkLogsForRunAttemptUploadUrl(e,t,r),a=await Eo(s,"application/json",i);if(!a.ok)throw new Error(`Failed to upload network logs: ${a.statusText}`)}catch(s){e.error({err:s},"Failed to upload network logs")}}async storeHtmlSnapshot(e,t,r){try{let{uploadUrl:o}=await this.client.generateHtmlSnapshotUploadUrl(e,t),i=await Eo(o,"text/html",r);if(!i.ok)throw new Error(`Failed to upload network logs: ${i.statusText}`)}catch(o){e.error({err:o},"Failed to upload html snapshot")}}async storeScreenshot(e,t,r){try{await this.client.uploadSnapshotScreenshot(e,t,{screenshot:r.toString("base64")})}catch(o){e.error({err:o},"Failed to upload screenshot")}}async storeA11yTreeSnapshot(e,t,r){return Promise.resolve()}async getConsoleLogsForRunAttempt(e,t,r){}async getNetworkLogsForRunAttempt(e,t,r){}async getHtmlSnapshot(e,t){}async getA11yTreeSnapshot(e,t){}async getScreenshot(e,t){}};function ad(n){let e={parentChain:[]};return Ta(n,e),e}function Ta(n,e){let{onPresetAction:t,onSimpleStepContainer:r,onConditional:o,earlyStop:i}=n;for(let s of n.steps)switch(s.type){case"PRESET_ACTION":if(t(s,e)&&i)return!0;break;case"CONDITIONAL":if(o?.(s,e)&&i)return!0;e.parentChain.push(s);for(let l of s.blocks)if(t(l.assertion,e)&&i||Ta({...n,steps:l.steps},e)&&i)return!0;if(Ta({...n,steps:s.elseSteps??[]},e)&&i)return!0;e.parentChain.pop();break;case"RESOLVED_MODULE":case"IFRAME":case"SECTION":case"AI_ACTION":if(r?.(s,e)&&i)return!0;if(s.steps){if(e.parentChain.push(s),Ta({...n,steps:s.steps},e)&&i)return!0;e.parentChain.pop()}break;case"AI_ACTION_DYNAMIC":{if(r?.(s,e)&&i)return!0;break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(s)}}function Ig(n,e,t,r){let o=Array.from(e),i=Array.from(r);for(let a=0;a<o.length;a++){if(o[a]!==i[a])return!1;i.shift()}return!!fR([n],t,i).result}function fR(n,e,t=[]){let r,o=[],i=(s,a)=>{let l=JSON.stringify(a.parentChain.map(p=>p.id)),c=t.length===0?!0:JSON.stringify(t)===l;return s.id===e&&c?(r=s,o=a.parentChain,!0):!1};return ad({steps:n,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:r,parentChain:o}}function Pg(n,e){e(n);for(let t in n){let r=n[t];r&&(Array.isArray(r)?Ea(r,e):typeof r=="object"&&Pg(r,e))}}function Ea(n,e){for(let t of n)t&&(Array.isArray(t)?Ea(t,e):typeof t=="object"&&Pg(t,e))}function Co({steps:n,topLevel:e=!0,...t}){let{stepCacheEntries:r,logger:o,keyPrefix:i}=t,s=[],a=[],l=0,c=(d,u)=>{try{let m=wr.parse(u.value);if(m.type!==d.type){o.warn({parsedCacheEntry:m,command:d},"Not using step cache due to type mismatch"),a.push(u.key);return}d.cache=m.cache,s.push(u.key)}catch(m){a.push(u.key),o.error({err:m,cacheEntry:u},"Not using step cache due to parsing error")}},p=(d,u)=>{let m=SR(d.id,u),h=m.find(g=>!!r[g]);h?c(d,r[h]):a.push(m[0])};for(let d of n)switch(d.type){case"RESOLVED_MODULE":{l+=d.steps.length;let{hits:m,misses:h}=Co({...t,steps:d.steps,keyPrefix:i?`${i}:${d.id}`:d.id,topLevel:!1});s=s.concat(m),a=a.concat(h);break}case"IFRAME":case"SECTION":case"AI_ACTION":{if(l+=d.steps?.length??0,!d.steps?.length)break;let{hits:m,misses:h}=Co({...t,steps:d.steps,topLevel:!1});s=s.concat(m),a=a.concat(h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!pc.includes(d.command.type)||(d.command.type==="TYPE"||d.command.type==="MOUSE_DRAG"||d.command.type==="VISUAL_DIFF"||d.command.type==="SCROLL_DOWN"||d.command.type==="SCROLL_UP"||d.command.type==="SCROLL_LEFT"||d.command.type==="SCROLL_RIGHT")&&!d.command.target||"cache"in d.command&&d.command.cache)continue;l++,p(d.command,i);break}case"CONDITIONAL":{for(let m of d.blocks){l++,p(m.assertion.command,i),l+=m.steps.length;let{hits:h,misses:g}=Co({...t,steps:m.steps,topLevel:!1});s=s.concat(h),a=a.concat(g);break}if(d.elseSteps){l+=d.elseSteps.length;let{hits:m,misses:h}=Co({...t,steps:d.elseSteps,topLevel:!1});s=s.concat(m),a=a.concat(h)}break}default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(d)}return e&&l&&a.length>0&&o.warn({totalSteps:l,cacheMisses:a,cacheHits:s,cacheEntries:r.length},"Step cache did not fully resolve"),{hits:s,misses:a}}function Lg(n,e){return e?`${e}:${n}`:n}function SR(n,e){let t=[],r=e?.split(":")??[];for(let o=r.length;o>=0;o--){let i=[...r.slice(o),n];t.push(i.join(":"))}return t.reverse(),t}function Og(n){let{moduleStepParents:e=[],moduleIdParents:t=[]}=n;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
15
15
  ${JSON.stringify(t)}`);let r=[];if(!n.skipIntermediateEntries)for(let o=e.length;o>0;o--){let i=t[o-1],s=e.slice(o,e.length).join(":");r.push({key:Lg(n.id,s),moduleId:i,organizationId:n.orgId,value:n.value})}return r.push({key:Lg(n.id,e.join(":")),organizationId:n.orgId,value:n.value,testId:n.testId}),r}function kg(n){switch(n.type){case"DRAG":{if(n.fromTarget.type==="coordinates"||n.toTarget.type==="coordinates"||!n.fromTarget?.a11yData||!n.toTarget?.a11yData)return;n.cache={fromTarget:n.fromTarget.a11yData,toTarget:n.toTarget.a11yData},delete n.fromTarget.a11yData,delete n.toTarget.a11yData;return}case"MOUSE_DRAG":case"HOVER":case"SCROLL_UP":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SELECT_OPTION":case"TYPE":case"VISUAL_DIFF":case"CLICK":case"FOCUS":case"ELEMENT_CHECK":case"BLUR":{if(n.target?.type==="coordinates"||!n.target?.a11yData)return;n.cache={target:n.target.a11yData},delete n.target.a11yData;return}default:return}}function Ng(n){let e=new Set;return Ea(n,t=>{if("type"in t&&t.type==="RESOLVED_MODULE"&&"moduleId"in t){let r=t.moduleId;typeof r=="string"&&!e.has(r)&&e.add(r)}}),e}function _g(n,e,t){e.length&&(n.type==="DRAG"?e.length!==2||!e.every(r=>r.cache)?t.warn({newTargets:e,cmd:n},"New targets for step are incorrect"):n.fromTarget.type==="description"&&n.toTarget.type==="description"&&(n.cache={fromTarget:e[0].cache,toTarget:e[1].cache}):e.length!==1||!e[0]?.cache?t.warn({newTargets:e,cmd:n},"New targets for step are incorrect"):"target"in n&&n.target&&n.target.type==="description"&&(n.cache={target:e[0].cache}))}function Me(n,e,t=!1){return n.length<e?n:n.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var Zn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},Qn={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},ld={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable"},cd={EXISTS:"does not exists",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable"};function yR(n){switch(n.type){case"ELEMENT_CONTENT":return`${n.negated?Qn[n.operation]:Zn[n.operation]} '${n.value}'`;case"ELEMENT_ATTRIBUTE":{let t=n.negated?Qn[n.operation]:Zn[n.operation];return n.operation==="EXISTS"?`attribute '${n.attr}' ${t}`:`attribute '${n.attr}' ${t} '${n.value}'`}case"ELEMENT_EXISTENCE":return n.negated?cd[n.condition]:ld[n.condition];default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}var vG={CONTENT:"The page"};function bR(n){switch(n.type){case"VALUE":return`the option with value ${n.value}`;case"LABEL":return`the option with label ${n.label}`;case"INDEX":return`the option at index ${n.index}`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function dd(n){switch(n.type){case"SUBSTRING":return`match substring '${n.url}'`;case"REGEX":return`match regex '${n.regex}'`;case"GLOB":return`match glob '${n.glob}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function wR(n){switch(n.type){case"CONTENT":return`${n.negated?Qn.CONTAINS:Zn.CONTAINS} '${n.value}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.type)}}function _r(n){switch(n.type){case"SUCCESS":return n.condition?.assertion?`Check success condition: ${n.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${n.goal}`;case"NAVIGATE":return`Go to URL: ${Me(n.url,30)}`;case"DIALOG":return`Automatically ${n.action.toLowerCase()} the next dialog`;case"CAPTCHA":return"Solve captchas on the page";case"GO_BACK":return"Go back to the previous page";case"GO_FORWARD":return"Go forward to the next page";case"SCROLL_DOWN":return`Scroll down ${n.deltaY?`${n.deltaY}px`:"1 page height"}${n.target?` in the container of: ${pt(n.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${n.deltaY?`${n.deltaY}px`:"1 page height"}${n.target?` in the container of: ${pt(n.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${n.deltaX?`${n.deltaX}px`:"1 page width"}${n.target?` in the container of: ${pt(n.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${n.deltaX?`${n.deltaX}px`:"1 page width"}${n.target?` in the container of: ${pt(n.target)}`:""}`;case"WAIT":return`Wait for ${n.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(n.target?.type==="coordinates")return`Click at coordinates: ${pt(n.target)}`;let t="";return n.target?.elementDescriptor.length?t=` on element: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` on element: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Click${t}`}case"FOCUS":return`Focus ${pt(n.target)}`;case"BLUR":return`Focus ${pt(n.target)}`;case"DRAG":return`Drag ${pt(n.fromTarget)} onto ${pt(n.toTarget)}`;case"MOUSE_DRAG":return n.target?.type==="description"&&n.target.elementDescriptor?`Click and drag ${pt(n.target)} by ${n.deltaX}px horizontally, ${n.deltaY}px vertically`:`Click and drag mouse by ${n.deltaX}px horizontally, ${n.deltaY}px vertically`;case"TYPE":{let t="";return n.target?.type==="coordinates"?t=` in element at coordinates: ${pt(n.target)}`:n.target?.elementDescriptor.length?t=` in element: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` in element: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Type '${n.value}'${t||""}`}case"HOVER":{let t="";return n.target.type==="coordinates"?t=` over coordinates: ${pt(n.target)}`:n.target.elementDescriptor.length>0?t=` over element: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` over element: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Hover${t}`}case"PRESS":return`Press ${n.value}`;case"SELECT_OPTION":{let t="",r=n.option??bR(n.choice);return n.target.type==="coordinates"?t=` from element at coordinates: ${pt(n.target)}`:n.target.elementDescriptor.length>0?t=` from: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` from: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${r}'${t}`}case"TAB":if(n.url)return`Switch to tab with substring: ${n.url}`;if(n.action)switch(n.action.type){case"SUBSTRING":return`Switch to tab with substring: ${n.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${n.action.pattern}`;case"INDEX":return`Switch to tab at index: ${n.action.index}`;default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${n.url}`;case"REQUEST":return`Send ${n.method} request to ${n.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${n.url}`;case"COOKIE":return`Set cookie: ${n.value}`;case"LOCAL_STORAGE":return`Set local storage: ${n.key}: ${n.value}`;case"JAVASCRIPT":return`Run JavaScript: ${Me(n.code,30)}`;case"AI_ASSERTION":return`Assertion: '${n.assertion}'`;case"AI_WAIT":return`Wait until assertion is true: '${n.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${n.target?`for element: ${pt(n.target)}`:"for entire page"}`;case"FILE_UPLOAD":return n.fileSource.type==="URL"?`Upload file: ${n.fileSource.url}`:`Upload file: ${n.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Assert the element ${pt(n.target)} ${yR(n.assertion)}`;case"PAGE_CHECK":return`Assert the page ${wR(n.assertion)}`;case"WAIT_FOR_URL":return n.url?`Wait for page URL to match: ${n.url}`:n.matcher?`Wait for page URL to ${dd(n.matcher)}`:"Wait for page URL to match";case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return n.pattern?`Register a listener for network requests that match ${n.pattern}`:"Register a listener for network requests";case"AWAIT_LISTENER":return n.key?`Wait for the listener ${n.key} to resolve`:"Wait for a listener to resolve";default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function Mg(n){let e=[];for(let t of n){t.sort((s,a)=>s.timestamp-a.timestamp);let r=[],o,i=1;for(let s of t)o&&o.text===s.text&&o.type===s.type&&JSON.stringify(o.args??null)===JSON.stringify(s.args??null)?i++:(o&&(i>1?o.args&&o.args.length?o.args.push(`(repeated ${i} times)`):o.text+=` (repeated ${i} times)`:r.push(o)),o=s,i=1);o&&r.push(o),e.push(r)}return e}import{cloneDeep as CG,unset as RG}from"lodash-es";function ln(n){switch(n.type){case"AI_ACTION":return`AI action: ${Me(n.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${Me(n.text,100)}`;case"PRESET_ACTION":return _r(n.command);case"MODULE":return`Module: ${n.id}`;case"RESOLVED_MODULE":return`Module: ${n.name}`;case"CONDITIONAL":return"Conditional step";case"IFRAME":return"Frame step";case"SECTION":return`Section${n.description?`with goal: ${Me(n.description,100)}`:""}`;default:return(t=>{throw new Error("You missed a case in the switch above")})(n)}}var vR="[FAILED]";async function Fg(n,e,t,r){if(t)if(t.startsWith("http")){let i=await(await fetch(t)).arrayBuffer();return`data:image/jpeg;base64,${Buffer.from(i).toString("base64")}`}else return t.startsWith("data:")?t:`data:image/jpeg;base64,${t}`;else if(r){let o=await e.getScreenshot(n,r);if(o)return`data:image/jpeg;base64,${Buffer.from(o).toString("base64")}`}}async function Ca(n,e,t,{numScreenshots:r=1,addIndices:o=!0,includeBeforeScreenshots:i=!1,includeDomState:s=!1,recursive:a=!0}){let l=[],c;for(let p=0;p<t.length;p++){let d=t[p],u=a?Mr(d):ln(d),m={description:`Step ${p}: ${u}`,startedAt:d.startedAt,finishedAt:d.finishedAt,beforeUrl:d.beforeUrl,afterUrl:d.afterUrl,message:d.message!=="Successfully executed preset action."?d.message:void 0,index:o?p:void 0};if(d.status==="FAILED"){m.description=`${vR} ${m.description}`,o&&(c=p);try{let h=Gm.array().parse(d.details);for(let g of h)"pageState"in g&&s&&(m.pageState=g.pageState)}catch{}}r>0&&p>=t.length-r&&(m.afterScreenshot=await Fg(n,e,d.afterScreenshot,d.afterSnapshot),i&&(m.beforeScreenshot=await Fg(n,e,d.beforeScreenshot,d.beforeSnapshot))),l.push(m)}return{results:l,failureIndex:c}}function Mr(n){let e=ln(n);switch(n.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":e+=`
16
16
  `;for(let t=0;t<n.results.length;t++)e+=Ve(`Sub-step ${t} in AI action:
17
17
  `,2),e+=`${Ve(Mr(n.results[t]),2)}
@@ -38,7 +38,7 @@ ${JSON.stringify(t)}`);let r=[];if(!n.skipIntermediateEntries)for(let o=e.length
38
38
  `,e+=Ve(`${"=".repeat(10)}
39
39
  `,2);return e}default:return(r=>{throw new Error("You missed a case in the switch above")})(n)}}function Ve(n,e){return n.split(`
40
40
  `).map(t=>" ".repeat(e)+t).join(`
41
- `)}function Dg(n,e){try{if(!n)return n;if(typeof n=="string")return Me(n,3e4);if(typeof n=="object"){let{jsonString:t}=Li(JSON.stringify(n,(r,o)=>e?.includes(r)||typeof o=="string"&&o.length>3e4?"REDACTED":o),2e4);return JSON.parse(t)}return n}catch{return n}}import{cloneDeep as WG}from"lodash-es";var xR=/^(?!.*\S+\s+\S+).*$/,TR=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,ER=/style="([^"]*)/g,CR=/data-[\w-]+/g,RR=n=>{switch(n.type){case"AI_WAIT":case"AI_ASSERTION":return{type:n.type,assertion:n.assertion};case"DRAG":if(n.fromTarget.type==="description")return{type:n.type,description:n.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(n.target?.type==="description")return{type:n.type,description:n.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function Ug(n){let e=RR(n),t=e.type==="AI_ASSERTION"||e.type==="AI_WAIT"?e.assertion:e.description;return!t||t==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:xR.test(t)&&TR.test(t)?{thoughts:"Too few words in the command description. Please add more words to the description.",category:"FEW_WORDS"}:ER.test(t)?{thoughts:"Style tag is not allowed in the command description. Please remove it and describe the command in a different way.",category:"STYLE_TAG"}:CR.test(t)?{thoughts:"Hardcoded data attributes are not recommend in the command description. If the attribute doesn't directly match the quotes, autohealing will fail.",category:"HARDCODED_ATTRIBUTE"}:new RegExp(`\\b${e.type}\\b`,"gi").test(t)?{thoughts:"The description contains the same word as the command type. Please remove it since the type of command is already known.",category:"TYPE_IN_DESCRIPTION"}:{thoughts:"NONE",category:"NONE"}}function Bg(n,e){if(!(!n.envs||!n.envs.length)){for(let t of n.envs){let r=t;e in t&&(r[e]&&(t.default=!0),delete r.defaultOnCloud,delete r.defaultOnLocal)}n.envs.some(t=>t.default)||(n.envs[0].default=!0)}}import{cloneDeep as pf}from"lodash-es";import OR from"diff-lines";import Aa,{gte as kR}from"semver";var zg={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async n=>(n=n.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),n=n.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),n)};var jg={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,r=t[t.length-1];return r&&r.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var AR=["target","fromTarget","toTarget"];function Hg(n){for(let e of AR){if(n[e]===void 0)continue;let t=n[e];t.elementDescriptor!==void 0?t.type="description":n[e]={type:"description",elementDescriptor:""}}}var $g={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":return Hg(e.command),e;case"AI_ACTION":{let t=e.commands;for(let r of t??[])Hg(r);return e}default:return e}})};import{v4 as IR}from"uuid";var Wg={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=IR()),e;default:return e}})};import{v4 as Gg}from"uuid";var Vg={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??Gg(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??Gg()}})),delete e.commands),e;default:return e}})};var qg={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as PR}from"uuid";var Kg={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>("id"in e&&typeof e.id=="string"||(e.id=PR()),e))};import{v4 as Yg}from"uuid";var Jg={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=Yg())}return e.id=Yg(),e})};var Xg={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as LR}from"uuid";var Zg={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=LR()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var Qg={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var ef={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&tf(t),e})};function tf(n){n&&Object.keys(n).forEach(e=>{if(typeof n[e]=="object"&&n[e]){tf(n[e]);return}if(typeof n[e]!="string")return;let t=n[e];e==="code"?n[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(n[e]=t.replace(/inputs\./g,"env."))})}var nf={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||t.url===void 0||(t.action={type:"SUBSTRING",substring:t.url},t.url=void 0),e})};var rf={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TYPE"?e:t.pressKeysSequentially===void 0?(t.delay=0,e):(t.pressKeysSequentially&&(t.pressKeysSequentially=void 0,t.delay=50),e)})};var of={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="WAIT_FOR_URL"||t.url===void 0||(t.matcher={type:"GLOB",glob:t.url},t.url=void 0),e})};var sf={name:"Migrate AI assertions to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async n=>n.map(e=>{if(e.type!=="AI_ASSERTION")return e;let r={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...r};return delete o.text,o}),stopOnFailure:!0};var Ra=new Set(["CLICK","TYPE","SELECT_OPTION"]),af={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e.command,r=t?.type,o=t?.elementDescriptor;return(o!==void 0||Ra.has(r))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(s=>{let a=s?.elementDescriptor,l=s?.type;(a!==void 0||Ra.has(l))&&(s.target={elementDescriptor:a??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(s=>{let a=s.command,l=a?.elementDescriptor,c=a?.type;(l!==void 0||Ra.has(c))&&(a.target={elementDescriptor:l??""}),s.commands&&Array.isArray(s.commands)&&s.commands.forEach(d=>{let u=d?.elementDescriptor,m=d?.type;(u!==void 0||Ra.has(m))&&(d.target={elementDescriptor:u??""})})}),e}),stopOnFailure:!0};var lf={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(r=>{if(r&&typeof r=="object"){let o=r;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var cf={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e.command,r=t?.type;return r?.startsWith("PRESET_")&&(t.type=r.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let s=i.type;s?.startsWith("PRESET_")&&(i.type=s.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let s=i.command,a=s?.type;a?.startsWith("PRESET_")&&(s.type=a.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(c=>{let p=c.type;p?.startsWith("PRESET_")&&(c.type=p.slice(7))})}),e}),stopOnFailure:!0};var Fr=[sf,lf,cf,af,zg,jg,$g,Wg,Vg,qg,Kg,Jg,Xg,Zg,Qg,ef,nf,rf,of];if(He!==Fr[Fr.length-1].toVersion)throw new Error("Please bump LATEST_VERSION in types package after adding a migration");Fr.forEach((n,e)=>{if(!Aa.valid(n.toVersion)||!Aa.valid(n.fromVersion))throw new Error(`Migration '${n.name}' has invalid version`);if(!Aa.gt(n.toVersion,n.fromVersion))throw new Error(`Migration '${n.name}' has toVersion <= fromVersion`);if(e===0)return;if(Fr[e-1].toVersion!==n.fromVersion)throw new Error(`Migration '${n.name}' at index ${e} is not contiguous with previous migration`)});function NR(n){return n.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var Gi=async({metadata:n,steps:e,logger:t,toVersion:r})=>{let o=e,{schemaVersion:i,id:s}=n,a=Fr.findIndex(p=>Aa.gt(p.toVersion,i));if(a===-1)return{steps:o,newVersion:i};let l=i;for(let p=a;p<Fr.length;p++){if(r&&kR(l,r)){t.debug("Stopping migration early because toVersion was reached");break}let d=Fr[p],u={id:s,migration:d.name,toVersion:d.toVersion};try{o=await df(o,d),l=d.toVersion}catch(m){throw t.error({err:m,...u},"Migration failed"),new Error(`Step migration ${d.name} failed: ${m}`)}}let c=OR(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return c.trim()&&t.debug({diffs:c,id:s},"Migration diffs"),{newVersion:l,steps:o}};async function df(n,e){let t=await e.execute(n);for(let r of t)for(let o of Object.keys(r)){if(!e.recursiveKeys.has(o))continue;let i=r[o];!i||!Array.isArray(i)||NR(i)&&(r[o]=await df(i,e))}return t}async function uf({rawSteps:n,metadata:e,logger:t,callbacks:r}){Bg(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:s}=await Ia({rawSteps:n.steps,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o}),a={...e,steps:i,schemaVersion:s};for(let l of["beforeSteps","afterSteps"]){let c=n[l];if(!c)continue;let{resolvedSteps:p}=await Ia({rawSteps:c,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o});a[l]=p}return{resolvedTest:a,moduleIds:Array.from(Object.keys(o))}}async function pd(n,e,t){let{newVersion:r,steps:o}=await Gi({metadata:n,steps:e,logger:t});try{return{steps:Ke.array().parse(o),newVersion:r}}catch(i){throw t.error({type:"zod",err:i,newVersion:r,id:n.id,steps:o},"Failed to parse test steps while migrating test"),new ya(`Failed to parse test steps while migrating test: ${i}`,n.id,"entity",{cause:i})}}async function Ia({rawSteps:n,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o={}}){let{newVersion:i,steps:s}=await pd(e,n,t),a=[];for(let l of s)a.push(await Vi({step:l,callbacks:r,logger:t,resolvedModuleCache:o}));return{resolvedSteps:a,newSchemaVersion:i}}async function Vi({step:n,callbacks:e,logger:t,resolvedModuleCache:r}){switch(n.type){case"AI_ACTION":return n;case"AI_ACTION_DYNAMIC":return n;case"PRESET_ACTION":return n;case"MODULE":{let l=n.moduleId,c=r[l];if(c)return{...pf(c),...n,type:"RESOLVED_MODULE"};let p=await e.onFetchModule({id:l,logger:t});if(!p)throw new Error(`Could not find module with id ${l}`);let{newVersion:d,steps:u}=await Gi({metadata:{id:l,schemaVersion:p.schemaVersion},steps:p.steps,logger:t}),m;try{m=Ke.array().parse(u)}catch(f){throw t.error({type:"zod",err:f,steps:u,newVersion:d,id:l},"Module failed to parse"),f}let h;try{h=await Promise.all(m.map(f=>Vi({step:f,callbacks:e,logger:t,resolvedModuleCache:r})))}catch(f){throw t.error({err:f,...n},`Failed to recursively resolve module '${p.name}': ${f}`),f}let g={...p,steps:h};return r[l]=pf(g),{...g,...n,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let l of n.blocks){let c=[];for(let p of l.steps)c.push(await Vi({step:p,callbacks:e,logger:t,resolvedModuleCache:r}));o.push({...l,steps:c})}let i;if(n.elseSteps){i=[];for(let l of n.elseSteps)i.push(await Vi({step:l,callbacks:e,logger:t,resolvedModuleCache:r}))}return{...n,blocks:o,elseSteps:i};case"SECTION":case"IFRAME":let s=[];for(let l of n.steps)s.push(await Vi({step:l,callbacks:e,logger:t,resolvedModuleCache:r}));return{...n,steps:s};default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function _R(n){return typeof n=="object"&&n!==null}function Mn(n){if(Array.isArray(n))return n.map(Mn);if(_R(n)){let e={};return Object.entries(n).forEach(([t,r])=>{r!==void 0&&(e[t]=Mn(r))}),e}return n}import{cloneDeep as mf}from"lodash-es";import{v4 as ud}from"uuid";async function Xe(n){let e=new Map,t=new Set,r=mf(n.stepLists.steps),o=await Dr({...n,steps:r,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t}),i={stepsToSave:{steps:o.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates};for(let s of["beforeSteps","afterSteps"]){let a=mf(n.stepLists[s]);if(!a)continue;let l=await Dr({...n,steps:a,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});i.cachesToSave.push(...l.cachesToSave),i.moduleUpdates.push(...l.moduleUpdates),i.stepsToSave[s]=l.stepsToSave}return i}async function Dr({steps:n,...e}){let{seenModules:t,cacheCreationParams:r,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:s,shouldCreateNewModuleId:a}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let c of n)switch(delete c.index,delete c.aiSuggested,c.id=e.createNewStepIds?ud():c.id,c.type){case"PRESET_ACTION":{let d=c.command;d.id=r?.createNewCacheIds?ud():d.id,kg(d),"cache"in d&&d.cache&&(r&&(l.cachesToSave=l.cachesToSave.concat(Og({id:d.id,orgId:r.orgId,testId:r.testId,value:wr.parse(d),moduleIdParents:o,moduleStepParents:i,skipIntermediateEntries:e.skipCacheIntermediateEntries}))),delete d.cache),d.thoughts&&delete d.thoughts,l.stepsToSave.push({...c,command:d});break}case"RESOLVED_MODULE":{let d=r?.createNewCacheIds?ud():c.id,u=c.moduleId;s.has(u)?u=s.get(u):a!==void 0&&(u=await a(c),s.set(c.moduleId,u));let{cachesToSave:m,stepsToSave:h,moduleUpdates:g}=await Dr({...e,steps:c.steps,cacheCreationParams:r?{...r,createNewCacheIds:!1}:void 0,moduleStepParents:[...i,d],moduleIdParents:[...o,u],skipCacheIntermediateEntries:r?.createNewCacheIds});l.moduleUpdates=l.moduleUpdates.concat(g),l.cachesToSave=l.cachesToSave.concat(m),t.has(u)||(t.add(u),l.moduleUpdates.push({...It.parse(c),steps:Ke.array().parse(h),moduleId:u}));let f={type:"MODULE",moduleId:u,inputs:c.inputs,id:d,skipped:c.skipped,cacheConfig:c.cacheConfig,envKey:c.envKey};l.stepsToSave.push(f);break}case"AI_ACTION":{if(!c.steps){l.stepsToSave.push(c);break}let{stepsToSave:d,cachesToSave:u}=await Dr({...e,steps:c.steps});try{c.steps=At.array().parse(d)}catch(m){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${m}`)}l.stepsToSave.push(c),l.cachesToSave=l.cachesToSave.concat(u);break}case"AI_ACTION_DYNAMIC":{l.stepsToSave.push(c);break}case"CONDITIONAL":{let d=[];for(let m of c.blocks){let{stepsToSave:h,cachesToSave:g,moduleUpdates:f}=await Dr({...e,steps:m.steps});d.push({...m,steps:h}),l.cachesToSave=l.cachesToSave.concat(g),l.moduleUpdates=l.moduleUpdates.concat(f)}let u={...c,elseSteps:void 0,blocks:d};if(c.elseSteps){let{stepsToSave:m,cachesToSave:h,moduleUpdates:g}=await Dr({...e,steps:c.elseSteps});u.elseSteps=m,l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(g)}l.stepsToSave.push(u);break}case"IFRAME":case"SECTION":{let{stepsToSave:d,cachesToSave:u,moduleUpdates:m}=await Dr({...e,steps:c.steps}),h={...c,steps:d};l.moduleUpdates=l.moduleUpdates.concat(m),l.stepsToSave.push(h),l.cachesToSave=l.cachesToSave.concat(u);break}default:return(d=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(c)}return l}import{cloneDeep as MR}from"lodash-es";import{stringify as hf}from"yaml";async function gf(n,e=new Set){let t={id:n.id,name:n.name,description:n.description,baseUrl:n.baseUrl,schemaVersion:n.schemaVersion,advanced:n.advanced,retries:n.retries,envs:n.envs,disabled:n.disabled,labels:n.labels},r={},o=await FR({originalStepLists:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},modules:r,processedModuleNames:e}),i={fileType:he.TEST,...t,beforeSteps:o.beforeSteps&&o.beforeSteps.length>0?o.beforeSteps:void 0,steps:o.steps,afterSteps:o.afterSteps&&o.afterSteps.length>0?o.afterSteps:void 0};return{test:hf(i),modules:r}}async function FR({originalStepLists:n,modules:e,processedModuleNames:t}){let r=MR(n);Object.values(r).forEach(s=>{DR(s??[])});let{stepsToSave:o,moduleUpdates:i}=await Xe({stepLists:r});for(let s of i)t.has(s.name)||(e[s.name]=UR(s),t.add(s.name));return o}function DR(n){ad({steps:n,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function UR(n){let e=It.parse(n),t={fileType:he.MODULE,...e,schemaVersion:He,steps:n.steps};return hf(t)}async function ne(n,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},n);function i(){clearTimeout(o),e?.removeEventListener("abort",i),r(e?.reason)}})}async function qi({promiseGenerator:n,signal:e,codePath:t,logger:r}){let i=Date.now(),s=setInterval(()=>{if(e?.aborted){clearInterval(s);return}r?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((a,l)=>{function c(){clearInterval(s),e?.removeEventListener("abort",c),l(e?.reason)}if(e?.aborted){l(e?.reason),clearInterval(s);return}e?.addEventListener("abort",c),(async()=>{try{a(await n())}catch(p){l(p)}finally{clearInterval(s),e?.removeEventListener("abort",c)}})()})}async function Ur({promiseGenerator:n,timeoutMs:e,codePath:t,logger:r,signal:o}){let i=!1,s=new AbortController,a=()=>{s.abort()},l=setTimeout(()=>{i||s.abort()},e);o?.addEventListener("abort",a);try{return await qi({promiseGenerator:n,signal:s.signal,codePath:t,logger:r})}finally{i=!0,o?.removeEventListener("abort",a),clearTimeout(l)}}function Pa(n){let e=[];for(let t of n)switch(t.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(t);break;case"RESOLVED_MODULE":{let r={...t,type:"MODULE"};e.push(kn.parse(r));break}case"IFRAME":case"SECTION":{let r={...t,steps:Pa(t.steps)};e.push(Ke.parse(r));break}case"CONDITIONAL":{let r={...t,blocks:t.blocks.map(o=>({assertion:o.assertion,steps:Pa(o.steps)})),elseSteps:t.elseSteps?Pa(t.elseSteps):void 0};e.push(xr.parse(r));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function La(n){return Pa([n])[0]}import BR from"picomatch";var md=(n,e,t)=>{t?.caseInsensitive&&(n=n.toLowerCase());let r;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;r=n.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;r=n===e.glob||BR(o)(n);break}case"REGEX":{r=new RegExp(e.regex).test(n);break}}return t?.negated?!r:r};var Ro=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}async saveStepCacheEntries(e,t,r){try{await this.client.updateStepCaches({entries:e,testId:t})}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let t=await this.client.getStepCacheForTest({testId:e.testId,organizationId:e.organizationId,steps:e.steps,schemaVersion:e.schemaVersion}),{hits:r}=Co({steps:e.steps,stepCacheEntries:t,logger:e.logger});this.client.updateCacheLastUsedDate(r,e.logger)}fetchIconKnowledgeBase(e,t){return this.client.fetchIconKnowledgeBase(e,t)}saveNewIcons(e,t,r){return this.client.saveNewIcons(e,t,r)}};import{Faker as zR,en as jR}from"@faker-js/faker";var Ao="v1",er=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new zR({locale:jR}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Ao}/tools/ai/generate`,{method:"POST",body:t}).catch(r=>{throw r instanceof an?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Ao}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof an?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Ao}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof an?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Ao}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof an?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Ao}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof an?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Ao}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof an?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as HR}from"zod";var Io=class extends Mt{constructor(e){super(e)}async rankChunksWithAi(e,t){let r={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:t.abortSignal});return oh.parse(o)}async rankChunksWithRag(e,t){let r=await this.sendRequest(`/${M}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Wi,...e},signal:t.abortSignal});return rh.parse(r)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${M}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return HR.string().parse(t)}async getElementLocation(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/locate-element`,{method:"POST",body:r,signal:t.abortSignal});return Bh.parse(o)}async getAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/assertion`,{method:"POST",body:r,signal:t.abortSignal});return nd.parse(o)}async getLintStepResult(e,t){let r={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/lint/step`,{method:"POST",body:r,signal:t.abortSignal});return Uh.parse(o)}async getVisualAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/visual-assertion`,{method:"POST",body:r,signal:t.abortSignal});return nd.parse(o)}async getAiActionCommand(e,t){let r=await this.sendRequest(`/${M}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Dh.parse(r)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${M}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let r=await this.sendRequest(`/${M}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Ec.parse(r)}async getReverseMappedDescription(e,t){let r=await this.sendRequest(`/${M}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return zh.parse(r)}async getTextExtraction(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/text-extraction`,{method:"POST",body:r,signal:t.abortSignal});return Tc.parse(o)}async getTestResultClassification(e,t){let r=await this.sendRequest(`/${M}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Mc.parse(r)}async getExtractedKeywords(e,t){let r=await this.sendRequest(`/${M}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return nh.parse(r)}async getAutohealingProposal(e,t){let r=await this.sendRequest(`/${M}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Yu.parse(r)}async getFailureRecoveryProposal(e,t){let r=await this.sendRequest(`/${M}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Ju.parse(r)}async getIframeRegex(e,t){let r=await this.sendRequest(`/${M}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Ou.parse(r)}};var Br=class extends Mt{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let r=await this.sendRequest(`/${M}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return ku.parse(r)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var Oa=class{constructor(e){this.client=e}async uploadResultsArchive(e){let{uploadUrl:t,id:r}=await this.client.generateTestResultsUploadUrl(),o=await Eo(t,"application/zip",e);if(!o.ok)throw new Error(`Failed to upload test results: ${await o.text()}`);let{runGroupId:i}=await this.client.startProcessingResultsUpload(r);return i}};import{PostHog as $R}from"posthog-node";var Po=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var ff=n=>{let e=n.reason===void 0?new DOMException("This operation was aborted.","AbortError"):n.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};async function D(n,e){let{milliseconds:t,fallback:r,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a;return new Promise((l,c)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:d}=e;d.aborted&&c(ff(d)),a=()=>{c(ff(d))},d.addEventListener("abort",a)}if(t===Number.POSITIVE_INFINITY){n.then(l,c);return}let p=new Po;s=i.setTimeout.call(void 0,()=>{if(r){try{l(r())}catch(d){c(d)}return}"cancel"in n&&typeof n.cancel=="function"&&n.cancel(),o instanceof Error?c(o):(p.message=o??`Promise timed out after ${t} milliseconds`,c(p))},t),(async()=>{try{l(await n)}catch(d){c(d)}})()}).catch(l=>{throw l}).finally(()=>{s!==void 0&&i.clearTimeout.call(void 0,s),a!==void 0&&e.signal&&e.signal.removeEventListener("abort",a)})}async function Sf(n,e){let t,r=0,o=3,i,s;for(;r<o;)try{let a=await D(n.getAllFlagsAndPayloads(e),{milliseconds:5e3});i=a.featureFlags,s=a.featureFlagPayloads;break}catch(a){t=a,r++,await new Promise(l=>setTimeout(l,100*r))}if(i&&s)return{flags:i,payloads:s};throw t}var Lo=class n extends ji{constructor(t,r,o,i){super(o,i);this.client=t;this.orgId=r}static async init(t,r){let o=r??new $R("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:i,payloads:s}=await Sf(o,t);return new n(o,t,i,s)}async refresh(){let{flags:t,payloads:r}=await Sf(this.client,this.orgId);this.flags=t,this.payloads=r}};import{Server as EL}from"socket.io";import{cloneDeep as WR}from"lodash-es";var GR={showOverlay:!1},hd=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:t,cleanup:r,clientIp:o,sessionId:i,browserbaseSessionId:s}){return this.sessions.set(i,{controller:e,context:t,cleanup:r,clientIp:o,browserbaseSessionId:s,browserBehavior:WR(GR)}),i}removeSession(e,t){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:i}=o;try{i.setClosed(),await i.browser.cleanup()}catch(s){t.error({err:s},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(s){t.error({err:s},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}},Z=new hd;function yf(n,e,t){let r=Date.now(),o=Date.now(),i,s,a,l,c=!1,p=async(h,g)=>{if(!h.closed&&!h.isInPageLoad)try{let f=a;a=void 0;let S=h.url(),v=g.toEditorDisplayCopy();JSON.stringify(v)===JSON.stringify(i)&&S===l&&r>o||(n.emit("browserState",{logsPerPage:f?.logsPerPage,harPages:f?.harPages,harEntries:f?.harEntries,viewport:h.getViewport(),url:S,iframeSrcUrls:s??[],context:v,isInPageLoad:h.isInPageLoad}),r=Date.now()),l=S,i=v}catch(f){if(!n.connected)return;let S=f instanceof Error?f.message:`${f}`;if(S.includes("Frame was detached")||S.includes("Not attached to an active page")||S.includes("browser has been closed")||S.includes("UserInfrastructureError"))return;t.error({err:f,sessionId:e},"Error grabbing browser state")}},d=setInterval(()=>{let h=Z.getSession(e),g=h?.controller?.browser;if(!g||g.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(d);return}p(g,h.context)},1e3),u=(h,g)=>!!(JSON.stringify(h)!==JSON.stringify(s)||g.logsPerPage.some(f=>f.length>0)||g.harPages&&Object.keys(g.harPages).length>0||g.harEntries&&Object.keys(g.harEntries).length>0),m=setInterval(async()=>{let g=Z.getSession(e)?.controller?.browser;if(!g||g.closed){clearInterval(m);return}else if(c)return;c=!0;try{let f=await g.getAllFrameUrls(),S=g.retrieveAndClearDebugData();u(f,S)&&(s=f,a=S,o=Date.now())}catch(f){t.warn({err:f},"Failed to fetch extended details")}finally{c=!1}},2500);return{timers:[d,m]}}var tr={};var VR=n=>()=>{let{sessionId:e}=n.metadata;tr[e]?.abort?.abort()},bf={event:"cancelApiTest",createHandler:VR};import{CookieJar as cA}from"tough-cookie";import{randomUUID as eA}from"crypto";import{faker as qR}from"@faker-js/faker";import KR from"assert";import YR from"axios";import JR from"moment";import*as XR from"otpauth";import ZR from"pg";async function wf(n){let e;try{e=new URL(n.url).hostname}catch{}let t=[];return n.headers.getSetCookie()?.forEach(r=>{let o=ha(r,e);t.push(...o)}),t}var QR=Object.getPrototypeOf(async function(){}).constructor;async function vf(n,e,t){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o}=e.bindings,i=e.tools,s={},a=(f,S)=>{o[f]=S,s[f]=S},l={},c=(f,S)=>{o[f]=S,l[f]=S},p;r.includes("Octokit")&&(p=(await import("@octokit/rest")).Octokit);let d;r.includes("createAppAuth")&&(d=(await import("@octokit/auth-app")).createAppAuth);let u=async()=>await Promise.resolve(new QR("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai",r)(YR,JR,i.fakerInstance??qR,KR,ZR,p,d,XR,wf,o,a,c,S=>i.sms.send(S),S=>i.sms.fetchLatest(S),i.email,i.sms,i.ai)),m=!0,h,g;try{h=await D(u(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal})}catch(f){t.error(`[${n}] Error executing code: ${f}`),m=!1,f instanceof Po?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:h,variableUpdates:s,persistentVariableUpdates:l,success:m,error:g}}async function xf({code:n,fragment:e,context:t,localTools:r,logger:o,signal:i,timeoutMs:s=Kn}){let a=eA(),l=await vf(a,{code:n,options:{fragment:e,timeoutMs:s},bindings:t.toObjectCopy(),tools:r,signal:i},o);return y.debug(`[${a}] Got execution result: ${JSON.stringify(l)}`),l}import{createHmac as tA,randomUUID as nA}from"crypto";import rA from"fetch-retry";var oA=rA(global.fetch,{retries:3,retryOn:function(n,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(n){return Math.pow(2,n)*500}}),Tf=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Ef=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function Cf({orgId:n,code:e,fragment:t,context:r,timeoutMs:o=Kn,retries:i=2,signal:s,logger:a}){if(!Tf)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,p=0;if(!Ef)throw new Error("Missing lambda auth secret.");let d=tA("sha256",Ef).update(n).digest("hex");for(;p<=i;){p++,s?.throwIfAborted();let m={id:nA(),orgId:n,momenticLambdaAuthHash:d,code:e,fragment:t,state:r.toObjectCopy(),timeoutMs:o};try{if(l=await D(oA(Tf,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:s}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(h){c=h}}if(c)throw a.error({err:c},"Failed to evaluate code remotely"),c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let u;try{u=uh.parse(await l.json())}catch(m){throw new Error(`Code evaluation server returned invalid response: ${m}`)}if(u.error)throw new Error(`Code evaluation error: ${u.error}`);return u}async function Fn(n){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Cf(n);else if(n.localTools)e=await xf({...n,localTools:n.localTools});else throw new Error("No code evaluation environment available");if(e.error)throw new Error(`Code evaluation error: ${e.error}`);if(e.variableUpdates)for(let[t,r]of Object.entries(e.variableUpdates))n.context.setVariable(t,r);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await n.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,r]of Object.entries(e.persistentVariableUpdates))n.context.setVariable(t,r)}return e.result}async function Ut(n){let{orgId:e,s:t,context:r,logger:o,signal:i,flagStore:s,retries:a=2,timeoutMs:l=Kn,allowUndefined:c=!1}=n,p=/{{(.*?)}}/g,d=t.matchAll(p),u=t;for(let m of d){if(m.length<2)continue;let h=m[1].trim(),g;try{g=await Fn({orgId:e,code:h,fragment:!0,context:r,timeoutMs:l,logger:o,retries:a,localTools:n.localTools,signal:i,flagStore:s})}catch(S){throw o.error({err:S,value:t},"Error evaluating template string"),S}if(g===void 0&&!c)throw new R("UserConfigurationError",`Template fragment '${h}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let f=typeof g=="string"?g:`${g}`;f=f.replaceAll(/\$/g,"$$$$"),u=u.replace(m[0],f)}return u}async function Oo(n){return Rf(n)}async function Rf({obj:n,bannedKeys:e,allowList:t,context:r,prefixPath:o="",replacements:i={},...s}){for(let a in n){if(e.includes(a))continue;let l=!1;if(t)if(t.includes(a))l=!0;else continue;let c=n[a],p=o?`${o}.${a}`:a;if(typeof c=="string"&&c.includes("{{")){let d=await Ut({s:c,context:r,...s});if(c===d)continue;i[p]=c,n[a]=d}else typeof c=="object"&&c!==null&&!Array.isArray(c)&&await Rf({obj:c,bannedKeys:e,context:r,prefixPath:p,replacements:i,allowList:l?void 0:t,...s})}return i}import sA from"fetch-cookie";import{cloneDeep as aA}from"lodash-es";var ka=(n,e)=>{try{let{hostname:t,pathname:r}=new URL(n),{hostname:o,pathname:i}=new URL(e);return t!==o||r!==i}catch{return!1}},ko=n=>{try{return new URL(n),!0}catch{return!1}},Af=n=>!n.toLowerCase().startsWith("http"),No=(n,e)=>{try{return new URL(n,e),!0}catch{return!1}};function nr(n,e){try{return!!new URL(n).origin.trim()}catch(t){return e?.error({url:n,err:t},"Invalid URL in check"),!1}}var iA=3e4;async function Na({command:n,logger:e,baseUrl:t,fetchImplementation:r=fetch}){let o=n.timeout??iA/1e3,i=Object.fromEntries(Object.entries(n.headers||{}).filter(([m,h])=>m&&h)),s=new URLSearchParams;Object.entries(n.params||{}).filter(([m,h])=>m&&h).forEach(([m,h])=>{s.append(m,h)});let a=s.toString(),l;if(ko(n.url)&&(l=n.url),t&&No(n.url,t)&&(l=new URL(n.url,t).toString()),!l)throw new R("ActionFailureError",`Invalid URL: ${n.url}`);e.debug({url:l,searchParams:a,headers:i,body:n.body,method:n.method},"Making HTTP request");let p=await D((async()=>{let m=a?`${l}?${a}`:l;try{return await r(m,{headers:i,method:n.method,body:n.body})}catch(h){throw e.error({err:h},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${h}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!p.ok){let m;try{m=await p.text()}catch(h){m=`Failed to read response body: ${h}`}throw new R("ActionFailureError",`Fetch request failed with status ${p.status}: ${m}`)}let d={};p.headers.forEach((m,h)=>{d[h]=m});let u={status:p.status,headers:d};return p.headers.get("content-type")?.includes("json")?u.json=await p.json():p.headers.get("content-type")?.includes("text")&&(u.text=await p.text()),u}async function If(n){let{fixtures:e,inputs:t}=n,{context:r}=e,{orgId:o,step:i}=t,s=aA(i);await Oo({obj:s,orgId:o,bannedKeys:["code"],...e});let a=await lA(n);return s.envKey&&a.data&&r.setVariable(s.envKey,a.data),a}async function lA(n){let{fixtures:e,inputs:t}=n,{step:r,orgId:o,baseUrl:i}=t,{cookieJar:s}=e,a=new Date;switch(r.type){case"JAVASCRIPT":{let c=await Fn({code:r.code,orgId:o,fragment:!!r.fragment,timeoutMs:r.timeout?r.timeout*1e3:void 0,...e});try{JSON.stringify(c)}catch(p){return{...r,startedAt:a,finishedAt:new Date,status:"FAILED",message:`JavaScript return value is not serializable: ${p instanceof Error?p.message:`${p}`}`}}return{...r,startedAt:a,finishedAt:new Date,message:"JavaScript code executed successfully",status:"SUCCESS",data:c}}case"REQUEST":{let c=sA(fetch,s),p=await Na({command:r,logger:e.logger,baseUrl:i,fetchImplementation:c});return{...r,startedAt:a,finishedAt:new Date,status:"SUCCESS",message:"Request executed successfully",data:p}}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}async function Pf(n){let{inputs:e,fixtures:t,callbacks:r}=n,{signal:o}=t,{steps:i,orgId:s,baseUrl:a}=e,{test:l,step:c}=r,p={startedAt:new Date,status:"RUNNING",results:[]},d=p.results,u=new cA,m={cookieJar:u,...t};for(let h of i){let g=new Date;c.onStarted?.(h.id);let f;try{o?.throwIfAborted(),f=await If({inputs:{step:h,baseUrl:a,orgId:s},fixtures:m})}catch(S){o?.aborted?f={...h,startedAt:g,finishedAt:new Date,status:"CANCELLED",message:"Step cancelled by user."}:f={...h,startedAt:g,finishedAt:new Date,status:"FAILED",message:`Step failed: ${S instanceof Error?S.message:`${S}`}`}}if(d.push(f),c.onFinished?.({result:f,cookies:fa(u,new URL(a).hostname)}),l.updateAttemptProgress?.({results:d}),f.status!=="SUCCESS"){p.status=f.status==="CANCELLED"?"CANCELLED":"FAILED";break}}return p.status==="RUNNING"&&(p.status="PASSED"),p.finishedAt=new Date,l.onFinished?.(),p}async function Lf(n){let{socket:e,storage:t}=n,r=n.socket.id,{testId:o}=e.handshake.query;if(typeof o!="string")throw new Error(`Received invalid test ID that does not parse as a string: ${o}`);let i=await t.getOrgId({type:"api-test",testId:o}),{baseUrl:s,envName:a,environmentVariables:l}=await gd({testId:o,orgId:i,logger:n.logger,storage:t,authorization:n.authorization}),c={type:"api-test",orgId:await n.storage.getOrgId({type:"api-test",testId:o}),testId:o,sessionId:r,latestContext:new Pt({baseUrl:s||"",currentUrl:s||"",variablesFromEnvironment:l,envName:a})};return tr[r]=c,c}async function gd({testId:n,orgId:e,logger:t,storage:r,authorization:o}){let i=await r.fetchApiTestMetadata(n,e,t);if(!i)throw new Error(`Failed to fetch API test metadata for test ID: ${n}`);let s;o?.type==="API_KEY"&&(s=new er({httpClient:new Mt({...o,logger:t}),fakerSeed:void 0}));let a=i.envs?.find(d=>d.default),l;a&&(l=await r.fetchEnvironment(e,a.name,t));let c=i.baseUrl||l?.variables?.[Pe];if(!c)throw new Error("Base URL is empty in both API test options and the configured environment");let p={...l?.variables};return{baseUrl:c,envName:l?.name,environmentVariables:p,localCodeEvalTools:s}}var dA=n=>async(e,t)=>{let{steps:r}=e,{authorization:o,metadata:i,socket:s,storage:a,logger:l,flagStoreFactory:c}=n,{orgId:p,testId:d,sessionId:u}=i,m=l.child({testId:d,orgId:p,sessionId:u}),h=tr[u];if(!h)throw new Error(`No api testing session with id ${u} could be found. Please reconnect and try again.`);let g=new AbortController;h.abort=g;let f=h.latestContext,{localCodeEvalTools:S,baseUrl:v}=await gd({testId:d,orgId:p,logger:m,storage:a,authorization:o}),b={context:f,logger:m,localTools:S,signal:g.signal,flagStore:await c(p)},E=await Pf({inputs:{steps:r,orgId:p,baseUrl:v},fixtures:b,callbacks:{test:{onFinished:()=>{s.emit("apiTestFinished")}},step:{onStarted:I=>{s.emit("apiStepStarted",I)},onFinished:I=>{s.emit("apiStepFinished",I)}}}});t({result:E})},Of={event:"executeApiTest",createHandler:dA};var pA=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async()=>{e.info({sessionId:t},"Cancel event received");let r=Z.getSession(t);if(!r)throw new Error("No active session found");try{r.controller.setClosed()}catch{}}},kf={event:"cancel",createHandler:pA};var uA=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async(r,o)=>{let i=Z.getSession(t);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let a=await s.getBrowserState({skipWait:!0});o({a11yTree:a.serialize()})}catch(a){e.error({err:a},"Error fetching a11y tree from the browser"),o({err:a.message})}}},Nf={event:"fetchA11yTree",createHandler:uA};var mA=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async(r,o)=>{let i=Z.getSession(t);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let a=await s.html();o({html:a})}catch(a){e.error({err:a},"Error fetching DOM from the browser"),a.name==="TimeoutError"?o({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):o({err:a.message})}}},_f={event:"fetchDom",createHandler:mA};var hA=({metadata:n,logger:e})=>{let{sessionId:t,type:r}=n;return o=>{e.info({sessionId:t,reason:o},`Disconnect event received (${o})`),r==="e2e"?Z.removeSession(t,e):r==="api-test"&&delete tr[t]}},Mf={event:"disconnect",createHandler:hA};function Jt(n){let{result:e,nestedResults:t}=n;if(!n.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=gA(t);fA(e,r,o);let i=[...n.asyncTasks];n.asyncTasks.push((async()=>{try{await SA(i,e,r,o)}catch(s){n.logger.error({result:n.result,err:s},"Error hoisting scalar result metadata")}})())}function gA(n){let e=n[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertion){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let r=n[n.length-1],o;for(;;){switch(r.type){case"PRESET_ACTION":{o=r;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!r.results.length){o=r;break}r=r.results[r.results.length-1];break;default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function fA(n,e,t){e&&(n.beforeUrl=e.beforeUrl),t&&(n.afterUrl=t.afterUrl,n.data=t.data,t.status!=="SUCCESS"&&(n.message=t.message))}async function SA(n,e,t,r){await Promise.allSettled(n),t&&(e.beforeSnapshot=t.beforeSnapshot),r&&(e.afterSnapshot=r.afterSnapshot)}import Ki from"os";import yA from"v8";var Ff,vn,bA=Ki.platform(),wA=Ki.cpus().map(n=>({model:n.model,speed:n.speed}));function Df(n){let e=()=>{try{let t=!1,r=vA(),o=xA();r.freeMemory<1e6&&(t=!0);let i=yA.getHeapStatistics(),s=i.used_heap_size,a=i.heap_size_limit;s/a>.9&&(t=!0),t?n.warn({memory:r,cpu:o,heapStats:i},"Critical resource usage metrics detected"):n.debug({memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,1e4),cpuMetadata:wA,platform:bA}}function vA(){let n=Ki.totalmem(),e=Ki.freemem(),t=n-e;return{totalMemory:n,freeMemory:e,usedMemory:t}}function xA(){let n=Ki.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of n)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!vn)return vn=t,null;let r={user:t.user-vn.user,nice:t.nice-vn.nice,sys:t.sys-vn.sys,idle:t.idle-vn.idle,irq:t.irq-vn.irq,total:t.total-vn.total};return Ff={measurementTime:e,intervalMs:e-vn.measurementTime,user:r.user/r.total*100,nice:r.nice/r.total*100,sys:r.sys/r.total*100,idle:r.idle/r.total*100,irq:r.irq/r.total*100,total:100-r.idle/r.total*100},vn=t,Ff}import{hostname as AA}from"os";async function Bf(n){let{command:e,tracer:t,timeoutMs:r,targetingWrapper:o,disableCache:i,fixtures:s}=n,{logger:a,abortSignal:l}=s;if(e.target&&!Vn(e.target))throw new Error("Element assertion with x/y is not supported yet");let c=e.assertion.type==="ELEMENT_EXISTENCE"&&e.assertion.negated,p=Date.now(),d=0,u,m=500;for(;d<2||Date.now()-p<r;){d++,d>1&&await ne(m,l),l?.throwIfAborted();try{let{newTarget:h,elementInteractedDisplayString:g,result:f}=await o({ctx:s.ctx,tracer:t,command:e,target:e.target,cache:e.cache?.target,action:async S=>TA(S.locator,n),options:{disableCache:i,useSelector:!!e.useSelector,iframeUrl:e.iframeUrl,disableGlobalLocatorRedirect:!0,source:c?"NEGATED_CHECK":void 0}});if(u={success:f.success,data:f.data,err:f.err,newTarget:h,elementInteractedDisplayString:g},!f.success){u=f,m=Math.min(m*2,1e4);continue}return u}catch(h){if(l?.throwIfAborted(),c)return{success:!0,thoughts:`The element described does not exist on the page: ${h.message}`};if(a.warn({err:h},"Element assertion ended in error, retrying..."),!(h instanceof R)||h.reason!="ActionFailureError")throw h;u={success:!1,err:h}}}if(!u)throw new Error(`Failed to evaluate manual element assertion in ${r}ms.`);return u}async function TA(n,{command:e,fixtures:t}){let r=e.assertion;await t.browser.highlight(n);let o=!0,i,s;switch(r.type){case"ELEMENT_CONTENT":{let a=await n.textContent()??"";if(s={elementTextContent:Me(a,500,!0)},!Uf(a,r.value,r.operation,!!r.negated)){let l=r.negated?Zn[r.operation]:Qn[r.operation];o=!1,i=new R("AssertionFailureError",`The content ${l} '${r.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{s={elementOuterHtml:Me(await n.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let a;try{a=await n.getAttribute(r.attr,{timeout:3e3})??""}catch(l){i=new R("AssertionFailureError",`The element does not have an attribute named ${r.attr}: ${l}`),o=!1;break}if(!Uf(a,r.value,r.operation,!!r.negated)){let l=r.negated?Zn[r.operation]:Qn[r.operation];o=!1,r.operation==="EXISTS"?i=r.negated?new R("AssertionFailureError",`The attribute ${r.attr} ${l}: ${a}`):new R("AssertionFailureError",`The attribute ${r.attr} ${l}`):i=new R("AssertionFailureError",`The attribute ${r.attr} ${l} '${r.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(r.condition){case"VISIBLE":{o=await n.isVisible({timeout:bn*1e3});break}case"EDITABLE":{o=await n.isEditable({timeout:bn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await n.isEnabled({timeout:bn*1e3});break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.condition)}if(o=r.negated?!o:o,!o){let a=r.negated?ld[r.condition]:cd[r.condition];i=new R("AssertionFailureError",`The element ${a}`)}break}}return{success:o,data:s,err:i}}function Uf(n,e,t,r){let o;switch(t){case"CONTAINS":{o=n.includes(e);break}case"EQUALS":{o=n.trim()===e.trim();break}case"STARTS_WITH":{o=n.trim().startsWith(e);break}case"EXISTS":{o=n.trim().length>0;break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return r?!o:o}import{Jimp as EA}from"jimp";async function Yi(n,e){let t=await n.screenshot(e),r=await EA.fromBuffer(t);return{buffer:t,width:Math.ceil(r.bitmap.width??0),height:Math.ceil(r.bitmap.height??0)}}import{Jimp as zf}from"jimp";import fd from"jpeg-js";import CA from"pixelmatch";async function jf({ctx:n,tracer:e,command:t,disableCache:r,browser:o,targetingWrapper:i,logger:s,screenshotStorage:a}){if(t.target&&!Vn(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:s});let l={clearHighlights:!0,hideCaret:!0},c;t.target?.elementDescriptor?c=(await i({ctx:n,tracer:e,command:t,target:t.target,cache:t.cache?.target??t.target?.a11yData,action:async W=>Yi(o,{locator:W.locator,...l}),options:{disableCache:!!r,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl,disableGlobalLocatorRedirect:!0}})).result:c=await Yi(o,l);let p=await a.prepareGoldenScreenshotForComparison(s,t,c);if((c.height!==p.height||c.width!==p.width)&&s.debug({currHeight:c.height,currWidth:c.width,savedHeight:p.height,savedWidth:p.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-p.height)>10||Math.abs(c.width-p.width)>10){let U=`${c.width}x${c.height}`,W=`${p.width}x${p.height}`;return{fail:!0,thoughts:`Current screenshot (${U}) does not match saved screenshot dimensions (${W}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:p.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await zf.fromBuffer(c.buffer),u={width:c.width,height:c.height},m=await zf.fromBuffer(p.buffer),h={width:p.width,height:p.height},g,f=u.width*u.height,S=h.width*h.height,v=Math.abs(u.height-h.height),b=Math.abs(u.width-h.width);if(f>S){let U=d.cover({w:h.width,h:h.height});c.buffer=await U.getBuffer("image/jpeg"),g="current",c.width=h.width,c.height=h.height}else if(S>f){let U=m.cover({w:u.width,h:u.height});p.buffer=await U.getBuffer("image/jpeg"),g="saved"}let x={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},C=t.threshold??.1,I=CA(fd.decode(p.buffer).data,fd.decode(c.buffer).data,x.data,c.width,c.height,{threshold:C,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,N=I>C*100,P=`Visual diff of ${I.toFixed(2)}% detected, which is ${N?"over":"under"} the threshold of ${C*100}%.`;if(g&&(P+=` The ${g} screenshot was cropped since it was taller by ${v} pixels and wider by ${b} pixels.`),N)throw new R("ActionFailureError",P);return{fail:N,thoughts:P,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:fd.encode(x,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var RA=5e3;async function _a({timeout:n=bn,...e}){let t=Date.now(),r=n*1e3,o=r+1e4,i,s=0,a=500;for(;s-t<r;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let l=Date.now();i=await Hf(e),s=Date.now();let c=s-l;if(c>1e3&&e.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await ne(a,e.signal),a=Math.min(Math.floor(a*1.5),RA);else return i}return i=await Hf(e),i}async function Hf({assertion:n,browser:e,flagStore:t}){switch(n.type){case"CONTENT":{let o,i=!1,s;try{let a;if(t.isBooleanFlagEnabled("auto_expand_iframes")){let l=await e.evaluateFunctionInAllFrames($f,{value:n.value,negated:!!n.negated,returnHtml:!1});i=l.some(c=>c.evaluation),a=l.find(c=>c.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:a}=await e.evaluateFunctionInPage($f,{value:n.value,negated:!!n.negated,returnHtml:!0}));if(!i){let l=n.negated?Zn.CONTAINS:Qn.CONTAINS;s=new R("AssertionFailureError",`The page ${l} '${n.value}'.`),o=a}}catch(a){s=new R("AssertionFailureError",`Failed to evaluate page content assertion: ${a instanceof Error?a.message:`${a}`}`)}return{success:i,err:s,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.type)}}function $f({value:n,negated:e,returnHtml:t}){let r=document.documentElement.outerHTML,o=r.includes(n)===!e;return r.length>1e4&&(r=r.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?r:void 0}}var Sd=async n=>{let{step:e,resolvedInputs:t}=n.moduleParams,{logger:r,context:o,storage:i,codeEvalTools:s,controller:a}=n.fixtures,l=a.browser,{orgId:c,runId:p}=n.inputs,d=a.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),r.debug({inputs:t,moduleId:e.moduleId},"Set module inputs"));let u,m=!1,h,g;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",S=await Ut({orgId:c,s:f,context:o,logger:r,localTools:s,signal:d,flagStore:a.flagStore});g={orgId:c,cacheKeys:[S,...Object.entries(t).map(([b,x])=>`${b}:${x}`)]},r.debug({original:f,keyParams:g},"Module cache key params");let v=Date.now();for(;Date.now()-v<Fh;){d?.throwIfAborted();let b=await i.getCacheResult(g);if(b){r.debug({cacheResult:b},"Got result from module execution cache"),u=Ma(e,t,"SUCCESS"),u.message="Used cached module result.",u.data=JSON.parse(b),m=!0;break}else r.debug({cacheKey:f,keyParams:g},"No cache result found, continuing with lock acquisition");let x=await i.acquireCacheLock({keyParams:g,clientMetadata:`hostName:${AA()};runId:${p}`},d);if(x.acquired){h=x.keyPrefix,r.info({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Acquired cache lock and proceeding with module execution");break}else r.debug({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Failed to acquire cache lock, retrying...");await ne(2500+Math.random()*1e4,d)}}try{if(!u)u=await IA(n);else if(e.autoAuth){let f=ga.safeParse(u.data);if(!f.success)throw new R("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);r.debug("Automatically loading auth state after cached module result"),await l.loadAuthState(f.data);let S=!1,v=e.advanced?.cacheInvalidation;if(v&&v.type==="PAGE_CHECK"){let b={type:"CONTENT",value:v.substring},x=await _a({timeout:bn,assertion:b,browser:l,flagStore:a.flagStore,logger:r,signal:d});x.success?r.debug({invalResult:x},"Cached result still valid after page check, continuing..."):(r.info({invalResult:x},"Invalidating cached result due to page check failure"),S=!0)}if(g&&S)return await i.deleteCacheResult(g),Sd(n)}}finally{try{h!==void 0&&!m&&u?.status==="SUCCESS"&&await PA({step:e,result:u,browser:a.browser,cacheKeyPrefix:h,logger:r,storage:i})}finally{h!==void 0&&await i.releaseCacheLock(h)}}return u},IA=async n=>{let{step:e,tracer:t}=n.moduleParams,r=Ma(e,n.moduleParams.resolvedInputs,"SUCCESS"),o=await t.startSubSteps(),{status:i,results:s}=await rr(n.work,()=>n.executeStepList({...n,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}}));return r.results=s,r.status=i,r.finishedAt=new Date,Jt({asyncTasks:n.work.asyncTasks,nestedResults:s,result:r,logger:n.fixtures.logger}),r};function Ma(n,e,t){let r={};return Object.entries(e).forEach(([i,s])=>{r[i]=JSON.stringify(s)}),{type:"MODULE",id:n.id,moduleId:n.moduleId,moduleName:n.name,startedAt:new Date,cacheConfig:n.cacheConfig,inputs:r,results:[],finishedAt:new Date,status:t}}async function Wf({orgId:n,step:e,context:t,logger:r,flagStore:o,codeEvalTools:i,signal:s}){let a={};try{for(let l of e.parameters??[]){let c=e.inputs?.[l]??e.defaultParameters?.[l];if(!c){r.warn(`No value or default found for parameter '${l}' that is required by module '${e.name}'`);continue}a[l]=await Fn({orgId:n,code:c,fragment:!0,context:t,logger:r,localTools:i,signal:s,flagStore:o})}return a}catch(l){throw s?.throwIfAborted(),new R("UserConfigurationError",`Failed to evaluate module inputs: ${l}`)}}async function PA({step:n,result:e,browser:t,cacheKeyPrefix:r,logger:o,storage:i}){let s=n.cacheConfig?.cacheExpiryMs;(!s||s===hg)&&(s=n.defaultCacheTtl??gg);let a;n.autoAuth?a=JSON.stringify(await t.saveAuthState()):e.data!==void 0?a=JSON.stringify(e.data):a='""',o.debug({cacheKeyPrefix:r,ttlMs:s,truncatedCacheResultJson:Dg(a)},"Setting module cache result"),await i.setCacheResult({result:a,keyPrefix:r,ttlMs:s})}async function or(n,e,t){let r=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,s="FAILED",a;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(a="Step aborted by user.",s="CANCELLED"):o instanceof R?a=`${o}`:a=`An unexpected error occurred: ${o.message}`,n.type==="RESOLVED_MODULE"){let l=Ma(n,{},"FAILED");return l.message=a,l.startedAt=r,l.finishedAt=i,l}return{...La(n),startedAt:r,finishedAt:i,status:s,data:null,message:a,results:[]}}}async function rr(n,e){let t=!1;try{return n&&!n.state.failureRecoveryDisabled&&(n.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{n&&t&&(n.state.failureRecoveryDisabled=void 0)}}import{randomUUID as Gf}from"crypto";import{cloneDeep as OA}from"lodash-es";function Fa(n,e){n.state.healingDetails?n.state.healingDetails.push(e):n.state.healingDetails=[e]}var Da=async n=>{let{step:e,tracer:t}=n.presetParams,{logger:r,controller:o,context:i,billingReporter:s}=n.fixtures,{collectDebugData:a}=n.options,{testMetadata:l,suiteMetadata:c}=n.inputs,p=e.command.type,d=r.child({commandType:p,stepId:e.id,commandId:e.command.id}),u=Ui(e.command);n.work.asyncTasks.push(s.reportCreditsUsed(d,p,u,{testId:l?.id,testName:l?.name,suiteId:c?.id,suiteName:c?.name}));let m=o.browser.url(),h=new Date,g,f=Gf(),S=Gf();if(a)try{g=await o.browser.screenshot({retries:1,clearHighlights:!0});let E=await o.browser.getRawCondensedHtml();t.attachBeforeHtmlSnapshot({logger:d,snapshotId:f,html:E}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(d,f,E))}catch(E){d.debug({err:E},"Failed to take screenshot before step, likely because the page is still loading. This is non-fatal and does not affect the test.")}let v,b,x,C=pa();try{let E=await o.executePresetCommand(C,t,e.command,i,l?.advanced.disableAICaching??!1);E.beforeScreenshotOverride&&(g=E.beforeScreenshotOverride),x=E.afterScreenshotOverride;let{proposedStep:I}=kA({work:n.work,step:e,newTargets:E.newTargets,logger:d}),N=new Date,P=o.browser.url();b={beforeUrl:m,afterUrl:P,startedAt:h,finishedAt:N,viewport:o.browser.getViewport(),status:E.fail?"FAILED":"SUCCESS",elementInteracted:E.elementInteracted},v={...e,message:E.thoughts??NA(E.newTargets)??"Successfully executed preset action.",beforeUrl:m,afterUrl:P,finishedAt:N,startedAt:h,status:E.fail?"FAILED":"SUCCESS",data:E.data,results:[b],details:C.details,proposedStep:I},"assertion"in e.command&&(v.message=E.thoughts||"Assertion passed.")}catch(E){d.error({message:E.message,stack:E.stack},`Failed executing preset step ${_r(e.command)}`);let I=o.browser.url(),N=new Date,P=E instanceof Error?E.message:`${E}`;E instanceof R&&E.getLastScreenshotBuffer()&&(x=E.getLastScreenshotBuffer()),b={beforeUrl:m,afterUrl:I,startedAt:h,finishedAt:N,viewport:o.browser.getViewport(),status:E instanceof DOMException&&E.name==="AbortError"?"CANCELLED":"FAILED",message:P},v={...e,startedAt:h,finishedAt:N,beforeUrl:m,afterUrl:I,status:E instanceof DOMException&&E.name==="AbortError"?"CANCELLED":"FAILED",message:P,failureReason:E instanceof R?E.reason:void 0,results:[b],details:C.details}}if(a)try{x||(x=await o.browser.screenshot({retries:1}));let E=await o.browser.getRawCondensedHtml();t.attachAfterHtmlSnapshot({logger:d,snapshotId:S,html:E}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(d,S,E))}catch(E){d.debug({err:E},"Failed store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return b.beforeSnapshot=f,v.beforeSnapshot=f,b.afterSnapshot=S,v.afterSnapshot=S,g&&(t.attachBeforeScreenshot({logger:d,snapshotId:f,screenshot:g}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(d,f,g))),x&&(t.attachAfterScreenshot({logger:d,snapshotId:S,screenshot:x}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(d,S,x))),v};function kA({work:n,step:e,newTargets:t,logger:r}){if(!t?.length)return{proposedStep:void 0};let o=e.command;_g(o,t,r);let i=t[0]?.description;if(i&&"target"in o&&o.target&&o.target.type==="description"){let s={...o,target:{...o.target,elementDescriptor:i}},a={...OA(e),command:s};return Fa(n,{type:"DESCRIPTION_UPDATE",thoughts:`Updated element description after the original element could not be found on the page. New element location reasoning: ${t[0]?.thoughts}`}),{proposedStep:a}}return{proposedStep:void 0}}function NA(n){if(n?.length){if(n.length===1&&n[0]?.thoughts)return n[0].thoughts;if(n.length===2&&n.every(e=>e.thoughts))return`Located first element: ${n[0]?.thoughts}
41
+ `)}function Dg(n,e){try{if(!n)return n;if(typeof n=="string")return Me(n,3e4);if(typeof n=="object"){let{jsonString:t}=Li(JSON.stringify(n,(r,o)=>e?.includes(r)||typeof o=="string"&&o.length>3e4?"REDACTED":o),2e4);return JSON.parse(t)}return n}catch{return n}}import{cloneDeep as WG}from"lodash-es";var xR=/^(?!.*\S+\s+\S+).*$/,TR=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,ER=/style="([^"]*)/g,CR=/data-[\w-]+/g,RR=n=>{switch(n.type){case"AI_WAIT":case"AI_ASSERTION":return{type:n.type,assertion:n.assertion};case"DRAG":if(n.fromTarget.type==="description")return{type:n.type,description:n.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(n.target?.type==="description")return{type:n.type,description:n.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function Ug(n){let e=RR(n),t=e.type==="AI_ASSERTION"||e.type==="AI_WAIT"?e.assertion:e.description;return!t||t==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:xR.test(t)&&TR.test(t)?{thoughts:"Too few words in the command description. Please add more words to the description.",category:"FEW_WORDS"}:ER.test(t)?{thoughts:"Style tag is not allowed in the command description. Please remove it and describe the command in a different way.",category:"STYLE_TAG"}:CR.test(t)?{thoughts:"Hardcoded data attributes are not recommend in the command description. If the attribute doesn't directly match the quotes, autohealing will fail.",category:"HARDCODED_ATTRIBUTE"}:new RegExp(`\\b${e.type}\\b`,"gi").test(t)?{thoughts:"The description contains the same word as the command type. Please remove it since the type of command is already known.",category:"TYPE_IN_DESCRIPTION"}:{thoughts:"NONE",category:"NONE"}}function Bg(n,e){if(!(!n.envs||!n.envs.length)){for(let t of n.envs){let r=t;e in t&&(r[e]&&(t.default=!0),delete r.defaultOnCloud,delete r.defaultOnLocal)}n.envs.some(t=>t.default)||(n.envs[0].default=!0)}}import{cloneDeep as pf}from"lodash-es";import OR from"diff-lines";import Aa,{gte as kR}from"semver";var zg={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async n=>(n=n.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),n=n.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),n)};var jg={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,r=t[t.length-1];return r&&r.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var AR=["target","fromTarget","toTarget"];function Hg(n){for(let e of AR){if(n[e]===void 0)continue;let t=n[e];t.elementDescriptor!==void 0?t.type="description":n[e]={type:"description",elementDescriptor:""}}}var $g={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":return Hg(e.command),e;case"AI_ACTION":{let t=e.commands;for(let r of t??[])Hg(r);return e}default:return e}})};import{v4 as IR}from"uuid";var Wg={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=IR()),e;default:return e}})};import{v4 as Gg}from"uuid";var Vg={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??Gg(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??Gg()}})),delete e.commands),e;default:return e}})};var qg={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as PR}from"uuid";var Kg={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>("id"in e&&typeof e.id=="string"||(e.id=PR()),e))};import{v4 as Yg}from"uuid";var Jg={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=Yg())}return e.id=Yg(),e})};var Xg={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as LR}from"uuid";var Zg={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=LR()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var Qg={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var ef={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&tf(t),e})};function tf(n){n&&Object.keys(n).forEach(e=>{if(typeof n[e]=="object"&&n[e]){tf(n[e]);return}if(typeof n[e]!="string")return;let t=n[e];e==="code"?n[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(n[e]=t.replace(/inputs\./g,"env."))})}var nf={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||t.url===void 0||(t.action={type:"SUBSTRING",substring:t.url},t.url=void 0),e})};var rf={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TYPE"?e:t.pressKeysSequentially===void 0?(t.delay=0,e):(t.pressKeysSequentially&&(t.pressKeysSequentially=void 0,t.delay=50),e)})};var of={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="WAIT_FOR_URL"||t.url===void 0||(t.matcher={type:"GLOB",glob:t.url},t.url=void 0),e})};var sf={name:"Migrate AI assertions to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async n=>n.map(e=>{if(e.type!=="AI_ASSERTION")return e;let r={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...r};return delete o.text,o}),stopOnFailure:!0};var Ra=new Set(["CLICK","TYPE","SELECT_OPTION"]),af={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e.command,r=t?.type,o=t?.elementDescriptor;return(o!==void 0||Ra.has(r))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(s=>{let a=s?.elementDescriptor,l=s?.type;(a!==void 0||Ra.has(l))&&(s.target={elementDescriptor:a??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(s=>{let a=s.command,l=a?.elementDescriptor,c=a?.type;(l!==void 0||Ra.has(c))&&(a.target={elementDescriptor:l??""}),s.commands&&Array.isArray(s.commands)&&s.commands.forEach(d=>{let u=d?.elementDescriptor,m=d?.type;(u!==void 0||Ra.has(m))&&(d.target={elementDescriptor:u??""})})}),e}),stopOnFailure:!0};var lf={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(r=>{if(r&&typeof r=="object"){let o=r;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var cf={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e.command,r=t?.type;return r?.startsWith("PRESET_")&&(t.type=r.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let s=i.type;s?.startsWith("PRESET_")&&(i.type=s.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let s=i.command,a=s?.type;a?.startsWith("PRESET_")&&(s.type=a.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(c=>{let p=c.type;p?.startsWith("PRESET_")&&(c.type=p.slice(7))})}),e}),stopOnFailure:!0};var Fr=[sf,lf,cf,af,zg,jg,$g,Wg,Vg,qg,Kg,Jg,Xg,Zg,Qg,ef,nf,rf,of];if(He!==Fr[Fr.length-1].toVersion)throw new Error("Please bump LATEST_VERSION in types package after adding a migration");Fr.forEach((n,e)=>{if(!Aa.valid(n.toVersion)||!Aa.valid(n.fromVersion))throw new Error(`Migration '${n.name}' has invalid version`);if(!Aa.gt(n.toVersion,n.fromVersion))throw new Error(`Migration '${n.name}' has toVersion <= fromVersion`);if(e===0)return;if(Fr[e-1].toVersion!==n.fromVersion)throw new Error(`Migration '${n.name}' at index ${e} is not contiguous with previous migration`)});function NR(n){return n.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var Gi=async({metadata:n,steps:e,logger:t,toVersion:r})=>{let o=e,{schemaVersion:i,id:s}=n,a=Fr.findIndex(p=>Aa.gt(p.toVersion,i));if(a===-1)return{steps:o,newVersion:i};let l=i;for(let p=a;p<Fr.length;p++){if(r&&kR(l,r)){t.debug("Stopping migration early because toVersion was reached");break}let d=Fr[p],u={id:s,migration:d.name,toVersion:d.toVersion};try{o=await df(o,d),l=d.toVersion}catch(m){throw t.error({err:m,...u},"Migration failed"),new Error(`Step migration ${d.name} failed: ${m}`)}}let c=OR(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return c.trim()&&t.debug({diffs:c,id:s},"Migration diffs"),{newVersion:l,steps:o}};async function df(n,e){let t=await e.execute(n);for(let r of t)for(let o of Object.keys(r)){if(!e.recursiveKeys.has(o))continue;let i=r[o];!i||!Array.isArray(i)||NR(i)&&(r[o]=await df(i,e))}return t}async function uf({rawSteps:n,metadata:e,logger:t,callbacks:r}){Bg(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:s}=await Ia({rawSteps:n.steps,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o}),a={...e,steps:i,schemaVersion:s};for(let l of["beforeSteps","afterSteps"]){let c=n[l];if(!c)continue;let{resolvedSteps:p}=await Ia({rawSteps:c,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o});a[l]=p}return{resolvedTest:a,moduleIds:Array.from(Object.keys(o))}}async function pd(n,e,t){let{newVersion:r,steps:o}=await Gi({metadata:n,steps:e,logger:t});try{return{steps:Ke.array().parse(o),newVersion:r}}catch(i){throw t.error({type:"zod",err:i,newVersion:r,id:n.id,steps:o},"Failed to parse test steps while migrating test"),new ya(`Failed to parse test steps while migrating test: ${i}`,n.id,"entity",{cause:i})}}async function Ia({rawSteps:n,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o={}}){let{newVersion:i,steps:s}=await pd(e,n,t),a=[];for(let l of s)a.push(await Vi({step:l,callbacks:r,logger:t,resolvedModuleCache:o}));return{resolvedSteps:a,newSchemaVersion:i}}async function Vi({step:n,callbacks:e,logger:t,resolvedModuleCache:r}){switch(n.type){case"AI_ACTION":return n;case"AI_ACTION_DYNAMIC":return n;case"PRESET_ACTION":return n;case"MODULE":{let l=n.moduleId,c=r[l];if(c)return{...pf(c),...n,type:"RESOLVED_MODULE"};let p=await e.onFetchModule({id:l,logger:t});if(!p)throw new Error(`Could not find module with id ${l}`);let{newVersion:d,steps:u}=await Gi({metadata:{id:l,schemaVersion:p.schemaVersion},steps:p.steps,logger:t}),m;try{m=Ke.array().parse(u)}catch(f){throw t.error({type:"zod",err:f,steps:u,newVersion:d,id:l},"Module failed to parse"),f}let h;try{h=await Promise.all(m.map(f=>Vi({step:f,callbacks:e,logger:t,resolvedModuleCache:r})))}catch(f){throw t.error({err:f,...n},`Failed to recursively resolve module '${p.name}': ${f}`),f}let g={...p,steps:h};return r[l]=pf(g),{...g,...n,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let l of n.blocks){let c=[];for(let p of l.steps)c.push(await Vi({step:p,callbacks:e,logger:t,resolvedModuleCache:r}));o.push({...l,steps:c})}let i;if(n.elseSteps){i=[];for(let l of n.elseSteps)i.push(await Vi({step:l,callbacks:e,logger:t,resolvedModuleCache:r}))}return{...n,blocks:o,elseSteps:i};case"SECTION":case"IFRAME":let s=[];for(let l of n.steps)s.push(await Vi({step:l,callbacks:e,logger:t,resolvedModuleCache:r}));return{...n,steps:s};default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function _R(n){return typeof n=="object"&&n!==null}function Mn(n){if(Array.isArray(n))return n.map(Mn);if(_R(n)){let e={};return Object.entries(n).forEach(([t,r])=>{r!==void 0&&(e[t]=Mn(r))}),e}return n}import{cloneDeep as mf}from"lodash-es";import{v4 as ud}from"uuid";async function Xe(n){let e=new Map,t=new Set,r=mf(n.stepLists.steps),o=await Dr({...n,steps:r,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t}),i={stepsToSave:{steps:o.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates};for(let s of["beforeSteps","afterSteps"]){let a=mf(n.stepLists[s]);if(!a)continue;let l=await Dr({...n,steps:a,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});i.cachesToSave.push(...l.cachesToSave),i.moduleUpdates.push(...l.moduleUpdates),i.stepsToSave[s]=l.stepsToSave}return i}async function Dr({steps:n,...e}){let{seenModules:t,cacheCreationParams:r,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:s,shouldCreateNewModuleId:a}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let c of n)switch(delete c.index,delete c.aiSuggested,c.id=e.createNewStepIds?ud():c.id,c.type){case"PRESET_ACTION":{let d=c.command;d.id=r?.createNewCacheIds?ud():d.id,kg(d),"cache"in d&&d.cache&&(r&&(l.cachesToSave=l.cachesToSave.concat(Og({id:d.id,orgId:r.orgId,testId:r.testId,value:wr.parse(d),moduleIdParents:o,moduleStepParents:i,skipIntermediateEntries:e.skipCacheIntermediateEntries}))),delete d.cache),d.thoughts&&delete d.thoughts,l.stepsToSave.push({...c,command:d});break}case"RESOLVED_MODULE":{let d=r?.createNewCacheIds?ud():c.id,u=c.moduleId;s.has(u)?u=s.get(u):a!==void 0&&(u=await a(c),s.set(c.moduleId,u));let{cachesToSave:m,stepsToSave:h,moduleUpdates:g}=await Dr({...e,steps:c.steps,cacheCreationParams:r?{...r,createNewCacheIds:!1}:void 0,moduleStepParents:[...i,d],moduleIdParents:[...o,u],skipCacheIntermediateEntries:r?.createNewCacheIds});l.moduleUpdates=l.moduleUpdates.concat(g),l.cachesToSave=l.cachesToSave.concat(m),t.has(u)||(t.add(u),l.moduleUpdates.push({...It.parse(c),steps:Ke.array().parse(h),moduleId:u}));let f={type:"MODULE",moduleId:u,inputs:c.inputs,id:d,skipped:c.skipped,cacheConfig:c.cacheConfig,envKey:c.envKey};l.stepsToSave.push(f);break}case"AI_ACTION":{if(!c.steps){l.stepsToSave.push(c);break}let{stepsToSave:d,cachesToSave:u}=await Dr({...e,steps:c.steps});try{c.steps=At.array().parse(d)}catch(m){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${m}`)}l.stepsToSave.push(c),l.cachesToSave=l.cachesToSave.concat(u);break}case"AI_ACTION_DYNAMIC":{l.stepsToSave.push(c);break}case"CONDITIONAL":{let d=[];for(let m of c.blocks){let{stepsToSave:h,cachesToSave:g,moduleUpdates:f}=await Dr({...e,steps:m.steps});d.push({...m,steps:h}),l.cachesToSave=l.cachesToSave.concat(g),l.moduleUpdates=l.moduleUpdates.concat(f)}let u={...c,elseSteps:void 0,blocks:d};if(c.elseSteps){let{stepsToSave:m,cachesToSave:h,moduleUpdates:g}=await Dr({...e,steps:c.elseSteps});u.elseSteps=m,l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(g)}l.stepsToSave.push(u);break}case"IFRAME":case"SECTION":{let{stepsToSave:d,cachesToSave:u,moduleUpdates:m}=await Dr({...e,steps:c.steps}),h={...c,steps:d};l.moduleUpdates=l.moduleUpdates.concat(m),l.stepsToSave.push(h),l.cachesToSave=l.cachesToSave.concat(u);break}default:return(d=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(c)}return l}import{cloneDeep as MR}from"lodash-es";import{stringify as hf}from"yaml";async function gf(n,e=new Set){let t={id:n.id,name:n.name,description:n.description,baseUrl:n.baseUrl,schemaVersion:n.schemaVersion,advanced:n.advanced,retries:n.retries,envs:n.envs,disabled:n.disabled,labels:n.labels},r={},o=await FR({originalStepLists:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},modules:r,processedModuleNames:e}),i={fileType:he.TEST,...t,beforeSteps:o.beforeSteps&&o.beforeSteps.length>0?o.beforeSteps:void 0,steps:o.steps,afterSteps:o.afterSteps&&o.afterSteps.length>0?o.afterSteps:void 0};return{test:hf(i),modules:r}}async function FR({originalStepLists:n,modules:e,processedModuleNames:t}){let r=MR(n);Object.values(r).forEach(s=>{DR(s??[])});let{stepsToSave:o,moduleUpdates:i}=await Xe({stepLists:r});for(let s of i)t.has(s.name)||(e[s.name]=UR(s),t.add(s.name));return o}function DR(n){ad({steps:n,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function UR(n){let e=It.parse(n),t={fileType:he.MODULE,...e,schemaVersion:He,steps:n.steps};return hf(t)}async function ne(n,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},n);function i(){clearTimeout(o),e?.removeEventListener("abort",i),r(e?.reason)}})}async function qi({promiseGenerator:n,signal:e,codePath:t,logger:r}){let i=Date.now(),s=setInterval(()=>{if(e?.aborted){clearInterval(s);return}r?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((a,l)=>{function c(){clearInterval(s),e?.removeEventListener("abort",c),l(e?.reason)}if(e?.aborted){l(e?.reason),clearInterval(s);return}e?.addEventListener("abort",c),(async()=>{try{a(await n())}catch(p){l(p)}finally{clearInterval(s),e?.removeEventListener("abort",c)}})()})}async function Ur({promiseGenerator:n,timeoutMs:e,codePath:t,logger:r,signal:o}){let i=!1,s=new AbortController,a=()=>{s.abort()},l=setTimeout(()=>{i||s.abort()},e);o?.addEventListener("abort",a);try{return await qi({promiseGenerator:n,signal:s.signal,codePath:t,logger:r})}finally{i=!0,o?.removeEventListener("abort",a),clearTimeout(l)}}function Pa(n){let e=[];for(let t of n)switch(t.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(t);break;case"RESOLVED_MODULE":{let r={...t,type:"MODULE"};e.push(kn.parse(r));break}case"IFRAME":case"SECTION":{let r={...t,steps:Pa(t.steps)};e.push(Ke.parse(r));break}case"CONDITIONAL":{let r={...t,blocks:t.blocks.map(o=>({assertion:o.assertion,steps:Pa(o.steps)})),elseSteps:t.elseSteps?Pa(t.elseSteps):void 0};e.push(xr.parse(r));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function La(n){return Pa([n])[0]}import BR from"picomatch";var md=(n,e,t)=>{t?.caseInsensitive&&(n=n.toLowerCase());let r;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;r=n.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;r=n===e.glob||BR(o)(n);break}case"REGEX":{r=new RegExp(e.regex).test(n);break}}return t?.negated?!r:r};var Ro=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}async saveStepCacheEntries(e,t,r){try{await this.client.updateStepCaches({entries:e,testId:t})}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let t=await this.client.getStepCacheForTest({testId:e.testId,organizationId:e.organizationId,steps:e.steps,schemaVersion:e.schemaVersion}),{hits:r}=Co({steps:e.steps,stepCacheEntries:t,logger:e.logger});this.client.updateCacheLastUsedDate(r,e.logger)}fetchIconKnowledgeBase(e,t){return this.client.fetchIconKnowledgeBase(e,t)}saveNewIcons(e,t,r){return this.client.saveNewIcons(e,t,r)}};import{Faker as zR,en as jR}from"@faker-js/faker";var Ao="v1",er=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new zR({locale:jR}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Ao}/tools/ai/generate`,{method:"POST",body:t}).catch(r=>{throw r instanceof an?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Ao}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof an?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Ao}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof an?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Ao}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof an?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Ao}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof an?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Ao}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof an?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as HR}from"zod";var Io=class extends Mt{constructor(e){super(e)}async rankChunksWithAi(e,t){let r={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:t.abortSignal});return oh.parse(o)}async rankChunksWithRag(e,t){let r=await this.sendRequest(`/${M}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Wi,...e},signal:t.abortSignal});return rh.parse(r)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${M}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return HR.string().parse(t)}async getElementLocation(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/locate-element`,{method:"POST",body:r,signal:t.abortSignal});return Bh.parse(o)}async getAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/assertion`,{method:"POST",body:r,signal:t.abortSignal});return nd.parse(o)}async getLintStepResult(e,t){let r={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/lint/step`,{method:"POST",body:r,signal:t.abortSignal});return Uh.parse(o)}async getVisualAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/visual-assertion`,{method:"POST",body:r,signal:t.abortSignal});return nd.parse(o)}async getAiActionCommand(e,t){let r=await this.sendRequest(`/${M}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Dh.parse(r)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${M}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let r=await this.sendRequest(`/${M}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Ec.parse(r)}async getReverseMappedDescription(e,t){let r=await this.sendRequest(`/${M}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return zh.parse(r)}async getTextExtraction(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/text-extraction`,{method:"POST",body:r,signal:t.abortSignal});return Tc.parse(o)}async getTestResultClassification(e,t){let r=await this.sendRequest(`/${M}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Mc.parse(r)}async getExtractedKeywords(e,t){let r=await this.sendRequest(`/${M}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return nh.parse(r)}async getAutohealingProposal(e,t){let r=await this.sendRequest(`/${M}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Yu.parse(r)}async getFailureRecoveryProposal(e,t){let r=await this.sendRequest(`/${M}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Ju.parse(r)}async getIframeRegex(e,t){let r=await this.sendRequest(`/${M}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Ou.parse(r)}};var Br=class extends Mt{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let r=await this.sendRequest(`/${M}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return ku.parse(r)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var Oa=class{constructor(e){this.client=e}async uploadResultsArchive(e){let{uploadUrl:t,id:r}=await this.client.generateTestResultsUploadUrl(),o=await Eo(t,"application/zip",e);if(!o.ok)throw new Error(`Failed to upload test results: ${await o.text()}`);let{runGroupId:i}=await this.client.startProcessingResultsUpload(r);return i}};import{PostHog as $R}from"posthog-node";var Po=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var ff=n=>{let e=n.reason===void 0?new DOMException("This operation was aborted.","AbortError"):n.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};async function D(n,e){let{milliseconds:t,fallback:r,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a;return new Promise((l,c)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:d}=e;d.aborted&&c(ff(d)),a=()=>{c(ff(d))},d.addEventListener("abort",a)}if(t===Number.POSITIVE_INFINITY){n.then(l,c);return}let p=new Po;s=i.setTimeout.call(void 0,()=>{if(r){try{l(r())}catch(d){c(d)}return}"cancel"in n&&typeof n.cancel=="function"&&n.cancel(),o instanceof Error?c(o):(p.message=o??`Promise timed out after ${t} milliseconds`,c(p))},t),(async()=>{try{l(await n)}catch(d){c(d)}})()}).catch(l=>{throw l}).finally(()=>{s!==void 0&&i.clearTimeout.call(void 0,s),a!==void 0&&e.signal&&e.signal.removeEventListener("abort",a)})}async function Sf(n,e){let t,r=0,o=3,i,s;for(;r<o;)try{let a=await D(n.getAllFlagsAndPayloads(e),{milliseconds:5e3});i=a.featureFlags||{},s=a.featureFlagPayloads||{};break}catch(a){t=a,r++,await new Promise(l=>setTimeout(l,100*r))}if(i&&s)return{flags:i,payloads:s};throw t}var Lo=class n extends ji{constructor(t,r,o,i){super(o,i);this.client=t;this.orgId=r}static async init(t,r){let o=r??new $R("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:i,payloads:s}=await Sf(o,t);return new n(o,t,i,s)}async refresh(){let{flags:t,payloads:r}=await Sf(this.client,this.orgId);this.flags=t,this.payloads=r}};import{Server as EL}from"socket.io";import{cloneDeep as WR}from"lodash-es";var GR={showOverlay:!1},hd=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:t,cleanup:r,clientIp:o,sessionId:i,browserbaseSessionId:s}){return this.sessions.set(i,{controller:e,context:t,cleanup:r,clientIp:o,browserbaseSessionId:s,browserBehavior:WR(GR)}),i}removeSession(e,t){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:i}=o;try{i.setClosed(),await i.browser.cleanup()}catch(s){t.error({err:s},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(s){t.error({err:s},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}},Z=new hd;function yf(n,e,t){let r=Date.now(),o=Date.now(),i,s,a,l,c=!1,p=async(h,g)=>{if(!h.closed&&!h.isInPageLoad)try{let f=a;a=void 0;let S=h.url(),v=g.toEditorDisplayCopy();JSON.stringify(v)===JSON.stringify(i)&&S===l&&r>o||(n.emit("browserState",{logsPerPage:f?.logsPerPage,harPages:f?.harPages,harEntries:f?.harEntries,viewport:h.getViewport(),url:S,iframeSrcUrls:s??[],context:v,isInPageLoad:h.isInPageLoad}),r=Date.now()),l=S,i=v}catch(f){if(!n.connected)return;let S=f instanceof Error?f.message:`${f}`;if(S.includes("Frame was detached")||S.includes("Not attached to an active page")||S.includes("browser has been closed")||S.includes("UserInfrastructureError"))return;t.error({err:f,sessionId:e},"Error grabbing browser state")}},d=setInterval(()=>{let h=Z.getSession(e),g=h?.controller?.browser;if(!g||g.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(d);return}p(g,h.context)},1e3),u=(h,g)=>!!(JSON.stringify(h)!==JSON.stringify(s)||g.logsPerPage.some(f=>f.length>0)||g.harPages&&Object.keys(g.harPages).length>0||g.harEntries&&Object.keys(g.harEntries).length>0),m=setInterval(async()=>{let g=Z.getSession(e)?.controller?.browser;if(!g||g.closed){clearInterval(m);return}else if(c)return;c=!0;try{let f=await g.getAllFrameUrls(),S=g.retrieveAndClearDebugData();u(f,S)&&(s=f,a=S,o=Date.now())}catch(f){t.warn({err:f},"Failed to fetch extended details")}finally{c=!1}},2500);return{timers:[d,m]}}var tr={};var VR=n=>()=>{let{sessionId:e}=n.metadata;tr[e]?.abort?.abort()},bf={event:"cancelApiTest",createHandler:VR};import{CookieJar as cA}from"tough-cookie";import{randomUUID as eA}from"crypto";import{faker as qR}from"@faker-js/faker";import KR from"assert";import YR from"axios";import JR from"moment";import*as XR from"otpauth";import ZR from"pg";async function wf(n){let e;try{e=new URL(n.url).hostname}catch{}let t=[];return n.headers.getSetCookie()?.forEach(r=>{let o=ha(r,e);t.push(...o)}),t}var QR=Object.getPrototypeOf(async function(){}).constructor;async function vf(n,e,t){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o}=e.bindings,i=e.tools,s={},a=(f,S)=>{o[f]=S,s[f]=S},l={},c=(f,S)=>{o[f]=S,l[f]=S},p;r.includes("Octokit")&&(p=(await import("@octokit/rest")).Octokit);let d;r.includes("createAppAuth")&&(d=(await import("@octokit/auth-app")).createAppAuth);let u=async()=>await Promise.resolve(new QR("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai",r)(YR,JR,i.fakerInstance??qR,KR,ZR,p,d,XR,wf,o,a,c,S=>i.sms.send(S),S=>i.sms.fetchLatest(S),i.email,i.sms,i.ai)),m=!0,h,g;try{h=await D(u(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal})}catch(f){t.error(`[${n}] Error executing code: ${f}`),m=!1,f instanceof Po?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:h,variableUpdates:s,persistentVariableUpdates:l,success:m,error:g}}async function xf({code:n,fragment:e,context:t,localTools:r,logger:o,signal:i,timeoutMs:s=Kn}){let a=eA(),l=await vf(a,{code:n,options:{fragment:e,timeoutMs:s},bindings:t.toObjectCopy(),tools:r,signal:i},o);return y.debug(`[${a}] Got execution result: ${JSON.stringify(l)}`),l}import{createHmac as tA,randomUUID as nA}from"crypto";import rA from"fetch-retry";var oA=rA(global.fetch,{retries:3,retryOn:function(n,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(n){return Math.pow(2,n)*500}}),Tf=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Ef=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function Cf({orgId:n,code:e,fragment:t,context:r,timeoutMs:o=Kn,retries:i=2,signal:s,logger:a}){if(!Tf)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,p=0;if(!Ef)throw new Error("Missing lambda auth secret.");let d=tA("sha256",Ef).update(n).digest("hex");for(;p<=i;){p++,s?.throwIfAborted();let m={id:nA(),orgId:n,momenticLambdaAuthHash:d,code:e,fragment:t,state:r.toObjectCopy(),timeoutMs:o};try{if(l=await D(oA(Tf,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:s}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(h){c=h}}if(c)throw a.error({err:c},"Failed to evaluate code remotely"),c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let u;try{u=uh.parse(await l.json())}catch(m){throw new Error(`Code evaluation server returned invalid response: ${m}`)}if(u.error)throw new Error(`Code evaluation error: ${u.error}`);return u}async function Fn(n){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Cf(n);else if(n.localTools)e=await xf({...n,localTools:n.localTools});else throw new Error("No code evaluation environment available");if(e.error)throw new Error(`Code evaluation error: ${e.error}`);if(e.variableUpdates)for(let[t,r]of Object.entries(e.variableUpdates))n.context.setVariable(t,r);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await n.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,r]of Object.entries(e.persistentVariableUpdates))n.context.setVariable(t,r)}return e.result}async function Ut(n){let{orgId:e,s:t,context:r,logger:o,signal:i,flagStore:s,retries:a=2,timeoutMs:l=Kn,allowUndefined:c=!1}=n,p=/{{(.*?)}}/g,d=t.matchAll(p),u=t;for(let m of d){if(m.length<2)continue;let h=m[1].trim(),g;try{g=await Fn({orgId:e,code:h,fragment:!0,context:r,timeoutMs:l,logger:o,retries:a,localTools:n.localTools,signal:i,flagStore:s})}catch(S){throw o.error({err:S,value:t},"Error evaluating template string"),S}if(g===void 0&&!c)throw new R("UserConfigurationError",`Template fragment '${h}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let f=typeof g=="string"?g:`${g}`;f=f.replaceAll(/\$/g,"$$$$"),u=u.replace(m[0],f)}return u}async function Oo(n){return Rf(n)}async function Rf({obj:n,bannedKeys:e,allowList:t,context:r,prefixPath:o="",replacements:i={},...s}){for(let a in n){if(e.includes(a))continue;let l=!1;if(t)if(t.includes(a))l=!0;else continue;let c=n[a],p=o?`${o}.${a}`:a;if(typeof c=="string"&&c.includes("{{")){let d=await Ut({s:c,context:r,...s});if(c===d)continue;i[p]=c,n[a]=d}else typeof c=="object"&&c!==null&&!Array.isArray(c)&&await Rf({obj:c,bannedKeys:e,context:r,prefixPath:p,replacements:i,allowList:l?void 0:t,...s})}return i}import sA from"fetch-cookie";import{cloneDeep as aA}from"lodash-es";var ka=(n,e)=>{try{let{hostname:t,pathname:r}=new URL(n),{hostname:o,pathname:i}=new URL(e);return t!==o||r!==i}catch{return!1}},ko=n=>{try{return new URL(n),!0}catch{return!1}},Af=n=>!n.toLowerCase().startsWith("http"),No=(n,e)=>{try{return new URL(n,e),!0}catch{return!1}};function nr(n,e){try{return!!new URL(n).origin.trim()}catch(t){return e?.error({url:n,err:t},"Invalid URL in check"),!1}}var iA=3e4;async function Na({command:n,logger:e,baseUrl:t,fetchImplementation:r=fetch}){let o=n.timeout??iA/1e3,i=Object.fromEntries(Object.entries(n.headers||{}).filter(([m,h])=>m&&h)),s=new URLSearchParams;Object.entries(n.params||{}).filter(([m,h])=>m&&h).forEach(([m,h])=>{s.append(m,h)});let a=s.toString(),l;if(ko(n.url)&&(l=n.url),t&&No(n.url,t)&&(l=new URL(n.url,t).toString()),!l)throw new R("ActionFailureError",`Invalid URL: ${n.url}`);e.debug({url:l,searchParams:a,headers:i,body:n.body,method:n.method},"Making HTTP request");let p=await D((async()=>{let m=a?`${l}?${a}`:l;try{return await r(m,{headers:i,method:n.method,body:n.body})}catch(h){throw e.error({err:h},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${h}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!p.ok){let m;try{m=await p.text()}catch(h){m=`Failed to read response body: ${h}`}throw new R("ActionFailureError",`Fetch request failed with status ${p.status}: ${m}`)}let d={};p.headers.forEach((m,h)=>{d[h]=m});let u={status:p.status,headers:d};return p.headers.get("content-type")?.includes("json")?u.json=await p.json():p.headers.get("content-type")?.includes("text")&&(u.text=await p.text()),u}async function If(n){let{fixtures:e,inputs:t}=n,{context:r}=e,{orgId:o,step:i}=t,s=aA(i);await Oo({obj:s,orgId:o,bannedKeys:["code"],...e});let a=await lA(n);return s.envKey&&a.data&&r.setVariable(s.envKey,a.data),a}async function lA(n){let{fixtures:e,inputs:t}=n,{step:r,orgId:o,baseUrl:i}=t,{cookieJar:s}=e,a=new Date;switch(r.type){case"JAVASCRIPT":{let c=await Fn({code:r.code,orgId:o,fragment:!!r.fragment,timeoutMs:r.timeout?r.timeout*1e3:void 0,...e});try{JSON.stringify(c)}catch(p){return{...r,startedAt:a,finishedAt:new Date,status:"FAILED",message:`JavaScript return value is not serializable: ${p instanceof Error?p.message:`${p}`}`}}return{...r,startedAt:a,finishedAt:new Date,message:"JavaScript code executed successfully",status:"SUCCESS",data:c}}case"REQUEST":{let c=sA(fetch,s),p=await Na({command:r,logger:e.logger,baseUrl:i,fetchImplementation:c});return{...r,startedAt:a,finishedAt:new Date,status:"SUCCESS",message:"Request executed successfully",data:p}}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}async function Pf(n){let{inputs:e,fixtures:t,callbacks:r}=n,{signal:o}=t,{steps:i,orgId:s,baseUrl:a}=e,{test:l,step:c}=r,p={startedAt:new Date,status:"RUNNING",results:[]},d=p.results,u=new cA,m={cookieJar:u,...t};for(let h of i){let g=new Date;c.onStarted?.(h.id);let f;try{o?.throwIfAborted(),f=await If({inputs:{step:h,baseUrl:a,orgId:s},fixtures:m})}catch(S){o?.aborted?f={...h,startedAt:g,finishedAt:new Date,status:"CANCELLED",message:"Step cancelled by user."}:f={...h,startedAt:g,finishedAt:new Date,status:"FAILED",message:`Step failed: ${S instanceof Error?S.message:`${S}`}`}}if(d.push(f),c.onFinished?.({result:f,cookies:fa(u,new URL(a).hostname)}),l.updateAttemptProgress?.({results:d}),f.status!=="SUCCESS"){p.status=f.status==="CANCELLED"?"CANCELLED":"FAILED";break}}return p.status==="RUNNING"&&(p.status="PASSED"),p.finishedAt=new Date,l.onFinished?.(),p}async function Lf(n){let{socket:e,storage:t}=n,r=n.socket.id,{testId:o}=e.handshake.query;if(typeof o!="string")throw new Error(`Received invalid test ID that does not parse as a string: ${o}`);let i=await t.getOrgId({type:"api-test",testId:o}),{baseUrl:s,envName:a,environmentVariables:l}=await gd({testId:o,orgId:i,logger:n.logger,storage:t,authorization:n.authorization}),c={type:"api-test",orgId:await n.storage.getOrgId({type:"api-test",testId:o}),testId:o,sessionId:r,latestContext:new Pt({baseUrl:s||"",currentUrl:s||"",variablesFromEnvironment:l,envName:a})};return tr[r]=c,c}async function gd({testId:n,orgId:e,logger:t,storage:r,authorization:o}){let i=await r.fetchApiTestMetadata(n,e,t);if(!i)throw new Error(`Failed to fetch API test metadata for test ID: ${n}`);let s;o?.type==="API_KEY"&&(s=new er({httpClient:new Mt({...o,logger:t}),fakerSeed:void 0}));let a=i.envs?.find(d=>d.default),l;a&&(l=await r.fetchEnvironment(e,a.name,t));let c=i.baseUrl||l?.variables?.[Pe];if(!c)throw new Error("Base URL is empty in both API test options and the configured environment");let p={...l?.variables};return{baseUrl:c,envName:l?.name,environmentVariables:p,localCodeEvalTools:s}}var dA=n=>async(e,t)=>{let{steps:r}=e,{authorization:o,metadata:i,socket:s,storage:a,logger:l,flagStoreFactory:c}=n,{orgId:p,testId:d,sessionId:u}=i,m=l.child({testId:d,orgId:p,sessionId:u}),h=tr[u];if(!h)throw new Error(`No api testing session with id ${u} could be found. Please reconnect and try again.`);let g=new AbortController;h.abort=g;let f=h.latestContext,{localCodeEvalTools:S,baseUrl:v}=await gd({testId:d,orgId:p,logger:m,storage:a,authorization:o}),b={context:f,logger:m,localTools:S,signal:g.signal,flagStore:await c(p)},E=await Pf({inputs:{steps:r,orgId:p,baseUrl:v},fixtures:b,callbacks:{test:{onFinished:()=>{s.emit("apiTestFinished")}},step:{onStarted:I=>{s.emit("apiStepStarted",I)},onFinished:I=>{s.emit("apiStepFinished",I)}}}});t({result:E})},Of={event:"executeApiTest",createHandler:dA};var pA=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async()=>{e.info({sessionId:t},"Cancel event received");let r=Z.getSession(t);if(!r)throw new Error("No active session found");try{r.controller.setClosed()}catch{}}},kf={event:"cancel",createHandler:pA};var uA=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async(r,o)=>{let i=Z.getSession(t);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let a=await s.getBrowserState({skipWait:!0});o({a11yTree:a.serialize()})}catch(a){e.error({err:a},"Error fetching a11y tree from the browser"),o({err:a.message})}}},Nf={event:"fetchA11yTree",createHandler:uA};var mA=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async(r,o)=>{let i=Z.getSession(t);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let a=await s.html();o({html:a})}catch(a){e.error({err:a},"Error fetching DOM from the browser"),a.name==="TimeoutError"?o({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):o({err:a.message})}}},_f={event:"fetchDom",createHandler:mA};var hA=({metadata:n,logger:e})=>{let{sessionId:t,type:r}=n;return o=>{e.info({sessionId:t,reason:o},`Disconnect event received (${o})`),r==="e2e"?Z.removeSession(t,e):r==="api-test"&&delete tr[t]}},Mf={event:"disconnect",createHandler:hA};function Jt(n){let{result:e,nestedResults:t}=n;if(!n.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=gA(t);fA(e,r,o);let i=[...n.asyncTasks];n.asyncTasks.push((async()=>{try{await SA(i,e,r,o)}catch(s){n.logger.error({result:n.result,err:s},"Error hoisting scalar result metadata")}})())}function gA(n){let e=n[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertion){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let r=n[n.length-1],o;for(;;){switch(r.type){case"PRESET_ACTION":{o=r;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!r.results.length){o=r;break}r=r.results[r.results.length-1];break;default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function fA(n,e,t){e&&(n.beforeUrl=e.beforeUrl),t&&(n.afterUrl=t.afterUrl,n.data=t.data,t.status!=="SUCCESS"&&(n.message=t.message))}async function SA(n,e,t,r){await Promise.allSettled(n),t&&(e.beforeSnapshot=t.beforeSnapshot),r&&(e.afterSnapshot=r.afterSnapshot)}import Ki from"os";import yA from"v8";var Ff,vn,bA=Ki.platform(),wA=Ki.cpus().map(n=>({model:n.model,speed:n.speed}));function Df(n){let e=()=>{try{let t=!1,r=vA(),o=xA();r.freeMemory<1e6&&(t=!0);let i=yA.getHeapStatistics(),s=i.used_heap_size,a=i.heap_size_limit;s/a>.9&&(t=!0),t?n.warn({memory:r,cpu:o,heapStats:i},"Critical resource usage metrics detected"):n.debug({memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,1e4),cpuMetadata:wA,platform:bA}}function vA(){let n=Ki.totalmem(),e=Ki.freemem(),t=n-e;return{totalMemory:n,freeMemory:e,usedMemory:t}}function xA(){let n=Ki.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of n)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!vn)return vn=t,null;let r={user:t.user-vn.user,nice:t.nice-vn.nice,sys:t.sys-vn.sys,idle:t.idle-vn.idle,irq:t.irq-vn.irq,total:t.total-vn.total};return Ff={measurementTime:e,intervalMs:e-vn.measurementTime,user:r.user/r.total*100,nice:r.nice/r.total*100,sys:r.sys/r.total*100,idle:r.idle/r.total*100,irq:r.irq/r.total*100,total:100-r.idle/r.total*100},vn=t,Ff}import{hostname as AA}from"os";async function Bf(n){let{command:e,tracer:t,timeoutMs:r,targetingWrapper:o,disableCache:i,fixtures:s}=n,{logger:a,abortSignal:l}=s;if(e.target&&!Vn(e.target))throw new Error("Element assertion with x/y is not supported yet");let c=e.assertion.type==="ELEMENT_EXISTENCE"&&e.assertion.negated,p=Date.now(),d=0,u,m=500;for(;d<2||Date.now()-p<r;){d++,d>1&&await ne(m,l),l?.throwIfAborted();try{let{newTarget:h,elementInteractedDisplayString:g,result:f}=await o({ctx:s.ctx,tracer:t,command:e,target:e.target,cache:e.cache?.target,action:async S=>TA(S.locator,n),options:{disableCache:i,useSelector:!!e.useSelector,iframeUrl:e.iframeUrl,disableGlobalLocatorRedirect:!0,source:c?"NEGATED_CHECK":void 0}});if(u={success:f.success,data:f.data,err:f.err,newTarget:h,elementInteractedDisplayString:g},!f.success){u=f,m=Math.min(m*2,1e4);continue}return u}catch(h){if(l?.throwIfAborted(),c)return{success:!0,thoughts:`The element described does not exist on the page: ${h.message}`};if(a.warn({err:h},"Element assertion ended in error, retrying..."),!(h instanceof R)||h.reason!="ActionFailureError")throw h;u={success:!1,err:h}}}if(!u)throw new Error(`Failed to evaluate manual element assertion in ${r}ms.`);return u}async function TA(n,{command:e,fixtures:t}){let r=e.assertion;await t.browser.highlight(n);let o=!0,i,s;switch(r.type){case"ELEMENT_CONTENT":{let a=await n.textContent()??"";if(s={elementTextContent:Me(a,500,!0)},!Uf(a,r.value,r.operation,!!r.negated)){let l=r.negated?Zn[r.operation]:Qn[r.operation];o=!1,i=new R("AssertionFailureError",`The content ${l} '${r.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{s={elementOuterHtml:Me(await n.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let a;try{a=await n.getAttribute(r.attr,{timeout:3e3})??""}catch(l){i=new R("AssertionFailureError",`The element does not have an attribute named ${r.attr}: ${l}`),o=!1;break}if(!Uf(a,r.value,r.operation,!!r.negated)){let l=r.negated?Zn[r.operation]:Qn[r.operation];o=!1,r.operation==="EXISTS"?i=r.negated?new R("AssertionFailureError",`The attribute ${r.attr} ${l}: ${a}`):new R("AssertionFailureError",`The attribute ${r.attr} ${l}`):i=new R("AssertionFailureError",`The attribute ${r.attr} ${l} '${r.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(r.condition){case"VISIBLE":{o=await n.isVisible({timeout:bn*1e3});break}case"EDITABLE":{o=await n.isEditable({timeout:bn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await n.isEnabled({timeout:bn*1e3});break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.condition)}if(o=r.negated?!o:o,!o){let a=r.negated?ld[r.condition]:cd[r.condition];i=new R("AssertionFailureError",`The element ${a}`)}break}}return{success:o,data:s,err:i}}function Uf(n,e,t,r){let o;switch(t){case"CONTAINS":{o=n.includes(e);break}case"EQUALS":{o=n.trim()===e.trim();break}case"STARTS_WITH":{o=n.trim().startsWith(e);break}case"EXISTS":{o=n.trim().length>0;break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return r?!o:o}import{Jimp as EA}from"jimp";async function Yi(n,e){let t=await n.screenshot(e),r=await EA.fromBuffer(t);return{buffer:t,width:Math.ceil(r.bitmap.width??0),height:Math.ceil(r.bitmap.height??0)}}import{Jimp as zf}from"jimp";import fd from"jpeg-js";import CA from"pixelmatch";async function jf({ctx:n,tracer:e,command:t,disableCache:r,browser:o,targetingWrapper:i,logger:s,screenshotStorage:a}){if(t.target&&!Vn(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:s});let l={clearHighlights:!0,hideCaret:!0},c;t.target?.elementDescriptor?c=(await i({ctx:n,tracer:e,command:t,target:t.target,cache:t.cache?.target??t.target?.a11yData,action:async W=>Yi(o,{locator:W.locator,...l}),options:{disableCache:!!r,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl,disableGlobalLocatorRedirect:!0}})).result:c=await Yi(o,l);let p=await a.prepareGoldenScreenshotForComparison(s,t,c);if((c.height!==p.height||c.width!==p.width)&&s.debug({currHeight:c.height,currWidth:c.width,savedHeight:p.height,savedWidth:p.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-p.height)>10||Math.abs(c.width-p.width)>10){let U=`${c.width}x${c.height}`,W=`${p.width}x${p.height}`;return{fail:!0,thoughts:`Current screenshot (${U}) does not match saved screenshot dimensions (${W}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:p.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await zf.fromBuffer(c.buffer),u={width:c.width,height:c.height},m=await zf.fromBuffer(p.buffer),h={width:p.width,height:p.height},g,f=u.width*u.height,S=h.width*h.height,v=Math.abs(u.height-h.height),b=Math.abs(u.width-h.width);if(f>S){let U=d.cover({w:h.width,h:h.height});c.buffer=await U.getBuffer("image/jpeg"),g="current",c.width=h.width,c.height=h.height}else if(S>f){let U=m.cover({w:u.width,h:u.height});p.buffer=await U.getBuffer("image/jpeg"),g="saved"}let x={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},C=t.threshold??.1,I=CA(fd.decode(p.buffer).data,fd.decode(c.buffer).data,x.data,c.width,c.height,{threshold:C,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,N=I>C*100,P=`Visual diff of ${I.toFixed(2)}% detected, which is ${N?"over":"under"} the threshold of ${C*100}%.`;if(g&&(P+=` The ${g} screenshot was cropped since it was taller by ${v} pixels and wider by ${b} pixels.`),N)throw new R("ActionFailureError",P);return{fail:N,thoughts:P,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:fd.encode(x,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var RA=5e3;async function _a({timeout:n=bn,...e}){let t=Date.now(),r=n*1e3,o=r+1e4,i,s=0,a=500;for(;s-t<r;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let l=Date.now();i=await Hf(e),s=Date.now();let c=s-l;if(c>1e3&&e.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await ne(a,e.signal),a=Math.min(Math.floor(a*1.5),RA);else return i}return i=await Hf(e),i}async function Hf({assertion:n,browser:e,flagStore:t}){switch(n.type){case"CONTENT":{let o,i=!1,s;try{let a;if(t.isBooleanFlagEnabled("auto_expand_iframes")){let l=await e.evaluateFunctionInAllFrames($f,{value:n.value,negated:!!n.negated,returnHtml:!1});i=l.some(c=>c.evaluation),a=l.find(c=>c.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:a}=await e.evaluateFunctionInPage($f,{value:n.value,negated:!!n.negated,returnHtml:!0}));if(!i){let l=n.negated?Zn.CONTAINS:Qn.CONTAINS;s=new R("AssertionFailureError",`The page ${l} '${n.value}'.`),o=a}}catch(a){s=new R("AssertionFailureError",`Failed to evaluate page content assertion: ${a instanceof Error?a.message:`${a}`}`)}return{success:i,err:s,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.type)}}function $f({value:n,negated:e,returnHtml:t}){let r=document.documentElement.outerHTML,o=r.includes(n)===!e;return r.length>1e4&&(r=r.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?r:void 0}}var Sd=async n=>{let{step:e,resolvedInputs:t}=n.moduleParams,{logger:r,context:o,storage:i,codeEvalTools:s,controller:a}=n.fixtures,l=a.browser,{orgId:c,runId:p}=n.inputs,d=a.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),r.debug({inputs:t,moduleId:e.moduleId},"Set module inputs"));let u,m=!1,h,g;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",S=await Ut({orgId:c,s:f,context:o,logger:r,localTools:s,signal:d,flagStore:a.flagStore});g={orgId:c,cacheKeys:[S,...Object.entries(t).map(([b,x])=>`${b}:${x}`)]},r.debug({original:f,keyParams:g},"Module cache key params");let v=Date.now();for(;Date.now()-v<Fh;){d?.throwIfAborted();let b=await i.getCacheResult(g);if(b){r.debug({cacheResult:b},"Got result from module execution cache"),u=Ma(e,t,"SUCCESS"),u.message="Used cached module result.",u.data=JSON.parse(b),m=!0;break}else r.debug({cacheKey:f,keyParams:g},"No cache result found, continuing with lock acquisition");let x=await i.acquireCacheLock({keyParams:g,clientMetadata:`hostName:${AA()};runId:${p}`},d);if(x.acquired){h=x.keyPrefix,r.info({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Acquired cache lock and proceeding with module execution");break}else r.debug({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Failed to acquire cache lock, retrying...");await ne(2500+Math.random()*1e4,d)}}try{if(!u)u=await IA(n);else if(e.autoAuth){let f=ga.safeParse(u.data);if(!f.success)throw new R("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);r.debug("Automatically loading auth state after cached module result"),await l.loadAuthState(f.data);let S=!1,v=e.advanced?.cacheInvalidation;if(v&&v.type==="PAGE_CHECK"){let b={type:"CONTENT",value:v.substring},x=await _a({timeout:bn,assertion:b,browser:l,flagStore:a.flagStore,logger:r,signal:d});x.success?r.debug({invalResult:x},"Cached result still valid after page check, continuing..."):(r.info({invalResult:x},"Invalidating cached result due to page check failure"),S=!0)}if(g&&S)return await i.deleteCacheResult(g),Sd(n)}}finally{try{h!==void 0&&!m&&u?.status==="SUCCESS"&&await PA({step:e,result:u,browser:a.browser,cacheKeyPrefix:h,logger:r,storage:i})}finally{h!==void 0&&await i.releaseCacheLock(h)}}return u},IA=async n=>{let{step:e,tracer:t}=n.moduleParams,r=Ma(e,n.moduleParams.resolvedInputs,"SUCCESS"),o=await t.startSubSteps(),{status:i,results:s}=await rr(n.work,()=>n.executeStepList({...n,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}}));return r.results=s,r.status=i,r.finishedAt=new Date,Jt({asyncTasks:n.work.asyncTasks,nestedResults:s,result:r,logger:n.fixtures.logger}),r};function Ma(n,e,t){let r={};return Object.entries(e).forEach(([i,s])=>{r[i]=JSON.stringify(s)}),{type:"MODULE",id:n.id,moduleId:n.moduleId,moduleName:n.name,startedAt:new Date,cacheConfig:n.cacheConfig,inputs:r,results:[],finishedAt:new Date,status:t}}async function Wf({orgId:n,step:e,context:t,logger:r,flagStore:o,codeEvalTools:i,signal:s}){let a={};try{for(let l of e.parameters??[]){let c=e.inputs?.[l]??e.defaultParameters?.[l];if(!c){r.warn(`No value or default found for parameter '${l}' that is required by module '${e.name}'`);continue}a[l]=await Fn({orgId:n,code:c,fragment:!0,context:t,logger:r,localTools:i,signal:s,flagStore:o})}return a}catch(l){throw s?.throwIfAborted(),new R("UserConfigurationError",`Failed to evaluate module inputs: ${l}`)}}async function PA({step:n,result:e,browser:t,cacheKeyPrefix:r,logger:o,storage:i}){let s=n.cacheConfig?.cacheExpiryMs;(!s||s===hg)&&(s=n.defaultCacheTtl??gg);let a;n.autoAuth?a=JSON.stringify(await t.saveAuthState()):e.data!==void 0?a=JSON.stringify(e.data):a='""',o.debug({cacheKeyPrefix:r,ttlMs:s,truncatedCacheResultJson:Dg(a)},"Setting module cache result"),await i.setCacheResult({result:a,keyPrefix:r,ttlMs:s})}async function or(n,e,t){let r=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,s="FAILED",a;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(a="Step aborted by user.",s="CANCELLED"):o instanceof R?a=`${o}`:a=`An unexpected error occurred: ${o.message}`,n.type==="RESOLVED_MODULE"){let l=Ma(n,{},"FAILED");return l.message=a,l.startedAt=r,l.finishedAt=i,l}return{...La(n),startedAt:r,finishedAt:i,status:s,data:null,message:a,results:[]}}}async function rr(n,e){let t=!1;try{return n&&!n.state.failureRecoveryDisabled&&(n.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{n&&t&&(n.state.failureRecoveryDisabled=void 0)}}import{randomUUID as Gf}from"crypto";import{cloneDeep as OA}from"lodash-es";function Fa(n,e){n.state.healingDetails?n.state.healingDetails.push(e):n.state.healingDetails=[e]}var Da=async n=>{let{step:e,tracer:t}=n.presetParams,{logger:r,controller:o,context:i,billingReporter:s}=n.fixtures,{collectDebugData:a}=n.options,{testMetadata:l,suiteMetadata:c}=n.inputs,p=e.command.type,d=r.child({commandType:p,stepId:e.id,commandId:e.command.id}),u=Ui(e.command);n.work.asyncTasks.push(s.reportCreditsUsed(d,p,u,{testId:l?.id,testName:l?.name,suiteId:c?.id,suiteName:c?.name}));let m=o.browser.url(),h=new Date,g,f=Gf(),S=Gf();if(a)try{g=await o.browser.screenshot({retries:1,clearHighlights:!0});let E=await o.browser.getRawCondensedHtml();t.attachBeforeHtmlSnapshot({logger:d,snapshotId:f,html:E}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(d,f,E))}catch(E){d.debug({err:E},"Failed to take screenshot before step, likely because the page is still loading. This is non-fatal and does not affect the test.")}let v,b,x,C=pa();try{let E=await o.executePresetCommand(C,t,e.command,i,l?.advanced.disableAICaching??!1);E.beforeScreenshotOverride&&(g=E.beforeScreenshotOverride),x=E.afterScreenshotOverride;let{proposedStep:I}=kA({work:n.work,step:e,newTargets:E.newTargets,logger:d}),N=new Date,P=o.browser.url();b={beforeUrl:m,afterUrl:P,startedAt:h,finishedAt:N,viewport:o.browser.getViewport(),status:E.fail?"FAILED":"SUCCESS",elementInteracted:E.elementInteracted},v={...e,message:E.thoughts??NA(E.newTargets)??"Successfully executed preset action.",beforeUrl:m,afterUrl:P,finishedAt:N,startedAt:h,status:E.fail?"FAILED":"SUCCESS",data:E.data,results:[b],details:C.details,proposedStep:I},"assertion"in e.command&&(v.message=E.thoughts||"Assertion passed.")}catch(E){d.error({message:E.message,stack:E.stack},`Failed executing preset step ${_r(e.command)}`);let I=o.browser.url(),N=new Date,P=E instanceof Error?E.message:`${E}`;E instanceof R&&E.getLastScreenshotBuffer()&&(x=E.getLastScreenshotBuffer()),b={beforeUrl:m,afterUrl:I,startedAt:h,finishedAt:N,viewport:o.browser.getViewport(),status:E instanceof DOMException&&E.name==="AbortError"?"CANCELLED":"FAILED",message:P},v={...e,startedAt:h,finishedAt:N,beforeUrl:m,afterUrl:I,status:E instanceof DOMException&&E.name==="AbortError"?"CANCELLED":"FAILED",message:P,failureReason:E instanceof R?E.reason:void 0,results:[b],details:C.details}}if(a)try{x||(x=await o.browser.screenshot({retries:1}));let E=await o.browser.getRawCondensedHtml();t.attachAfterHtmlSnapshot({logger:d,snapshotId:S,html:E}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(d,S,E))}catch(E){d.debug({err:E},"Failed store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return b.beforeSnapshot=f,v.beforeSnapshot=f,b.afterSnapshot=S,v.afterSnapshot=S,g&&(t.attachBeforeScreenshot({logger:d,snapshotId:f,screenshot:g}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(d,f,g))),x&&(t.attachAfterScreenshot({logger:d,snapshotId:S,screenshot:x}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(d,S,x))),v};function kA({work:n,step:e,newTargets:t,logger:r}){if(!t?.length)return{proposedStep:void 0};let o=e.command;_g(o,t,r);let i=t[0]?.description;if(i&&"target"in o&&o.target&&o.target.type==="description"){let s={...o,target:{...o.target,elementDescriptor:i}},a={...OA(e),command:s};return Fa(n,{type:"DESCRIPTION_UPDATE",thoughts:`Updated element description after the original element could not be found on the page. New element location reasoning: ${t[0]?.thoughts}`}),{proposedStep:a}}return{proposedStep:void 0}}function NA(n){if(n?.length){if(n.length===1&&n[0]?.thoughts)return n[0].thoughts;if(n.length===2&&n.every(e=>e.thoughts))return`Located first element: ${n[0]?.thoughts}
42
42
  Located second element: ${n[1]?.thoughts}`}}var yd=["ability","able","aboard","about","above","accept","accident","according","account","accurate","acres","across","act","action","active","activity","actual","actually","add","addition","additional","adjective","adult","adventure","advice","affect","afraid","after","afternoon","again","against","age","ago","agree","ahead","aid","air","airplane","alike","alive","all","allow","almost","alone","along","aloud","alphabet","already","also","although","am","among","amount","ancient","angle","angry","animal","announced","another","answer","ants","any","anybody","anyone","anything","anyway","anywhere","apart","apartment","appearance","apple","applied","appropriate","are","area","arm","army","around","arrange","arrangement","arrive","arrow","art","article","as","aside","ask","asleep","at","ate","atmosphere","atom","atomic","attached","attack","attempt","attention","audience","author","automobile","available","average","avoid","aware","away","baby","back","bad","badly","bag","balance","ball","balloon","band","bank","bar","bare","bark","barn","base","baseball","basic","basis","basket","bat","battle","be","bean","bear","beat","beautiful","beauty","became","because","become","becoming","bee","been","before","began","beginning","begun","behavior","behind","being","believed","bell","belong","below","belt","bend","beneath","bent","beside","best","bet","better","between","beyond","bicycle","bigger","biggest","bill","birds","birth","birthday","bit","bite","black","blank","blanket","blew","blind","block","blood","blow","blue","board","boat","body","bone","book","border","born","both","bottle","bottom","bound","bow","bowl","box","boy","brain","branch","brass","brave","bread","break","breakfast","breath","breathe","breathing","breeze","brick","bridge","brief","bright","bring","broad","broke","broken","brother","brought","brown","brush","buffalo","build","building","built","buried","burn","burst","bus","bush","business","busy","but","butter","buy","by","cabin","cage","cake","call","calm","came","camera","camp","can","canal","cannot","cap","capital","captain","captured","car","carbon","card","care","careful","carefully","carried","carry","case","cast","castle","cat","catch","cattle","caught","cause","cave","cell","cent","center","central","century","certain","certainly","chain","chair","chamber","chance","change","changing","chapter","character","characteristic","charge","chart","check","cheese","chemical","chest","chicken","chief","child","children","choice","choose","chose","chosen","church","circle","circus","citizen","city","class","classroom","claws","clay","clean","clear","clearly","climate","climb","clock","close","closely","closer","cloth","clothes","clothing","cloud","club","coach","coal","coast","coat","coffee","cold","collect","college","colony","color","column","combination","combine","come","comfortable","coming","command","common","community","company","compare","compass","complete","completely","complex","composed","composition","compound","concerned","condition","congress","connected","consider","consist","consonant","constantly","construction","contain","continent","continued","contrast","control","conversation","cook","cookies","cool","copper","copy","corn","corner","correct","correctly","cost","cotton","could","count","country","couple","courage","course","court","cover","cow","cowboy","crack","cream","create","creature","crew","crop","cross","crowd","cry","cup","curious","current","curve","customs","cut","cutting","daily","damage","dance","danger","dangerous","dark","darkness","date","daughter","dawn","day","dead","deal","dear","death","decide","declared","deep","deeply","deer","definition","degree","depend","depth","describe","desert","design","desk","detail","determine","develop","development","diagram","diameter","did","die","differ","difference","different","difficult","difficulty","dig","dinner","direct","direction","directly","dirt","dirty","disappear","discover","discovery","discuss","discussion","disease","dish","distance","distant","divide","division","do","doctor","does","dog","doing","doll","dollar","done","donkey","door","dot","double","doubt","down","dozen","draw","drawn","dream","dress","drew","dried","drink","drive","driven","driver","driving","drop","dropped","drove","dry","duck","due","dug","dull","during","dust","duty","each","eager","ear","earlier","early","earn","earth","easier","easily","east","easy","eat","eaten","edge","education","effect","effort","egg","eight","either","electric","electricity","element","elephant","eleven","else","empty","end","enemy","energy","engine","engineer","enjoy","enough","enter","entire","entirely","environment","equal","equally","equator","equipment","escape","especially","essential","establish","even","evening","event","eventually","ever","every","everybody","everyone","everything","everywhere","evidence","exact","exactly","examine","example","excellent","except","exchange","excited","excitement","exciting","exclaimed","exercise","exist","expect","experience","experiment","explain","explanation","explore","express","expression","extra","eye","face","facing","fact","factor","factory","failed","fair","fairly","fall","fallen","familiar","family","famous","far","farm","farmer","farther","fast","fastened","faster","fat","father","favorite","fear","feathers","feature","fed","feed","feel","feet","fell","fellow","felt","fence","few","fewer","field","fierce","fifteen","fifth","fifty","fight","fighting","figure","fill","film","final","finally","find","fine","finest","finger","finish","fire","fireplace","firm","first","fish","five","fix","flag","flame","flat","flew","flies","flight","floating","floor","flow","flower","fly","fog","folks","follow","food","foot","football","for","force","foreign","forest","forget","forgot","forgotten","form","former","fort","forth","forty","forward","fought","found","four","fourth","fox","frame","free","freedom","frequently","fresh","friend","friendly","frighten","frog","from","front","frozen","fruit","fuel","full","fully","fun","function","funny","fur","furniture","further","future","gain","game","garage","garden","gas","gasoline","gate","gather","gave","general","generally","gentle","gently","get","getting","giant","gift","girl","give","given","giving","glad","glass","globe","go","goes","gold","golden","gone","good","goose","got","government","grabbed","grade","gradually","grain","grandfather","grandmother","graph","grass","gravity","gray","great","greater","greatest","greatly","green","grew","ground","group","grow","grown","growth","guard","guess","guide","gulf","gun","habit","had","hair","half","halfway","hall","hand","handle","handsome","hang","happen","happened","happily","happy","harbor","hard","harder","hardly","has","hat","have","having","hay","he","headed","heading","health","heard","hearing","heart","heat","heavy","height","held","hello","help","helpful","her","herd","here","herself","hidden","hide","high","higher","highest","highway","hill","him","himself","his","history","hit","hold","hole","hollow","home","honor","hope","horn","horse","hospital","hot","hour","house","how","however","huge","human","hundred","hung","hungry","hunt","hunter","hurried","hurry","hurt","husband","ice","idea","identity","if","ill","image","imagine","immediately","importance","important","impossible","improve","in","inch","include","including","income","increase","indeed","independent","indicate","individual","industrial","industry","influence","information","inside","instance","instant","instead","instrument","interest","interior","into","introduced","invented","involved","iron","is","island","it","its","itself","jack","jar","jet","job","join","joined","journey","joy","judge","jump","jungle","just","keep","kept","key","kids","kill","kind","kitchen","knew","knife","know","knowledge","known","label","labor","lack","lady","laid","lake","lamp","land","language","large","larger","largest","last","late","later","laugh","law","lay","layers","lead","leader","leaf","learn","least","leather","leave","leaving","led","left","leg","length","lesson","let","letter","level","library","lie","life","lift","light","like","likely","limited","line","lion","lips","liquid","list","listen","little","live","living","load","local","locate","location","log","lonely","long","longer","look","loose","lose","loss","lost","lot","loud","love","lovely","low","lower","luck","lucky","lunch","lungs","lying","machine","machinery","mad","made","magic","magnet","mail","main","mainly","major","make","making","man","managed","manner","manufacturing","many","map","mark","market","married","mass","massage","master","material","mathematics","matter","may","maybe","me","meal","mean","means","meant","measure","meat","medicine","meet","melted","member","memory","men","mental","merely","met","metal","method","mice","middle","might","mighty","mile","military","milk","mill","mind","mine","minerals","minute","mirror","missing","mission","mistake","mix","mixture","model","modern","molecular","moment","money","monkey","month","mood","moon","more","morning","most","mostly","mother","motion","motor","mountain","mouse","mouth","move","movement","movie","moving","mud","muscle","music","musical","must","my","myself","mysterious","nails","name","nation","national","native","natural","naturally","nature","near","nearby","nearer","nearest","nearly","necessary","neck","needed","needle","needs","negative","neighbor","neighborhood","nervous","nest","never","new","news","newspaper","next","nice","night","nine","no","nobody","nodded","noise","none","noon","nor","north","nose","not","note","noted","nothing","notice","noun","now","number","numeral","nuts","object","observe","obtain","occasionally","occur","ocean","of","off","offer","office","officer","official","oil","old","older","oldest","on","once","one","only","onto","open","operation","opinion","opportunity","opposite","or","orange","orbit","order","ordinary","organization","organized","origin","original","other","ought","our","ourselves","out","outer","outline","outside","over","own","owner","oxygen","pack","package","page","paid","pain","paint","pair","palace","pale","pan","paper","paragraph","parallel","parent","park","part","particles","particular","particularly","partly","parts","party","pass","passage","past","path","pattern","pay","peace","pen","pencil","people","per","percent","perfect","perfectly","perhaps","period","person","personal","pet","phrase","physical","piano","pick","picture","pictured","pie","piece","pig","pile","pilot","pine","pink","pipe","pitch","place","plain","plan","plane","planet","planned","planning","plant","plastic","plate","plates","play","pleasant","please","pleasure","plenty","plural","plus","pocket","poem","poet","poetry","point","pole","police","policeman","political","pond","pony","pool","poor","popular","population","porch","port","position","positive","possible","possibly","post","pot","potatoes","pound","pour","powder","power","powerful","practical","practice","prepare","present","president","press","pressure","pretty","prevent","previous","price","pride","primitive","principal","principle","printed","private","prize","probably","problem","process","produce","product","production","program","progress","promised","proper","properly","property","protection","proud","prove","provide","public","pull","pupil","pure","purple","purpose","push","put","putting","quarter","queen","question","quick","quickly","quiet","quietly","quite","rabbit","race","radio","railroad","rain","raise","ran","ranch","range","rapidly","rate","rather","raw","rays","reach","read","reader","ready","real","realize","rear","reason","recall","receive","recent","recently","recognize","record","red","refer","refused","region","regular","related","relationship","religious","remain","remarkable","remember","remove","repeat","replace","replied","report","represent","require","research","respect","rest","result","return","review","rhyme","rhythm","rice","rich","ride","riding","right","ring","rise","rising","river","road","roar","rock","rocket","rocky","rod","roll","roof","room","root","rope","rose","rough","round","route","row","rubbed","rubber","rule","ruler","run","running","rush","sad","saddle","safe","safety","said","sail","sale","salmon","salt","same","sand","sang","sat","satellites","satisfied","save","saved","saw","say","scale","scared","scene","school","science","scientific","scientist","score","screen","sea","search","season","seat","second","secret","section","see","seed","seeing","seems","seen","seldom","select","selection","sell","send","sense","sent","sentence","separate","series","serious","serve","service","sets","setting","settle","settlers","seven","several","shade","shadow","shake","shaking","shall","shallow","shape","share","sharp","she","sheep","sheet","shelf","shells","shelter","shine","shinning","ship","shirt","shoe","shoot","shop","shore","short","shorter","shot","should","shoulder","shout","show","shown","shut","sick","sides","sight","sign","signal","silence","silent","silk","silly","silver","similar","simple","simplest","simply","since","sing","single","sink","sister","sit","sitting","situation","six","size","skill","skin","sky","slabs","slave","sleep","slept","slide","slight","slightly","slip","slipped","slope","slow","slowly","small","smaller","smallest","smell","smile","smoke","smooth","snake","snow","so","soap","social","society","soft","softly","soil","solar","sold","soldier","solid","solution","solve","some","somebody","somehow","someone","something","sometime","somewhere","son","song","soon","sort","sound","source","south","southern","space","speak","special","species","specific","speech","speed","spell","spend","spent","spider","spin","spirit","spite","split","spoken","sport","spread","spring","square","stage","stairs","stand","standard","star","stared","start","state","statement","station","stay","steady","steam","steel","steep","stems","step","stepped","stick","stiff","still","stock","stomach","stone","stood","stop","stopped","store","storm","story","stove","straight","strange","stranger","straw","stream","street","strength","stretch","strike","string","strip","strong","stronger","struck","structure","struggle","stuck","student","studied","studying","subject","substance","success","successful","such","sudden","suddenly","sugar","suggest","suit","sum","summer","sun","sunlight","supper","supply","support","suppose","sure","surface","surprise","surrounded","swam","sweet","swept","swim","swimming","swing","swung","syllable","symbol","system","table","tail","take","taken","tales","talk","tall","tank","tape","task","taste","taught","tax","tea","teach","teacher","team","tears","teeth","telephone","television","tell","temperature","ten","tent","term","terrible","test","than","thank","that","thee","them","themselves","then","theory","there","therefore","these","they","thick","thin","thing","think","third","thirty","this","those","thou","though","thought","thousand","thread","three","threw","throat","through","throughout","throw","thrown","thumb","thus","thy","tide","tie","tight","tightly","till","time","tin","tiny","tip","tired","title","to","tobacco","today","together","told","tomorrow","tone","tongue","tonight","too","took","tool","top","topic","torn","total","touch","toward","tower","town","toy","trace","track","trade","traffic","trail","train","transportation","trap","travel","treated","tree","triangle","tribe","trick","tried","trip","troops","tropical","trouble","truck","trunk","truth","try","tube","tune","turn","twelve","twenty","twice","two","type","typical","uncle","under","underline","understanding","unhappy","union","unit","universe","unknown","unless","until","unusual","up","upon","upper","upward","us","use","useful","using","usual","usually","valley","valuable","value","vapor","variety","various","vast","vegetable","verb","vertical","very","vessels","victory","view","village","visit","visitor","voice","volume","vote","vowel","voyage","wagon","wait","walk","wall","want","war","warm","warn","was","wash","waste","watch","water","wave","way","we","weak","wealth","wear","weather","week","weigh","weight","welcome","well","went","were","west","western","wet","whale","what","whatever","wheat","wheel","when","whenever","where","wherever","whether","which","while","whispered","whistle","white","who","whole","whom","whose","why","wide","widely","wife","wild","will","willing","win","wind","window","wing","winter","wire","wise","wish","with","within","without","wolf","women","won","wonder","wonderful","wood","wooden","wool","word","wore","work","worker","world","worried","worry","worse","worth","would","wrapped","write","writer","writing","written","wrong","wrote","yard","year","yellow","yes","yesterday","yet","you","young","younger","your","yourself","youth","zero","zebra","zipper","zoo","zulu"];function Vf(n){return new Array(n).fill(0).map(()=>yd[Math.floor(Math.random()*yd.length)]).join("-")}async function qf({codePath:n,screenshotBuff:e,storage:t,logger:r}){if(e)try{let o=await t.uploadScreenshot(e);return r.debug({screenshotUrl:o,codePath:n},"Saved screenshot for debugging"),o}catch(o){r.error({err:o,codePath:n},"Failed to save screenshot for debugging")}}async function xn({frameConfig:n,action:e,browser:t}){let r=t.getActiveFrameConfig();n?t.setActiveFrameConfig(n):r?.type==="auto"&&t.setActiveFrameConfig(void 0);try{return await e()}finally{t.setActiveFrameConfig(r)}}var Ua="MOMENTIC_RUN_ID",Kf="FINAL_SCREENSHOT_URL";import{cloneDeep as HA}from"lodash-es";async function Yf(n){let{step:e,tracer:t}=n.conditionalParams,{logger:r,controller:o}=n.fixtures,i=new Date,s=La(e),a=e.elseSteps,l=!0,c=[],p,d=pa();for(let f=0;f<e.blocks.length;f++){r.info(`Evaluating condition ${f} in conditional step`);let S=e.blocks[f];try{let v=await Da({...n,presetParams:{tracer:t,step:S.assertion}});c.push(v),r.info(`Condition ${f} resolved to true, executing the corresponding ${S.steps.length} steps`),l=!1,a=S.steps,p=v}catch(v){r.info({err:v},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(a)l&&r.info("No conditions resolved to true, executing the else block steps");else return r.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...s,status:"SUCCESS",startedAt:i,data:c[c.length-1]?.data,message:c[c.length-1]?.message,results:[],finishedAt:new Date,details:d.details};r.info(`Executing ${a.length} steps in the selected conditional block`);let u=await n.conditionalParams.tracer.startSubSteps(),m=await n.executeStepList({...n,listParams:{steps:a,containerName:"conditional block",tracer:u}}),g={...s,assertion:p,...m,startedAt:i,finishedAt:new Date};return Jt({asyncTasks:n.work.asyncTasks,nestedResults:[...c,...m.results],result:g,logger:r}),g}import{randomUUID as Jf}from"crypto";var Xf=async n=>{let{controller:e}=n.fixtures;await e.browser.waitForDOMStability();let t=await e.browser.screenshot({}),r=await _A(n);r.finishedAt=new Date,Jt({asyncTasks:n.work.asyncTasks,result:r,nestedResults:r.results,logger:n.fixtures.logger});let o=await e.browser.screenshot({}),i=Jf();r.beforeSnapshot=i,n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(n.fixtures.logger,i,t));let s=Jf();return r.afterSnapshot=s,n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(n.fixtures.logger,s,o)),r},_A=async n=>{let{step:e,tracer:t}=n.aiStepParams,{controller:r,context:o,logger:i}=n.fixtures,s={...e,startedAt:new Date,beforeTestContext:o.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in e&&e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS"))throw new R("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let l=await t.startSubSteps(),{status:c}=await n.executeStepList({...n,listParams:{steps:e.steps,containerName:"AI action",results:s.results,tracer:l}});return s.finishedAt=new Date,s.status=c,s}catch(l){i.warn({err:l},"Failed executing saved deprecated AI action steps");let c=r.executeAbortController.signal.aborted;s.message=l instanceof Error?l.message:`${l}`,s.status=c?"CANCELLED":"FAILED"}return s};import{randomUUID as bd}from"crypto";var Zf=15,MA=7,Qf=async n=>{let{controller:e}=n.fixtures;await e.browser.waitForDOMStability();let t=await e.browser.screenshot({}),r=await FA(n);r.finishedAt=new Date,Jt({asyncTasks:n.work.asyncTasks,result:r,nestedResults:r.results,logger:n.fixtures.logger});let o=await e.browser.screenshot({}),i=bd();r.beforeSnapshot=i,n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(n.fixtures.logger,i,t));let s=bd();return r.afterSnapshot=s,n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(n.fixtures.logger,s,o)),r},FA=async n=>{let{step:e,tracer:t}=n.aiStepParams,{testMetadata:r,orgId:o}=n.inputs,{controller:i,context:s,logger:a,codeEvalTools:l}=n.fixtures,{step:c}=n.callbacks,p=`${e.id}-${Date.now()}`,d=a.child({stepId:e.id,langfuseSessionId:p}),u={...e,startedAt:new Date,beforeTestContext:s.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},m=await Ut({orgId:o,s:e.text,context:s,logger:d,localTools:l,flagStore:i.flagStore});await i.browser.waitForDOMStability({logger:d});let g=`data:image/jpeg;base64,${(await i.browser.screenshot({clearHighlights:!0,retries:2})).toString("base64")}`,f=[],S=0,v=0,b,x;for(;;){if(S>Zf)return u.message=`Exceeded the maximum number of commands allowed per AI step (${Zf})`,u.status="FAILED",u;if(i.executeAbortController.signal.aborted)return u.message="Test execution was cancelled",u.status="CANCELLED",u;c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let C=await i.evaluateAiAction({goal:m,startingScreenshot:S===0?void 0:g,history:f,logger:d,langfuseSessionId:p,lastError:x}),{evaluation:E,reasoning:I,summary:N}=C;d.info(C,"Got AI evaluation");let P=u.results[S-1]?.id;switch(E.type){case"DONE":return u.message=`Our AI evaluator confirmed all tasks are complete: ${I}`,u.status="SUCCESS",P&&c.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"SUCCESS",message:`${N}
43
43
  ${I}`}),u;case"RIGHT_TRACK":{b=void 0,S===0?c.onDynamicAIActionEvaluatingEvent?.({stepId:e.id,status:"RUNNING",message:I}):P&&c.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"SUCCESS",message:I});break}case"WRONG_TRACK":{if(b=`${I}
44
44
  ${E.feedback}`,v++,v>=MA)return u.message=`Our AI agent requires additional information to achieve this goal:
@@ -3580,7 +3580,7 @@ ${i.stack}`),a.status(500).send("Internal Server Error")}),n){let i=zw.static(n,
3580
3580
 
3581
3581
  Using Command Prompt on Windows:
3582
3582
  for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
3583
- `)}import u_ from"events";import Cu from"fs";import m_ from"open";import tc from"path";import{fileURLToPath as h_}from"url";import cN from"diff-lines";import{gt as dN}from"semver";import{execSync as Gk}from"child_process";import{platform as Vk}from"os";function Kp(){return Ww()?(y.info("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),y.info("If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations."),y.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),2):(y.info("Setting device pixel ratio to 1."),y.info("If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations"),y.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),1)}function Ww(){return Vk()==="darwin"&&Gk("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Yp(n){Ww()&&n===1&&(y.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),y.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import qk from"@actions/exec";import Kk from"@actions/io";import Yk from"quote";import Jk from"string-argv";async function Gw(n,e=!0){let t=Jk(n),r=await Kk.which(t[0],!0),o=t.slice(1),i=qk.exec(Yk(r),o,{delay:100});if(e)return i}import{existsSync as Xk,statSync as Zk}from"fs";var Ol=!!process.env.CI||!process.stdout.isTTY||!!process.env.TF_BUILD;function Cs(n){try{return Xk(n)&&Zk(n).isDirectory()}catch(e){return y.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import Qk from"csv-parser";import{createReadStream as eN}from"fs";function Jp(n){return new Promise((e,t)=>{let r=[];eN(n).pipe(Qk()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import kl from"semver";import{z as Nl}from"zod";var Ht="1.1.10",tN="https://registry.npmjs.org/momentic",nN=Nl.object({versions:Nl.record(Nl.string(),Nl.unknown()).optional()});async function Vw(n){try{await rN(n)}catch(e){y.warn({err:e},"Failed to check CLI version against NPM servers")}}async function rN(n){if(!Ht){n.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let r=0;r<2;r++)try{let o=await D(fetch(tN),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=nN.parse(i).versions;break}catch(o){n.warn({err:o},"Failed to fetch npm registry data")}if(!e){n.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let r of Object.keys(e))kl.valid(r)&&(!t||kl.gt(r,t))&&kl.gt(r,Ht)&&kl.lt(r,"2.0.0")&&!r.includes("alpha")&&(t=r);t&&(y.warn(`Update available: v${Ht} -> v${t}`),y.warn("This version may be missing critical fixes, features, and security updates."),y.warn(`Run "npx momentic@${t} -V" to update`))}import{existsSync as iN,mkdirSync as sN,statSync as aN}from"fs";import{dirname as lN}from"path";import Kw from"readline/promises";import{hostname as oN}from"os";var Q=Rl({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:oN(),disableConsoleLogs:!0}).child({version:"1.1.10"});var Xp=!1,Yw=(()=>{try{return aN("/.dockerenv"),!0}catch{return!1}})();async function lt(n,e){if(Ol||Xp||Yw)return!0;Q.flush(),await new Promise(s=>setTimeout(s,500));let t=Kw.createInterface({input:process.stdin,output:process.stdout}),r=n.split("."),o;if(r.length===1)o=n;else{let s=`${r.slice(0,r.length-1).join(".").trim()}.`;e?y.warn(s):y.log(s),o=r[r.length-1].trim()}let i=await t.question(`${o} ('y' for yes / n for no / 'A' to accept all) `);return t.close(),i==="A"?(Xp=!0,setTimeout(()=>{Xp=!1},3e3),!0):i.toLowerCase()==="y"}async function Zp(n){let e=lN(n);return Cs(e)?iN(n)?lt(`File '${qw(n)}' already exists. Overwrite existing content?`,!0):!0:await lt(`Directory '${qw(e)}' doesn't exist. Create it now?`,!0)?(sN(e,{recursive:!0}),!0):!1}function qw(n){return n.replace(/(\s+)/g,"\\$1")}async function Jw(n,e){if(Ol||Yw)return e;let t=Kw.createInterface({input:process.stdin,output:process.stdout}),r=await t.question(`${n} `);return t.close(),r.trim()||e}async function Xw({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){dN(e.schemaVersion,He)&&(y.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),Ng(e.steps).forEach(g=>{t.modules[g]||(y.error(`The test patch contains a module with id ${g} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!i&&!await lt("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let a=n.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<a&&!i&&!await lt("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?",!0)&&process.exit(1);let l=rs(n.fullFilePath,o,t),c=l.steps;if(!Array.isArray(c))throw new Error(`Test ${n.fullFilePath} is missing steps array`);let p,d;if(e.schemaVersion!==He){let{steps:g,newVersion:f}=await Gi({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:y});p=f,d=ve.array().parse(g)}else d=ve.array().parse(e.steps);let{stepsToSave:u,moduleUpdates:m}=await Xe({stepLists:{steps:d}});u.beforeSteps=l.beforeSteps??void 0,u.afterSteps=l.afterSteps??void 0;let h=cN(JSON.stringify(c,void 0,2),JSON.stringify(u,void 0,2),{n_surrounding:5});y.dimmed("=".repeat(30)),y.dimmed(h),y.dimmed("=".repeat(30)),y.dimmed(""),p&&y.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${p}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await lt("Do you want to apply this patch?")&&(y.dimmed("Cancelled."),process.exit(1)),Yr(n.relativePath,u,p??e.schemaVersion,t.project),y.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as Zw}from"crypto";async function Qw({fix:n,project:e}){let t=ke(e,y),r=Object.values(t.tests),o={},i={},s=new Set,a=0;for(let l of r)try{let c=rs(l.fullFilePath,Q,t),p=c.steps;if(!p||p.length===0||!Array.isArray(p)){y.debug(`Test ${l.name} (${l.relativePath}) has no steps, skipping...`);continue}let d=Nt.parse(c),u=await pd(d,p,y),m=!1,h=!1;u.steps.forEach((g,f)=>{if(!g.id){y.error(`Step ${f} in test '${l.name}' (${l.relativePath}) does not have an ID`),h=!0;return}let S=o[g.id]?.testId,v=o[g.id]?.testRelativePath;if(S?(a++,h=!0,S===l.id?y.error(`Multiple steps in the test '${l.name}' (${l.relativePath}) have the same ID '${g.id}'`):y.error(`Step ${f} in test '${l.name}' (${l.relativePath}) has the ID ${g.id} which is duplicated in test ${v}`),n&&(m=!0,g.id=Zw())):o[g.id]={testId:l.id,testRelativePath:l.relativePath},g.type!=="PRESET_ACTION")return;let b=g.command.id,x=i[b]?.testId,C=i[b]?.testRelativePath;x?(a++,h=!0,x===l.id?y.error(`Multiple commands in the test '${l.name}' (${l.relativePath}) have the same ID '${b}'`):y.error(`Command ${f} in test '${l.name}' (${l.relativePath}) has the ID ${b} which is duplicated in test ${C}`),n&&(m=!0,g.command.id=Zw())):i[b]={testId:l.id,testRelativePath:l.relativePath}}),h&&y.dimmed("=".repeat(80)),m&&n&&(Yr(l.relativePath,{beforeSteps:c.beforeSteps,steps:u.steps,afterSteps:c.afterSteps},He,e),s.add(l.fullFilePath))}catch(c){y.error({err:c},`Failed to parse test ${l.name} (${l.relativePath})`);continue}a>0?(y.error(`Found errors in ${a} steps`),n?y.warn(`Modified the following files:
3583
+ `)}import u_ from"events";import Cu from"fs";import m_ from"open";import tc from"path";import{fileURLToPath as h_}from"url";import cN from"diff-lines";import{gt as dN}from"semver";import{execSync as Gk}from"child_process";import{platform as Vk}from"os";function Kp(){return Ww()?(y.info("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),y.info("If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations."),y.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),2):(y.info("Setting device pixel ratio to 1."),y.info("If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations"),y.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),1)}function Ww(){return Vk()==="darwin"&&Gk("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Yp(n){Ww()&&n===1&&(y.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),y.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import qk from"@actions/exec";import Kk from"@actions/io";import Yk from"quote";import Jk from"string-argv";async function Gw(n,e=!0){let t=Jk(n),r=await Kk.which(t[0],!0),o=t.slice(1),i=qk.exec(Yk(r),o,{delay:100});if(e)return i}import{existsSync as Xk,statSync as Zk}from"fs";var Ol=!!process.env.CI||!process.stdout.isTTY||!!process.env.TF_BUILD;function Cs(n){try{return Xk(n)&&Zk(n).isDirectory()}catch(e){return y.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import Qk from"csv-parser";import{createReadStream as eN}from"fs";function Jp(n){return new Promise((e,t)=>{let r=[];eN(n).pipe(Qk()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import kl from"semver";import{z as Nl}from"zod";var Ht="1.1.11",tN="https://registry.npmjs.org/momentic",nN=Nl.object({versions:Nl.record(Nl.string(),Nl.unknown()).optional()});async function Vw(n){try{await rN(n)}catch(e){y.warn({err:e},"Failed to check CLI version against NPM servers")}}async function rN(n){if(!Ht){n.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let r=0;r<2;r++)try{let o=await D(fetch(tN),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=nN.parse(i).versions;break}catch(o){n.warn({err:o},"Failed to fetch npm registry data")}if(!e){n.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let r of Object.keys(e))kl.valid(r)&&(!t||kl.gt(r,t))&&kl.gt(r,Ht)&&kl.lt(r,"2.0.0")&&!r.includes("alpha")&&(t=r);t&&(y.warn(`Update available: v${Ht} -> v${t}`),y.warn("This version may be missing critical fixes, features, and security updates."),y.warn(`Run "npx momentic@${t} -V" to update`))}import{existsSync as iN,mkdirSync as sN,statSync as aN}from"fs";import{dirname as lN}from"path";import Kw from"readline/promises";import{hostname as oN}from"os";var Q=Rl({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:oN(),disableConsoleLogs:!0}).child({version:"1.1.11"});var Xp=!1,Yw=(()=>{try{return aN("/.dockerenv"),!0}catch{return!1}})();async function lt(n,e){if(Ol||Xp||Yw)return!0;Q.flush(),await new Promise(s=>setTimeout(s,500));let t=Kw.createInterface({input:process.stdin,output:process.stdout}),r=n.split("."),o;if(r.length===1)o=n;else{let s=`${r.slice(0,r.length-1).join(".").trim()}.`;e?y.warn(s):y.log(s),o=r[r.length-1].trim()}let i=await t.question(`${o} ('y' for yes / n for no / 'A' to accept all) `);return t.close(),i==="A"?(Xp=!0,setTimeout(()=>{Xp=!1},3e3),!0):i.toLowerCase()==="y"}async function Zp(n){let e=lN(n);return Cs(e)?iN(n)?lt(`File '${qw(n)}' already exists. Overwrite existing content?`,!0):!0:await lt(`Directory '${qw(e)}' doesn't exist. Create it now?`,!0)?(sN(e,{recursive:!0}),!0):!1}function qw(n){return n.replace(/(\s+)/g,"\\$1")}async function Jw(n,e){if(Ol||Yw)return e;let t=Kw.createInterface({input:process.stdin,output:process.stdout}),r=await t.question(`${n} `);return t.close(),r.trim()||e}async function Xw({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){dN(e.schemaVersion,He)&&(y.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),Ng(e.steps).forEach(g=>{t.modules[g]||(y.error(`The test patch contains a module with id ${g} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!i&&!await lt("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let a=n.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<a&&!i&&!await lt("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?",!0)&&process.exit(1);let l=rs(n.fullFilePath,o,t),c=l.steps;if(!Array.isArray(c))throw new Error(`Test ${n.fullFilePath} is missing steps array`);let p,d;if(e.schemaVersion!==He){let{steps:g,newVersion:f}=await Gi({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:y});p=f,d=ve.array().parse(g)}else d=ve.array().parse(e.steps);let{stepsToSave:u,moduleUpdates:m}=await Xe({stepLists:{steps:d}});u.beforeSteps=l.beforeSteps??void 0,u.afterSteps=l.afterSteps??void 0;let h=cN(JSON.stringify(c,void 0,2),JSON.stringify(u,void 0,2),{n_surrounding:5});y.dimmed("=".repeat(30)),y.dimmed(h),y.dimmed("=".repeat(30)),y.dimmed(""),p&&y.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${p}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await lt("Do you want to apply this patch?")&&(y.dimmed("Cancelled."),process.exit(1)),Yr(n.relativePath,u,p??e.schemaVersion,t.project),y.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as Zw}from"crypto";async function Qw({fix:n,project:e}){let t=ke(e,y),r=Object.values(t.tests),o={},i={},s=new Set,a=0;for(let l of r)try{let c=rs(l.fullFilePath,Q,t),p=c.steps;if(!p||p.length===0||!Array.isArray(p)){y.debug(`Test ${l.name} (${l.relativePath}) has no steps, skipping...`);continue}let d=Nt.parse(c),u=await pd(d,p,y),m=!1,h=!1;u.steps.forEach((g,f)=>{if(!g.id){y.error(`Step ${f} in test '${l.name}' (${l.relativePath}) does not have an ID`),h=!0;return}let S=o[g.id]?.testId,v=o[g.id]?.testRelativePath;if(S?(a++,h=!0,S===l.id?y.error(`Multiple steps in the test '${l.name}' (${l.relativePath}) have the same ID '${g.id}'`):y.error(`Step ${f} in test '${l.name}' (${l.relativePath}) has the ID ${g.id} which is duplicated in test ${v}`),n&&(m=!0,g.id=Zw())):o[g.id]={testId:l.id,testRelativePath:l.relativePath},g.type!=="PRESET_ACTION")return;let b=g.command.id,x=i[b]?.testId,C=i[b]?.testRelativePath;x?(a++,h=!0,x===l.id?y.error(`Multiple commands in the test '${l.name}' (${l.relativePath}) have the same ID '${b}'`):y.error(`Command ${f} in test '${l.name}' (${l.relativePath}) has the ID ${b} which is duplicated in test ${C}`),n&&(m=!0,g.command.id=Zw())):i[b]={testId:l.id,testRelativePath:l.relativePath}}),h&&y.dimmed("=".repeat(80)),m&&n&&(Yr(l.relativePath,{beforeSteps:c.beforeSteps,steps:u.steps,afterSteps:c.afterSteps},He,e),s.add(l.fullFilePath))}catch(c){y.error({err:c},`Failed to parse test ${l.name} (${l.relativePath})`);continue}a>0?(y.error(`Found errors in ${a} steps`),n?y.warn(`Modified the following files:
3584
3584
  ${[...s].map(l=>`- ${l}`).join(`
3585
3585
  `)}`):y.warn("To fix these errors automatically, re-run this check with the --fix flag and then commit the resulting changes"),process.exit(1)):(y.success("No step ID errors found!"),process.exit(0))}async function ev({project:n}){let e=ke(n,y),t=Object.values(e.tests),r=await il(e,Q),o={},i={},s={},a={},l=new Set,c=new Set,p=new Set,d=new Set;for(let m of t)o[m.id]?s[m.id]?s[m.id].push(m.fullFilePath):s[m.id]=[o[m.id],m.fullFilePath]:o[m.id]=m.fullFilePath,i[m.name]?a[m.name]?a[m.name].push(m.fullFilePath):a[m.name]=[i[m.name],m.fullFilePath]:i[m.name]=m.fullFilePath;for(let m of r)d.has(m.moduleId)&&l.add(m.moduleId),p.has(m.name)&&c.add(m.name),d.add(m.moduleId),p.add(m.name);if(Object.entries(s).length>0||Object.entries(a).length>0||l.size>0||c.size>0){for(let[m,h]of Object.entries(s))for(let g of h)y.error(`Test ID ${m} is duplicated in ${g}`);for(let[m,h]of Object.entries(a))for(let g of h)y.error(`Test Name ${m} is duplicated in ${g}`);for(let m of l)y.error(`Module id ${m} is duplicated in your project`);for(let m of c)y.error(`Module name ${m} is duplicated in your project`);process.exit(1)}y.success("No duplicates detected. All test and module names and ids are unique."),process.exit(0)}import{cloneDeep as pN}from"lodash-es";async function _l({client:n,skipPrompts:e,project:t}){let r=await n.getAllEnvironments(),o=pN(t.config);o.environments||(o.environments=[]);for(let i of r){let s=o.environments?.find(a=>a.name===i.name);if(s)!e&&!await lt(`Environment ${i.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),s.baseUrl=i.variables[Pe],delete i.variables[Pe],s.envVariables=i.variables;else{let a=i.variables[Pe];delete i.variables[Pe],o.environments.push({name:i.name,baseUrl:a,envVariables:i.variables})}}Zo(o,t.configFilePath),y.success(`Pulled ${r.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as tv}from"crypto";import nv from"fs";async function ov({testsToFetch:n,client:e,all:t,yes:r}){let{tests:o,modules:i}=await e.getTestYAMLExport({paths:n,all:t}),s=0;for(let[l,c]of Object.entries(o)){let p=rv(l,he.TEST);!r&&!await Zp(p)||(s+=1,nv.writeFileSync(p,c,"utf-8"),Q.info({checksum:tv("md5").update(c).digest("hex")},`Wrote '${p}'`))}let a=0;for(let[l,c]of Object.entries(i)){let p=rv(l,he.MODULE);!r&&!await Zp(p)||(a+=1,nv.writeFileSync(p,c,"utf-8"),Q.info({checksum:tv("md5").update(c).digest("hex")},`Wrote '${p}'`))}s===0?y.success("Pulled 0 tests."):y.success(`Pulled ${s} test${s>1?"s":""}${a?` and ${a} module${a>1?"s":""}`:""}!`)}function rv(n,e){switch(e){case he.TEST:return`${Le(n)}.${_t.TEST}`;case he.MODULE:return`${Le(n)}.${_t.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function iv(n){let{project:e,client:t,skipPrompts:r}=n;y.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),y.info("Importing environments from Momentic Cloud."),y.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await lt("Are you sure you want to proceed?",!0)||(y.info("Aborting..."),process.exit(1)),await _l({client:t,project:e,skipPrompts:r}),y.success(`Successfully imported environments from Momentic Cloud. We recommend pulling secrets out of ${e.configFilePath} into .env files or dynamically set environment variables for security.`),y.info("Importing tests and modules from Momentic Cloud."),await ov({testsToFetch:[],client:t,all:!0,yes:r}),y.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}import $t from"fs";import Qr from"path";import uN from"yaml";function sv(){Cs("momentic")||(y.error(`The migration command should be ran from the v0 root Momentic directory, which should contain a folder called 'momentic'. No folder named 'momentic' was found in the current working directory (${process.cwd()}).`),process.exit(1));let n={name:"default",include:xs,environments:[]};y.info("Migrating environments");let e=av(["momentic/environments"],mN);for(let r of e){let o=uN.parse($t.readFileSync(r,"utf-8"));try{let i=Js.parse(o),s=i.variables[Pe]??"";delete i.variables[Pe],n.environments?.push({name:i.name,baseUrl:s,envVariables:i.variables})}catch(i){y.error(`${r} failed to parse as a valid environment file.`),y.error(i),process.exit(1)}}y.info("Migrating tests");let t=pp("./momentic",y);for(let r of t){let o=Qr.join(...r.fullPathSegments),i=Qr.join(Qr.dirname(o),`${r.fileName.slice(0,-5)}.test.yaml`);y.info(`Moving test ${o} to ${i}`),$t.renameSync(o,i)}if(Cs("momentic/modules")){y.info("Migrating modules");for(let r of $t.readdirSync("./momentic/modules")){if(!r.endsWith(".yaml"))continue;let o=Qr.resolve(Qr.join("./momentic/modules",r));if(!$t.readFileSync(o,"utf-8").includes("schemaVersion")){y.warn(`Skipping file ${o} since it does not have valid Momentic module contents`);continue}let s=`${o.slice(0,-5)}.module.yaml`;y.info(`Moving module ${o} to ${s}`),$t.renameSync(o,s)}}return y.info("Writing new project configuration file"),Zo(n,"momentic.config.yaml"),$t.rmSync("./momentic/environments",{recursive:!0,force:!0}),$t.rmSync("./momentic/fixtures",{recursive:!0,force:!0}),y.success("Migration succeeded!"),y.info("Going forward:"),y.info(` - You can store test and module files anywhere under the project root (${process.cwd()})`),y.info(" - Environment details and other common options are tracked in the root momentic.config.yaml file"),n}function av(n,e,t=new Set){for(let r of n){let o=Qr.resolve(r),i=!1;try{i=$t.existsSync(o)&&$t.statSync(o).isDirectory()}catch(s){y.error({err:s},`Error reading path ${o} during collect paths`)}if(o&&i){let s=$t.readdirSync(o).map(a=>Qr.join(o,a));av(s,e,t);continue}if(o.endsWith(".yaml")){try{if(!$t.existsSync(o)||!$t.statSync(o).isFile()){y.warn(`File not found or unreadable: ${o}`);continue}}catch(s){y.error({err:s},`Error reading file ${o} during collect paths`);continue}if(!e(o))continue;t.add(o)}}return t}function mN(n){return n.endsWith(".yaml")?$t.readFileSync(n,"utf8").includes("momentic/environment")?!0:(y.warn(`Skipping YAML that is not a Momentic environment: ${n}`),!1):!1}import{Argument as ii,Option as Ne}from"@commander-js/extra-typings";import{validateHeaderValue as hN}from"http";import{cpus as lv}from"os";import{parse as Upe}from"yaml";import{z as q}from"zod";var Ml=58888,Qp=30*60*1e3,jn=new Ne("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var."),gr=new Ne("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise."),fr=new Ne("-y, --yes","Skip all confirmation prompts."),eu=new Ne("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),tu=new Ne("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified. Defaults to ${Qp/1e3} seconds.`),Fl=new Ne("--custom-headers <customHeaders...>","Specify custom headers in the form HEADER=VALUE to be sent with each request during the test. Multiple entries can be provided."),nu=new Ne("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),dv=new Ne("--reporter <reporter>","Output report files in a standardized format to a local directory. See the --reporter-dir flag for information on the output directory.").choices(Object.values(Mi)),pv=new Ne("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml. Defaults to 'reports' if unset."),ru=new Ne("--output-dir <outputDir>","[Alpha] Output directory to store run artifacts such as screenshots, results, and logs. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml. This directory will be cleared at the start of execution."),uv=new Ne("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),mv=new Ne("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),ou=new Ne("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio."),hv=new Ne("--port <port>",`Port to run the app on. Defaults to ${Ml}.`),iu=new Ne("--input-csv <inputCsv>","Path to a CSV file on disk where each row represents a set of inputs that will be made available to all tests that are ran. The first line of the CSV must be the input names."),Dl=new Ne("--env <env>","Name of the environment to use when running tests."),Ul=new Ne("--url-override <urlOverride>","Fully qualified url (e.g. https://www.google.com) to start all tests from. Overrides any default starting url set from the test or environment."),gv=new Ne("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>parseInt(n,10)),Sr=new Ne("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file (*.momentic.config.yaml)"),su=new Ne("-f, --filter <filter>","Run tests within the project that has a name equal to the filter provided. This option cannot be used together with file path or directory arguments, but substring matches are allowed."),fv=new Ne("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(n=>parseInt(n,10)),Sv=new Ne("--fix","Attempt to fix any issues found. This option will write changes to your local file system."),yv=new ii("<tests...>",`One or more test paths to queue on Momentic Cloud.
3586
3586
 
@@ -3596,7 +3596,7 @@ ${n.map(d=>` - ${d}`).join(`
3596
3596
  `),n.forEach(d=>{if(!uu.existsSync(d))throw new Error(`Path '${d}' does not exist.`);let u,m;try{u=uu.statSync(d),m=u.isDirectory()}catch(g){y.warn({err:g},`Skipping path ${d} because it cannot be read`);return}let h=mu.resolve(d);Object.values(e.tests).filter(g=>m?g.fullFilePath.startsWith(h):g.fullFilePath===h).forEach(g=>{a.add(g.fullFilePath)})})):(y.info(`Reading all tests from the project and running those matching the following substring filters:
3597
3597
  ${n.map(d=>` - ${d}`).join(`
3598
3598
  `)}`),Object.values(e.tests).forEach(d=>{n.some(u=>d.relativePath.includes(u))&&a.add(d.fullFilePath)}))}else{!r&&!await lt("No test paths or substrings were provided. Do you want to run all tests?")&&(y.error("Cancelled by user."),process.exit(1));let c=Object.values(e.tests);y.info(`Reading all ${c.length} tests in the project from local disk.`),c.forEach(p=>{a.add(p.fullFilePath)})}for(let c of a){let p=mu.relative(t.rootDir,c);o&&!o.some(d=>new RegExp(d).test(p))&&a.delete(c),i&&i.some(d=>new RegExp(d).test(p))&&a.delete(c)}let l=Array.from(a).map(async c=>{try{let p=await os(c,Q,e);if(zN.gt(p.schemaVersion,He)&&y.warn(`Test ${c} has schema version ${p.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),p.disabled)return null;if(s&&s.length>0){let d=p.labels||[];if(!s.some(m=>d.includes(m)))return null}return{...p,fullFilePath:c,relativeFilePath:mu.relative(t.rootDir,c)}}catch(p){y.error(`Failed to read and resolve test at '${c}': ${p}`),process.exit(1)}});return Promise.all(l).then(UN)}import{cloneDeep as Gv}from"lodash-es";async function jv({orgId:n,codeEvalTools:e,logger:t,outputDefinitions:r,testContext:o,flagStore:i}){let s={};for(let a of r){let{name:l,value:c}=a;s[l]=await Ut({orgId:n,s:c,localTools:e,logger:t,context:o,flagStore:i})}return s}async function Hv({baseUrl:n,envName:e,devicePixelRatio:t,apiClient:r,test:o,storageClient:i,codeEvalTools:s,generator:a,orgId:l,variables:c,logger:p,customHeaders:d,testInputs:u,localBrowserConfig:m,visualDiffScreenshotStorage:h,flagStore:g}){let f=await ja({advanced:{...m,...o.advanced},customHeaders:d,envVariables:c,envName:e,baseUrl:n,logger:p,localTools:s,orgId:l,flagStore:g}),S={baseUrl:r.baseUrl,apiKey:r.apiKey,logger:Q};f.browserType==="Google Chrome"&&await eo(["chrome"]);let v=g.isBooleanFlagEnabled("icon_knowledge_base")?await i.fetchIconKnowledgeBase(l,p):null,b;try{b=await dn.init({baseUrl:n,logger:p,userBrowserSettings:f,storage:i,flagStore:g,enricher:new Br(S,a),contextArgs:{viewport:o.advanced.viewport??Dt,deviceScaleFactor:t},iconKnowledgeBase:v})}catch(E){let I=E.message;if(I.includes("Executable doesn't exist")||I.includes("install your dependencies"))y.error("The headless browser used by Momentic is not installed correctly. Re-installing the necessary dependencies before starting the test. We strongly recommend installing browsers correctly before execution."),await eo(au,!0),b=await dn.init({baseUrl:n,logger:p,userBrowserSettings:f,storage:i,flagStore:g,enricher:new Br(S,a),contextArgs:{viewport:o.advanced.viewport??Dt,deviceScaleFactor:t},iconKnowledgeBase:v});else throw E}let x=new Bo({browser:b,generator:a,logger:p,orgId:l,scratchPadId:void 0,storage:i,flagStore:g,localCodeEvalTools:s,visualDiffScreenshotStorage:h,analytics:new ni,slowMoMs:f.slowMoMs}),C=new Pt({baseUrl:n,currentUrl:x.browser.url(),variablesFromEnvironment:c,envName:e});return o.parameters&&await Promise.all(o.parameters.map(async E=>{let{name:I,defaultValue:N,required:P}=E,U=u?.[I];P&&U===void 0&&(y.error(`Required parameter '${I}' is required by test '${o.name}' but not provided`),process.exit(1));let W=await Ut({orgId:l,s:U??N,localTools:s,logger:p,context:Pt.dummyContext(C.getEnvName()),flagStore:g});C.setMomenticSystemVariable(I,W)})),{controller:x,context:C}}import{randomUUID as jN}from"crypto";async function $v({testId:n,apiClient:e,testAdvancedSettings:t,aiSettingsFromEnv:r,logger:o,noReport:i}){if(i)return o.debug("The CLI is not running in a CI environment or --no-report was explicitly passed"),!1;if(t.failureRecovery===!1||t.failureRecovery===void 0&&!r?.failureRecovery)return!1;let s;try{s=await e.getPastTestResults(n,{afterTime:Date.now()-7*24*60*60*1e3})}catch(l){return o.error({err:l},"Test is not eligible for recovery since we failed to fetch the recent test results"),!1}return s.some(l=>l.status==="PASSED")?!0:(o.debug({recentRuns:s},"Test is not eligible for recovery because there are only failures in the past 7 days"),!1)}async function Wv({attemptInputs:n,attemptFixtures:e,attemptMetadata:t}){let{attemptNumber:r,orgId:o,runId:i,runAttemptId:s}=t,{controller:a,context:l,flagStore:c,analytics:p,codeEvalTools:d,storageClient:u,debugDataStorage:m,logger:h,apiClient:g,billingReporter:f,tracer:S}=e,{test:v,orgSettings:b,noReport:x}=n;h.info(`Running test '${v.name}' locally${x?"":` and reporting results to https://app.momentic.ai/runs/${i}`}`);let C={controller:a,storage:u,debugDataStorage:m,billingReporter:f,analytics:p,context:l,logger:h,codeEvalTools:d},E={orgId:o,runId:i||jN(),runAttemptId:s,testMetadata:v,steps:v.steps,beforeSteps:v.beforeSteps,afterSteps:v.afterSteps},I={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await $v({noReport:x,currentAttempt:r,testId:v.id,flagStore:c,apiClient:g,testAdvancedSettings:v.advanced,aiSettingsFromEnv:b.ai,logger:h})};return await za({fixtures:C,inputs:E,options:I,callbacks:{step:{},test:{onTestComplete:async()=>{await a.browser.cleanup()},onProposedTestSteps:async U=>g.uploadProposedSteps(U,h)}},testParams:{tracer:S}})}async function Vv(n){let{testDefinition:e,logger:t}=n,r=new Date;try{return await HN(n)}catch(o){let i="Fatal error running test";return y.error(`${i}: ${o.message}`),t.error({err:o},i),{parameters:n,failureReason:"UnknownError",failureDetails:{errorMessage:o.message,errorStack:o.stack},status:"FAILED",attempts:0,test:e,filePath:e.relativeFilePath,startedAt:r,lastAttemptStartedAt:r,finishedAt:new Date,outputs:{}}}}async function HN(n){let{testDefinition:e,project:t,apiClient:r,orgId:o,urlOverride:i,runSigIntHandlers:s,runGroupTracer:a,logger:l}=n,c=new Ro(r,o),p=Gv(e.steps);try{await c.resolveStepCacheEntries({organizationId:o,testId:e.id,steps:p,schemaVersion:e.schemaVersion,logger:l})}catch(S){throw l.error({err:S},"Failed to resolve step cache entries"),new Error(`Failed to resolve step cache entries. Please ensure you are running using a supported version of Momentic. If you believe this is a Momentic issue, please contact Support with the following error: ${S}`)}let d=n.envName??WN(e),u,m={};if(d){try{u=is(d,t,l)}catch(S){let v=`Failed to resolve environment ${d} for test ${e.name}: ${S}`;throw new Error(v)}m=u.variables}let h=e.baseUrl;if(i)h=i;else if(!h){let S=m[Pe];typeof S=="string"&&(h=S)}if(!h){let S=`Cannot run test with no base URL and no ${Pe} variable defined in its environment`;throw new Error(S)}let g=await a.startRun({logger:l,originalSteps:{beforeSteps:e.beforeSteps,steps:e.steps,afterSteps:e.afterSteps},testId:e.id,testName:e.name,testLabels:e.labels,baseUrl:h,environmentName:d,schemaVersion:e.schemaVersion}),f=l.child(g.loggerBindings||{});Object.entries(g.envVarBindings||{}).forEach(([S,v])=>{m[S]=v});try{let S=await $N({...n,variables:m,envName:d,stepsWithCaches:p,resolvedEnv:u,baseUrl:h,storageClient:c,tracer:g,logger:f});return await g.finish({logger:l,status:S.status,finishedAt:S.finishedAt,failureDetails:S.failureDetails,failureReason:S.failureReason,isFlake:S.isFlake}),{runId:g.runId,...S}}finally{s?.pop()}}async function $N(n){let{testDefinition:e,stepsWithCaches:t,project:r,regenerateGoldenFiles:o,apiClient:i,generator:s,baseUrl:a,storageClient:l,orgId:c,envName:p,urlOverride:d,customHeaders:u,testInputs:m,variables:h,resolvedEnv:g,noReport:f,retriesOverride:S,devicePixelRatio:v,logUpdate:b,tracer:x,logger:C}=n,E=new Date,I=new ei(r,o),N={ai:r.config.ai},P={envName:p,urlOverride:d,customHeaders:u,testInputs:m},U,W=Math.abs(S??r.config.retries??e.retries??0),_=[];C.info({labels:e.labels,name:e.name},"Starting test run using CLI");for(let B=0;B<=W;B++){let L=await x.startAttempt(),j=C.child(L.loggerBindings||{}),O={...e,steps:Gv(t)};B!==0&&b("RETRY",`attempt ${B+1}/${W+1}`);let ee=new Date,me=await Lo.init(c,i),nt=new er({httpClient:new Mt({baseUrl:i.baseUrl,apiKey:i.apiKey,logger:j}),fakerSeed:me.isBooleanFlagEnabled("faker_constant_seed")?ph:void 0});try{let{controller:ue,context:Se}=await Hv({baseUrl:a,envName:p,apiClient:i,devicePixelRatio:v,logger:j,storageClient:l,codeEvalTools:nt,test:O,generator:s,orgId:c,variables:h,customHeaders:u,testInputs:m,localBrowserConfig:g?.browser??r.config.browser,visualDiffScreenshotStorage:I,flagStore:me});U=await Wv({attemptMetadata:{attemptNumber:B+1,orgId:c,runId:x.runId},attemptFixtures:{logger:j,storageClient:l,billingReporter:new xo,analytics:new ni,debugDataStorage:new Or,codeEvalTools:nt,flagStore:me,apiClient:i,context:Se,controller:ue,tracer:L},attemptInputs:{test:O,orgSettings:N,noReport:f}});let De=new Date;await L.finish({logger:j,result:U,updatedSteps:{steps:O.steps,beforeSteps:O.beforeSteps,afterSteps:O.afterSteps}}),_.unshift(U.status);let rt=await jv({orgId:c,codeEvalTools:nt,logger:j,outputDefinitions:e.outputs??[],testContext:Se,flagStore:me}),St=$m(_),Pn=B+1;if(U.status!=="FAILED")return{...U,parameters:P,test:O,filePath:O.relativeFilePath,startedAt:E,lastAttemptStartedAt:ee,finishedAt:De,attempts:Pn,baseUrl:a,outputs:rt,isFlake:St};let G=U.failedStepResult,nn=G?.message||"Unknown failure",di=G?.failureReason??vh(nn)??"UnknownError",Ue=j.child({errResult:G,failureReason:di,errorMessage:nn,numAttempts:W+1,name:O.name});if(B<W){Ue.warn(`Retrying failed execution attempt for run: ${nn}`);continue}return Ue.error(`Test failed after all exhausting attempts: ${nn}`),{...U,parameters:P,failureDetails:{errorMessage:nn},failureReason:di,test:O,filePath:O.relativeFilePath,startedAt:E,lastAttemptStartedAt:ee,finishedAt:De,attempts:B+1,baseUrl:a,outputs:rt}}catch(ue){let Se=`Encountered fatal platform error while running test '${O.name}': ${ue}`,De=new Date,rt=B+1;j.error({err:ue},Se),y.error(Se);let St={errorMessage:ue.message,errStack:ue.stack},Pn={status:"FAILED",failureDetails:St,failureReason:"InternalPlatformError",finishedAt:De};return await L.finish({logger:j,result:{status:"FAILED",results:[]}}),{...Pn,parameters:P,test:O,filePath:O.relativeFilePath,startedAt:E,lastAttemptStartedAt:ee,finishedAt:new Date,attempts:rt,baseUrl:a,outputs:{}}}}throw new Error("This code should not be reachable")}function WN(n){for(let e of n.envs??[])if(e.default)return e.name}import{diff as GN}from"deep-object-diff";async function li(n,e,t,r,o){let i=Di(o.type);if(i&&await e.reportCreditsUsed(n,o.type,i,{testId:t,testName:r}),"command"in o){let s=Ui(o.command);s&&await e.reportCreditsUsed(n,o.command.type,s,{testId:t,testName:r})}}var hu=class{constructor(e,t,r,o){this.testId=e;this.testName=t;this.billingReporter=r;this.asyncWork=o}getParentStepIdChain(){return[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}heal(){}async finish(){}async startSubSteps(){return new Vl(this.testId,this.testName,this.billingReporter,this.asyncWork)}},Vl=class{constructor(e,t,r,o){this.testId=e;this.testName=t;this.billingReporter=r;this.asyncWork=o}getParentStepIdChain(){return[]}async startStep(e){let{logger:t,step:r}=e;return this.asyncWork.push(li(t,this.billingReporter,this.testId,this.testName,r)),new hu(this.testId,this.testName,this.billingReporter,this.asyncWork)}},gu=class{constructor(e,t,r,o,i,s,a){this.orgId=e;this.testId=t;this.testName=r;this.client=o;this.billingReporter=i;this.originalSteps=s;this.asyncWork=a}trackStatus(){}attachNetworkLogs(){}attachConsoleLogs(){}async finish(e){let{logger:t,result:r,updatedSteps:o}=e;if(r?.status!=="PASSED"||!o)return;let i=GN(this.originalSteps,o);if(Object.keys(i).length!==0){t.debug({changes:i},"Updating steps post-run success in cli");try{let{cachesToSave:s}=await Xe({stepLists:o,cacheCreationParams:{testId:this.testId,orgId:this.orgId}});await this.client.updateStepCaches({testId:this.testId,entries:s})}catch(s){t.error({err:s},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async startStepList(){return new Vl(this.testId,this.testName,this.billingReporter,this.asyncWork)}},fu=class{constructor(e,t,r,o,i,s,a){this.orgId=e;this.testId=t;this.testName=r;this.client=o;this.billingReporter=i;this.originalSteps=s;this.asyncWork=a}async finish(){}trackStatus(){}async startAttempt(){return new gu(this.orgId,this.testId,this.testName,this.client,this.billingReporter,this.originalSteps,this.asyncWork)}},ql=class{constructor(e,t,r){this.orgId=e;this.client=t;this.billingReporter=r}asyncWork=[];async finish(){await Promise.allSettled(this.asyncWork)}trackStatus(){}async startRun(e){return this.asyncWork.push(this.billingReporter.reportBillableEvent(e.logger,"test-run",{testId:e.testId,testName:e.testName})),new fu(this.orgId,e.testId,e.testName,this.client,this.billingReporter,e.originalSteps,this.asyncWork)}};import{randomUUID as qv}from"crypto";import{diff as t_}from"deep-object-diff";import VN from"adm-zip";import Hn from"fs";import to from"path";var Is=class n{constructor(e){this.filePath=e;Hn.rmSync(this.filePath,{recursive:!0,force:!0}),Hn.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new n(to.join(this.filePath,e))}storeFile(e){let{name:t,contents:r}=e,o=to.join(this.filePath,t);Hn.writeFileSync(o,r)}createRunArchive(e){return new Su(to.join(this.filePath,"runs"),e)}},Su=class{constructor(e,t){this.filePath=e;this.tempPath=to.join(e,`.${t}`),this.finalPath=to.join(e,`${t}.zip`),Hn.rmSync(this.tempPath,{recursive:!0,force:!0}),Hn.rmSync(this.finalPath,{recursive:!0,force:!0}),Hn.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;cd(e){return new Is(to.join(this.tempPath,e))}storeFile(e){let{name:t,contents:r}=e,o=to.join(this.tempPath,t);Hn.writeFileSync(o,r)}close(){let e=new VN;e.addLocalFolder(this.tempPath,void 0,r=>r!==".DS_Store");let t=e.toBuffer();Hn.writeFileSync(this.finalPath,t),Hn.rmSync(this.tempPath,{recursive:!0,force:!0})}};import qN from"simple-git";var Re=qN();function Kl(n){if(n.startsWith("git@")){let e=n.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let r=t[0],o=t[1];return`${r}/${o}`}}}else if(n.startsWith("http")||n.startsWith("https")){let t=new URL(n).pathname.split("/").filter(Boolean);if(t.length>=2){let r=t[0],o=t[1].replace(".git","");return`${r}/${o}`}}}async function Ae(n){try{return(await n).trim()}catch(e){Q.error({err:e},"Failed to run git command");return}}function KN(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps"}async function YN(){let[n,e,t,r]=await Promise.all([Ae(Re.show(["--no-patch","--format=%ci"])),Ae(Re.listRemote(["--get-url","origin"])),Ae(Re.show(["-s","--pretty=%B"])),Ae(Re.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:n?new Date(n):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:`${process.env.GITHUB_RUN_ID}:${process.env.GITHUB_RUN_ATTEMPT}`}}async function JN(){let[n,e,t]=await Promise.all([Ae(Re.listRemote(["--get-url","origin"])),Ae(Re.show(["-s","--pretty=%B"])),Ae(Re.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:n,gitCommitMessage:e,gitCommitAuthorName:t,gitlabProjectPath:process.env.CI_SERVER_HOST,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function XN(){let[n,e,t,r]=await Promise.all([Ae(Re.show(["--no-patch","--format=%ci"])),Ae(Re.listRemote(["--get-url","origin"])),Ae(Re.show(["-s","--pretty=%B"])),Ae(Re.show(["-s","--pretty=%an"]))]),o=e?.includes("github.com"),i=e?.includes("gitlab.com"),s=e?Kl(e):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:n?new Date(n):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:o?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env.CIRCLE_WORKFLOW_ID}:${process.env.CIRCLE_WORKFLOW_JOB_ID}`}}async function ZN(){let[n,e,t]=await Promise.all([Ae(Re.show(["--no-patch","--format=%ci"])),Ae(Re.show(["-s","--pretty=%B"])),Ae(Re.show(["-s","--pretty=%an"]))]),r=process.env.BUILDKITE_REPO,o=r?.includes("github.com"),i=r?.includes("gitlab.com"),s=r?Kl(r):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:n?new Date(n):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:r,gitCommitMessage:e,gitCommitAuthorName:t,githubRepository:o?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function QN(){let[n,e,t]=await Promise.all([Ae(Re.show(["--no-patch","--format=%ci"])),Ae(Re.show(["-s","--pretty=%B"])),Ae(Re.show(["-s","--pretty=%an"]))]),r=process.env["Build.Repository.Uri"],o=r?.includes("github.com"),i=r?.includes("gitlab.com"),s=r?Kl(r):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:n?new Date(n):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:r,gitCommitMessage:e,gitCommitAuthorName:t,githubRepository:o?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function e_(){let[n,e,t,r,o,i,s]=await Promise.all([Ae(Re.revparse(["HEAD"])),Ae(Re.revparse(["--short","HEAD"])),Ae(Re.revparse(["--abbrev-ref","HEAD"])),Ae(Re.listRemote(["--get-url","origin"])),Ae(Re.show(["--no-patch","--format=%ci"])),Ae(Re.show(["-s","--pretty=%B"])),Ae(Re.show(["-s","--pretty=%an"]))]),a=r?.includes("github.com"),l=r?.includes("gitlab.com"),c=r?Kl(r):void 0;return{gitCommitSha:n,gitCommitShaShort:e,gitBranchName:t,gitOriginUrl:r,gitCommitTimestamp:o?new Date(o):void 0,gitCommitMessage:i,gitCommitAuthorName:s,githubRepository:a?c:void 0,gitlabProjectPath:l?c:void 0,pipelineId:void 0}}async function Yl(n){let e=KN();if(!e)return n.debug("No CI run environment detected, falling back to git"),e_();switch(n.debug(`Using CI runner environment variables from ${e} to get git metadata`),e){case"GithubActions":return YN();case"GitlabCI":return JN();case"CircleCI":return XN();case"Buildkite":return ZN();case"AzureDevOps":return QN()}}function n_(n){switch(n){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function r_(n){switch(n){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var yu=class{constructor(e,t,r,o,i,s){this.testId=e;this.testName=t;this.metadata=r;this.diskStorage=o;this.billingReporter=i;this.asyncWork=s}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:r}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:"before.jpeg",contents:r})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:r}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:"after.jpeg",contents:r})}attachBeforeHtmlSnapshot(e){let{snapshotId:t,html:r}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:"before.html",contents:r})}attachAfterHtmlSnapshot(e){let{snapshotId:t,html:r}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:"after.html",contents:r})}heal(e){let{healType:t}=e;this.metadata.healMetadata={healType:t,healedAt:new Date}}async finishInternal(e){if(this.finished)return;this.finished=!0,await Promise.all(this.children.map(r=>r.finish({status:r_(e.status),finishedAt:e.finishedAt})));let t={...this.metadata,status:e.status,finishedAt:e.finishedAt,message:e.message};this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)})}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=this.diskStorage.cd("substeps"),t=new Jl(this.testId,this.testName,e,this.billingReporter,this.asyncWork);return this.children.push(t),t}},Jl=class{constructor(e,t,r,o,i){this.testId=e;this.testName=t;this.diskStorage=r;this.billingReporter=o;this.asyncWork=i}children=[];finished=!1;getParentStepIdChain(){return[]}async startStep(e){let{logger:t,step:r}=e;this.asyncWork.push(li(t,this.billingReporter,this.testId,this.testName,r));let o=this.diskStorage.cd(r.id),i={step:r,status:"RUNNING",startedAt:new Date};o.storeFile({name:"metadata.json",contents:JSON.stringify(i,null,2)});let s=new yu(this.testId,this.testName,i,o,this.billingReporter,this.asyncWork);return this.children.push(s),s}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:n_(e.status),finishedAt:e.finishedAt}))))}},bu=class{constructor(e,t,r,o,i,s,a,l,c){this.orgId=e;this.testId=t;this.testName=r;this.originalSteps=o;this.metadata=i;this.client=s;this.diskStorage=a;this.billingReporter=l;this.asyncWork=c}finished=!1;children=[];trackStatus(){}attachNetworkLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(t,null,2)})}attachConsoleLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(t,null,2)})}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,result:r,updatedSteps:o}=e,i={...this.metadata,status:r.status,finishedAt:new Date,results:r.results,beforeResults:r.beforeResults,afterResults:r.afterResults};if(await Promise.all(this.children.map(a=>a.finish({status:i.status,finishedAt:i.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(i,null,2)}),r?.status!=="PASSED"||!o)return;let s=t_(this.originalSteps,o);if(Object.keys(s).length!==0){t.debug({changes:s},"Updating steps post-run success in cli");try{let{cachesToSave:a}=await Xe({stepLists:o,cacheCreationParams:{testId:this.testId,orgId:this.orgId}});await this.client.updateStepCaches({testId:this.testId,entries:a})}catch(a){t.error({err:a},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async startStepList(){let e=this.diskStorage.cd("steps"),t=new Jl(this.testId,this.testName,e,this.billingReporter,this.asyncWork);return this.children.push(t),t}},wu=class{constructor(e,t,r,o,i,s,a,l,c,p){this.orgId=e;this.testId=t;this.testName=r;this.internalRunId=o;this.originalSteps=i;this.metadata=s;this.client=a;this.diskStorage=l;this.billingReporter=c;this.asyncWork=p}children=[];finished=!1;get envVarBindings(){return{[Ua]:this.internalRunId}}async finish(e){if(this.finished)return;this.finished=!0;let t={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1};await Promise.all(this.children.map(r=>r.finish({logger:e.logger,result:{status:t.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}trackStatus(){}async startAttempt(){this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let e=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),t={startedAt:new Date,status:"RUNNING"};e.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)});let r=new bu(this.orgId,this.testId,this.testName,this.originalSteps,t,this.client,e,this.billingReporter,this.asyncWork);return this.children.push(r),r}},Xl=class n{constructor(e,t,r,o,i,s){this.orgId=e;this.runGroupId=t;this.metadata=r;this.client=o;this.diskStorage=i;this.billingReporter=s;this.asyncWork=[]}children=[];finished=!1;asyncWork;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start(e,t,r,o){let i=await Yl(y),s=qv(),a={...i,trigger:Lt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Ht||He},l=new Is(t);return l.storeFile({name:"metadata.json",contents:JSON.stringify(a,null,2)}),new n(e,s,a,r,l,o)}async finish(e){if(this.finished)return;this.finished=!0;let{status:t}=e,r={...this.metadata,status:t,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:r.status,finishedAt:r.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)}),await Promise.allSettled(this.asyncWork)}trackStatus(){}async startRun(e){let t=qv(),r=this.diskStorage.createRunArchive(t),o={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,labels:e.testLabels,trigger:"CLI",status:"RUNNING",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,cliVersion:Ht,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0};r.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)}),this.asyncWork.push(this.billingReporter.reportBillableEvent(e.logger,"test-run",{eventId:t,testId:e.testId,testName:e.testName}));let i=new wu(this.orgId,e.testId,e.testName,t,e.originalSteps,o,this.client,r,this.billingReporter,this.asyncWork);return this.children.push(i),i}};import{diff as o_}from"deep-object-diff";var vu=class{constructor(e,t,r,o,i,s,a,l,c,p,d,u){this.orgId=e;this.testId=t;this.testName=r;this.runId=o;this.attemptId=i;this.step=s;this.originalSteps=a;this.client=l;this.analytics=c;this.debugDataStorage=p;this.billingReporter=d;this.asyncWork=u}startedAt=new Date;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{logger:t,snapshotId:r,screenshot:o}=e;this.asyncWork.push(this.debugDataStorage.storeScreenshot(t,r,o))}attachAfterScreenshot(e){let{logger:t,snapshotId:r,screenshot:o}=e;this.asyncWork.push(this.debugDataStorage.storeScreenshot(t,r,o))}attachBeforeHtmlSnapshot(e){let{logger:t,snapshotId:r,html:o}=e;this.asyncWork.push(this.debugDataStorage.storeHtmlSnapshot(t,r,o))}attachAfterHtmlSnapshot(e){let{logger:t,snapshotId:r,html:o}=e;this.asyncWork.push(this.debugDataStorage.storeHtmlSnapshot(t,r,o))}heal(e){let{healType:t}=e;this.step.type==="PRESET_ACTION"&&this.analytics.track({type:"execution:step_heal",heal_type:t,step_type:this.step.type,command_type:this.step.command.type,duration_ms:Date.now()-this.startedAt.getTime()})}async finish(e){let{step:t}=e,r=new Date;switch(t.status){case"SUCCESS":this.analytics.track({type:"execution:step_success",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:r.getTime()-this.startedAt.getTime()});break;case"FAILED":{let o="command"in t?t.command.type:t.type;this.analytics.track({type:"execution:step_fail",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:r.getTime()-this.startedAt.getTime(),fail_reason:t.message??`${o} failed`});break}case"CANCELLED":this.analytics.track({type:"execution:step_cancel",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:r.getTime()-this.startedAt.getTime()});break;default:throw new Error(`Unexpected status: ${t.status}`)}}async startSubSteps(){return new Zl(this.orgId,this.testId,this.testName,this.runId,this.attemptId,this.originalSteps,this.client,this.analytics,this.debugDataStorage,this.billingReporter,this.asyncWork)}},Zl=class{constructor(e,t,r,o,i,s,a,l,c,p,d){this.orgId=e;this.testId=t;this.testName=r;this.runId=o;this.attemptId=i;this.originalSteps=s;this.client=a;this.analytics=l;this.debugDataStorage=c;this.billingReporter=p;this.asyncWork=d}getParentStepIdChain(){return[]}async startStep(e){let{logger:t,step:r}=e;this.asyncWork.push(li(t,this.billingReporter,this.testId,this.testName,r));let o=this.analytics.child({step_id:r.id});return o.track({type:"execution:step_start",step_type:r.type==="RESOLVED_MODULE"?"MODULE":r.type,command_type:"command"in r?r.command.type:void 0}),new vu(this.orgId,this.testId,this.testName,this.runId,this.attemptId,r,this.originalSteps,this.client,o,this.debugDataStorage,this.billingReporter,this.asyncWork)}},xu=class{constructor(e,t,r,o,i,s,a,l,c,p,d){this.orgId=e;this.testId=t;this.testName=r;this.runId=o;this.attemptId=i;this.originalSteps=s;this.client=a;this.analytics=l;this.debugDataStorage=c;this.billingReporter=p;this.asyncWork=d}get loggerBindings(){return{runAttemptId:this.attemptId}}trackStatus(){}attachNetworkLogs(e){let{logger:t,logs:r}=e;this.asyncWork.push(this.debugDataStorage.storeNetworkLogsForRunAttempt(t,this.runId,this.attemptId,r))}attachConsoleLogs(e){let{logger:t,logs:r}=e;this.asyncWork.push(this.debugDataStorage.storeConsoleLogsForRunAttempt(t,this.runId,this.attemptId,r))}async finish(e){let{logger:t,result:r,updatedSteps:o}=e;if(await this.client.updateRunAttempt(this.runId,this.attemptId,{status:r.status,finishedAt:new Date,results:r.results,beforeResults:r.beforeResults,afterResults:r.afterResults}),r?.status!=="PASSED"||!o)return;let i=o_(this.originalSteps,o);if(Object.keys(i).length!==0){t.debug({changes:i},"Updating steps post-run success in cli");try{let{cachesToSave:s}=await Xe({stepLists:o,cacheCreationParams:{testId:this.testId,orgId:this.orgId}});await this.client.updateStepCaches({testId:this.testId,entries:s})}catch(s){t.error({err:s},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async startStepList(){return new Zl(this.orgId,this.testId,this.testName,this.runId,this.attemptId,this.originalSteps,this.client,this.analytics,this.debugDataStorage,this.billingReporter,this.asyncWork)}},Tu=class{constructor(e,t,r,o,i,s,a,l,c,p){this.orgId=e;this.testId=t;this.testName=r;this.runId=o;this.originalSteps=i;this.client=s;this.analytics=a;this.debugDataStorage=l;this.billingReporter=c;this.asyncWork=p;this.startedAt=new Date}attempts=0;startedAt=new Date;get loggerBindings(){return{runId:this.runId}}get envVarBindings(){return{[Ua]:this.runId}}async finish(e){let t=e.finishedAt||new Date,r=t.getTime()-this.startedAt.getTime();switch(e.status){case"PASSED":this.analytics.track({type:"execution:test_success",attempt_count:this.attempts,duration_ms:r,is_flake:e.isFlake||!1});break;case"CANCELLED":this.analytics.track({type:"execution:test_cancel",duration_ms:r,attempt_count:this.attempts});break;case"FAILED":this.analytics.track({type:"execution:test_fail",attempt_count:this.attempts,duration_ms:r,fail_reason:e.failureDetails?.errorMessage??"unknown"});break}await this.client.updateRun(this.runId,{status:e.status,finishedAt:t,flake:e.isFlake,failureDetails:e.failureDetails,failureReason:e.failureReason})}trackStatus(){}async startAttempt(){this.attempts++,await this.client.updateRun(this.runId,{status:"RUNNING",attempts:this.attempts});let{id:e}=await this.client.createRunAttempt(this.runId);return new xu(this.orgId,this.testId,this.testName,this.runId,e,this.originalSteps,this.client,this.analytics,this.debugDataStorage,this.billingReporter,this.asyncWork)}},Ql=class n{constructor(e,t,r,o,i,s,a,l){this.orgId=e;this.runGroupId=t;this.gitMetadata=r;this.client=o;this.analytics=i;this.debugDataStorage=s;this.billingReporter=a;this.startedAt=l;this.asyncWork=[]}asyncWork;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.gitMetadata.gitBranchName}}static async start(e,t,r,o,i){let s=await Yl(y),a=new Date,{id:l}=await t.createRunGroup({...s,trigger:Lt.CLI,startedAt:a,status:"RUNNING",cliVersion:Ht}),c=r.child({commit_sha:s?.gitCommitSha,commit_sha_short:s?.gitCommitShaShort,branch_name:s?.gitBranchName,origin_url:s?.gitOriginUrl,commit_timestamp:s?.gitCommitTimestamp,github_repository:s?.githubRepository,gitlab_project_path:s?.gitlabProjectPath,pipeline_id:s?.pipelineId,run_group_id:l});return new n(e,l,s,t,c,o,i,a)}async finish(e){let{status:t}=e,r=new Date;await this.client.updateRunGroup(this.runGroupId,{status:t,finishedAt:r});let o=r.getTime()-this.startedAt.getTime();switch(t){case"PASSED":this.analytics.track({type:"execution:run_group_success",duration_ms:o});break;case"FAILED":this.analytics.track({type:"execution:run_group_fail",duration_ms:o});break;case"CANCELLED":this.analytics.track({type:"execution:run_group_cancel",duration_ms:o});break}await Promise.allSettled(this.asyncWork)}trackStatus(){}async startRun(e){let{id:t}=await this.client.createRun({stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,labels:e.testLabels,trigger:"CLI",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,cliVersion:Ht,schemaVersion:e.schemaVersion}),r=this.analytics.child({run_id:t,test_id:e.testId,test_name:e.testName,label_names:e.testLabels});return this.asyncWork.push(this.billingReporter.reportBillableEvent(e.logger,"test-run",{eventId:t,testId:e.testId,testName:e.testName})),r.track({type:"execution:test_start"}),new Tu(this.orgId,e.testId,e.testName,t,e.originalSteps,this.client,r,this.debugDataStorage,this.billingReporter,this.asyncWork)}};async function Kv(n){let{logger:e,tests:t,yes:r,start:o,waitOn:i,client:s,debugDataStorage:a,billingReporter:l,analytics:c,project:p,report:d,retriesOverride:u,urlOverride:m,envName:h,orgId:g,devicePixelRatio:f,customHeaders:S,testInputMatrix:v,reporter:b,include:x,exclude:C,labels:E,reporterDir:I="reports",outputDir:N,waitOnTimeout:P=60,parallel:U=p.config.parallel??1,shardIndex:W=1,shardCount:_=1,regenerateGoldenFiles:B}=n;o&&(e.info({orgId:g},`Executing start command: ${o}`),await Gw(o,!1)),i&&(e.info({orgId:g},`Waiting for url: ${i} with timeout: ${P} seconds.`),await s_({resources:[i],interval:2500,timeout:P*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let L=new Io({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:e}),j=ke(p,y),O=await zv({tests:t,momenticFiles:j,yes:r,project:p,include:x,exclude:C,labels:E}),ee=[];O.forEach((Ue,Wn)=>{v?v.forEach((ro,yt)=>{ee.push({testIndex:Wn,inputs:ro,inputIndex:yt})}):ee.push({testIndex:Wn,inputs:void 0,inputIndex:void 0})}),_&&_>1&&(ee=a_(ee,W,_));let me=`Running ${ee.length} tests with ${U} workers`;e.info({allTestsToRunWithInputs:ee,shardCount:_,shardIndex:W,orgId:g},me),y.dimmed(me),ee.forEach(Ue=>{y.dimmed(` - ${[O[Ue.testIndex].relativeFilePath]}${typeof Ue.inputIndex=="number"?` with input set ${Ue.inputIndex}`:""}`)}),y.log("");let nt=[],ue=new Date,Se=new Set,De=()=>{let Ue=s.getAppUrl(),Wn=si({results:nt,startTime:ue.getTime(),onFailed:yt=>{$l(yt,yt.filePath)},getDisplayLine:yt=>{let yr=` - ${yt.filePath}${yt.proposedTest?" [AUTO-HEALED] ":""}`;return d&&yt.runId&&(yr+=` (${Ue}/runs/${yt.runId})`),yr},entity:"test"}),ro=nt.filter(yt=>!!yt.proposedTest);return ro.length>0&&y.warn(`${ro.length} tests passed with auto-healing. Please use the run links printed above to review proposed changes and apply them locally.`),Wn},rt=new ql(g,s,l);N?rt=await Xl.start(g,N,s,l):d&&(rt=await Ql.start(g,s,c,a,l));let St=e.child(rt.loggerBindings||{}),Pn=[],G=async()=>{y.warn("SIGINT received. Stopping tests and printing latest results..."),await rt.finish({logger:St,status:"CANCELLED"}),De(),await Promise.allSettled(Pn.map(Ue=>Ue())),process.exit(1)};process.on("SIGINT",G);let nn={};for(let Ue=0;Ue<ee.length;Ue++){let Wn=Object.values(nn);Wn.length===U&&await Promise.race(Wn.map(yr=>yr.promise));let ro=ee[Ue],yt=`test-${Ue}`;nn[yt]={done:!1,promise:(async({testIndex:yr,inputs:Ru})=>{let pi=O[yr];Se.add({testIndex:yr,inputs:Ru});let ox=pi.relativeFilePath.includes("..")?pi.fullFilePath:pi.relativeFilePath,Ps=(ct,ui)=>{let oo=(nc,Au)=>{let sx=Math.floor((Au-nc.length)/2);return nc.padStart(sx+nc.length).padEnd(Au)};ct=ct.toUpperCase();let Ln=ct;ct.includes("FAIL")?Ln=ci.bgRed.white(oo("FAIL",8)):ct.includes("PASS")?Ln=ci.bgGreen.white(oo("PASS",8)):ct.includes("START")?Ln=ci.bgBlue.white(oo("START",8)):ct.includes("CANCEL")?Ln=ci.bgYellow.white(oo("CANCEL",8)):ct.includes("RETRY")?Ln=ci.bgYellow.white(oo("RETRY",8)):ct.includes("RUN")||ct.includes("PROG")?Ln=ci.bgMagenta.white(oo("RUNNING",8)):St.warn(`Unknown status tried to be logged in run test locally: ${ct}`),i_||(Ln=`[${Ln}]`),y.log(`${Ln} ${ox} ${ui?`${ui} `:""}(${Se.size}/${ee.length})`)};Ps("START");let ix=setInterval(()=>Ps("RUN"),5*60*1e3);try{let ct=await Vv({testDefinition:pi,project:p,testInputs:Ru,orgId:g,devicePixelRatio:f,apiClient:s,runGroupTracer:rt,generator:L,retriesOverride:u,urlOverride:m,envName:h,noReport:!d,customHeaders:S,regenerateGoldenFiles:B,logUpdate:Ps,runSigIntHandlers:d?Pn:void 0,logger:St});Ps(ct.status),nt.push(ct)}catch(ct){let ui=`Encountered unexpected fatal error when running test '${pi.name}': ${ct.message}`;y.error(ui),St.error(ui)}finally{clearInterval(ix),nn[yt].done=!0,delete nn[yt]}})(ro)}}await Promise.allSettled(Object.values(nn).map(Ue=>Ue.promise));let di="PASSED";return nt.some(Ue=>Ue.status==="FAILED")&&(di="FAILED"),await rt.finish({logger:St,status:di}),process.off("SIGINT",G),b&&await Bv(St,a,b,{projectConfigPath:p.configFilePath,suiteName:p.config.name,startedAt:ue,finishedAt:new Date,runs:nt},I??"reports"),De()}function a_(n,e,t){if(t>n.length&&(y.warn(`Shard count ${t} is greater than the number of tests ${n.length}! Some workers won't have any tests to run.`),t=Math.max(t,n.length),e>t))return[];let r=Math.floor((e-1)*(n.length/t)),o=Math.floor(e*(n.length/t));return n.sort().filter((s,a)=>a>=r&&a<o)}import $n from"fs";import no from"path";var Yv={status:(n,e)=>{if(n===e)return n;if(n==="PASSED"&&e==="PASSED")return"PASSED";if(n==="FAILED"||e==="FAILED")return"FAILED";if(n==="CANCELLED"||e==="CANCELLED")return"PASSED";throw new Error("Invalid run status merge")},startedAt:(n,e)=>{if(!n||!e)throw new Error("Invalid start time merge");return n<e?n:e},updatedAt:(n,e)=>{if(!n||!e)throw new Error("Invalid update time merge");return n>e?n:e},finishedAt:(n,e)=>{if(!n||!e)throw new Error("Invalid finish time merge");return n>e?n:e},gitCommitTimestamp:(n,e)=>{if(!(!n&&!e)){if(!n||!e||n.getTime()!==e.getTime())throw new Error("Git commit timestamps must match to be merged");return n}}};function Jv(n,e){let t=n[e];if(!t)throw new Error(`No metadata value found for key: ${e}`);return t}function l_(n,e,t){let r=Jv(n,t),o=Jv(e,t);if(t in Yv){let i=Yv[t];return i(r,o)}if(r!==o)throw new Error(`Metadata values for key "${t}" do not match: "${r}" vs "${o}"`);return r}function Xv(n,e){$n.rmSync(n,{recursive:!0,force:!0});let t=$n.readdirSync(e).filter(s=>s!==".DS_Store").map(s=>no.join(e,s));$n.mkdirSync(n,{recursive:!0});let r=no.join(t[0],"metadata.json"),o=id.parse(JSON.parse($n.readFileSync(r,"utf-8")));for(let s of t){let a=no.join(s,"runs");if(!$n.existsSync(a))continue;let l=$n.readdirSync(a);for(let d of l){let u=no.join(a,d),m=no.join(n,"runs",d);$n.cpSync(u,m,{recursive:!0})}let c=no.join(s,"metadata.json"),p=id.parse(JSON.parse($n.readFileSync(c,"utf-8")));for(let d in p){let u=d;o[u]=l_(o,p,u)}}let i=no.join(n,"metadata.json");$n.writeFileSync(i,JSON.stringify(o,null,2))}import Zv from"adm-zip";import c_ from"fs";import ec from"path";function Qv(n){let e=new Zv;e.addLocalFile(ec.join(n,"metadata.json"));for(let t of c_.readdirSync(ec.join(n,"runs"))){if(!t.endsWith(".zip"))continue;let r=t.replace(/\.zip$/,""),o=new Zv(ec.join(n,"runs",t));for(let i of o.getEntries())i.isDirectory||e.addFile(ec.join("runs",r,i.entryName),i.getData())}return e.toBuffer()}var ex=new ri({platform:"cli"},{flushAt:1,flushInterval:0});oc||Q.warn("Sentry is not enabled in this environment due to unsupported node version");var g_=process.argv.some(n=>n.includes("--log-level"))&&process.argv.some(n=>n.includes("debug")),Eu=n=>{g_&&y.dimmed(n)},Et=new d_;Et.name("momentic").description("CLI").version(Ht||"unknown");Et.command("install-browsers").option("-f, --force","Force reinstallation even if the browser executables already exist on disk.").argument("[browsers...]","Browsers to install",["chromium"]).action(async(n,e)=>{await eo(Rv(n),e.force)});Et.addOption(new tn("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",n=>{n==="debug"&&y.info("Enabling debug logging"),y.setMinLevel(n.toLowerCase())});Et.addOption(new tn("--verbose","enable verbose logging")).on("option:verbose",()=>{Q.enableConsoleLogs(),y.setMinLevel(0)});Et.command("check-config").addOption(Sr).action(async n=>{gn({configFilePath:n.config})});var tx=Et.command("checks").alias("check").description("Perform various project checks");tx.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(Sr).addOption(Sv).action(async n=>{let e=await fn(n),t=gn({configFilePath:n.config});await Qw({project:t,fix:e.fix})});tx.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(Sr).action(async n=>{let e=gn({configFilePath:n.config});await ev({project:e})});var f_=Et.command("migrate").description("Migrate and upgrade tooling");f_.command("v0-v1").addOption(fr).addOption(jn).action(async n=>{let e=await fn(n);if(!e.yes&&!await lt("This command will migrate and then delete your previous Momentic files. All members of your team should transition to the V1 CLI at the same time. Please backup your local directory for safety before proceeding. Continue?",!0)&&process.exit(1),!sv().environments?.length&&await lt("In the V1 CLI, all environment configuration should be committed to a central `momentic.config.yaml` file, which you should commit to your source control repository. Sensitive data can be managed through `.env` files or by injecting the secret into the environment and then referencing them in `envVariables` with ${VAR} syntax. Would you like to pull the latest environments from Momentic Cloud into your `momentic.config.yaml` file?",!0)){let{apiKey:r,server:o}=e,i=gn({}),s=new st({baseUrl:o,apiKey:r,logger:Q});await _l({client:s,project:i,skipPrompts:e.yes}),y.success("Successfully imported environments from Momentic Cloud.")}});Et.command("import-from-cloud").addOption(jn).addOption(gr).addOption(Sr).addOption(fr).action(async n=>{let e=await fn(n),{apiKey:t,server:r,config:o,yes:i}=e,s=gn({configFilePath:o}),a=new st({baseUrl:r,apiKey:t,logger:Q});await iv({client:a,project:s,skipPrompts:i}),process.exit(0)});Et.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new tn("--name <name>","Name of the project")).action(async n=>{y.info(`Welcome to the Momentic project setup wizard! \u{1F680}
3599
- `),y.info("This wizard will help you bootstrap a new Momentic project. If you need to import existing assets from Momentic Cloud, you can call the 'import-from-cloud' command after initialization."),Cu.existsSync(Xo)&&(y.error("A momentic.config.yaml file already exists in this directory. Please rename or remove it to initialize a new project."),process.exit(1));let t={name:n.name??await Jw("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:xs};Zo(t,Xo),y.success(`Initialized Momentic project file at ${tc.resolve(Xo)}`)});Et.command("app").addOption(jn).addOption(gr).addOption(fr).addOption(ou).addOption(hv).addOption(Sr).action(async n=>{let e=await fn(n),{apiKey:t,port:r=Ml,yes:o,server:i,pixelRatio:s}=e,a=new st({baseUrl:i,apiKey:t,logger:Q});await lu({client:a,skipPrompts:o,installBrowsers:!0});let l=h_(import.meta.url),c=tc.dirname(l),p=tc.resolve(c,"..","static"),d=tc.resolve(c,"..","assets"),u=s??Kp();Yp(u),mi(),await Hw({momenticServerUrl:i,apiKey:t,serverPort:r,appPort:r,staticDir:p,assetsDir:d,devicePixelRatio:u,version:"1.1.10"});let m=`http://localhost:${r}`;await m_(m)});var nx=Et.command("queue").description("Queue tests or suites to run on Momentic Cloud");nx.command("suites").description("Run one or more suites on Momentic Cloud").addOption(jn).addOption(gr).addOption(eu).addOption(tu).addOption(fr).addArgument(wv).addOption(Ul).addOption(Dl).addOption(Fl).action(async(n,e)=>{let{apiKey:t,server:r,wait:o,waitTimeout:i,env:s,urlOverride:a,customHeaders:l}=await fn(e),c=new st({baseUrl:r,apiKey:t,logger:Q});(!n||!Array.isArray(n)||!n.length)&&(y.error("Must pass at least one suite to run."),process.exit(1));let{orgId:p}=await c.getAuthInfo();await Ov({client:c,orgId:p,wait:o,suitePaths:n,waitTimeout:i,env:s,urlOverride:a,customHeaders:Bl(l)})});nx.command("tests").description("Run one or more tests on Momentic Cloud").addOption(jn).addOption(gr).addOption(fr).addOption(Fl).addOption(iu).addOption(Ul).addOption(Dl).addOption(eu).addOption(tu).addArgument(yv).action(async(n,e)=>{let t=await fn(e),{all:r,apiKey:o,customHeaders:i,env:s,server:a,inputCsv:l,urlOverride:c,wait:p,waitTimeout:d,yes:u}=t,m=Bl(i);for(let S of n)(S.endsWith(".yaml")||Cu.existsSync(S))&&y.warn("Are you trying to run a test on your local machine? If so, please use the 'run' command instead of the 'queue' command");let h=new st({baseUrl:a,apiKey:o,logger:Q}),{orgId:g}=await h.getAuthInfo(),f;l&&(f=await Jp(l)),await kv({client:h,orgId:g,tests:n,all:r,customHeaders:m,env:s,urlOverride:c,wait:p,waitTimeout:d,testInputMatrix:f,yes:u}),process.exit(0)});var S_=Et.command("run").alias("test").description("Run tests on the local machine");S_.addOption(jn).addOption(gr).addOption(Sr).addOption(su).addOption(fr).addOption(Fl).addOption(iu).addOption(Dl).addOption(Ul).addOption(nu).addOption(ou).addOption(new tn("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new tn("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new tn("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.")).addOption(new tn("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.")).addOption(new tn("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.")).addOption(new tn("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new tn("--update-golden-files","Update locally stored golden files for steps that this is enabled for.")).addOption(nu).addOption(dv).addOption(pv).addOption(ru).addOption(gv).addOption(fv).addOption(uv).addOption(mv).addArgument(bv).action(async(n,e)=>{y.debug("Run tests invoked");let t=await fn(e);y.debug(t,"Parsed CLI options");let r=Bl(t.customHeaders),o=gn({configFilePath:t.config,nameFilter:t.filter});y.debug({projectName:o.config.name},"Identified project config");let i=new st({baseUrl:t.server,apiKey:t.apiKey,logger:Q});y.debug("Checking API key and dependencies");let{orgId:s,userId:a}=await lu({client:i,skipPrompts:t.yes,installBrowsers:!0});y.debug("API key check and browser installation complete");let l=new va(i),c=new xa(i),p=t.outputDir??o.config.outputDir,d=ex.child({org_id:s,user_id:a,cli_version:Ht,trigger:"CLI"}),u;t.inputCsv&&(u=await Jp(t.inputCsv));let m=t.pixelRatio??Kp();Yp(m);let h=Q.child({orgId:s,userId:a,cliVersion:Ht,trigger:"CLI"});try{(await Kv({...t,retriesOverride:t.retries,devicePixelRatio:m,tests:n,project:o,client:i,debugDataStorage:c,billingReporter:l,analytics:d,outputDir:p,customHeaders:r,envName:t.env,orgId:s,testInputMatrix:u,logger:h,regenerateGoldenFiles:t.updateGoldenFiles})).failed>0?process.exit(1):process.exit(0)}catch(g){y.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),y.error(g),process.exit(1)}});var y_=Et.command("apply").description("Apply an operation to local resources");y_.command("patch").addOption(jn).addOption(gr).addOption(Sr).addOption(su).addOption(fr).addOption(new tn("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new tn("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async n=>{let e=await fn(n),{apiKey:t,server:r,config:o,yes:i}=e,s=gn({configFilePath:o}),a=new st({baseUrl:r,apiKey:t,logger:Q}),l=ke(s,y),c=l.tests[n.to]??Object.values(l.tests).find(d=>Le(d.name)===n.to.trim());c||(y.error(`No test matching '${n.to}' could be found in the current project.`),process.exit(1));let p=await a.fetchTestFragment(n.from);await Xw({client:a,test:c,fragment:p,yes:i,entities:l,logger:Q}),process.exit(0)});var rx=Et.command("results").description("Merge and upload test results.");rx.command("merge").description("Merge test results files.").addOption(ru).addArgument(vv).action(async(n,e)=>{let t=await fn(e),{outputDir:r}=t;r||(y.error("Output directory is required."),process.exit(1)),Xv(r,n)});rx.command("upload").description("Upload test results to Momentic cloud.").addOption(jn).addOption(gr).addArgument(xv).action(async(n,e)=>{let t=await fn(e),{apiKey:r,server:o}=t,i=new st({baseUrl:o,apiKey:r,logger:Q}),s=new Oa(i);try{let a=Qv(n);Cu.writeFileSync("test.zip",a);let l=await s.uploadResultsArchive(a),c=`${i.getAppUrl()}/run-groups/${l}`;y.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`),process.exit(0)}catch(a){let l;a instanceof Error?l=a.message:typeof a=="string"?l=a:l="Unknown error",y.error(`Failed to upload test results: ${l}.`),process.exit(1)}});async function b_(){Eu("Main program started"),await Vw(Q),Eu("CLI version check complete");try{await Et.parseAsync(process.argv),mi()}catch(n){let e={};try{e.playwrightVersion=p_("npx playwright --version").toString()}catch(t){Q.error({err:t},"Error fetching debug information")}Q.error({err:n,debugInfo:e},"Uncaught error in CLI"),Q.flush(),rc(n,e),y.error(n),mi(),process.exit(1)}}u_.setMaxListeners(50);process.on("warning",n=>{Q.warn({err:n},`Node warning received on CLI: ${n.message}`)});Eu("CLI parsing setup complete");b_();
3599
+ `),y.info("This wizard will help you bootstrap a new Momentic project. If you need to import existing assets from Momentic Cloud, you can call the 'import-from-cloud' command after initialization."),Cu.existsSync(Xo)&&(y.error("A momentic.config.yaml file already exists in this directory. Please rename or remove it to initialize a new project."),process.exit(1));let t={name:n.name??await Jw("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:xs};Zo(t,Xo),y.success(`Initialized Momentic project file at ${tc.resolve(Xo)}`)});Et.command("app").addOption(jn).addOption(gr).addOption(fr).addOption(ou).addOption(hv).addOption(Sr).action(async n=>{let e=await fn(n),{apiKey:t,port:r=Ml,yes:o,server:i,pixelRatio:s}=e,a=new st({baseUrl:i,apiKey:t,logger:Q});await lu({client:a,skipPrompts:o,installBrowsers:!0});let l=h_(import.meta.url),c=tc.dirname(l),p=tc.resolve(c,"..","static"),d=tc.resolve(c,"..","assets"),u=s??Kp();Yp(u),mi(),await Hw({momenticServerUrl:i,apiKey:t,serverPort:r,appPort:r,staticDir:p,assetsDir:d,devicePixelRatio:u,version:"1.1.11"});let m=`http://localhost:${r}`;await m_(m)});var nx=Et.command("queue").description("Queue tests or suites to run on Momentic Cloud");nx.command("suites").description("Run one or more suites on Momentic Cloud").addOption(jn).addOption(gr).addOption(eu).addOption(tu).addOption(fr).addArgument(wv).addOption(Ul).addOption(Dl).addOption(Fl).action(async(n,e)=>{let{apiKey:t,server:r,wait:o,waitTimeout:i,env:s,urlOverride:a,customHeaders:l}=await fn(e),c=new st({baseUrl:r,apiKey:t,logger:Q});(!n||!Array.isArray(n)||!n.length)&&(y.error("Must pass at least one suite to run."),process.exit(1));let{orgId:p}=await c.getAuthInfo();await Ov({client:c,orgId:p,wait:o,suitePaths:n,waitTimeout:i,env:s,urlOverride:a,customHeaders:Bl(l)})});nx.command("tests").description("Run one or more tests on Momentic Cloud").addOption(jn).addOption(gr).addOption(fr).addOption(Fl).addOption(iu).addOption(Ul).addOption(Dl).addOption(eu).addOption(tu).addArgument(yv).action(async(n,e)=>{let t=await fn(e),{all:r,apiKey:o,customHeaders:i,env:s,server:a,inputCsv:l,urlOverride:c,wait:p,waitTimeout:d,yes:u}=t,m=Bl(i);for(let S of n)(S.endsWith(".yaml")||Cu.existsSync(S))&&y.warn("Are you trying to run a test on your local machine? If so, please use the 'run' command instead of the 'queue' command");let h=new st({baseUrl:a,apiKey:o,logger:Q}),{orgId:g}=await h.getAuthInfo(),f;l&&(f=await Jp(l)),await kv({client:h,orgId:g,tests:n,all:r,customHeaders:m,env:s,urlOverride:c,wait:p,waitTimeout:d,testInputMatrix:f,yes:u}),process.exit(0)});var S_=Et.command("run").alias("test").description("Run tests on the local machine");S_.addOption(jn).addOption(gr).addOption(Sr).addOption(su).addOption(fr).addOption(Fl).addOption(iu).addOption(Dl).addOption(Ul).addOption(nu).addOption(ou).addOption(new tn("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new tn("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new tn("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.")).addOption(new tn("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.")).addOption(new tn("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.")).addOption(new tn("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new tn("--update-golden-files","Update locally stored golden files for steps that this is enabled for.")).addOption(nu).addOption(dv).addOption(pv).addOption(ru).addOption(gv).addOption(fv).addOption(uv).addOption(mv).addArgument(bv).action(async(n,e)=>{y.debug("Run tests invoked");let t=await fn(e);y.debug(t,"Parsed CLI options");let r=Bl(t.customHeaders),o=gn({configFilePath:t.config,nameFilter:t.filter});y.debug({projectName:o.config.name},"Identified project config");let i=new st({baseUrl:t.server,apiKey:t.apiKey,logger:Q});y.debug("Checking API key and dependencies");let{orgId:s,userId:a}=await lu({client:i,skipPrompts:t.yes,installBrowsers:!0});y.debug("API key check and browser installation complete");let l=new va(i),c=new xa(i),p=t.outputDir??o.config.outputDir,d=ex.child({org_id:s,user_id:a,cli_version:Ht,trigger:"CLI"}),u;t.inputCsv&&(u=await Jp(t.inputCsv));let m=t.pixelRatio??Kp();Yp(m);let h=Q.child({orgId:s,userId:a,cliVersion:Ht,trigger:"CLI"});try{(await Kv({...t,retriesOverride:t.retries,devicePixelRatio:m,tests:n,project:o,client:i,debugDataStorage:c,billingReporter:l,analytics:d,outputDir:p,customHeaders:r,envName:t.env,orgId:s,testInputMatrix:u,logger:h,regenerateGoldenFiles:t.updateGoldenFiles})).failed>0?process.exit(1):process.exit(0)}catch(g){y.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),y.error(g),process.exit(1)}});var y_=Et.command("apply").description("Apply an operation to local resources");y_.command("patch").addOption(jn).addOption(gr).addOption(Sr).addOption(su).addOption(fr).addOption(new tn("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new tn("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async n=>{let e=await fn(n),{apiKey:t,server:r,config:o,yes:i}=e,s=gn({configFilePath:o}),a=new st({baseUrl:r,apiKey:t,logger:Q}),l=ke(s,y),c=l.tests[n.to]??Object.values(l.tests).find(d=>Le(d.name)===n.to.trim());c||(y.error(`No test matching '${n.to}' could be found in the current project.`),process.exit(1));let p=await a.fetchTestFragment(n.from);await Xw({client:a,test:c,fragment:p,yes:i,entities:l,logger:Q}),process.exit(0)});var rx=Et.command("results").description("Merge and upload test results.");rx.command("merge").description("Merge test results files.").addOption(ru).addArgument(vv).action(async(n,e)=>{let t=await fn(e),{outputDir:r}=t;r||(y.error("Output directory is required."),process.exit(1)),Xv(r,n)});rx.command("upload").description("Upload test results to Momentic cloud.").addOption(jn).addOption(gr).addArgument(xv).action(async(n,e)=>{let t=await fn(e),{apiKey:r,server:o}=t,i=new st({baseUrl:o,apiKey:r,logger:Q}),s=new Oa(i);try{let a=Qv(n);Cu.writeFileSync("test.zip",a);let l=await s.uploadResultsArchive(a),c=`${i.getAppUrl()}/run-groups/${l}`;y.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`),process.exit(0)}catch(a){let l;a instanceof Error?l=a.message:typeof a=="string"?l=a:l="Unknown error",y.error(`Failed to upload test results: ${l}.`),process.exit(1)}});async function b_(){Eu("Main program started"),await Vw(Q),Eu("CLI version check complete");try{await Et.parseAsync(process.argv),mi()}catch(n){let e={};try{e.playwrightVersion=p_("npx playwright --version").toString()}catch(t){Q.error({err:t},"Error fetching debug information")}Q.error({err:n,debugInfo:e},"Uncaught error in CLI"),Q.flush(),rc(n,e),y.error(n),mi(),process.exit(1)}}u_.setMaxListeners(50);process.on("warning",n=>{Q.warn({err:n},`Node warning received on CLI: ${n.message}`)});Eu("CLI parsing setup complete");b_();
3600
3600
  /*! Bundled license information:
3601
3601
 
3602
3602
  is-buffer/index.js:
@@ -3608,4 +3608,4 @@ is-buffer/index.js:
3608
3608
  *)
3609
3609
  */
3610
3610
  //# sourceMappingURL=cli.js.map
3611
- //# debugId=b9a19da0-3de9-5151-a7c3-c7bbfbbf1a85
3611
+ //# debugId=f34cad2a-8e48-5044-a601-5f7a2dec8aab