momentic 1.1.3 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/cli.js +5 -5
  2. package/package.json +1 -1
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]="db115a00-082c-55ef-b6e5-7fbf05267b88")}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]="13012ffc-d6dc-5b22-8381-06f1a7d8b176")}catch(e){}}();
4
4
  var sx=Object.create;var Iu=Object.defineProperty;var ax=Object.getOwnPropertyDescriptor;var lx=Object.getOwnPropertyNames;var cx=Object.getPrototypeOf,dx=Object.prototype.hasOwnProperty;var nn=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var px=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of lx(e))!dx.call(n,o)&&o!==t&&Iu(n,o,{get:()=>e[o],enumerable:!(r=ax(e,o))||r.enumerable});return n};var Pu=(n,e,t)=>(t=n!=null?sx(cx(n)):{},px(e||!n||!n.__esModule?Iu(t,"default",{value:n,enumerable:!0}):t,n));var ly=nn((Ja,$d)=>{"use strict";(function(n){typeof define=="function"&&define.amd?define([],n):typeof Ja=="object"?(Ja=n(),typeof $d=="object"&&($d.exports=Ja)):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}),x=f._extend(s,{},S);x._instanceClass=l,l._members=new x}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 dy=nn((A7,cy)=>{"use strict";var pP=ly(),$r=pP._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 $r(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 $r(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 $r(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($r.prototype,"all",{get:function(){return this._list}});Object.defineProperty($r.prototype,"map",{get:function(){return this._map}});cy.exports=$r;typeof window<"u"&&(window.HashArray=$r)});var uy=nn((I7,py)=>{"use strict";py.exports=dy()});var hy=nn((P7,my)=>{"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}};my.exports=e})()});var Gd=nn((L7,gy)=>{"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("")}}};gy.exports=Wd});var yy=nn((O7,Sy)=>{"use strict";Sy.exports=function(n){return n!=null&&(fy(n)||uP(n)||!!n._isBuffer)};function fy(n){return!!n.constructor&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}function uP(n){return typeof n.readFloatLE=="function"&&typeof n.slice=="function"&&fy(n.slice(0,0))}});var wy=nn((k7,by)=>{"use strict";(function(){var n=hy(),e=Gd().utf8,t=yy(),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 x=c,b=p,w=d,E=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+x>>>0,p=p+b>>>0,d=d+w>>>0,u=u+E>>>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,by.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 xy=nn((N7,Kd)=>{"use strict";var Vd=uy(),mP=wy(),hP=1024,vy=/^[\s]*$/,gP=[{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 Ji=function(n,e){this.options=e||{},this.options.ignoreCase=this.options.ignoreCase===void 0?!0:this.options.ignoreCase,this.options.maxCacheSize=this.options.maxCacheSize||hP,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||gP,this.options.insertFullUnsplitKey=this.options.hasOwnProperty("insertFullUnsplitKey")?this.options.insertFullUnsplitKey:!1,this.options.defaultReducer=this.options.hasOwnProperty("defaultReducer")?this.options.defaultReducer:Ji.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))}Ji.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 vy.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++)vy.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 mP(t)}return typeof this.options.idFieldOrFunction=="function"?this.options.idFieldOrFunction(n):n[this.options.idFieldOrFunction]}};Ji.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=Ji;Kd.exports.default=Ji});var Ey=nn((_7,Ty)=>{"use strict";Ty.exports=xy()});var Sb=nn((fie,fb)=>{"use strict";fb.exports=hb;function hb(n,e,t){n instanceof RegExp&&(n=mb(n,t)),e instanceof RegExp&&(e=mb(e,t));var r=gb(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 mb(n,e){var t=e.match(n);return t?t[0]:null}hb.range=gb;function gb(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 Cb=nn((Sie,Eb)=>{"use strict";var yb=Sb();Eb.exports=kL;var bb="\0SLASH"+Math.random()+"\0",wb="\0OPEN"+Math.random()+"\0",mp="\0CLOSE"+Math.random()+"\0",vb="\0COMMA"+Math.random()+"\0",xb="\0PERIOD"+Math.random()+"\0";function up(n){return parseInt(n,10)==n?parseInt(n,10):n.charCodeAt(0)}function LL(n){return n.split("\\\\").join(bb).split("\\{").join(wb).split("\\}").join(mp).split("\\,").join(vb).split("\\.").join(xb)}function OL(n){return n.split(bb).join("\\").split(wb).join("{").split(mp).join("}").split(vb).join(",").split(xb).join(".")}function Tb(n){if(!n)return[""];var e=[],t=yb("{","}",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=Tb(i);return i.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),e.push.apply(e,s),e}function kL(n){return n?(n.substr(0,2)==="{}"&&(n="\\{\\}"+n.substr(2)),os(LL(n),!0).map(OL)):[]}function NL(n){return"{"+n+"}"}function _L(n){return/^-?0\d/.test(n)}function ML(n,e){return n<=e}function FL(n,e){return n>=e}function os(n,e){var t=[],r=yb("{","}",n);if(!r)return[n];var o=r.pre,i=r.post.length?os(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,os(n)):[n];var u;if(p)u=r.body.split(/\.\./);else if(u=Tb(r.body),u.length===1&&(u=os(u[0],!1).map(NL),u.length===1))return i.map(function(D){return r.pre+u[0]+D});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,x=ML,b=g<h;b&&(S*=-1,x=FL);var w=u.some(_L);m=[];for(var E=h;x(E,g);E+=S){var C;if(c)C=String.fromCharCode(E),C==="\\"&&(C="");else if(C=String(E),w){var I=f-C.length;if(I>0){var N=new Array(I+1).join("0");E<0?C="-"+N+C.slice(1):C=N+C}}m.push(C)}}else{m=[];for(var P=0;P<u.length;P++)m.push.apply(m,os(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 nc=(n,e)=>{},ui=()=>{},rc=!1;try{let n=await import("@sentry/node"),{nodeProfilingIntegration:e}=await import("@sentry/profiling-node");nc=n.captureException,ui=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(),rc=!0}catch{}import{Command as i_,Option as en}from"@commander-js/extra-typings";import{execSync as s_}from"child_process";import Uw from"body-parser";import Dk from"cors";import Uk from"dedent";import Bk from"events";import Bw,{Router as zk}from"express";import jk from"http";import{z as Lu}from"zod";var b_=Lu.object({input:Lu.string()});import{z as je}from"zod";var x_=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()}),T_=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 Re}from"uuid";import*as v 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 ue}from"zod";ye(ue);var Nu=ue.object({plan:ue.string().optional(),evidence:ue.string().optional(),thoughts:ue.string(),result:ue.boolean(),relevantElements:ue.array(ue.number()).optional()}),ro=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(ro||{});var ux=ue.object({type:ue.literal("ELEMENT_CONTENT"),negated:ue.boolean().optional(),operation:ue.nativeEnum(ro),value:ue.string()}).openapi({ref:"ElementContentAssertion"}),mx=ue.object({type:ue.literal("ELEMENT_ATTRIBUTE"),negated:ue.boolean().optional(),operation:ue.nativeEnum(ro),attr:ue.string(),value:ue.string()}).openapi({ref:"ElementAttributeValueAssertion"}),mi=(o=>(o.EXISTS="EXISTS",o.VISIBLE="VISIBLE",o.ENABLED="ENABLED",o.EDITABLE="EDITABLE",o))(mi||{}),hx=ue.object({type:ue.literal("ELEMENT_EXISTENCE"),negated:ue.boolean().optional(),condition:ue.nativeEnum(mi).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),_u=ue.discriminatedUnion("type",[ux,mx,hx]).openapi({ref:"ManualElementAssertion"});var gx=ue.object({type:ue.literal("CONTENT"),negated:ue.boolean().optional(),value:ue.string()}).openapi({ref:"PageContentAssertion"}),Mu=ue.discriminatedUnion("type",[gx]).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||{}),fx=K.object({mPathSelectorTokens:K.string().array(),frameSrcRegex:K.string().optional(),frameUrlRegex:K.string().optional(),indices:K.number().array()}),yr=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:fx.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 Sx=K.object({type:K.literal("description"),elementDescriptor:K.string(),a11yData:yr.optional().describe("DEPRECATED: new a11y cache is stored in DB and resolved into the 'cache' field")}).openapi({ref:"DescriptionTarget"}),yx=K.object({x:K.number(),y:K.number()}),bx=K.object({type:K.literal("coordinates"),pixels:yx}).openapi({ref:"CoordinatesTarget"});function Vn(n){return n.type==="description"}function Sn(n){return n.type==="coordinates"}var ct=K.discriminatedUnion("type",[Sx,bx]).openapi({ref:"ElementTarget"});function oc(n){if(!n)return!1;switch(n.type){case"description":return!!n.elementDescriptor}return!0}function dt(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 Is=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")}),Ps=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(v);var Y=v.object({thoughts:v.string().optional(),id:v.string().uuid().describe("unique identifier to this step, used for step cache")}),$t=v.object({useSelector:v.boolean().optional(),force:v.boolean().optional(),disableCache:v.boolean().optional().describe("disable element caching for this step"),iframeUrl:v.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),yn=v.object({target:yr}).optional().openapi({ref:"SingleTargetCache"}),Os=v.object({loadTimeout:v.number().int().max(60).optional().describe("Max seconds for the page to load")}),wx=Y.merge(Os).merge(v.object({type:v.literal("NAVIGATE"),url:v.string()})).openapi({ref:"NavigateCommand"}),ks=$t.merge(v.object({cache:yn})),oo=Y.merge(ks.merge(v.object({target:ct.optional(),type:v.literal("SCROLL_UP"),deltaY:v.number().optional()}))).openapi({ref:"ScrollUpCommand"}),io=Y.merge(ks.merge(v.object({target:ct.optional(),type:v.literal("SCROLL_DOWN"),deltaY:v.number().optional()}))).openapi({ref:"ScrollDownCommand"}),so=Y.merge(ks.merge(v.object({target:ct.optional(),type:v.literal("SCROLL_LEFT"),deltaX:v.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),ao=Y.merge(ks.merge(v.object({target:ct.optional(),type:v.literal("SCROLL_RIGHT"),deltaX:v.number().optional()}))).openapi({ref:"ScrollRightCommand"}),z_=v.discriminatedUnion("type",[oo,io,so,ao]).openapi({ref:"AllScrollCommands"}),vx=Y.merge(v.object({type:v.literal("DIALOG"),action:v.union([v.literal("ACCEPT"),v.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),xx=Y.merge(v.object({type:v.literal("WAIT"),delay:v.number()})).openapi({ref:"WaitCommand"}),Tx=v.discriminatedUnion("type",[v.object({type:v.literal("SUBSTRING"),url:v.string()}),v.object({type:v.literal("GLOB"),glob:v.string()}),v.object({type:v.literal("REGEX"),regex:v.string()})]),Ex=v.object({caseInsensitive:v.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:v.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:v.number().int().optional().describe("Max seconds to wait for the URL to match")}),Cx=Y.extend({type:v.literal("WAIT_FOR_URL"),url:v.string().optional().describe("Deprecated: url or glob to wait for. New commands should use the discriminated matcher field."),matcher:Tx.optional()}).merge(Ex).openapi({ref:"WaitUrlCommand"}),Rx=Y.merge(Os).merge(v.object({type:v.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),Ax=Y.merge(v.object({type:v.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),Ix=Y.merge(v.object({type:v.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),Px=Y.extend({type:v.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),Lx=Y.extend({type:v.literal("AUTH_LOAD"),storageState:v.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),sc=Y.merge($t).extend({type:v.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),Ox=Y.extend({type:v.literal("COPY"),value:v.string()}).openapi({ref:"CopyCommand"}),kx=Y.extend({type:v.literal("PASTE")}).openapi({ref:"PasteCommand"}),Nx=Y.merge(Ps).extend({type:v.literal("JAVASCRIPT"),envKey:v.string().optional()}).openapi({ref:"JavaScriptCommand"}),hi=Y.merge($t).merge(v.object({type:v.literal("CLICK"),target:ct,doubleClick:v.boolean().optional(),rightClick:v.boolean().optional(),waitForUrl:v.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:v.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:v.number().optional(),downloadTimeoutMs:v.number().optional(),cache:yn,relativePosition:v.object({x:v.number(),y:v.number()}).optional()})).openapi({ref:"ClickCommand"}),gi=Y.merge($t).merge(v.object({type:v.literal("DRAG"),fromTarget:ct,toTarget:ct,steps:v.number().optional(),hoverSeconds:v.number().optional().describe("Seconds to hover the object before dropping"),cache:v.object({fromTarget:yr.optional(),toTarget:yr.optional()}).optional()})).openapi({ref:"DragCommand"}),fi=Y.merge($t).merge(v.object({type:v.literal("MOUSE_DRAG"),target:ct.optional(),deltaX:v.string().describe("pixels to move horizontally, can be template"),deltaY:v.string().describe("pixels to move vertically, can be template"),steps:v.number().optional(),cache:yn})).openapi({ref:"MouseDragCommand"}),Si=Y.merge($t).merge(v.object({type:v.literal("HOVER"),target:ct,cache:yn})).openapi({ref:"HoverCommand"}),yi=Y.merge($t).merge(v.object({type:v.literal("FOCUS"),target:ct,cache:yn})).openapi({ref:"FocusCommand"}),bi=Y.merge($t).extend({type:v.literal("BLUR"),target:ct.optional(),cache:yn}).openapi({ref:"BlurCommand"}),_x=v.object({type:v.literal("URL"),url:v.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),Mx=v.object({type:v.literal("USER_FILE"),name:v.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),Fx=Y.extend({type:v.literal("FILE_UPLOAD"),fileSource:v.discriminatedUnion("type",[_x,Mx]),filename:v.string().optional()}).openapi({ref:"FileUploadCommand"}),Dx=v.discriminatedUnion("type",[v.object({type:v.literal("VALUE"),value:v.string()}),v.object({type:v.literal("LABEL"),label:v.string()}),v.object({type:v.literal("INDEX"),index:v.number().int()})]),wi=Y.merge($t).extend({type:v.literal("SELECT_OPTION"),target:ct,cache:yn,option:v.string().describe("option value, deprecated old field").optional(),choice:Dx.optional().describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),ac=v.union([v.literal("MULTIMODAL"),v.literal("VISION_ONLY")]),lc=Y.merge(v.object({type:v.literal("AI_ASSERTION"),assertion:v.string(),disableCache:v.boolean().optional(),iframeUrl:v.string().optional(),contextChoice:ac.optional(),timeout:v.number().int().optional().describe("Max seconds to wait for assertion to be true")})).openapi({ref:"AIAssertionCommand"}),Ux=lc.extend({type:v.literal("AI_WAIT")}).openapi({ref:"AIWaitCommand"}),bn=5,cc=600,vi=Y.merge($t).extend({type:v.literal("ELEMENT_CHECK"),target:ct,assertion:_u,cache:yn,timeout:v.number().int().min(0).max(cc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),Bx=Y.extend({type:v.literal("PAGE_CHECK"),assertion:Mu,iframeUrl:v.string().optional().describe("url or url regex for the iframe"),timeout:v.number().int().min(0).max(cc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),zx=Y.merge(v.object({type:v.literal("AI_EXTRACT"),goal:v.string(),schema:v.string().optional(),envKey:v.string().optional(),disableCache:v.boolean().optional(),iframeUrl:v.string().optional()})).openapi({ref:"AIExtractCommand"}),jx=v.object({clearContent:v.boolean().optional(),forceClearContent:v.boolean().optional(),pressKeysSequentially:v.boolean().optional().describe("Deprecated: this is now the default. Please set delay to zero if you wish to achieve instant typing behavior."),delay:v.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:v.boolean().optional(),pressEnter:v.boolean().optional()}),Uu=25,xi=Y.merge($t).merge(jx).extend({type:v.literal("TYPE"),target:ct.optional(),value:v.string(),cache:yn}).openapi({ref:"TypeCommand"}),Hx=Y.merge(v.object({type:v.literal("PRESS"),value:v.string(),repeat:v.number().optional(),convertMeta:v.boolean().optional(),delayMs:v.number().optional()})).openapi({ref:"PressCommand"}),$x=v.object({type:v.literal("SUBSTRING"),substring:v.string()}),Wx=v.object({type:v.literal("REGEX"),pattern:v.string()}),Gx=v.object({type:v.literal("INDEX"),index:v.number()}),Vx=v.discriminatedUnion("type",[$x,Wx,Gx]),qx=Y.merge(Os).merge(v.object({type:v.literal("TAB"),url:v.string().optional().describe("deprecated field - new instances should use the discriminated union"),action:Vx.optional()})).openapi({ref:"TabCommand"}),Kx=Y.merge(Os).merge(v.object({type:v.literal("NEW_TAB"),url:v.string()})).openapi({ref:"NewTabCommand"}),Yx=Y.merge(v.object({type:v.literal("COOKIE"),value:v.string()})).openapi({ref:"CookieCommand"}),Jx=Y.merge(v.object({type:v.literal("LOCAL_STORAGE"),key:v.string(),value:v.string()})).openapi({ref:"LocalStorageCommand"}),Xx=Y.extend({type:v.literal("REQUEST")}).merge(Is).openapi({ref:"RequestCommand"}),Zx=Y.extend({type:v.literal("GRAPHQL_REQUEST")}).merge(Du).openapi({ref:"GraphQLRequestCommand"}),Qx=Y.merge(v.object({type:v.literal("SUCCESS"),condition:lc.optional()})).openapi({ref:"SuccessCommand"}),eT=Y.merge(v.object({type:v.literal("FAILURE")})).openapi({ref:"FailureCommand"}),tT=v.object({data:v.string().describe("location at which to find a jpg"),width:v.number(),height:v.number()}),Ti=Y.merge($t).merge(v.object({type:v.literal("VISUAL_DIFF"),threshold:v.number().optional().describe("default 0.1"),target:ct.optional(),screenshot:tT.optional(),cache:yn})).openapi({ref:"VisualDiffCommand"}),nT=Y.merge(v.object({type:v.literal("REGISTER_REQUEST_LISTENER"),pattern:v.string(),key:v.string()})).openapi({ref:"RegisterRequestListenerCommand"}),rT=Y.merge(v.object({type:v.literal("AWAIT_LISTENER"),key:v.string(),timeout:v.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),Bu=v.discriminatedUnion("type",[hi,xi,Hx,wi,wx,io,oo,lc,Si,xx,Qx]),oT=v.discriminatedUnion("type",[Ux,zx,Lx,Px,sc,Yx,Ox,vx,gi,vi,Fx,Ax,Ix,Nx,Jx,fi,Kx,Bx,kx,Rx,Xx,Zx,so,ao,qx,Ti,yi,bi,Cx,nT,rT]),lo=v.discriminatedUnion("type",[...Bu.options,...oT.options]).openapi({ref:"Command"}),Ns=v.discriminatedUnion("type",[...Bu.options,eT]);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:Re(),type:n};break;case"AUTH_LOAD":{e={id:Re(),type:n,storageState:""};break}case"AI_EXTRACT":e={id:Re(),type:n,goal:""};break;case"DIALOG":e={id:Re(),type:n,action:"DISMISS"};break;case"DRAG":e={id:Re(),type:n,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Re(),type:n,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Re(),type:n,url:""};break;case"WAIT":e={id:Re(),type:n,delay:1};break;case"BLUR":e={id:Re(),type:n};break;case"HOVER":case"FOCUS":case"CLICK":e={id:Re(),type:n,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:Re(),type:n,value:"",clearContent:!0};break;case"SELECT_OPTION":e={id:Re(),type:n,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":case"TAB":e={id:Re(),type:n,url:""};break;case"REQUEST":e={id:Re(),type:n,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:Re(),type:n,url:"",query:""};break;case"LOCAL_STORAGE":e={id:Re(),type:n,key:"",value:""};break;case"JAVASCRIPT":e={id:Re(),type:n,code:""};break;case"AI_WAIT":case"AI_ASSERTION":e={id:Re(),type:n,assertion:""};break;case"FILE_UPLOAD":{e={id:Re(),type:n,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Re(),type:n,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Re(),type:n,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:Re(),type:n,pattern:"",key:""};break}case"AWAIT_LISTENER":{e={id:Re(),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 iT}from"zod";var G_=iT.discriminatedUnion("type",[bi,sc,hi,gi,yi,Si,fi,oo,io,so,ao,wi,xi,Ti,vi]);function ju(n){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(n)}import{z as sT}from"zod";var Et={type:!0,cache:!0},br=sT.discriminatedUnion("type",[bi.pick(Et),hi.pick(Et),gi.pick(Et),vi.pick(Et),yi.pick(Et),Si.pick(Et),fi.pick(Et),oo.pick(Et),io.pick(Et),so.pick(Et),ao.pick(Et),wi.pick(Et),xi.pick(Et),Ti.pick(Et)]),dc=Object.values(Be).filter(n=>br.options.some(e=>e.shape.type.safeParse(n).success));lo.options.forEach(n=>{if("target"in n.shape&&!dc.includes(n.shape.type.value))throw new Error(`Command ${n.shape.type.value} has a target but no cache`)});import{z as uc}from"zod";import{z as pc}from"zod";import{z as co}from"zod";var Ct=co.object({index:co.number().optional().describe("global index within a test (in-order traversal)"),id:co.string(),skipped:co.boolean().optional(),envKey:co.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:co.boolean().optional()});ye(pc);var Rt=Ct.extend({type:pc.literal("PRESET_ACTION"),command:lo,skipped:pc.boolean().optional()}).openapi({ref:"PresetAction"});ye(uc);var wr=Ct.extend({type:uc.literal("AI_ACTION"),text:uc.string(),steps:Rt.array().optional()}).openapi({ref:"AIAction"});import{z as se}from"zod";var aT=se.object({cacheKey:se.string(),cacheExpiryMs:se.number()}),mc=Ct.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:aT.optional()}),kn=mc.extend({type:se.literal("MODULE"),moduleId:se.string().uuid()}),lT=se.union([kn.pick({type:!0,moduleId:!0}),se.record(se.unknown())]),cT=se.object({type:se.literal("URL_REGEX"),regex:se.string()}),dT=se.object({type:se.literal("PAGE_CHECK"),substring:se.string()}),hc=se.object({cacheInvalidation:se.discriminatedUnion("type",[dT,cT]).optional()}),At=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:hc.nullish()});import{z as rt}from"zod";import{z as gc}from"zod";ye(gc);var po=Ct.extend({type:gc.literal("AI_ACTION_DYNAMIC"),text:gc.string()}).openapi({ref:"AIActionDynamic"});import{z as Hu}from"zod";var fc=Ct.extend({type:Hu.literal("CONDITIONAL"),skipped:Hu.boolean().optional()});import{z as _s}from"zod";var pT=_s.object({type:_s.literal("url"),url:_s.string()}),Ei=Ct.extend({type:_s.literal("IFRAME"),identifier:pT});import{z as Wt}from"zod";var Sc=(r=>(r.ALWAYS="ALWAYS",r.ON_FAILURE="ON_FAILURE",r.ON_ACTION_FAILURE="ON_ACTION_FAILURE",r))(Sc||{});var uT=Wt.discriminatedUnion("type",[Wt.object({type:Wt.literal("NAVIGATE_URL"),url:Wt.string().url()}),Wt.object({type:Wt.literal("GO_TO_SECTION_START")})]),mT=Wt.object({trigger:Wt.nativeEnum(Sc).optional(),attempts:Wt.number().int().optional(),restartBehavior:uT}),Ci=Ct.extend({type:Wt.literal("SECTION"),description:Wt.string().describe("user provided goal of what the section should accomplish"),plan:Wt.string().array().optional(),autohealingConfig:mT.optional()});var $u=At.merge(mc).extend({type:rt.literal("RESOLVED_MODULE"),steps:rt.lazy(()=>ve.array())}),yc=At.extend({steps:rt.lazy(()=>ve.array())}),bc=Ei.extend({steps:rt.lazy(()=>Ke.array())}),hT=Ei.extend({steps:rt.lazy(()=>ve.array())}),wc=Ci.extend({steps:rt.lazy(()=>Ke.array())}),gT=Ci.extend({steps:rt.lazy(()=>ve.array())}),vr=fc.extend({blocks:rt.object({assertion:rt.lazy(()=>Rt),steps:rt.lazy(()=>Ke.array())}).array(),elseSteps:rt.lazy(()=>Ke.array().optional())}),fT=fc.extend({blocks:rt.object({assertion:rt.lazy(()=>Rt),steps:rt.lazy(()=>ve.array())}).array(),elseSteps:rt.lazy(()=>ve.array().optional())}),Ke=rt.discriminatedUnion("type",[Rt,wr,po,kn,vr,bc,wc]),ve=rt.discriminatedUnion("type",[Rt,wr,po,$u,fT,hT,gT]);import{z as Gt}from"zod";var ST=Gt.object({steps:Ke.array(),beforeSteps:Ke.array().nullish(),afterSteps:Ke.array().nullish()}),uo=Gt.object({steps:ve.array(),beforeSteps:ve.array().nullish(),afterSteps:ve.array().nullish()}),xr=Gt.object({steps:Gt.record(Gt.string(),Gt.unknown()).array(),beforeSteps:Gt.record(Gt.string(),Gt.unknown()).array().nullish(),afterSteps:Gt.record(Gt.string(),Gt.unknown()).array().nullish()});var He="1.0.19";import{z as Tr}from"zod";var vc=Tr.object({key:Tr.string(),testId:Tr.string().optional(),moduleId:Tr.string().optional(),organizationId:Tr.string(),value:br}),Wu=Tr.record(Tr.string(),vc);var Gu=k.object({phrase:k.string()}),xc=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()])}),WF=k.object({text:k.string()}),Vu=k.object({thoughts:k.string(),review:k.string().optional(),id:k.number().int()}),Ms=(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))(Ms||{});var qu=k.object({thoughts:k.string(),category:k.nativeEnum(Ms)}),yT=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()})]),GF=k.object({thoughts:k.string(),patches:yT.array()}),Ku=[k.literal("add"),k.literal("replace"),k.literal("remove")],bT=k.object({op:k.union(Ku),path:k.string(),value:ve.optional()}),Yu=k.object({patches:bT.array(),thoughts:k.string()});var wT=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:wT.or(k.null())}),VF=k.object({thoughts:k.string(),evaluation:k.number().min(1).max(10)}),qF=k.object({observations:k.string(),reasoning:k.string(),command:Ns});var Tc=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 QF=te.object({thoughts:te.string().optional().describe("only provided if a description was provided"),target:yr.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 Ri(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 Ai=(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))(Ai||{}),mo=te.object({matched:te.boolean(),reason:te.string().optional().describe("Human understandable description"),logs:te.string().array().optional().describe("Logs for debugging")}),vT=mo.extend({type:te.literal("A11Y_ID")}),xT=mo.extend({type:te.literal("USER_SELECTOR")}),TT=mo.extend({type:te.literal("CSS_SELECTOR"),selectors:te.string().array()}),ET=mo.extend({type:te.literal("HTML_DISTANCE"),distance:te.number().optional(),closestElement:te.string().optional(),savedElement:te.string().optional()}),CT=mo.extend({type:te.literal("TEMPLATE_MATCHING"),elementImageUrl:te.string().url()}),RT=mo.extend({type:te.literal("AUTO_FRAME"),logs:te.string().array().optional()}),Zu=te.discriminatedUnion("type",[vT,xT,TT,ET,CT,RT]);import{z as Ni}from"zod";import{z as KE}from"zod";import*as J from"zod";import{cloneDeep as Li}from"lodash-es";var AT=n=>{let e=Qu(n,0);if(e===void 0||!PT(n[e]))return;let t=Qu(n,e+1);if(t!==void 0)return LT(n,e,t)},em=AT,Qu=(n,e)=>{for(let t=e;t<n.length;t+=1){let r=n[t];if(!IT(r))return t}},IT=n=>n===" "||n===" "||n===`
5
5
  `||n==="\r",PT=n=>n==="{"||n==="[",LT=(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 OT(r);if(r===void 0)r=i;else if(r[0]===i)r+=i;else return}},OT=n=>n===void 0?0:n[0]===" "?n.length:n;var tm=(n,e)=>{let t=Ec(n,"toPrecision",e,e);return t===void 0?Ec(n,"toExponential",e,e):t},Ec=(n,e,t,r)=>{let i=n[e](r).replace(kT,"$1").replace(NT,"$1");return i.length<=t?i:r===1?void 0:Ec(n,e,t,r-1)},kT=/(e)\+/iu,NT=/\.?0*($|e)/iu;var rm=(n,e)=>{if(typeof n!="string")throw new TypeError(`Input must be a JSON string: ${n}`);_T(e)},_T=n=>{if(MT(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}`)},MT=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 Fs=(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>=WT&&r<=GT?om(n,e,t+1):t},Ds=(n,e,t)=>{if(t===void 0)return t;let r=im(e,t);return FT(n,r)},FT=(n,e)=>DT(n,e)?e-3:UT(n,e)?e-2:BT(n,e)?e-1:e,DT=(n,e)=>e>=3&&n[e-3]>=zT&&n[e-3]<=jT,UT=(n,e)=>e>=2&&n[e-2]>=HT,BT=(n,e)=>e>=1&&n[e-1]>=$T,im=(n,e)=>e<0||Object.is(e,-0)?Math.max(n+e,0):e,zT=240,jT=244,HT=224,$T=194,WT=128,GT=191;var sm=(n,e,t)=>{let r=globalThis.Buffer.from(n),o=Fs(r,r.length,e),i=Ds(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 Us=n=>VT(n)?n.replace(am,lm):n,VT=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 Ac=({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 Ic=(n,e,t)=>e<0||Object.is(e,-0)?ZT(n,e,t):XT(n,e,t),XT=(n,e,t)=>Ac({input:n,targetByteCount:e,firstStartSurrogate:55296,lastStartSurrogate:56319,firstEndSurrogate:56320,lastEndSurrogate:57343,increment:1,canBacktrack:t,shift:0,charIndexInit:0}),ZT=(n,e,t)=>Ac({input:n,targetByteCount:-e,firstStartSurrogate:56320,lastStartSurrogate:57343,firstEndSurrogate:55296,lastEndSurrogate:56319,increment:-1,canBacktrack:!t,shift:1,charIndexInit:n.length-1});var Bs=(n,e,t)=>{let r=Ic(n,e,!1),o=QT(n,t),i=r===0&&o===void 0?n:n.slice(r,o);return Us(i)},QT=(n,e)=>{if(e===void 0)return e;let t=Ic(n,e,!0);return t===n.length?void 0:t};var dm=(n,e,t)=>{let{textEncoder:r,textDecoder:o}=eE(),i=tE(n),{written:s}=r.encodeInto(n,i),a=Fs(i,s,e),l=Ds(i,s,t),c=l===void 0?s:Math.min(l,s),p=i.subarray(a,c);return o.decode(p)},eE=()=>(Pc===void 0&&(Pc=new globalThis.TextEncoder,cm=new globalThis.TextDecoder("utf8",{fatal:!1})),{textEncoder:Pc,textDecoder:cm}),Pc,cm,tE=n=>{let e=n.length*3;return e>nE?new Uint8Array(e):((zs===void 0||zs.length<e)&&(zs=new Uint8Array(e)),zs)},nE=1e5,zs;var pm=(n,e)=>{if(e===void 0)return e;let t=Lc(n,e);return t>=n.length*um?void 0:t},Lc=(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}`);rE(e),oE(t)},rE=n=>{if(n===void 0)throw new TypeError("Second argument is required.");hm("Second",n)},oE=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<Oc;r+=1){let o=iE(n,r);o<=127||(e&&(e=!1),o>2047&&(t+=1))}return{asciiOnly:e,longCharsPercentage:t/Oc}},iE=(n,e)=>{let t=Oc-1,r=1-(t-e)/t,o=Math.round(r*(n.length-1));return n.charCodeAt(o)},Oc=50;var sE=(n,e,t)=>{if(mm(n,e,t),n==="")return n;let r=Lc(n,e),o=pm(n,t);return o===void 0&&Object.is(r,0)?Us(n):aE(n,r,o)},fm=sE,aE=(n,e,t)=>{if(n.length<=lE)return Bs(n,e,t);let{asciiOnly:r,longCharsPercentage:o}=gm(n);return r?dE(n,e,t):o>=cE?Bs(n,e,t):Sm(n,e,t)},lE=200,cE=.4,dE=(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):Bs(n,e,t);var bm=(n,e)=>{let t=JSON.stringify(n),r=mE(t),o=fm(r,0,e-ym.length-Ii.length*2),s=`${pE(o)}${ym}`;return hE(s)},pE=n=>n.replace(uE,""),uE=/(\\|\\u[0-9a-fA-F]{0,3})$/u,mE=n=>n.slice(Ii.length,-Ii.length),hE=n=>`${Ii}${n}${Ii}`,Ii='"',ym="...";var wm=n=>globalThis.Buffer.byteLength(n);var kc=n=>{let e=n.length,t=e;for(let r=0;r<e;r+=1){let o=n.charCodeAt(r);if(o<=gE)continue;if(o<=fE){t+=1;continue}if(t+=2,o<SE||o>yE)continue;let i=n.charCodeAt(r+1);i<bE||i>wE||(r+=1)}return t},gE=127,fE=2047,SE=55296,yE=56319,bE=56320,wE=57343;var vm=()=>vE.bind(void 0,new TextEncoder),vE=(n,e)=>{let t=xE(e);return n.encodeInto(e,t).written},xE=n=>{let e=n.length*3;return e>TE?new Uint8Array(e):((js===void 0||js.length<e)&&(js=new Uint8Array(e)),js)},TE=1e5,js;var CE=()=>"Buffer"in globalThis&&"byteLength"in globalThis.Buffer?wm:"TextEncoder"in globalThis?RE.bind(void 0,vm()):kc,RE=(n,e)=>e.length<100?kc(e):n(e),xm=CE();var Tm=n=>{if(n===null)return AE;if(n===!0)return IE;if(n===!1)return PE;let e=typeof n;return e==="object"?LE:e==="number"?JSON.stringify(n).length:Nc(n)},AE=4,IE=4,PE=5,LE=2,Nc=n=>xm(JSON.stringify(n));var Hs=({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=Nc(n),s=Pm(e);return o+i+OE+s},OE=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:kE,kE=1;var $s=({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}=Hs({size:a,increment:r,maxSize:o,truncatedProps:e,path:u,value:d});return h?{empty:s,size:m,truncatedProps:g}:NE({value:d,truncatedProps:e,path:u,maxSize:o,empty:s,size:a,newSize:m,truncateValue:l,indent:c,depth:p})},NE=({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=$s({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=$s({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 Ws=({value:n,truncatedProps:e,path:t,size:r,maxSize:o,indent:i,depth:s})=>{let a=Cm(n),{size:l,stop:c,truncatedProps:p}=Hs({size:r,increment:a,maxSize:o,truncatedProps:e,path:t,value:n});return c?{value:void 0,size:l,truncatedProps:p}:_E({value:n,truncatedProps:p,path:t,size:l,maxSize:o,indent:i,depth:s})},_E=({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:Ws,indent:i,depth:s}):Om({object:n,truncatedProps:e,path:t,size:r,maxSize:o,truncateValue:Ws,indent:i,depth:s});var ME=(n,e)=>{rm(n,e);let t=FE(n),r=DE(n),{value:o,truncatedProps:i}=Ws({value:r,truncatedProps:[],path:[],size:0,maxSize:e,indent:t,depth:0});return{jsonString:UE({newValue:o,value:r,maxSize:e,indent:t}),truncatedProps:i}},Pi=ME,FE=n=>{let e=em(n);return typeof e=="string"?e.length:e},DE=n=>{try{return JSON.parse(n)}catch(e){throw new TypeError(`Invalid JSON string: "${n}"
@@ -443,7 +443,7 @@ function addEvaluateCssSelectorsScript() {
443
443
  const ratioThreshold = ldistThreshold;
444
444
  const lRatio = customWindow.ldist(serializedCandidate, serializedNodeWithText) / Math.min(serializedCandidate.length, serializedNodeWithText.length);
445
445
  const serializedNodeWithTextWithoutClass = serializedNodeWithText.replace(
446
- /class="[^>]+"/g,
446
+ / class="[^"]+"/g,
447
447
  ""
448
448
  );
449
449
  const serializedCandidateWithoutClass = customWindow.serializeElementOnlyWithText(bestElement, {
@@ -3572,7 +3572,7 @@ ${i.stack}`),a.status(500).send("Internal Server Error")}),n){let i=Bw.static(n,
3572
3572
 
3573
3573
  Using Command Prompt on Windows:
3574
3574
  for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
3575
- `)}import a_ from"events";import Cu from"fs";import l_ from"open";import ec from"path";import{fileURLToPath as c_}from"url";import aN from"diff-lines";import{gt as lN}from"semver";import{execSync as $k}from"child_process";import{platform as Wk}from"os";function Kp(){return $w()?(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 $w(){return Wk()==="darwin"&&$k("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Yp(n){$w()&&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 Gk from"@actions/exec";import Vk from"@actions/io";import qk from"quote";import Kk from"string-argv";async function Ww(n,e=!0){let t=Kk(n),r=await Vk.which(t[0],!0),o=t.slice(1),i=Gk.exec(qk(r),o,{delay:100});if(e)return i}import{existsSync as Yk,statSync as Jk}from"fs";var Ll=!!process.env.CI||!process.stdout.isTTY||!!process.env.TF_BUILD;function Ts(n){try{return Yk(n)&&Jk(n).isDirectory()}catch(e){return y.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import Xk from"csv-parser";import{createReadStream as Zk}from"fs";function Jp(n){return new Promise((e,t)=>{let r=[];Zk(n).pipe(Xk()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import Ol from"semver";import{z as kl}from"zod";var jt="1.1.3",Qk="https://registry.npmjs.org/momentic",eN=kl.object({versions:kl.record(kl.string(),kl.unknown()).optional()});async function Gw(n){try{await tN(n)}catch(e){y.warn({err:e},"Failed to check CLI version against NPM servers")}}async function tN(n){if(!jt){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 U(fetch(Qk),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=eN.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))Ol.valid(r)&&(!t||Ol.gt(r,t))&&Ol.gt(r,jt)&&Ol.lt(r,"2.0.0")&&!r.includes("alpha")&&(t=r);t&&(y.warn(`Update available: v${jt} -> 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 rN,mkdirSync as oN,statSync as iN}from"fs";import{dirname as sN}from"path";import qw from"readline/promises";import{hostname as nN}from"os";var Q=Cl({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:nN(),disableConsoleLogs:!0}).child({version:"1.1.3"});var Xp=!1,Kw=(()=>{try{return iN("/.dockerenv"),!0}catch{return!1}})();async function at(n,e){if(Ll||Xp||Kw)return!0;Q.flush(),await new Promise(s=>setTimeout(s,500));let t=qw.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=sN(n);return Ts(e)?rN(n)?at(`File '${Vw(n)}' already exists. Overwrite existing content?`,!0):!0:await at(`Directory '${Vw(e)}' doesn't exist. Create it now?`,!0)?(oN(e,{recursive:!0}),!0):!1}function Vw(n){return n.replace(/(\s+)/g,"\\$1")}async function Yw(n,e){if(Ll||Kw)return e;let t=qw.createInterface({input:process.stdin,output:process.stdout}),r=await t.question(`${n} `);return t.close(),r.trim()||e}async function Jw({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){lN(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)),Og(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 at("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 at("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=ts(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 $i({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 mt({stepLists:{steps:d}});u.beforeSteps=l.beforeSteps??void 0,u.afterSteps=l.afterSteps??void 0;let h=aN(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 at("Do you want to apply this patch?")&&(y.dimmed("Cancelled."),process.exit(1)),qr(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 Xw}from"crypto";async function Zw({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=ts(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=kt.parse(c),u=await dd(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,x=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 ${x}`),n&&(m=!0,g.id=Xw())):o[g.id]={testId:l.id,testRelativePath:l.relativePath},g.type!=="PRESET_ACTION")return;let b=g.command.id,w=i[b]?.testId,E=i[b]?.testRelativePath;w?(a++,h=!0,w===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 ${E}`),n&&(m=!0,g.command.id=Xw())):i[b]={testId:l.id,testRelativePath:l.relativePath}}),h&&y.dimmed("=".repeat(80)),m&&n&&(qr(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:
3575
+ `)}import a_ from"events";import Cu from"fs";import l_ from"open";import ec from"path";import{fileURLToPath as c_}from"url";import aN from"diff-lines";import{gt as lN}from"semver";import{execSync as $k}from"child_process";import{platform as Wk}from"os";function Kp(){return $w()?(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 $w(){return Wk()==="darwin"&&$k("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Yp(n){$w()&&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 Gk from"@actions/exec";import Vk from"@actions/io";import qk from"quote";import Kk from"string-argv";async function Ww(n,e=!0){let t=Kk(n),r=await Vk.which(t[0],!0),o=t.slice(1),i=Gk.exec(qk(r),o,{delay:100});if(e)return i}import{existsSync as Yk,statSync as Jk}from"fs";var Ll=!!process.env.CI||!process.stdout.isTTY||!!process.env.TF_BUILD;function Ts(n){try{return Yk(n)&&Jk(n).isDirectory()}catch(e){return y.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import Xk from"csv-parser";import{createReadStream as Zk}from"fs";function Jp(n){return new Promise((e,t)=>{let r=[];Zk(n).pipe(Xk()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import Ol from"semver";import{z as kl}from"zod";var jt="1.1.4",Qk="https://registry.npmjs.org/momentic",eN=kl.object({versions:kl.record(kl.string(),kl.unknown()).optional()});async function Gw(n){try{await tN(n)}catch(e){y.warn({err:e},"Failed to check CLI version against NPM servers")}}async function tN(n){if(!jt){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 U(fetch(Qk),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=eN.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))Ol.valid(r)&&(!t||Ol.gt(r,t))&&Ol.gt(r,jt)&&Ol.lt(r,"2.0.0")&&!r.includes("alpha")&&(t=r);t&&(y.warn(`Update available: v${jt} -> 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 rN,mkdirSync as oN,statSync as iN}from"fs";import{dirname as sN}from"path";import qw from"readline/promises";import{hostname as nN}from"os";var Q=Cl({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:nN(),disableConsoleLogs:!0}).child({version:"1.1.4"});var Xp=!1,Kw=(()=>{try{return iN("/.dockerenv"),!0}catch{return!1}})();async function at(n,e){if(Ll||Xp||Kw)return!0;Q.flush(),await new Promise(s=>setTimeout(s,500));let t=qw.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=sN(n);return Ts(e)?rN(n)?at(`File '${Vw(n)}' already exists. Overwrite existing content?`,!0):!0:await at(`Directory '${Vw(e)}' doesn't exist. Create it now?`,!0)?(oN(e,{recursive:!0}),!0):!1}function Vw(n){return n.replace(/(\s+)/g,"\\$1")}async function Yw(n,e){if(Ll||Kw)return e;let t=qw.createInterface({input:process.stdin,output:process.stdout}),r=await t.question(`${n} `);return t.close(),r.trim()||e}async function Jw({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){lN(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)),Og(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 at("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 at("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=ts(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 $i({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 mt({stepLists:{steps:d}});u.beforeSteps=l.beforeSteps??void 0,u.afterSteps=l.afterSteps??void 0;let h=aN(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 at("Do you want to apply this patch?")&&(y.dimmed("Cancelled."),process.exit(1)),qr(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 Xw}from"crypto";async function Zw({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=ts(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=kt.parse(c),u=await dd(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,x=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 ${x}`),n&&(m=!0,g.id=Xw())):o[g.id]={testId:l.id,testRelativePath:l.relativePath},g.type!=="PRESET_ACTION")return;let b=g.command.id,w=i[b]?.testId,E=i[b]?.testRelativePath;w?(a++,h=!0,w===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 ${E}`),n&&(m=!0,g.command.id=Xw())):i[b]={testId:l.id,testRelativePath:l.relativePath}}),h&&y.dimmed("=".repeat(80)),m&&n&&(qr(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:
3576
3576
  ${[...s].map(l=>`- ${l}`).join(`
3577
3577
  `)}`):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 Qw({project:n}){let e=ke(n,y),t=Object.values(e.tests),r=await ol(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 cN}from"lodash-es";async function Nl({client:n,skipPrompts:e,project:t}){let r=await n.getAllEnvironments(),o=cN(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 at(`Environment ${i.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),s.baseUrl=i.variables[Ae],delete i.variables[Ae],s.envVariables=i.variables;else{let a=i.variables[Ae];delete i.variables[Ae],o.environments.push({name:i.name,baseUrl:a,envVariables:i.variables})}}Xo(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 ev}from"crypto";import tv from"fs";async function rv({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=nv(l,he.TEST);!r&&!await Zp(p)||(s+=1,tv.writeFileSync(p,c,"utf-8"),Q.info({checksum:ev("md5").update(c).digest("hex")},`Wrote '${p}'`))}let a=0;for(let[l,c]of Object.entries(i)){let p=nv(l,he.MODULE);!r&&!await Zp(p)||(a+=1,tv.writeFileSync(p,c,"utf-8"),Q.info({checksum:ev("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 nv(n,e){switch(e){case he.TEST:return`${Pe(n)}.${Nt.TEST}`;case he.MODULE:return`${Pe(n)}.${Nt.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function ov(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 at("Are you sure you want to proceed?",!0)||(y.info("Aborting..."),process.exit(1)),await Nl({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 rv({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 Ht from"fs";import Xr from"path";import dN from"yaml";function iv(){Ts("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:ws,environments:[]};y.info("Migrating environments");let e=sv(["momentic/environments"],pN);for(let r of e){let o=dN.parse(Ht.readFileSync(r,"utf-8"));try{let i=Ks.parse(o),s=i.variables[Ae]??"";delete i.variables[Ae],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=Xr.join(...r.fullPathSegments),i=Xr.join(Xr.dirname(o),`${r.fileName.slice(0,-5)}.test.yaml`);y.info(`Moving test ${o} to ${i}`),Ht.renameSync(o,i)}if(Ts("momentic/modules")){y.info("Migrating modules");for(let r of Ht.readdirSync("./momentic/modules")){if(!r.endsWith(".yaml"))continue;let o=Xr.resolve(Xr.join("./momentic/modules",r));if(!Ht.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}`),Ht.renameSync(o,s)}}return y.info("Writing new project configuration file"),Xo(n,"momentic.config.yaml"),Ht.rmSync("./momentic/environments",{recursive:!0,force:!0}),Ht.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 sv(n,e,t=new Set){for(let r of n){let o=Xr.resolve(r),i=!1;try{i=Ht.existsSync(o)&&Ht.statSync(o).isDirectory()}catch(s){y.error({err:s},`Error reading path ${o} during collect paths`)}if(o&&i){let s=Ht.readdirSync(o).map(a=>Xr.join(o,a));sv(s,e,t);continue}if(o.endsWith(".yaml")){try{if(!Ht.existsSync(o)||!Ht.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 pN(n){return n.endsWith(".yaml")?Ht.readFileSync(n,"utf8").includes("momentic/environment")?!0:(y.warn(`Skipping YAML that is not a Momentic environment: ${n}`),!1):!1}import{Argument as oi,Option as Ne}from"@commander-js/extra-typings";import{validateHeaderValue as uN}from"http";import{cpus as av}from"os";import{parse as kpe}from"yaml";import{z as q}from"zod";var _l=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."),hr=new Ne("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise."),gr=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.`),Ml=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}),cv=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(_i)),dv=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."),pv=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."),uv=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."),mv=new Ne("--port <port>",`Port to run the app on. Defaults to ${_l}.`),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."),Fl=new Ne("--env <env>","Name of the environment to use when running tests."),Dl=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."),hv=new Ne("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>parseInt(n,10)),fr=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."),gv=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)),fv=new Ne("--fix","Attempt to fix any issues found. This option will write changes to your local file system."),Sv=new oi("<tests...>",`One or more test paths to queue on Momentic Cloud.
3578
3578
 
@@ -3588,7 +3588,7 @@ ${n.map(d=>` - ${d}`).join(`
3588
3588
  `),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:
3589
3589
  ${n.map(d=>` - ${d}`).join(`
3590
3590
  `)}`),Object.values(e.tests).forEach(d=>{n.some(u=>d.relativePath.includes(u))&&a.add(d.fullFilePath)}))}else{!r&&!await at("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 ns(c,Q,e);if(UN.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(FN)}import{cloneDeep as Wv}from"lodash-es";async function zv({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 Dt({orgId:n,s:c,localTools:e,logger:t,context:o,flagStore:i})}return s}async function jv({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 za({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 Zr(["chrome"]);let x=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 Ur(S),contextArgs:{viewport:o.advanced.viewport??rn,deviceScaleFactor:t},iconKnowledgeBase:x})}catch(C){let I=C.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 Zr(au,!0),b=await dn.init({baseUrl:n,logger:p,userBrowserSettings:f,storage:i,flagStore:g,enricher:new Ur(S),contextArgs:{viewport:o.advanced.viewport??rn,deviceScaleFactor:t},iconKnowledgeBase:x});else throw C}let w=new Do({browser:b,generator:a,logger:p,orgId:l,scratchPadId:void 0,storage:i,flagStore:g,localCodeEvalTools:s,visualDiffScreenshotStorage:h,analytics:new ti,slowMoMs:f.slowMoMs}),E=new It({baseUrl:n,currentUrl:w.browser.url(),variablesFromEnvironment:c,envName:e});return o.parameters&&await Promise.all(o.parameters.map(async C=>{let{name:I,defaultValue:N,required:P}=C,D=u?.[I];P&&D===void 0&&(y.error(`Required parameter '${I}' is required by test '${o.name}' but not provided`),process.exit(1));let W=await Dt({orgId:l,s:D??N,localTools:s,logger:p,context:It.dummyContext(E.getEnvName()),flagStore:g});E.setMomenticSystemVariable(I,W)})),{controller:w,context:E}}import{randomUUID as BN}from"crypto";async function Hv({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 $v({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:x,orgSettings:b,noReport:w}=n;h.info(`Running test '${x.name}' locally${w?"":` and reporting results to https://app.momentic.ai/runs/${i}`}`);let E={controller:a,storage:u,debugDataStorage:m,billingReporter:f,analytics:p,context:l,logger:h,codeEvalTools:d},C={orgId:o,runId:i||BN(),runAttemptId:s,testMetadata:x,steps:x.steps,beforeSteps:x.beforeSteps,afterSteps:x.afterSteps},I={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await Hv({noReport:w,currentAttempt:r,testId:x.id,flagStore:c,apiClient:g,testAdvancedSettings:x.advanced,aiSettingsFromEnv:b.ai,logger:h})};return await Ba({fixtures:E,inputs:C,options:I,callbacks:{step:{},test:{onTestComplete:async()=>{await a.browser.cleanup()},onProposedTestSteps:async D=>g.uploadProposedSteps(D,h)}},testParams:{tracer:S}})}async function Gv(n){let{testDefinition:e,logger:t}=n,r=new Date;try{return await zN(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 zN(n){let{testDefinition:e,project:t,apiClient:r,orgId:o,urlOverride:i,runSigIntHandlers:s,runGroupTracer:a,logger:l}=n,c=new Eo(r,o),p=Wv(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??HN(e),u,m={};if(d){try{u=rs(d,t,l)}catch(S){let x=`Failed to resolve environment ${d} for test ${e.name}: ${S}`;throw new Error(x)}m=u.variables}let h=e.baseUrl;if(i)h=i;else if(!h){let S=m[Ae];typeof S=="string"&&(h=S)}if(!h){let S=`Cannot run test with no base URL and no ${Ae} 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,x])=>{m[S]=x});try{s?.push(async()=>{await g.finish({status:"CANCELLED"})});let S=await jN({...n,variables:m,envName:d,stepsWithCaches:p,resolvedEnv:u,baseUrl:h,storageClient:c,tracer:g,logger:f});return await g.finish({status:S.status,finishedAt:S.finishedAt,failureDetails:S.failureDetails,failureReason:S.failureReason,isFlake:S.isFlake}),{runId:g.runId,...S}}finally{s?.pop()}}async function jN(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:x,logUpdate:b,tracer:w,logger:E}=n,C=new Date,I=new Qo(r,o),N={ai:r.config.ai},P={envName:p,urlOverride:d,customHeaders:u,testInputs:m},D,W=Math.abs(S??r.config.retries??e.retries??0),_=[];E.info("Starting test run using CLI");for(let B=0;B<=W;B++){let L=await w.startAttempt(),j=E.child(L.loggerBindings||{}),O={...e,steps:Wv(t)};B!==0&&b("RETRY",`attempt ${B+1}/${W+1}`);let ee=new Date,me=await Ao.init(c,i),tt=new Qn({httpClient:new _t({baseUrl:i.baseUrl,apiKey:i.apiKey,logger:j}),fakerSeed:me.isBooleanFlagEnabled("faker_constant_seed")?ph:void 0});try{let{controller:ce,context:Se}=await jv({baseUrl:a,envName:p,apiClient:i,devicePixelRatio:x,logger:j,storageClient:l,codeEvalTools:tt,test:O,generator:s,orgId:c,variables:h,customHeaders:u,testInputs:m,localBrowserConfig:g?.browser??r.config.browser,visualDiffScreenshotStorage:I,flagStore:me});D=await $v({attemptMetadata:{attemptNumber:B+1,orgId:c,runId:w.runId},attemptFixtures:{logger:j,storageClient:l,billingReporter:new wo,analytics:new ti,debugDataStorage:new Lr,codeEvalTools:tt,flagStore:me,apiClient:i,context:Se,controller:ce,tracer:L},attemptInputs:{test:O,orgSettings:N,noReport:f}});let De=new Date;await L.finish({logger:j,result:D}),_.unshift(D.status);let nt=await zv({orgId:c,codeEvalTools:tt,logger:j,outputDefinitions:e.outputs??[],testContext:Se,flagStore:me}),Ft=$m(_),Pn=B+1;if(D.status!=="FAILED")return{...D,parameters:P,test:O,filePath:O.relativeFilePath,startedAt:C,lastAttemptStartedAt:ee,finishedAt:De,attempts:Pn,baseUrl:a,outputs:nt,isFlake:Ft};let G=D.failedStepResult,tn=G?.message||"Unknown failure",ci=G?.failureReason??vh(tn)??"UnknownError",Ue=j.child({errResult:G,failureReason:ci,errorMessage:tn,numAttempts:W+1,name:O.name});if(B<W){Ue.warn(`Retrying failed execution attempt for run: ${tn}`);continue}return Ue.error(`Test failed after all exhausting attempts: ${tn}`),{...D,parameters:P,failureDetails:{errorMessage:tn},failureReason:ci,test:O,filePath:O.relativeFilePath,startedAt:C,lastAttemptStartedAt:ee,finishedAt:De,attempts:B+1,baseUrl:a,outputs:nt}}catch(ce){let Se=`Encountered fatal platform error while running test '${O.name}': ${ce}`,De=new Date,nt=B+1;j.error({err:ce},Se),y.error(Se);let Ft={errorMessage:ce.message,errStack:ce.stack},Pn={status:"FAILED",failureDetails:Ft,failureReason:"InternalPlatformError",finishedAt:De};return await L.finish({logger:j,result:{status:"FAILED",results:[]}}),{...Pn,parameters:P,test:O,filePath:O.relativeFilePath,startedAt:C,lastAttemptStartedAt:ee,finishedAt:new Date,attempts:nt,baseUrl:a,outputs:{}}}}throw new Error("This code should not be reachable")}function HN(n){for(let e of n.envs??[])if(e.default)return e.name}async function ai(n,e,t,r,o){let i=Fi(o.type);if(i&&await e.reportCreditsUsed(n,o.type,i,{testId:t,testName:r}),"command"in o){let s=Di(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 Gl(this.testId,this.testName,this.billingReporter,this.asyncWork)}},Gl=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(ai(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){this.testId=e;this.testName=t;this.billingReporter=r;this.asyncWork=o}trackStatus(){}attachNetworkLogs(){}attachConsoleLogs(){}async finish(){}async startStepList(){return new Gl(this.testId,this.testName,this.billingReporter,this.asyncWork)}},fu=class{constructor(e,t,r,o){this.testId=e;this.testName=t;this.billingReporter=r;this.asyncWork=o}async finish(){}trackStatus(){}async startAttempt(){return new gu(this.testId,this.testName,this.billingReporter,this.asyncWork)}},Vl=class{constructor(e){this.billingReporter=e}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(e.testId,e.testName,this.billingReporter,this.asyncWork)}};import{randomUUID as Vv}from"crypto";import{diff as ZN}from"deep-object-diff";import $N from"adm-zip";import Hn from"fs";import Qr from"path";var Rs=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(Qr.join(this.filePath,e))}storeFile(e){let{name:t,contents:r}=e,o=Qr.join(this.filePath,t);Hn.writeFileSync(o,r)}createRunArchive(e){return new Su(Qr.join(this.filePath,"runs"),e)}},Su=class{constructor(e,t){this.filePath=e;this.tempPath=Qr.join(e,`.${t}`),this.finalPath=Qr.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 Rs(Qr.join(this.tempPath,e))}storeFile(e){let{name:t,contents:r}=e,o=Qr.join(this.tempPath,t);Hn.writeFileSync(o,r)}close(){let e=new $N;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 WN from"simple-git";var Ee=WN();function ql(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 Ce(n){try{return(await n).trim()}catch(e){Q.error({err:e},"Failed to run git command");return}}function GN(){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 VN(){let[n,e,t,r]=await Promise.all([Ce(Ee.show(["--no-patch","--format=%ci"])),Ce(Ee.listRemote(["--get-url","origin"])),Ce(Ee.show(["-s","--pretty=%B"])),Ce(Ee.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 qN(){let[n,e,t]=await Promise.all([Ce(Ee.listRemote(["--get-url","origin"])),Ce(Ee.show(["-s","--pretty=%B"])),Ce(Ee.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 KN(){let[n,e,t,r]=await Promise.all([Ce(Ee.show(["--no-patch","--format=%ci"])),Ce(Ee.listRemote(["--get-url","origin"])),Ce(Ee.show(["-s","--pretty=%B"])),Ce(Ee.show(["-s","--pretty=%an"]))]),o=e?.includes("github.com"),i=e?.includes("gitlab.com"),s=e?ql(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 YN(){let[n,e,t]=await Promise.all([Ce(Ee.show(["--no-patch","--format=%ci"])),Ce(Ee.show(["-s","--pretty=%B"])),Ce(Ee.show(["-s","--pretty=%an"]))]),r=process.env.BUILDKITE_REPO,o=r?.includes("github.com"),i=r?.includes("gitlab.com"),s=r?ql(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 JN(){let[n,e,t]=await Promise.all([Ce(Ee.show(["--no-patch","--format=%ci"])),Ce(Ee.show(["-s","--pretty=%B"])),Ce(Ee.show(["-s","--pretty=%an"]))]),r=process.env["Build.Repository.Uri"],o=r?.includes("github.com"),i=r?.includes("gitlab.com"),s=r?ql(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 XN(){let[n,e,t,r,o,i,s]=await Promise.all([Ce(Ee.revparse(["HEAD"])),Ce(Ee.revparse(["--short","HEAD"])),Ce(Ee.revparse(["--abbrev-ref","HEAD"])),Ce(Ee.listRemote(["--get-url","origin"])),Ce(Ee.show(["--no-patch","--format=%ci"])),Ce(Ee.show(["-s","--pretty=%B"])),Ce(Ee.show(["-s","--pretty=%an"]))]),a=r?.includes("github.com"),l=r?.includes("gitlab.com"),c=r?ql(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 Kl(n){let e=GN();if(!e)return n.debug("No CI run environment detected, falling back to git"),XN();switch(n.debug(`Using CI runner environment variables from ${e} to get git metadata`),e){case"GithubActions":return VN();case"GitlabCI":return qN();case"CircleCI":return KN();case"Buildkite":return YN();case"AzureDevOps":return JN()}}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}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 finish(e){let{step:t}=e,r={...this.metadata,status:t.status,finishedAt:t.finishedAt,message:t.message};this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)})}async startSubSteps(){let e=this.diskStorage.cd("substeps");return new Yl(this.testId,this.testName,e,this.billingReporter,this.asyncWork)}},Yl=class{constructor(e,t,r,o,i){this.testId=e;this.testName=t;this.diskStorage=r;this.billingReporter=o;this.asyncWork=i}getParentStepIdChain(){return[]}async startStep(e){let{logger:t,step:r}=e;this.asyncWork.push(ai(t,this.billingReporter,this.testId,this.testName,r));let o=this.diskStorage.cd(r.id),i={step:r,status:"RUNNING",startedAt:new Date};return o.storeFile({name:"metadata.json",contents:JSON.stringify(i,null,2)}),new yu(this.testId,this.testName,i,o,this.billingReporter,this.asyncWork)}},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}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){let{logger:t,result:r,updatedSteps:o}=e;if(this.metadata.status=r.status,this.metadata.finishedAt=new Date,this.metadata.results=r.results,this.metadata.beforeResults=r.beforeResults,this.metadata.afterResults=r.afterResults,this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)}),r?.status!=="PASSED"||!o)return;let i=ZN(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 mt({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(){let e=this.diskStorage.cd("steps");return new Yl(this.testId,this.testName,e,this.billingReporter,this.asyncWork)}},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}get envVarBindings(){return{[Da]:this.internalRunId}}async finish(e){let t={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1};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"};return e.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),new bu(this.orgId,this.testId,this.testName,this.originalSteps,t,this.client,e,this.billingReporter,this.asyncWork)}},Jl=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=[]}asyncWork;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start(e,t,r,o){let i=await Kl(y),s=Vv(),a={...i,trigger:Pt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:jt||He},l=new Rs(t);return l.storeFile({name:"metadata.json",contents:JSON.stringify(a,null,2)}),new n(e,s,a,r,l,o)}async finish(e){let{status:t}=e,r={...this.metadata,status:t,updatedAt:new Date,finishedAt:new Date};this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)}),await Promise.allSettled(this.asyncWork)}trackStatus(){}async startRun(e){let t=Vv(),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:jt,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0};return 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})),new wu(this.orgId,e.testId,e.testName,t,e.originalSteps,o,this.client,r,this.billingReporter,this.asyncWork)}};import{diff as QN}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 Xl(this.orgId,this.testId,this.testName,this.runId,this.attemptId,this.originalSteps,this.client,this.analytics,this.debugDataStorage,this.billingReporter,this.asyncWork)}},Xl=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(ai(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=QN(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 mt({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 Xl(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{[Da]: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)}},Zl=class n{constructor(e,t,r,o,i,s,a){this.orgId=e;this.runGroupId=t;this.gitMetadata=r;this.client=o;this.analytics=i;this.debugDataStorage=s;this.billingReporter=a;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 Kl(y),{id:a}=await t.createRunGroup({...s,trigger:Pt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:jt}),l=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:a});return new n(e,a,s,t,l,o,i)}async finish(e){let{status:t}=e,r=new Date;await this.client.updateRunGroup(this.runGroupId,{status:t,finishedAt:r});let o=r.getTime()-e.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:jt,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 qv(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:x,reporter:b,include:w,exclude:E,labels:C,reporterDir:I="reports",outputDir:N,waitOnTimeout:P=60,parallel:D=p.config.parallel??1,shardIndex:W=1,shardCount:_=1,regenerateGoldenFiles:B}=n;o&&(e.info({orgId:g},`Executing start command: ${o}`),await Ww(o,!1)),i&&(e.info({orgId:g},`Waiting for url: ${i} with timeout: ${P} seconds.`),await t_({resources:[i],interval:2500,timeout:P*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let L=new Ro({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:e}),j=ke(p,y),O=await Bv({tests:t,momenticFiles:j,yes:r,project:p,include:w,exclude:E,labels:C}),ee=[];O.forEach((Ue,Wn)=>{x?x.forEach((to,ft)=>{ee.push({testIndex:Wn,inputs:to,inputIndex:ft})}):ee.push({testIndex:Wn,inputs:void 0,inputIndex:void 0})}),_&&_>1&&(ee=n_(ee,W,_));let me=`Running ${ee.length} tests with ${D} 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 tt=[],ce=new Date,Se=new Set,De=()=>{let Ue=s.getAppUrl(),Wn=ii({results:tt,startTime:ce.getTime(),onFailed:ft=>{Hl(ft,ft.filePath)},getDisplayLine:ft=>{let Sr=` - ${ft.filePath}${ft.proposedTest?" [AUTO-HEALED] ":""}`;return d&&ft.runId&&(Sr+=` (${Ue}/runs/${ft.runId})`),Sr},entity:"test"}),to=tt.filter(ft=>!!ft.proposedTest);return to.length>0&&y.warn(`${to.length} tests passed with auto-healing. Please use the run links printed above to review proposed changes and apply them locally.`),Wn},nt=new Vl(l);N?nt=await Jl.start(g,N,s,l):d&&(nt=await Zl.start(g,s,c,a,l));let Ft=e.child(nt.loggerBindings||{}),Pn=[],G=async()=>{y.warn("SIGINT received. Stopping tests and printing latest results..."),await nt.finish({startedAt:ce,status:"CANCELLED"}),De(),await Promise.allSettled(Pn.map(Ue=>Ue())),process.exit(1)};process.on("SIGINT",G);let tn={};for(let Ue=0;Ue<ee.length;Ue++){let Wn=Object.values(tn);Wn.length===D&&await Promise.race(Wn.map(Sr=>Sr.promise));let to=ee[Ue],ft=`test-${Ue}`;tn[ft]={done:!1,promise:(async({testIndex:Sr,inputs:Ru})=>{let di=O[Sr];Se.add({testIndex:Sr,inputs:Ru});let rx=di.relativeFilePath.includes("..")?di.fullFilePath:di.relativeFilePath,As=(lt,pi)=>{let no=(tc,Au)=>{let ix=Math.floor((Au-tc.length)/2);return tc.padStart(ix+tc.length).padEnd(Au)};lt=lt.toUpperCase();let Ln=lt;lt.includes("FAIL")?Ln=li.bgRed.white(no("FAIL",8)):lt.includes("PASS")?Ln=li.bgGreen.white(no("PASS",8)):lt.includes("START")?Ln=li.bgBlue.white(no("START",8)):lt.includes("CANCEL")?Ln=li.bgYellow.white(no("CANCEL",8)):lt.includes("RETRY")?Ln=li.bgYellow.white(no("RETRY",8)):lt.includes("RUN")||lt.includes("PROG")?Ln=li.bgMagenta.white(no("RUNNING",8)):Ft.warn(`Unknown status tried to be logged in run test locally: ${lt}`),e_||(Ln=`[${Ln}]`),y.log(`${Ln} ${rx} ${pi?`${pi} `:""}(${Se.size}/${ee.length})`)};As("START");let ox=setInterval(()=>As("RUN"),5*60*1e3);try{let lt=await Gv({testDefinition:di,project:p,testInputs:Ru,orgId:g,devicePixelRatio:f,apiClient:s,runGroupTracer:nt,generator:L,retriesOverride:u,urlOverride:m,envName:h,noReport:!d,customHeaders:S,regenerateGoldenFiles:B,logUpdate:As,runSigIntHandlers:d?Pn:void 0,logger:Ft});As(lt.status),tt.push(lt)}catch(lt){let pi=`Encountered unexpected fatal error when running test '${di.name}': ${lt.message}`;y.error(pi),Ft.error(pi)}finally{clearInterval(ox),tn[ft].done=!0,delete tn[ft]}})(to)}}await Promise.allSettled(Object.values(tn).map(Ue=>Ue.promise));let ci="PASSED";return tt.some(Ue=>Ue.status==="FAILED")&&(ci="FAILED"),await nt.finish({startedAt:ce,status:ci}),process.off("SIGINT",G),b&&await Uv(Ft,a,b,{projectConfigPath:p.configFilePath,suiteName:p.config.name,startedAt:ce,finishedAt:new Date,runs:tt},I??"reports"),De()}function n_(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 eo from"path";var Kv={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 Yv(n,e){let t=n[e];if(!t)throw new Error(`No metadata value found for key: ${e}`);return t}function r_(n,e,t){let r=Yv(n,t),o=Yv(e,t);if(t in Kv){let i=Kv[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 Jv(n,e){$n.rmSync(n,{recursive:!0,force:!0});let t=$n.readdirSync(e).filter(s=>s!==".DS_Store").map(s=>eo.join(e,s));$n.mkdirSync(n,{recursive:!0});let r=eo.join(t[0],"metadata.json"),o=od.parse(JSON.parse($n.readFileSync(r,"utf-8")));for(let s of t){let a=eo.join(s,"runs");if(!$n.existsSync(a))continue;let l=$n.readdirSync(a);for(let d of l){let u=eo.join(a,d),m=eo.join(n,"runs",d);$n.cpSync(u,m,{recursive:!0})}let c=eo.join(s,"metadata.json"),p=od.parse(JSON.parse($n.readFileSync(c,"utf-8")));for(let d in p){let u=d;o[u]=r_(o,p,u)}}let i=eo.join(n,"metadata.json");$n.writeFileSync(i,JSON.stringify(o,null,2))}import Xv from"adm-zip";import o_ from"fs";import Ql from"path";function Zv(n){let e=new Xv;e.addLocalFile(Ql.join(n,"metadata.json"));for(let t of o_.readdirSync(Ql.join(n,"runs"))){if(!t.endsWith(".zip"))continue;let r=t.replace(/\.zip$/,""),o=new Xv(Ql.join(n,"runs",t));for(let i of o.getEntries())i.isDirectory||e.addFile(Ql.join("runs",r,i.entryName),i.getData())}return e.toBuffer()}var Qv=new ni({platform:"cli"},{flushAt:1,flushInterval:0});rc||Q.warn("Sentry is not enabled in this environment due to unsupported node version");var d_=process.argv.some(n=>n.includes("--log-level"))&&process.argv.some(n=>n.includes("debug")),Eu=n=>{d_&&y.dimmed(n)},Tt=new i_;Tt.name("momentic").description("CLI").version(jt||"unknown");Tt.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 Zr(Cv(n),e.force)});Tt.addOption(new en("--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())});Tt.addOption(new en("--verbose","enable verbose logging")).on("option:verbose",()=>{Q.enableConsoleLogs(),y.setMinLevel(0)});Tt.command("check-config").addOption(fr).action(async n=>{gn({configFilePath:n.config})});var ex=Tt.command("checks").alias("check").description("Perform various project checks");ex.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(fr).addOption(fv).action(async n=>{let e=await fn(n),t=gn({configFilePath:n.config});await Zw({project:t,fix:e.fix})});ex.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(fr).action(async n=>{let e=gn({configFilePath:n.config});await Qw({project:e})});var p_=Tt.command("migrate").description("Migrate and upgrade tooling");p_.command("v0-v1").addOption(gr).addOption(jn).action(async n=>{let e=await fn(n);if(!e.yes&&!await at("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),!iv().environments?.length&&await at("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 it({baseUrl:o,apiKey:r,logger:Q});await Nl({client:s,project:i,skipPrompts:e.yes}),y.success("Successfully imported environments from Momentic Cloud.")}});Tt.command("import-from-cloud").addOption(jn).addOption(hr).addOption(fr).addOption(gr).action(async n=>{let e=await fn(n),{apiKey:t,server:r,config:o,yes:i}=e,s=gn({configFilePath:o}),a=new it({baseUrl:r,apiKey:t,logger:Q});await ov({client:a,project:s,skipPrompts:i}),process.exit(0)});Tt.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new en("--name <name>","Name of the project")).action(async n=>{y.info(`Welcome to the Momentic project setup wizard! \u{1F680}
3591
- `),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(Jo)&&(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 Yw("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:ws};Xo(t,Jo),y.success(`Initialized Momentic project file at ${ec.resolve(Jo)}`)});Tt.command("app").addOption(jn).addOption(hr).addOption(gr).addOption(ou).addOption(mv).addOption(fr).action(async n=>{let e=await fn(n),{apiKey:t,port:r=_l,yes:o,server:i,pixelRatio:s}=e,a=new it({baseUrl:i,apiKey:t,logger:Q});await lu({client:a,skipPrompts:o,installBrowsers:!0});let l=c_(import.meta.url),c=ec.dirname(l),p=ec.resolve(c,"..","static"),d=ec.resolve(c,"..","assets"),u=s??Kp();Yp(u),ui(),await jw({momenticServerUrl:i,apiKey:t,serverPort:r,appPort:r,staticDir:p,assetsDir:d,devicePixelRatio:u,version:"1.1.3"});let m=`http://localhost:${r}`;await l_(m)});var tx=Tt.command("queue").description("Queue tests or suites to run on Momentic Cloud");tx.command("suites").description("Run one or more suites on Momentic Cloud").addOption(jn).addOption(hr).addOption(eu).addOption(tu).addOption(gr).addArgument(bv).addOption(Dl).addOption(Fl).addOption(Ml).action(async(n,e)=>{let{apiKey:t,server:r,wait:o,waitTimeout:i,env:s,urlOverride:a,customHeaders:l}=await fn(e),c=new it({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 Lv({client:c,orgId:p,wait:o,suitePaths:n,waitTimeout:i,env:s,urlOverride:a,customHeaders:Ul(l)})});tx.command("tests").description("Run one or more tests on Momentic Cloud").addOption(jn).addOption(hr).addOption(gr).addOption(Ml).addOption(iu).addOption(Dl).addOption(Fl).addOption(eu).addOption(tu).addArgument(Sv).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=Ul(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 it({baseUrl:a,apiKey:o,logger:Q}),{orgId:g}=await h.getAuthInfo(),f;l&&(f=await Jp(l)),await Ov({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 u_=Tt.command("run").alias("test").description("Run tests on the local machine");u_.addOption(jn).addOption(hr).addOption(fr).addOption(su).addOption(gr).addOption(Ml).addOption(iu).addOption(Fl).addOption(Dl).addOption(nu).addOption(ou).addOption(new en("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new en("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new en("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.")).addOption(new en("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.")).addOption(new en("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.")).addOption(new en("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new en("--update-golden-files","Update locally stored golden files for steps that this is enabled for.")).addOption(nu).addOption(cv).addOption(dv).addOption(ru).addOption(hv).addOption(gv).addOption(pv).addOption(uv).addArgument(yv).action(async(n,e)=>{y.debug("Run tests invoked");let t=await fn(e);y.debug(t,"Parsed CLI options");let r=Ul(t.customHeaders),o=gn({configFilePath:t.config,nameFilter:t.filter});y.debug({projectName:o.config.name},"Identified project config");let i=new it({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 wa(i),c=new va(i),p=t.outputDir??o.config.outputDir,d=Qv.child({org_id:s,user_id:a,cli_version:jt,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:jt,trigger:"CLI"});try{(await qv({...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 m_=Tt.command("apply").description("Apply an operation to local resources");m_.command("patch").addOption(jn).addOption(hr).addOption(fr).addOption(su).addOption(gr).addOption(new en("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new en("--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 it({baseUrl:r,apiKey:t,logger:Q}),l=ke(s,y),c=l.tests[n.to]??Object.values(l.tests).find(d=>Pe(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 Jw({client:a,test:c,fragment:p,yes:i,entities:l,logger:Q}),process.exit(0)});var nx=Tt.command("results").description("Merge and upload test results.");nx.command("merge").description("Merge test results files.").addOption(ru).addArgument(wv).action(async(n,e)=>{let t=await fn(e),{outputDir:r}=t;r||(y.error("Output directory is required."),process.exit(1)),Jv(r,n)});nx.command("upload").description("Upload test results to Momentic cloud.").addOption(jn).addOption(hr).addArgument(vv).action(async(n,e)=>{let t=await fn(e),{apiKey:r,server:o}=t,i=new it({baseUrl:o,apiKey:r,logger:Q}),s=new La(i);try{let a=Zv(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 h_(){Eu("Main program started"),await Gw(Q),Eu("CLI version check complete");try{await Tt.parseAsync(process.argv),ui()}catch(n){let e={};try{e.playwrightVersion=s_("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(),nc(n,e),y.error(n),ui(),process.exit(1)}}a_.setMaxListeners(50);process.on("warning",n=>{Q.warn({err:n},`Node warning received on CLI: ${n.message}`)});Eu("CLI parsing setup complete");h_();
3591
+ `),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(Jo)&&(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 Yw("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:ws};Xo(t,Jo),y.success(`Initialized Momentic project file at ${ec.resolve(Jo)}`)});Tt.command("app").addOption(jn).addOption(hr).addOption(gr).addOption(ou).addOption(mv).addOption(fr).action(async n=>{let e=await fn(n),{apiKey:t,port:r=_l,yes:o,server:i,pixelRatio:s}=e,a=new it({baseUrl:i,apiKey:t,logger:Q});await lu({client:a,skipPrompts:o,installBrowsers:!0});let l=c_(import.meta.url),c=ec.dirname(l),p=ec.resolve(c,"..","static"),d=ec.resolve(c,"..","assets"),u=s??Kp();Yp(u),ui(),await jw({momenticServerUrl:i,apiKey:t,serverPort:r,appPort:r,staticDir:p,assetsDir:d,devicePixelRatio:u,version:"1.1.4"});let m=`http://localhost:${r}`;await l_(m)});var tx=Tt.command("queue").description("Queue tests or suites to run on Momentic Cloud");tx.command("suites").description("Run one or more suites on Momentic Cloud").addOption(jn).addOption(hr).addOption(eu).addOption(tu).addOption(gr).addArgument(bv).addOption(Dl).addOption(Fl).addOption(Ml).action(async(n,e)=>{let{apiKey:t,server:r,wait:o,waitTimeout:i,env:s,urlOverride:a,customHeaders:l}=await fn(e),c=new it({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 Lv({client:c,orgId:p,wait:o,suitePaths:n,waitTimeout:i,env:s,urlOverride:a,customHeaders:Ul(l)})});tx.command("tests").description("Run one or more tests on Momentic Cloud").addOption(jn).addOption(hr).addOption(gr).addOption(Ml).addOption(iu).addOption(Dl).addOption(Fl).addOption(eu).addOption(tu).addArgument(Sv).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=Ul(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 it({baseUrl:a,apiKey:o,logger:Q}),{orgId:g}=await h.getAuthInfo(),f;l&&(f=await Jp(l)),await Ov({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 u_=Tt.command("run").alias("test").description("Run tests on the local machine");u_.addOption(jn).addOption(hr).addOption(fr).addOption(su).addOption(gr).addOption(Ml).addOption(iu).addOption(Fl).addOption(Dl).addOption(nu).addOption(ou).addOption(new en("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new en("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new en("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.")).addOption(new en("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.")).addOption(new en("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.")).addOption(new en("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new en("--update-golden-files","Update locally stored golden files for steps that this is enabled for.")).addOption(nu).addOption(cv).addOption(dv).addOption(ru).addOption(hv).addOption(gv).addOption(pv).addOption(uv).addArgument(yv).action(async(n,e)=>{y.debug("Run tests invoked");let t=await fn(e);y.debug(t,"Parsed CLI options");let r=Ul(t.customHeaders),o=gn({configFilePath:t.config,nameFilter:t.filter});y.debug({projectName:o.config.name},"Identified project config");let i=new it({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 wa(i),c=new va(i),p=t.outputDir??o.config.outputDir,d=Qv.child({org_id:s,user_id:a,cli_version:jt,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:jt,trigger:"CLI"});try{(await qv({...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 m_=Tt.command("apply").description("Apply an operation to local resources");m_.command("patch").addOption(jn).addOption(hr).addOption(fr).addOption(su).addOption(gr).addOption(new en("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new en("--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 it({baseUrl:r,apiKey:t,logger:Q}),l=ke(s,y),c=l.tests[n.to]??Object.values(l.tests).find(d=>Pe(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 Jw({client:a,test:c,fragment:p,yes:i,entities:l,logger:Q}),process.exit(0)});var nx=Tt.command("results").description("Merge and upload test results.");nx.command("merge").description("Merge test results files.").addOption(ru).addArgument(wv).action(async(n,e)=>{let t=await fn(e),{outputDir:r}=t;r||(y.error("Output directory is required."),process.exit(1)),Jv(r,n)});nx.command("upload").description("Upload test results to Momentic cloud.").addOption(jn).addOption(hr).addArgument(vv).action(async(n,e)=>{let t=await fn(e),{apiKey:r,server:o}=t,i=new it({baseUrl:o,apiKey:r,logger:Q}),s=new La(i);try{let a=Zv(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 h_(){Eu("Main program started"),await Gw(Q),Eu("CLI version check complete");try{await Tt.parseAsync(process.argv),ui()}catch(n){let e={};try{e.playwrightVersion=s_("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(),nc(n,e),y.error(n),ui(),process.exit(1)}}a_.setMaxListeners(50);process.on("warning",n=>{Q.warn({err:n},`Node warning received on CLI: ${n.message}`)});Eu("CLI parsing setup complete");h_();
3592
3592
  /*! Bundled license information:
3593
3593
 
3594
3594
  is-buffer/index.js:
@@ -3600,4 +3600,4 @@ is-buffer/index.js:
3600
3600
  *)
3601
3601
  */
3602
3602
  //# sourceMappingURL=cli.js.map
3603
- //# debugId=db115a00-082c-55ef-b6e5-7fbf05267b88
3603
+ //# debugId=13012ffc-d6dc-5b22-8381-06f1a7d8b176
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "momentic",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "bin": {
5
5
  "momentic": "./bin/cli.js"
6
6
  },