momentic 1.4.0 → 1.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js
CHANGED
|
@@ -1,57 +1,60 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
4
|
-
var cx=Object.create;var Iu=Object.defineProperty;var dx=Object.getOwnPropertyDescriptor;var px=Object.getOwnPropertyNames;var ux=Object.getPrototypeOf,mx=Object.prototype.hasOwnProperty;var sn=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var hx=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of px(e))!mx.call(n,o)&&o!==t&&Iu(n,o,{get:()=>e[o],enumerable:!(r=dx(e,o))||r.enumerable});return n};var Pu=(n,e,t)=>(t=n!=null?cx(ux(n)):{},hx(e||!n||!n.__esModule?Iu(t,"default",{value:n,enumerable:!0}):t,n));var Af=sn((tq,Rf)=>{"use strict";Rf.exports=Ef;function Ef(n,e,t){n instanceof RegExp&&(n=Tf(n,t)),e instanceof RegExp&&(e=Tf(e,t));var r=Cf(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 Tf(n,e){var t=e.match(n);return t?t[0]:null}Ef.range=Cf;function Cf(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 Mf=sn((nq,_f)=>{"use strict";var If=Af();_f.exports=qR;var Pf="\0SLASH"+Math.random()+"\0",Lf="\0OPEN"+Math.random()+"\0",wd="\0CLOSE"+Math.random()+"\0",Of="\0COMMA"+Math.random()+"\0",kf="\0PERIOD"+Math.random()+"\0";function bd(n){return parseInt(n,10)==n?parseInt(n,10):n.charCodeAt(0)}function GR(n){return n.split("\\\\").join(Pf).split("\\{").join(Lf).split("\\}").join(wd).split("\\,").join(Of).split("\\.").join(kf)}function VR(n){return n.split(Pf).join("\\").split(Lf).join("{").split(wd).join("}").split(Of).join(",").split(kf).join(".")}function Nf(n){if(!n)return[""];var e=[],t=If("{","}",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=Nf(i);return i.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),e.push.apply(e,s),e}function qR(n){return n?(n.substr(0,2)==="{}"&&(n="\\{\\}"+n.substr(2)),es(GR(n),!0).map(VR)):[]}function KR(n){return"{"+n+"}"}function YR(n){return/^-?0\d/.test(n)}function JR(n,e){return n<=e}function XR(n,e){return n>=e}function es(n,e){var t=[],r=If("{","}",n);if(!r)return[n];var o=r.pre,i=r.post.length?es(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+wd+r.post,es(n)):[n];var u;if(p)u=r.body.split(/\.\./);else if(u=Nf(r.body),u.length===1&&(u=es(u[0],!1).map(KR),u.length===1))return i.map(function(z){return r.pre+u[0]+z});var m;if(p){var h=bd(u[0]),g=bd(u[1]),f=Math.max(u[0].length,u[1].length),S=u.length==3?Math.abs(bd(u[2])):1,x=JR,v=g<h;v&&(S*=-1,x=XR);var b=u.some(YR);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),b){var I=f-C.length;if(I>0){var _=new Array(I+1).join("0");E<0?C="-"+_+C.slice(1):C=_+C}}m.push(C)}}else{m=[];for(var L=0;L<u.length;L++)m.push.apply(m,es(u[L],!1))}for(var L=0;L<m.length;L++)for(var s=0;s<i.length;s++){var a=o+m[L]+i[s];(!e||p||a)&&t.push(a)}}return t}});var vb=sn((bl,Tp)=>{"use strict";(function(n){typeof define=="function"&&define.amd?define([],n):typeof bl=="object"?(bl=n(),typeof Tp=="object"&&(Tp.exports=bl)):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(v){return this._superClass==o?!1:v==this._superClass||v==o?!0:this._superClass._extends(v)};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 Tb=sn((Uee,xb)=>{"use strict";var mO=vb(),Jr=mO._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 Jr(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 Jr(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 Jr(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(Jr.prototype,"all",{get:function(){return this._list}});Object.defineProperty(Jr.prototype,"map",{get:function(){return this._map}});xb.exports=Jr;typeof window<"u"&&(window.HashArray=Jr)});var Cb=sn((Bee,Eb)=>{"use strict";Eb.exports=Tb()});var Ab=sn((zee,Rb)=>{"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}};Rb.exports=e})()});var Cp=sn((jee,Ib)=>{"use strict";var Ep={utf8:{stringToBytes:function(n){return Ep.bin.stringToBytes(unescape(encodeURIComponent(n)))},bytesToString:function(n){return decodeURIComponent(escape(Ep.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("")}}};Ib.exports=Ep});var Ob=sn((Hee,Lb)=>{"use strict";Lb.exports=function(n){return n!=null&&(Pb(n)||hO(n)||!!n._isBuffer)};function Pb(n){return!!n.constructor&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}function hO(n){return typeof n.readFloatLE=="function"&&typeof n.slice=="function"&&Pb(n.slice(0,0))}});var Nb=sn(($ee,kb)=>{"use strict";(function(){var n=Ab(),e=Cp().utf8,t=Ob(),r=Cp().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,v=p,b=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+v>>>0,d=d+b>>>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,kb.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 Mb=sn((Wee,Ip)=>{"use strict";var Rp=Cb(),gO=Nb(),fO=1024,_b=/^[\s]*$/,SO=[{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 xs=function(n,e){this.options=e||{},this.options.ignoreCase=this.options.ignoreCase===void 0?!0:this.options.ignoreCase,this.options.maxCacheSize=this.options.maxCacheSize||fO,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||SO,this.options.insertFullUnsplitKey=this.options.hasOwnProperty("insertFullUnsplitKey")?this.options.insertFullUnsplitKey:!1,this.options.defaultReducer=this.options.hasOwnProperty("defaultReducer")?this.options.defaultReducer:xs.UNION_REDUCER,this.keyFields=n?n instanceof Array?n:[n]:[],this.root={},this.size=0,this.options.cache&&(this.getCache=new Rp("key"))};function Ap(n,e){return e.length===1?n[e[0]]:Ap(n[e[0]],e.slice(1,e.length))}xs.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?Ap(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 Rp("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 _b.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++)_b.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 Rp([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]:Ap(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 gO(t)}return typeof this.options.idFieldOrFunction=="function"?this.options.idFieldOrFunction(n):n[this.options.idFieldOrFunction]}};xs.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};Ip.exports=xs;Ip.exports.default=xs});var Db=sn((Gee,Fb)=>{"use strict";Fb.exports=Mb()});var oc=(n,e)=>{},ic=!1;try{let n=await import("@sentry/node");oc=n.captureException,n.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME}),ic=!0}catch{}import{Command as h_,Option as on}from"@commander-js/extra-typings";import{execSync as g_}from"child_process";import zw from"body-parser";import $k from"cors";import Wk from"dedent";import Gk from"events";import jw,{Router as Vk}from"express";import{diff as HR}from"deep-object-diff";import _t from"fs";import Bt from"path";import{z as Lu}from"zod";var I_=Lu.object({input:Lu.string()});import{z as ze}from"zod";var O_=ze.object({srcs:ze.array(ze.string()),urls:ze.array(ze.string()),desiredSrc:ze.string().optional(),desiredUrl:ze.string().optional()}),Ou=ze.object({srcRegex:ze.string().optional(),urlRegex:ze.string().optional()}),ku=ze.object({x:ze.number(),y:ze.number(),correlation:ze.number()}),k_=ze.object({searchImageBase64String:ze.string(),pageImageBase64String:ze.string(),id:ze.string().uuid(),timeoutMs:ze.number().max(1e4).min(0).optional()});import{z as k}from"zod";import{v4 as Ae}from"uuid";import*as w from"zod";function ye(n){if(typeof n.ZodType.prototype.openapi<"u")return;n.ZodType.prototype.openapi=function(o){return new this.constructor({...this._def,openapi:o})};let e=n.ZodObject.prototype.extend;n.ZodObject.prototype.extend=function(...o){let i=e.apply(this,o);return i._def.extendMetadata={extends:this},delete i._def.openapi,i};let t=n.ZodObject.prototype.omit;n.ZodObject.prototype.omit=function(...o){let i=t.apply(this,o);return delete i._def.extendMetadata,delete i._def.openapi,i};let r=n.ZodObject.prototype.pick;n.ZodObject.prototype.pick=function(...o){let i=r.apply(this,o);return delete i._def.extendMetadata,delete i._def.openapi,i}}import{z as he}from"zod";ye(he);var Nu=he.object({plan:he.string().optional(),evidence:he.string().optional(),thoughts:he.string(),result:he.boolean(),relevantElements:he.array(he.number()).optional()}),so=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(so||{});var gx=he.object({type:he.literal("ELEMENT_CONTENT"),negated:he.boolean().optional(),operation:he.nativeEnum(so),value:he.string()}).openapi({ref:"ElementContentAssertion"}),fx=he.object({type:he.literal("ELEMENT_ATTRIBUTE"),negated:he.boolean().optional(),operation:he.nativeEnum(so),attr:he.string(),value:he.string()}).openapi({ref:"ElementAttributeValueAssertion"}),fi=(o=>(o.EXISTS="EXISTS",o.VISIBLE="VISIBLE",o.ENABLED="ENABLED",o.EDITABLE="EDITABLE",o))(fi||{}),Sx=he.object({type:he.literal("ELEMENT_EXISTENCE"),negated:he.boolean().optional(),condition:he.nativeEnum(fi).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),_u=he.discriminatedUnion("type",[gx,fx,Sx]).openapi({ref:"ManualElementAssertion"});var yx=he.object({type:he.literal("CONTENT"),negated:he.boolean().optional(),value:he.string()}).openapi({ref:"PageContentAssertion"}),Mu=he.discriminatedUnion("type",[yx]).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||{}),bx=K.object({mPathSelectorTokens:K.string().array(),frameSrcRegex:K.string().optional(),frameUrlRegex:K.string().optional(),indices:K.number().array()}),wr=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:bx.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 wx=K.object({type:K.literal("description"),elementDescriptor:K.string(),a11yData:wr.optional().describe("DEPRECATED: new a11y cache is stored in DB and resolved into the 'cache' field")}).openapi({ref:"DescriptionTarget"}),vx=K.object({x:K.number(),y:K.number()}),xx=K.object({type:K.literal("coordinates"),pixels:vx}).openapi({ref:"CoordinatesTarget"});function Vn(n){return n.type==="description"}function yn(n){return n.type==="coordinates"}var ct=K.discriminatedUnion("type",[wx,xx]).openapi({ref:"ElementTarget"});function sc(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 ks=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")}),Ns=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 Ue=(W=>(W.AI_EXTRACT="AI_EXTRACT",W.AI_ASSERTION="AI_ASSERTION",W.AI_WAIT="AI_WAIT",W.AUTH_LOAD="AUTH_LOAD",W.AUTH_SAVE="AUTH_SAVE",W.BLUR="BLUR",W.CAPTCHA="CAPTCHA",W.CLICK="CLICK",W.COOKIE="COOKIE",W.COPY="COPY",W.DIALOG="DIALOG",W.DRAG="DRAG",W.ELEMENT_CHECK="ELEMENT_CHECK",W.FILE_UPLOAD="FILE_UPLOAD",W.FOCUS="FOCUS",W.GO_BACK="GO_BACK",W.GO_FORWARD="GO_FORWARD",W.HOVER="HOVER",W.JAVASCRIPT="JAVASCRIPT",W.LOCAL_STORAGE="LOCAL_STORAGE",W.MOUSE_DRAG="MOUSE_DRAG",W.NAVIGATE="NAVIGATE",W.NEW_TAB="NEW_TAB",W.PAGE_CHECK="PAGE_CHECK",W.PASTE="PASTE",W.PRESS="PRESS",W.REFRESH="REFRESH",W.REQUEST="REQUEST",W.GRAPHQL_REQUEST="GRAPHQL_REQUEST",W.SCROLL_DOWN="SCROLL_DOWN",W.SCROLL_UP="SCROLL_UP",W.SCROLL_LEFT="SCROLL_LEFT",W.SCROLL_RIGHT="SCROLL_RIGHT",W.SELECT_OPTION="SELECT_OPTION",W.SWITCH_TAB="TAB",W.TYPE="TYPE",W.VISUAL_DIFF="VISUAL_DIFF",W.WAIT="WAIT",W.WAIT_FOR_URL="WAIT_FOR_URL",W.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",W.AWAIT_LISTENER="AWAIT_LISTENER",W.SUCCESS="SUCCESS",W))(Ue||{});ye(w);var Y=w.object({thoughts:w.string().optional(),id:w.string().uuid().describe("unique identifier to this step, used for step cache")}),Gt=w.object({useSelector:w.boolean().optional(),force:w.boolean().optional(),disableCache:w.boolean().optional().describe("disable element caching for this step"),iframeUrl:w.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),bn=w.object({target:wr}).optional().openapi({ref:"SingleTargetCache"}),Ms=w.object({loadTimeout:w.number().int().max(60).optional().describe("Max seconds for the page to load")}),Tx=Y.merge(Ms).merge(w.object({type:w.literal("NAVIGATE"),url:w.string()})).openapi({ref:"NavigateCommand"}),Fs=Gt.merge(w.object({cache:bn})),ao=Y.merge(Fs.merge(w.object({target:ct.optional(),type:w.literal("SCROLL_UP"),deltaY:w.number().optional()}))).openapi({ref:"ScrollUpCommand"}),lo=Y.merge(Fs.merge(w.object({target:ct.optional(),type:w.literal("SCROLL_DOWN"),deltaY:w.number().optional()}))).openapi({ref:"ScrollDownCommand"}),co=Y.merge(Fs.merge(w.object({target:ct.optional(),type:w.literal("SCROLL_LEFT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),po=Y.merge(Fs.merge(w.object({target:ct.optional(),type:w.literal("SCROLL_RIGHT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollRightCommand"}),Y_=w.discriminatedUnion("type",[ao,lo,co,po]).openapi({ref:"AllScrollCommands"}),Ex=Y.merge(w.object({type:w.literal("DIALOG"),action:w.union([w.literal("ACCEPT"),w.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),Cx=Y.merge(w.object({type:w.literal("WAIT"),delay:w.number()})).openapi({ref:"WaitCommand"}),Rx=w.discriminatedUnion("type",[w.object({type:w.literal("SUBSTRING"),url:w.string()}),w.object({type:w.literal("GLOB"),glob:w.string()}),w.object({type:w.literal("REGEX"),regex:w.string()})]),Ax=w.object({caseInsensitive:w.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:w.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:w.number().int().optional().describe("Max seconds to wait for the URL to match")}),Ix=Y.extend({type:w.literal("WAIT_FOR_URL"),url:w.string().optional().describe("Deprecated: url or glob to wait for. New commands should use the discriminated matcher field."),matcher:Rx.optional()}).merge(Ax).openapi({ref:"WaitUrlCommand"}),Px=Y.merge(Ms).merge(w.object({type:w.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),Lx=Y.merge(w.object({type:w.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),Ox=Y.merge(w.object({type:w.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),kx=Y.extend({type:w.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),Nx=Y.extend({type:w.literal("AUTH_LOAD"),storageState:w.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),lc=Y.merge(Gt).extend({type:w.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),_x=Y.extend({type:w.literal("COPY"),value:w.string()}).openapi({ref:"CopyCommand"}),Mx=Y.extend({type:w.literal("PASTE")}).openapi({ref:"PasteCommand"}),Fx=Y.merge(Ns).extend({type:w.literal("JAVASCRIPT"),envKey:w.string().optional()}).openapi({ref:"JavaScriptCommand"}),Si=Y.merge(Gt).merge(w.object({type:w.literal("CLICK"),target:ct,doubleClick:w.boolean().optional(),rightClick:w.boolean().optional(),waitForUrl:w.string().optional().describe("Deprecated: wait for the click to trigger a page load or new tab that matches the provided URL or URL glob (e.g. https://google.com/**/*)."),waitForDownload:w.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:w.number().optional(),downloadTimeoutMs:w.number().optional(),cache:bn,relativePosition:w.object({x:w.number(),y:w.number()}).optional()})).openapi({ref:"ClickCommand"}),yi=Y.merge(Gt).merge(w.object({type:w.literal("DRAG"),fromTarget:ct,toTarget:ct,steps:w.number().optional(),hoverSeconds:w.number().optional().describe("Seconds to hover the object before dropping"),cache:w.object({fromTarget:wr.optional(),toTarget:wr.optional()}).optional()})).openapi({ref:"DragCommand"}),bi=Y.merge(Gt).merge(w.object({type:w.literal("MOUSE_DRAG"),target:ct.optional(),deltaX:w.string().describe("pixels to move horizontally, can be template"),deltaY:w.string().describe("pixels to move vertically, can be template"),steps:w.number().optional(),cache:bn})).openapi({ref:"MouseDragCommand"}),wi=Y.merge(Gt).merge(w.object({type:w.literal("HOVER"),target:ct,cache:bn})).openapi({ref:"HoverCommand"}),vi=Y.merge(Gt).merge(w.object({type:w.literal("FOCUS"),target:ct,cache:bn})).openapi({ref:"FocusCommand"}),xi=Y.merge(Gt).extend({type:w.literal("BLUR"),target:ct.optional(),cache:bn}).openapi({ref:"BlurCommand"}),Dx=w.object({type:w.literal("URL"),url:w.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),Ux=w.object({type:w.literal("USER_FILE"),name:w.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),Bx=Y.extend({type:w.literal("FILE_UPLOAD"),fileSource:w.discriminatedUnion("type",[Dx,Ux]),filename:w.string().optional()}).openapi({ref:"FileUploadCommand"}),zx=w.discriminatedUnion("type",[w.object({type:w.literal("VALUE"),value:w.string()}),w.object({type:w.literal("LABEL"),label:w.string()}),w.object({type:w.literal("INDEX"),index:w.coerce.string()})]),Ti=Y.merge(Gt).extend({type:w.literal("SELECT_OPTION"),target:ct,cache:bn,option:w.string().describe("option value, deprecated old field").optional(),choice:zx.optional().describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),cc=w.union([w.literal("MULTIMODAL"),w.literal("VISION_ONLY")]),dc=Y.merge(w.object({type:w.literal("AI_ASSERTION"),assertion:w.string(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional(),contextChoice:cc.optional(),timeout:w.number().int().optional().describe("Max seconds to wait for assertion to be true")})).openapi({ref:"AIAssertionCommand"}),jx=dc.extend({type:w.literal("AI_WAIT")}).openapi({ref:"AIWaitCommand"}),wn=5,pc=600,Ei=Y.merge(Gt).extend({type:w.literal("ELEMENT_CHECK"),target:ct,assertion:_u,cache:bn,timeout:w.number().int().min(0).max(pc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),Hx=Y.extend({type:w.literal("PAGE_CHECK"),assertion:Mu,iframeUrl:w.string().optional().describe("url or url regex for the iframe"),timeout:w.number().int().min(0).max(pc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),$x=Y.merge(w.object({type:w.literal("AI_EXTRACT"),goal:w.string(),schema:w.string().optional(),envKey:w.string().optional(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional()})).openapi({ref:"AIExtractCommand"}),Wx=w.object({clearContent:w.boolean().optional(),forceClearContent:w.boolean().optional(),pressKeysSequentially:w.boolean().optional().describe("Deprecated: this is now the default. Please set delay to zero if you wish to achieve instant typing behavior."),delay:w.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:w.boolean().optional(),pressEnter:w.boolean().optional()}),Uu=25,Ci=Y.merge(Gt).merge(Wx).extend({type:w.literal("TYPE"),target:ct.optional(),value:w.string(),cache:bn}).openapi({ref:"TypeCommand"}),Gx=Y.merge(w.object({type:w.literal("PRESS"),value:w.string(),repeat:w.number().optional(),convertMeta:w.boolean().optional(),delayMs:w.number().optional()})).openapi({ref:"PressCommand"}),Vx=w.object({type:w.literal("SUBSTRING"),substring:w.string()}),qx=w.object({type:w.literal("REGEX"),pattern:w.string()}),Kx=w.object({type:w.literal("INDEX"),index:w.coerce.string()}),Yx=w.discriminatedUnion("type",[Vx,qx,Kx]),Jx=Y.merge(Ms).merge(w.object({type:w.literal("TAB"),url:w.string().optional().describe("deprecated field - new instances should use the discriminated union"),action:Yx.optional()})).openapi({ref:"TabCommand"}),Xx=Y.merge(Ms).merge(w.object({type:w.literal("NEW_TAB"),url:w.string()})).openapi({ref:"NewTabCommand"}),Zx=Y.merge(w.object({type:w.literal("COOKIE"),value:w.string()})).openapi({ref:"CookieCommand"}),Qx=Y.merge(w.object({type:w.literal("LOCAL_STORAGE"),key:w.string(),value:w.string()})).openapi({ref:"LocalStorageCommand"}),eT=Y.extend({type:w.literal("REQUEST")}).merge(ks).openapi({ref:"RequestCommand"}),tT=Y.extend({type:w.literal("GRAPHQL_REQUEST")}).merge(Du).openapi({ref:"GraphQLRequestCommand"}),nT=Y.merge(w.object({type:w.literal("SUCCESS"),condition:dc.optional()})).openapi({ref:"SuccessCommand"}),rT=Y.merge(w.object({type:w.literal("FAILURE")})).openapi({ref:"FailureCommand"}),oT=w.object({data:w.string().describe("location at which to find a jpg"),width:w.number(),height:w.number()}),Ri=Y.merge(Gt).merge(w.object({type:w.literal("VISUAL_DIFF"),threshold:w.number().optional().describe("default 0.1"),target:ct.optional(),screenshot:oT.optional(),cache:bn})).openapi({ref:"VisualDiffCommand"}),iT=Y.merge(w.object({type:w.literal("REGISTER_REQUEST_LISTENER"),pattern:w.string(),key:w.string()})).openapi({ref:"RegisterRequestListenerCommand"}),sT=Y.merge(w.object({type:w.literal("AWAIT_LISTENER"),key:w.string(),timeout:w.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),Bu=w.discriminatedUnion("type",[Si,Ci,Gx,Ti,Tx,lo,ao,dc,wi,Cx,nT]),aT=w.discriminatedUnion("type",[jx,$x,Nx,kx,lc,Zx,_x,Ex,yi,Ei,Bx,Lx,Ox,Fx,Qx,bi,Xx,Hx,Mx,Px,eT,tT,co,po,Jx,Ri,vi,xi,Ix,iT,sT]),uo=w.discriminatedUnion("type",[...Bu.options,...aT.options]).openapi({ref:"Command"}),Ds=w.discriminatedUnion("type",[...Bu.options,rT]);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:Ae(),type:n};break;case"AUTH_LOAD":{e={id:Ae(),type:n,storageState:""};break}case"AI_EXTRACT":e={id:Ae(),type:n,goal:""};break;case"DIALOG":e={id:Ae(),type:n,action:"DISMISS"};break;case"DRAG":e={id:Ae(),type:n,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Ae(),type:n,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Ae(),type:n,url:""};break;case"WAIT":e={id:Ae(),type:n,delay:1};break;case"BLUR":e={id:Ae(),type:n};break;case"HOVER":case"FOCUS":case"CLICK":e={id:Ae(),type:n,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:Ae(),type:n,value:"",clearContent:!0};break;case"SELECT_OPTION":e={id:Ae(),type:n,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":case"TAB":e={id:Ae(),type:n,url:""};break;case"REQUEST":e={id:Ae(),type:n,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:Ae(),type:n,url:"",query:""};break;case"LOCAL_STORAGE":e={id:Ae(),type:n,key:"",value:""};break;case"JAVASCRIPT":e={id:Ae(),type:n,code:""};break;case"AI_WAIT":case"AI_ASSERTION":e={id:Ae(),type:n,assertion:""};break;case"FILE_UPLOAD":{e={id:Ae(),type:n,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Ae(),type:n,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Ae(),type:n,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:Ae(),type:n,pattern:"",key:""};break}case"AWAIT_LISTENER":{e={id:Ae(),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 lT}from"zod";var eM=lT.discriminatedUnion("type",[xi,lc,Si,yi,vi,wi,bi,ao,lo,co,po,Ti,Ci,Ri,Ei]);function ju(n){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(n)}import{z as cT}from"zod";var Et={type:!0,cache:!0},vr=cT.discriminatedUnion("type",[xi.pick(Et),Si.pick(Et),yi.pick(Et),Ei.pick(Et),vi.pick(Et),wi.pick(Et),bi.pick(Et),ao.pick(Et),lo.pick(Et),co.pick(Et),po.pick(Et),Ti.pick(Et),Ci.pick(Et),Ri.pick(Et)]),uc=Object.values(Ue).filter(n=>vr.options.some(e=>e.shape.type.safeParse(n).success));uo.options.forEach(n=>{if("target"in n.shape&&!uc.includes(n.shape.type.value))throw new Error(`Command ${n.shape.type.value} has a target but no cache`)});import{z as hc}from"zod";import{z as mc}from"zod";import{z as mo}from"zod";var Ct=mo.object({index:mo.number().optional().describe("global index within a test (in-order traversal)"),id:mo.string(),skipped:mo.boolean().optional(),envKey:mo.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:mo.boolean().optional()});ye(mc);var Rt=Ct.extend({type:mc.literal("PRESET_ACTION"),command:uo,skipped:mc.boolean().optional()}).openapi({ref:"PresetAction"});ye(hc);var xr=Ct.extend({type:hc.literal("AI_ACTION"),text:hc.string(),steps:Rt.array().optional()}).openapi({ref:"AIAction"});import{z as ae}from"zod";var dT=ae.object({cacheKey:ae.string(),cacheExpiryMs:ae.number()}),gc=Ct.extend({id:ae.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ae.record(ae.string()).optional(),cacheConfig:dT.optional()}),kn=gc.extend({type:ae.literal("MODULE"),moduleId:ae.string().uuid()}),pT=ae.union([kn.pick({type:!0,moduleId:!0}),ae.record(ae.unknown())]),uT=ae.object({type:ae.literal("URL_REGEX"),regex:ae.string()}),mT=ae.object({type:ae.literal("PAGE_CHECK"),substring:ae.string()}),fc=ae.object({cacheInvalidation:ae.discriminatedUnion("type",[mT,uT]).optional()}),At=ae.object({moduleId:ae.string().uuid(),name:ae.string(),description:ae.string().nullish(),enabled:ae.boolean().nullish(),parameters:ae.string().array().nullish(),defaultParameters:ae.record(ae.string(),ae.string()).nullish(),defaultCacheKey:ae.string().nullish(),defaultCacheTtl:ae.number().nullish(),defaultCacheAllInvocations:ae.boolean().nullish(),autoAuth:ae.boolean().nullish(),advanced:fc.nullish()});import{z as rt}from"zod";import{z as Sc}from"zod";ye(Sc);var ho=Ct.extend({type:Sc.literal("AI_ACTION_DYNAMIC"),text:Sc.string()}).openapi({ref:"AIActionDynamic"});import{z as Hu}from"zod";var yc=Ct.extend({type:Hu.literal("CONDITIONAL"),skipped:Hu.boolean().optional()});import{z as Us}from"zod";var hT=Us.object({type:Us.literal("url"),url:Us.string()}),Ai=Ct.extend({type:Us.literal("IFRAME"),identifier:hT});import{z as Vt}from"zod";var bc=(r=>(r.ALWAYS="ALWAYS",r.ON_FAILURE="ON_FAILURE",r.ON_ACTION_FAILURE="ON_ACTION_FAILURE",r))(bc||{});var gT=Vt.discriminatedUnion("type",[Vt.object({type:Vt.literal("NAVIGATE_URL"),url:Vt.string().url()}),Vt.object({type:Vt.literal("GO_TO_SECTION_START")})]),fT=Vt.object({trigger:Vt.nativeEnum(bc).optional(),attempts:Vt.number().int().optional(),restartBehavior:gT}),Ii=Ct.extend({type:Vt.literal("SECTION"),description:Vt.string().describe("user provided goal of what the section should accomplish"),plan:Vt.string().array().optional(),autohealingConfig:fT.optional()});var $u=At.merge(gc).extend({type:rt.literal("RESOLVED_MODULE"),steps:rt.lazy(()=>ve.array())}),wc=At.extend({steps:rt.lazy(()=>ve.array())}),vc=Ai.extend({steps:rt.lazy(()=>Ye.array())}),ST=Ai.extend({steps:rt.lazy(()=>ve.array())}),xc=Ii.extend({steps:rt.lazy(()=>Ye.array())}),yT=Ii.extend({steps:rt.lazy(()=>ve.array())}),Tr=yc.extend({blocks:rt.object({assertion:rt.lazy(()=>Rt),steps:rt.lazy(()=>Ye.array())}).array(),elseSteps:rt.lazy(()=>Ye.array().optional())}),bT=yc.extend({blocks:rt.object({assertion:rt.lazy(()=>Rt),steps:rt.lazy(()=>ve.array())}).array(),elseSteps:rt.lazy(()=>ve.array().optional())}),Ye=rt.discriminatedUnion("type",[Rt,xr,ho,kn,Tr,vc,xc]),ve=rt.discriminatedUnion("type",[Rt,xr,ho,$u,bT,ST,yT]);import{z as qt}from"zod";var wT=qt.object({steps:Ye.array(),beforeSteps:Ye.array().nullish(),afterSteps:Ye.array().nullish()}),go=qt.object({steps:ve.array(),beforeSteps:ve.array().nullish(),afterSteps:ve.array().nullish()}),Er=qt.object({steps:qt.record(qt.string(),qt.unknown()).array(),beforeSteps:qt.record(qt.string(),qt.unknown()).array().nullish(),afterSteps:qt.record(qt.string(),qt.unknown()).array().nullish()});var je="1.0.19";import{z as Cr}from"zod";var Tc=Cr.object({key:Cr.string(),testId:Cr.string().optional(),moduleId:Cr.string().optional(),organizationId:Cr.string(),value:vr}),Wu=Cr.record(Cr.string(),Tc);var Gu=k.object({phrase:k.string()}),Ec=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()])}),QF=k.object({text:k.string()}),Vu=k.object({thoughts:k.string(),review:k.string().optional(),id:k.number().int()}),Bs=(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))(Bs||{});var qu=k.object({thoughts:k.string(),category:k.nativeEnum(Bs)}),vT=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()})]),eD=k.object({thoughts:k.string(),patches:vT.array()}),Ku=[k.literal("add"),k.literal("replace"),k.literal("remove")],xT=k.object({op:k.union(Ku),path:k.string(),value:ve.optional()}),Yu=k.object({patches:xT.array(),thoughts:k.string()});var TT=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:TT.or(k.null())}),tD=k.object({thoughts:k.string(),evaluation:k.number().min(1).max(10)}),nD=k.object({observations:k.string(),reasoning:k.string(),command:Ds});var Cc=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 ee from"zod";var lD=ee.object({thoughts:ee.string().optional().describe("only provided if a description was provided"),target:wr.optional().describe("only provided if a description was provided"),pageState:ee.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:ee.object({label:ee.string(),value:ee.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:ee.object({data:ee.string(),height:ee.number().int(),width:ee.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Xu=ee.union([ee.literal("NEGATED_CHECK"),ee.literal("SELECT_OPTION"),ee.literal("TYPE")]);function Pi(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 Li=(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))(Li||{}),fo=ee.object({matched:ee.boolean(),reason:ee.string().optional().describe("Human understandable description"),logs:ee.string().array().optional().describe("Logs for debugging")}),ET=fo.extend({type:ee.literal("A11Y_ID")}),CT=fo.extend({type:ee.literal("USER_SELECTOR")}),RT=fo.extend({type:ee.literal("CSS_SELECTOR"),selectors:ee.string().array()}),AT=fo.extend({type:ee.literal("HTML_DISTANCE"),distance:ee.number().optional(),closestElement:ee.string().optional(),savedElement:ee.string().optional()}),IT=fo.extend({type:ee.literal("TEMPLATE_MATCHING"),elementImageUrl:ee.string().url()}),PT=fo.extend({type:ee.literal("AUTO_FRAME"),logs:ee.string().array().optional()}),Zu=ee.discriminatedUnion("type",[ET,CT,RT,AT,IT,PT]);import{z as Fi}from"zod";import{z as XE}from"zod";import*as J from"zod";import{cloneDeep as Ni}from"lodash-es";var LT=n=>{let e=Qu(n,0);if(e===void 0||!kT(n[e]))return;let t=Qu(n,e+1);if(t!==void 0)return NT(n,e,t)},em=LT,Qu=(n,e)=>{for(let t=e;t<n.length;t+=1){let r=n[t];if(!OT(r))return t}},OT=n=>n===" "||n===" "||n===`
|
|
5
|
-
`||
|
|
6
|
-
`)return
|
|
7
|
-
${e.message}`)}},jE=({newValue:n,value:e,maxSize:t,indent:r})=>n!==void 0?JSON.stringify(n,void 0,r):typeof e=="number"?tm(e,t):bm(e,t);import*as Rr from"zod";import{z as Ne}from"zod";var km=6e4,Ie="BASE_URL",Ys="CURRENT_URL",So="ENV_NAME",f0={[Ie]:"https://www.google.com"},Nm=Ne.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Js=Ne.object({name:Ne.string(),variables:Ne.record(Ne.string().describe("variable name"),Ne.string().describe("variable value"))}),yo=Ne.object({pageLoadTimeoutMs:Ne.number().optional().refine(n=>n===void 0||n<=km&&n>=-1,{message:`Page load timeout must be between 0 and ${km/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),localChromeExtensionPaths:Ne.string().array().optional(),extraHeaders:Ne.record(Ne.string(),Ne.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:Ne.string().optional(),disableGpu:Ne.boolean().optional(),ignoreHrefForCaching:Ne.boolean().optional().describe("When running locally often times <a> hrefs will be different every time, resulting in cache busting. This will ignore href in <a> matching when there is text content."),bustCacheOnBoundingBoxChange:Ne.boolean().optional().describe("Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed.")}),Xs=Ne.object({name:Ne.string(),variables:Ne.record(Ne.string().describe("variable name"),Ne.unknown().describe("variable value")),browser:yo.optional()});ye(Rr);var _i=Rr.object({env:Rr.record(Rr.unknown())}).openapi({ref:"TestContextSnapshot"}),HE="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",$E=[Ie,So],_m=[Ys,Ie,So],It=class n{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t={}){return new n({baseUrl:"about:blank",currentUrl:"about:blank",envName:e,variablesFromEnvironment:t})}static fromSnapshot({snapshot:e,environmentVariables:t}){let r=e.env[Ie]??"about:blank",o=e.env[Ys]??"about:blank",i=e.env[So],s={};for(let[l,c]of Object.entries(e.env))_m.includes(l)||(t??{})[l]===void 0&&(s[l]=c);return new n({baseUrl:r,currentUrl:o,dynamicVariables:s,envName:i,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=Ni(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){$E.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[So]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return Ni(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([r,o])=>_m.includes(r)||this.varsFromMomenticEnvironment[r]===void 0?[r,o]:[r,HE]));for(let[r,o]of Object.entries(e.env)){if(!o){e.env[r]=o;continue}let{jsonString:i}=ki(JSON.stringify(o),1e3);try{e.env[r]=JSON.parse(i)}catch{e.env[r]=void 0}}let{jsonString:t}=ki(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}setCurrentUrl(e){this.env[Ys]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=Ni(e.variablesFromEnvironment),this.setMomenticSystemVariable(Ie,e.baseUrl),e.envName&&this.setMomenticSystemVariable(So,e.envName)}getDynamicVariablesCopy(){return Ni(this.env)}getVariablesFromEnvironmentCopy(){return Ni(this.varsFromMomenticEnvironment)}};import{z as Ar}from"zod";ye(Ar);var de=(c=>(c.AI_PROVIDER="AIProviderError",c.USER_INFRA="UserInfrastructureError",c.ACTION_FAILURE="ActionFailureError",c.ASSERTION_FAILURE="AssertionFailureError",c.CONFIG_ERROR="UserConfigurationError",c.WEB_AGENT_PLATFORM="InternalWebAgentError",c.UNKNOWN_PLATFORM="InternalPlatformError",c.JOB_TIMEOUT="JobTimeoutError",c.UNKNOWN="UnknownError",c))(de||{});var Mm=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],Zs={ActionFailureError:"Action failure",AssertionFailureError:"Assertion failure",UserInfrastructureError:"Infrastructure failure",UserConfigurationError:"Configuration error",AIProviderError:"AI provider error",InternalWebAgentError:"Momentic AI agent error",JobTimeoutError:"Job timeout",InternalPlatformError:"Unknown Momentic platform error",UnknownError:"Unknown error"},bo={ActionFailureError:"A browser action such as a click or type failed to execute because of the underlying page state is incorrect, suggesting a bug in the application itself.",AssertionFailureError:"An AI assertion or check failed for a legitimate reason, such as a missing element, a change in the page structure, or an unexpected state (e.g. loading state).",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",UserInfrastructureError:"The user's web application exhibited an infrastructure failure, such as a page load timeout, a 5XX status code, maintenance page, or session crash.",UserConfigurationError:"The error message suggests a user-caused misconfiguration in the test, such as an undefined variable, a missing base URL, an empty test/module input parameter, or an invalid step option",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself.",InternalWebAgentError:"The AI testing framework failed to find the correct element or evaluate the assertion correctly, even though the test steps and application state look valid. In other words, the AI agent failed to understand the page.",UnknownError:"An unknown error occurred. Please refer to the failure details in the run for more information or reach out to Momentic Support for assistance.",InternalPlatformError:"An unknown error occurred with the Momentic platform."},Fc=Ar.object({reason:Ar.nativeEnum(de),summary:Ar.string()}).openapi({ref:"TestResultClassification"}),Qs=Ar.object({errorMessage:Ar.string(),errorStack:Ar.string().optional(),classification:Fc.optional()}).openapi({ref:"TestFailureDetails"});ye(J);var xe=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(xe||{}),Dc=(r=>(r.SUCCESS="SUCCESS",r.FAILED="FAILED",r.CANCELLED="CANCELLED",r))(Dc||{}),Uc=J.object({beforeUrl:J.string().optional(),afterUrl:J.string().optional(),message:J.string().optional(),beforeScreenshot:J.string().optional(),afterScreenshot:J.string().optional(),beforeSnapshot:J.string().optional(),afterSnapshot:J.string().optional(),startedAt:J.coerce.date(),finishedAt:J.coerce.date()}),WE=Uc.extend({viewport:J.object({height:J.number(),width:J.number()}),status:J.nativeEnum(Dc),message:J.string().optional(),elementInteracted:J.string().optional()}),qn=Uc.extend({status:J.nativeEnum(xe),message:J.string().optional(),data:J.unknown().optional(),beforeTestContext:_i.optional(),afterTestContext:_i.optional(),failureReason:J.nativeEnum(de).optional(),details:J.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),ea=qn.merge(Rt).extend({results:WE.array(),proposedStep:Rt.optional()}),GE=qn.merge(xr).extend({results:J.lazy(()=>ea.array())}),VE=qn.merge(ho).extend({results:J.lazy(()=>ea.array())}),qE=qn.merge(kn).extend({moduleName:J.string().optional(),results:J.lazy(()=>Nn.array())}),KE=qn.merge(Tr).extend({assertion:ea.optional(),results:J.lazy(()=>Nn.array()).describe("results for the block actually executed")}),YE=qn.merge(Ai).extend({results:J.lazy(()=>Nn.array())}),JE=qn.merge(Ii).extend({results:J.lazy(()=>Nn.array()),healingAttempts:J.lazy(()=>Nn.array().array()).optional()}),Nn=J.discriminatedUnion("type",[GE,VE,ea,qE,KE,YE,JE]),ta=qn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),na=Uc.extend({index:J.number().optional(),description:J.string(),pageState:J.string().optional()});var Bc=XE.object({results:Nn.array().describe("main results"),beforeResults:Nn.array().optional(),afterResults:Nn.array().optional()}),ra=Bc.partial();import{z as H}from"zod";import{z as be}from"zod";var ZE=be.object({type:be.literal("FAILURE_RECOVERY"),thoughts:be.string()}),QE=be.object({type:be.literal("DESCRIPTION_UPDATE"),thoughts:be.string()}),oa=be.discriminatedUnion("type",[QE,ZE]),ia=(e=>(e.AUTO_HEALING="AUTO_HEALING",e))(ia||{}),eC=be.object({testId:be.string(),name:be.string(),orgId:be.string(),runId:be.string(),purpose:be.nativeEnum(ia).catch("AUTO_HEALING"),steps:ve.array(),details:oa.or(oa.array()).optional()}),H0=eC.pick({name:!0,orgId:!0}),zc=be.object({id:be.string(),name:be.string().nullish(),createdAt:be.string().pipe(be.coerce.date()).or(be.date()),organizationId:be.string(),schemaVersion:be.string(),purpose:be.nativeEnum(ia).catch("AUTO_HEALING"),runId:be.string().nullish(),details:oa.or(oa.array()).nullish(),applied:be.boolean().nullish(),appliedAt:be.coerce.date().nullish()}),Fm=zc.extend({steps:ve.array()});import{isValidCron as tC}from"cron-validator";import{z as ie}from"zod";import{z as jc}from"zod";var sa=jc.object({width:jc.number().min(200).max(1e4),height:jc.number().min(200).max(1e4)}),Dm={"Desktop Large":{width:1920,height:1080},"Desktop Small":{width:1280,height:800},iPad:{width:768,height:1024},"Pixel 8":{width:448,height:998},"iPhone 15":{width:393,height:852}},G0=Object.keys(Dm);var Ut=Dm["Desktop Large"];var Um=1e4,Bm=2e3,Ir=(r=>(r.CHROMIUM="Chromium",r.GOOGLE_CHROME="Google Chrome",r.CHROME_FOR_TESTING="Chrome for Testing",r))(Ir||{});var aa=yo.extend({browserType:ie.nativeEnum(Ir).optional(),slowMoMs:ie.number().optional().refine(n=>n===void 0||n<=Bm&&n>=-1,{message:`Slow motion must be between 0 and ${Bm} milliseconds`}),smartWaitingTimeoutMs:ie.number().optional().refine(n=>n===void 0||n<=Um&&n>=-1,{message:`Smart waiting timeout must be between 0 and ${Um/1e3} seconds`}),basicAuthorization:ie.object({username:ie.string().optional(),password:ie.string().optional()}).optional(),disableJavaScript:ie.boolean().optional(),disableGpu:ie.boolean().optional()}),zm=["extraHeaders","basicAuthorization","localChromeExtensionPaths"];var nC=ie.object({disableAICaching:ie.boolean().default(!1),failureRecovery:ie.boolean().optional().describe("undefined means inherit org settings")});var rC=ie.object({viewport:sa.optional()}),wo=rC.merge(nC).merge(aa),vo=ie.object({cron:ie.string().refine(n=>tC(n),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:ie.boolean().default(!1),env:ie.string().optional(),timeZone:ie.string().default("America/Los_Angeles"),jobKey:ie.string().optional()}),xo=ie.object({onSuccess:ie.boolean().default(!1),failureMessage:ie.string().optional(),onFailure:ie.boolean().default(!0),successMessage:ie.string().optional()}),oC=ie.object({name:ie.string(),required:ie.boolean().optional(),defaultValue:ie.string().describe("this is not optional because we need a value when the editor is first loaded")}),la=oC.array(),iC=ie.object({name:ie.string(),value:ie.string()}),jm=iC.array(),ca=ie.object({name:ie.string(),default:ie.boolean().optional(),fixtures:Nm.array().optional()});ye(H);var Pt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ne=(a=>(a.PENDING="PENDING",a.RUNNING="RUNNING",a.PASSED="PASSED",a.FAILED="FAILED",a.CANCELLED="CANCELLED",a.RETRYING="RETRYING",a.WAITING_FOR_USER="WAITING_FOR_USER",a))(ne||{}),da=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(da||{});var Be=H.string().pipe(H.coerce.date()).or(H.date()),Mi=H.object({id:H.string(),runKey:H.string(),organizationId:H.string(),createdAt:Be,createdBy:H.string(),flake:H.boolean().nullish(),scheduledAt:Be.or(H.null()),startedAt:Be.or(H.null()),updatedAt:Be.nullish(),finishedAt:Be.or(H.null()),resolvedBaseUrl:H.string().nullish(),environmentName:H.string().nullish(),labels:H.array(H.string()).optional(),cliVersion:H.string().nullish(),section:H.nativeEnum(da).nullish(),status:H.nativeEnum(ne),trigger:H.nativeEnum(Pt),attempts:H.number(),runAttempts:H.array(H.object({id:H.string(),status:H.nativeEnum(ne),startedAt:Be.or(H.null()),finishedAt:Be.or(H.null())})).optional(),videos:H.array(H.string()).optional(),failureReason:H.nativeEnum(de).nullish(),failureDetails:Qs.nullish(),testFragments:H.array(zc).nullish(),localTestId:H.string().nullish(),testId:H.string().nullish(),testName:H.string().nullish(),test:H.object({name:H.string(),id:H.string()}).nullish().default(null),suiteId:H.string().nullish()}).openapi({ref:"RunMetadata"}),sC={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},pa=Mi.pick({...sC,test:!0}),Hm=Mi.omit({failureReason:!0,failureDetails:!0,test:!0}),Hc=Mi.extend({stepsSnapshot:H.array(H.record(H.unknown())).nullish(),resolvedInputs:H.record(H.string(),H.string()).nullish(),test:H.object({name:H.string(),id:H.string(),description:H.string().nullish(),baseUrl:H.string().nullish(),advanced:wo.nullish()}).nullish()}).merge(Bc),$m=n=>n.includes("PASSED")&&n.includes("FAILED");var aC=Fi.object({id:Fi.string().uuid(),startedAt:Be.or(Fi.null()),finishedAt:Be.or(Fi.null()),status:Fi.nativeEnum(ne)}).merge(ra),dU=aC.array();var Di=(o=>(o.JUNIT="junit",o.ALLURE="allure",o.ALLURE_JSON="allure-json",o.PLAYWRIGHT_JSON="playwright-json",o))(Di||{});import{z as He}from"zod";var lC=He.object({id:He.string(),status:He.nativeEnum(ne),trigger:He.nativeEnum(Pt),createdAt:Be,startedAt:Be.nullish(),finishedAt:Be.nullish(),gitCommitSha:He.string().nullish(),gitCommitShaShort:He.string().nullish(),gitCommitTimestamp:Be.nullish(),gitBranchName:He.string().nullish(),gitOriginUrl:He.string().nullish(),gitCommitMessage:He.string().nullish(),gitCommitAuthorName:He.string().nullish(),githubRepository:He.string().nullish(),gitlabProjectPath:He.string().nullish(),pipelineId:He.string().nullish(),cliVersion:He.string().nullish(),suite:He.object({id:He.string(),name:He.string()}).nullish(),runs:He.object({status:He.nativeEnum(ne)}).array()}).openapi({ref:"RunGroup"}),Wm=lC.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:pa.array()});import{z as Je}from"zod";var cC=Je.object({type:Je.literal("TARGETING"),name:Je.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:Zu.array(),pageState:Je.string().optional(),targetSource:Je.nativeEnum(Gn).optional(),targetUpdateTime:Je.string().optional()}),dC=Je.object({type:Je.literal("AI_LOCATION"),matched:Je.boolean(),pageState:Je.string().optional(),ragUsed:Je.boolean().optional(),thoughts:Je.string().optional()}),pC=Je.object({type:Je.literal("ASSERTION"),relevantElementsSerialized:Je.string().array().optional(),pageState:Je.string().optional(),ragUsed:Je.boolean().optional()}),Gm=Je.discriminatedUnion("type",[cC,dC,pC]);function ua(){return{details:[]}}import{z as _e}from"zod";var uC=_e.object({id:_e.string(),name:_e.string()}),EU=uC.merge(_e.object({createdAt:Be,createdBy:_e.string(),schedule:vo,notification:xo,environment:_e.object({name:_e.string()}).nullish(),beforeTests:_e.object({id:_e.string()}).array().nullish(),afterTests:_e.object({id:_e.string()}).array().nullish()})),Vm=_e.object({id:_e.string().uuid(),orgId:_e.string(),createdAt:Be,startedAt:Be.or(_e.null()),finishedAt:Be.or(_e.null()),status:_e.nativeEnum(ne),trigger:_e.nativeEnum(Pt),suite:_e.object({id:_e.string(),name:_e.string()}).nullish(),runs:Mi.array()}),CU=Vm.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),qm=Vm.extend({runs:pa.array()});var Kt=F.object({disableCache:F.boolean().optional(),loggerTags:F.record(F.string(),F.string()).optional(),langfuseSessionId:F.string().optional()}),mC=F.object({screenshotBase64AfterCommand:F.string(),urlAfterCommand:F.string(),serializedCommand:F.string(),elementInteracted:F.string().optional(),thoughts:F.string().optional()}),Km=F.object({goal:F.string(),browserState:F.string(),screenshot:F.string(),source:Xu.optional()}),Ym=F.object({target:F.string().or(F.number()),browserState:F.string().optional(),screenshot:F.string().optional(),boundingBox:F.object({x:F.number(),y:F.number(),height:F.number(),width:F.number()}).optional()}),Jm=F.object({goal:F.string(),browserState:F.string(),screenshot:F.string().optional(),returnSchema:F.string().optional()}),Xm=F.object({goal:F.string(),browserState:F.string(),screenshot:F.string(),url:F.string(),contextChoice:cc.optional()}),Zm=F.object({command:uo}),$c=F.object({goal:F.string(),browserState:F.string(),startingScreenshot:F.string().optional(),screenshot:F.string(),url:F.string(),history:mC.array(),actionHint:F.string().optional(),lastError:F.string().optional()}),Qm=F.object({results:na.array(),errorMessage:F.string(),errorStack:F.string().optional()}),eh=F.object({results:na.array(),goal:F.string(),errorMessage:F.string()}),th=F.object({failedResults:na.array(),nextStepsSerialized:F.string().array(),currentUrl:F.string(),currentPageState:F.string(),currentScreenshot:F.string()}),GU=F.object({description:F.string(),type:F.union([F.literal("locator"),F.literal("assertion"),F.literal("ai-action")]),excerpt:F.string()});import{z as Ui}from"zod";var KU=Ui.object({goal:Ui.string()}),nh=Ui.object({keywords:Ui.array(Ui.string())});import{z as St}from"zod";var Wc=St.object({content:St.string(),ids:St.string().array(),tokenLength:St.number()}),hC=St.object({chunks:Wc.array()}),XU=St.object({ids:St.string().array(),score:St.number(),tokenLength:St.number()}),ZU=hC.extend({description:St.string().describe("Input to pass to RAG engine"),tokenLimit:St.number()}),rh=St.object({ids:St.number().array()}),oh=St.object({indices:St.number().array()});var ih=n=>!(!n.org_id||!n.user_id||!n.platform);import{z as Pr}from"zod";var sh=Pr.object({id:Pr.string().uuid(),skipped:Pr.boolean().optional(),envKey:Pr.string().optional().describe("key in the environment to save the result of this step to")}),Gc=sh.merge(ks).extend({type:Pr.literal("REQUEST")}),Vc=sh.merge(Ns).extend({type:Pr.literal("JAVASCRIPT")}),qc=Pr.discriminatedUnion("type",[Vc,Gc]);import{z as Yt}from"zod";import{z as Lr}from"zod";var gC=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Pe=n=>{let e=n.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var ma=Lr.string().min(1).max(255).superRefine((n,e)=>{try{To(n)}catch(t){return e.addIssue({code:Lr.ZodIssueCode.custom,message:t.message,fatal:!0}),Lr.NEVER}});function To(n){if(n=n.toLowerCase().trim(),n.length===0||n.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(n))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(n.endsWith("-")||n.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(n.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(n))throw new Error(`"${n}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(n)||/^\s|\s$/.test(n))throw new Error("Name cannot start or end with a space or dot.");if(n.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(n==="none")throw new Error("Name cannot be 'none'.");if(n.match(gC))throw new Error("Name cannot be a UUID. Please choose a different name.")}var ha=Lr.preprocess(n=>n===null?"":n,Lr.union([Lr.string().url(),Lr.literal("")])).optional();var ah=Yt.object({id:Yt.string(),name:ma,description:Yt.string().optional().nullish(),baseUrl:ha.nullish(),schemaVersion:Yt.string(),advanced:Yt.unknown().optional(),retries:Yt.number(),envs:Yt.array(ca).nullish(),parameters:la.nullish()}),fC=Yt.object({createdAt:Yt.coerce.date(),updatedAt:Yt.coerce.date(),schedule:vo.nullish(),notification:xo.nullish(),createdBy:Yt.string(),organizationId:Yt.string()}),SC=ah.merge(fC),y1=SC.extend({steps:qc.array()}),b1=ah.extend({steps:qc.array()});import{z as Lt}from"zod";var lh=Lt.object({startedAt:Lt.coerce.date(),finishedAt:Lt.coerce.date(),status:Lt.nativeEnum(xe),message:Lt.string().optional(),data:Lt.unknown().optional()}),bC=lh.merge(Vc).extend({type:Lt.literal("JAVASCRIPT")}),wC=lh.merge(Gc).extend({type:Lt.literal("REQUEST")}),vC=Lt.discriminatedUnion("type",[bC,wC]),ch=Lt.object({startedAt:Lt.coerce.date(),finishedAt:Lt.coerce.date().nullish(),status:Lt.nativeEnum(ne),results:vC.array(),failureReason:Lt.string().nullish(),failureDetails:Qs.nullish()});import{z as Ot}from"zod";var xC=Ot.object({id:Ot.string(),organizationId:Ot.string(),createdAt:Ot.coerce.date(),updatedAt:Ot.coerce.date(),createdBy:Ot.string(),scheduledAt:Ot.coerce.date().nullish(),startedAt:Ot.coerce.date().nullish(),finishedAt:Ot.coerce.date().nullish(),status:Ot.nativeEnum(ne),trigger:Ot.nativeEnum(Pt),results:ch.array().nullish(),apiTestName:Ot.string().nullish(),apiTestPath:Ot.string().nullish(),apiTestId:Ot.string().nullish()}),I1=xC.pick({status:!0,startedAt:!0,finishedAt:!0});var Or=(t=>(t.TestRun="test-run",t.CreditsUsed="credits-used",t))(Or||{}),dh=3;function TC(n){return n==="MODULE"||n==="IFRAME"||n==="CONDITIONAL"||n==="SECTION"||n==="RESOLVED_MODULE"}function Bi(n){if(!TC(n))switch(n){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function zi(n){switch(n.type){case"AI_EXTRACT":case"AI_ASSERTION":case"AI_WAIT":return dh;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":return n.useSelector||!n.target||n.target.type!=="description"?0:1;case"DRAG":case"MOUSE_DRAG":return n.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":return 0;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}var Eo=class{async reportBillableEvent(e,t,r){}async reportCreditsUsed(e,t,r,o){}};function Kc(n,e){return{...n,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}import{parseString as EC,splitCookiesString as CC}from"set-cookie-parser";import{z as me}from"zod";var Yc=me.object({name:me.string(),value:me.string(),url:me.string().optional(),domain:me.string().optional(),path:me.string().optional(),expires:me.number().default(Date.now()/1e3+60*60*24*365),httpOnly:me.boolean().optional(),secure:me.boolean().default(!0),sameSite:me.union([me.literal("Strict"),me.literal("Lax"),me.literal("None")]).default("None")});function ga(n,e){let t=[],r=CC(n);for(let o of r){let i=EC(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let s;if(i.sameSite){let p=i.sameSite.trim().toLowerCase();if(p==="strict")s="Strict";else if(p==="lax")s="Lax";else if(p==="none")s="None";else throw new Error(`Invalid sameSite setting in cookie: ${p}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let a=Yc.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:s});t.push(a);let l=[a.name,...Object.keys(a)].map(p=>p.toLowerCase()),c=o.match(/\b(\S+)=([^;]*)/g);if(c)for(let p of c){let[d,u]=p.split("=");if(!d||!u)throw new Error(`Invalid key-value pair in cookie: ${p}`);l.includes(d.toLowerCase())||t.push({...a,name:d,value:u})}}return t}var RC=me.object({origin:me.string(),localStorage:me.array(me.object({name:me.string(),value:me.string()}))}),AC=me.object({entries:me.record(me.string(),me.array(me.tuple([me.unknown(),me.unknown()]))),version:me.number().optional()}),fa=me.object({cookies:Yc.array().optional(),origins:RC.array().optional(),idb:me.record(me.string(),AC).optional().describe("key is db name")});function Sa(n,e){let t=[];return n.cloneSync()?.serializeSync()?.cookies.forEach(r=>{let o=Yc.safeParse({name:r.key,...r});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),t.push(i)}),t}var J1=new Set(Object.values(Ue));var IC={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_WAIT:"AI wait",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"Local storage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",SUCCESS:"Done"},X1={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_WAIT:[],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],SUCCESS:[]},Z1={AI_ACTION:"Ask AI achieve a specific goal. Caches the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI whether something is true on the page, retrying until a configurable timeout.",AI_WAIT:"Wait until AI considers a condition to be true.",CLICK:"Click on an element on the page based on a description.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page based on a description.",HOVER:"Hover over an element on the page based on a description.",FILE_UPLOAD:"Automatically upload a file when the next file chooser is activated.",FOCUS:"Focus an element on the page based on a description.",BLUR:"Remove focus from an element on the page based on a description.",SELECT_OPTION:"Select an option from an HTML Select <select> element based on a description.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session",LOCAL_STORAGE:"Set a local storage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JSON snapshot including cookies, local storage, and IndexDB entries.",AUTH_SAVE:"Save auth state (cookies, local storage) into a JavaScript object format usable by 'Load auth state'.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's state using pre-built conditions, including URL and content checks.",WAIT_FOR_URL:"Wait for the active page's URL to match a specific URL or glob pattern. If a new tab is opened, this command will wait for the new tab's URL to match instead.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."};import{Faker as tB,en as nB}from"@faker-js/faker";import{z as $}from"zod";var ph=55555,sB=$.object({body:$.string(),to:$.string(),from:$.string()}),aB=$.object({from:$.string().optional(),to:$.string(),timeout:$.number().optional(),beforeDate:$.string().pipe($.coerce.date()).or($.date()).optional(),afterDate:$.string().pipe($.coerce.date()).or($.date()).optional()}),lB=$.object({to:$.string(),from:$.string(),subject:$.string(),body:$.string()}),cB=$.object({inbox:$.string(),afterDate:$.string().pipe($.coerce.date()).or($.date()).optional(),timeout:$.number().optional(),trimWhitespace:$.boolean().optional()}),dB=$.object({inbox:$.string(),limit:$.number().optional(),afterDate:$.string().pipe($.coerce.date()).or($.date()).optional(),trimWhitespace:$.boolean().optional()});var uh=$.object({result:$.unknown(),variableUpdates:$.record($.string(),$.unknown()).optional(),persistentVariableUpdates:$.record($.string(),$.unknown()).optional(),error:$.string().optional(),success:$.boolean()}),pB=$.object({id:$.string().optional(),orgId:$.string(),momenticLambdaAuthHash:$.string(),code:$.string(),fragment:$.boolean(),state:_i,timeoutMs:$.number().optional()}),Kn=15e3;import*as pt from"zod";ye(pt);var PC=pt.object({url:pt.string(),lineNumber:pt.number(),columnNumber:pt.number()}).openapi({ref:"CodeLocation"}),ya=pt.object({timestamp:pt.number(),text:pt.string(),type:pt.string(),tabIndex:pt.number(),args:pt.unknown().array().optional(),url:pt.string().optional(),location:PC.optional()}).openapi({ref:"ConsoleLog"}),mh=ya.array(),LC=mh.array();import*as Xc from"zod";import{z as A}from"zod";var OC=A.object({name:A.string(),version:A.string(),comment:A.string().optional()}),kC=A.object({name:A.string(),version:A.string(),comment:A.string().optional()}),NC=A.object({onContentLoad:A.number().optional(),onLoad:A.number().optional(),comment:A.string().optional()}),gh=A.object({startedDateTime:A.string(),id:A.string(),title:A.string().optional(),pageTimings:NC,comment:A.string().optional()}),_C=A.array(gh),MC=A.object({name:A.string(),value:A.string(),path:A.string().optional(),domain:A.string().optional(),expires:A.string().optional(),httpOnly:A.boolean().optional(),secure:A.boolean().optional(),comment:A.string().optional()}),fh=A.array(MC),FC=A.object({name:A.string(),value:A.string(),comment:A.string().optional()}),Sh=A.array(FC),DC=A.object({name:A.string(),value:A.string(),comment:A.string().optional()}),UC=A.array(DC),BC=A.object({name:A.string(),value:A.string().optional(),fileName:A.string().optional(),contentType:A.string().optional(),comment:A.string().optional()}),zC=A.array(BC),jC=A.object({mimeType:A.string(),params:zC,text:A.string(),comment:A.string().optional()}),HC=A.object({method:A.string(),url:A.string(),httpVersion:A.string().optional(),cookies:fh,headers:Sh,queryString:UC,postData:jC.optional(),headersSize:A.number().optional(),bodySize:A.number().optional(),comment:A.string().optional()}),$C=A.object({size:A.number().optional(),compression:A.number().optional(),mimeType:A.string().optional(),text:A.string().optional(),encoding:A.string().optional(),comment:A.string().optional()}),WC=A.object({status:A.number(),statusText:A.string(),httpVersion:A.string().optional(),cookies:fh,headers:Sh,content:$C,redirectURL:A.string().optional(),headersSize:A.number().optional(),bodySize:A.number().optional(),comment:A.string().optional()}),hh=A.object({expires:A.string().optional(),lastAccess:A.string(),eTag:A.string(),hitCount:A.number(),comment:A.string().optional()}),GC=A.object({beforeRequest:hh.optional(),afterRequest:hh.optional(),comment:A.string().optional()}),VC=A.object({blocked:A.number().optional(),dns:A.number().optional(),connect:A.number().optional(),send:A.number(),wait:A.number(),receive:A.number(),ssl:A.number().optional(),comment:A.string().optional()}),yh=A.object({pageref:A.string().optional(),startedDateTime:A.string(),time:A.number().optional(),request:HC,response:WC.optional(),cache:GC.optional(),timings:VC,serverIPAddress:A.string().optional(),connection:A.string().optional(),comment:A.string().optional(),_resourceType:A.string().optional()}),qC=A.array(yh),KC=A.object({version:A.string().default("1.1"),creator:OC.optional(),browser:kC.optional(),pages:_C.optional(),entries:qC,comment:A.string().optional()}),YC=A.object({log:KC}),bh=A.record(A.string(),gh),wh=A.record(A.string(),yh);function Jc(n,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(n).sort((t,r)=>new Date(t.startedDateTime).getTime()-new Date(r.startedDateTime).getTime()),entries:Object.values(e).sort((t,r)=>new Date(t.startedDateTime).getTime()-new Date(r.startedDateTime).getTime())}}}ye(Xc);var JC=Xc.object({logsPerPage:ya.array().array(),harPages:bh.optional(),harEntries:wh.optional()}).openapi({ref:"DebugData"});var kr=class{async getConsoleLogsForRunAttempt(e,t,r){}async getNetworkLogsForRunAttempt(e,t,r){}async getHtmlSnapshot(e,t){}async getA11yTreeSnapshot(e,t){}async getScreenshot(e,t){}async storeConsoleLogsForRunAttempt(e,t,r,o){}async storeNetworkLogsForRunAttempt(e,t,r,o){}async storeScreenshot(e,t,r){}async storeHtmlSnapshot(e,t,r){}};var ba=class extends Error{constructor(e,t,r,o={}){super(`The ${r} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};function vh(n){for(let e of Object.values(de))if(n.includes(e))return e}var R=class extends Error{reason;constructor(e,t,r){let o=!1;for(let i of Object.values(de))if(t.startsWith(i)){o=!0,e=i;break}if(r?.errOptions?.cause)super(o?t:`${e}: ${t}`,r?.errOptions);else{let i=o?t:`${e}${t?`: ${t}`:""}`;super(i,r?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e,Object.defineProperty(this,"lastScreenshotBuffer",{value:r?.lastScreenshotBuffer,enumerable:!1})}getLastScreenshotBuffer(){return"lastScreenshotBuffer"in this?this.lastScreenshotBuffer:void 0}toString(){return this.message}toJSON(){return{message:this.message}}},Yn=class extends Error{decisions;constructor(e,t,r={}){super(e,r),this.decisions=t,this.name="NoElementsFoundError"}toString(){return`${this.message}
|
|
3
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="ae9ffd6a-f90f-5f7a-8942-0748965aeb1f")}catch(e){}}();
|
|
4
|
+
var Gv=Object.create;var xu=Object.defineProperty;var Vv=Object.getOwnPropertyDescriptor;var qv=Object.getOwnPropertyNames;var Kv=Object.getPrototypeOf,Yv=Object.prototype.hasOwnProperty;var Tu=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Jv=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of qv(e))!Yv.call(r,o)&&o!==t&&xu(r,o,{get:()=>e[o],enumerable:!(n=Vv(e,o))||n.enumerable});return r};var Xv=(r,e,t)=>(t=r!=null?Gv(Kv(r)):{},Jv(e||!r||!r.__esModule?xu(t,"default",{value:r,enumerable:!0}):t,r));var Cf=Tu((D2,Ef)=>{"use strict";Ef.exports=xf;function xf(r,e,t){r instanceof RegExp&&(r=vf(r,t)),e instanceof RegExp&&(e=vf(e,t));var n=Tf(r,e,t);return n&&{start:n[0],end:n[1],pre:t.slice(0,n[0]),body:t.slice(n[0]+r.length,n[1]),post:t.slice(n[1]+e.length)}}function vf(r,e){var t=e.match(r);return t?t[0]:null}xf.range=Tf;function Tf(r,e,t){var n,o,i,a,s,l=t.indexOf(r),c=t.indexOf(e,l+1),p=l;if(l>=0&&c>0){if(r===e)return[l,c];for(n=[],i=t.length;p>=0&&!s;)p==l?(n.push(p),l=t.indexOf(r,p+1)):n.length==1?s=[n.pop(),c]:(o=n.pop(),o<i&&(i=o,a=c),c=t.indexOf(e,p+1)),p=l<c&&l>=0?l:c;n.length&&(s=[i,a])}return s}});var Nf=Tu((U2,Of)=>{"use strict";var Af=Cf();Of.exports=kA;var Rf="\0SLASH"+Math.random()+"\0",If="\0OPEN"+Math.random()+"\0",bd="\0CLOSE"+Math.random()+"\0",Pf="\0COMMA"+Math.random()+"\0",Lf="\0PERIOD"+Math.random()+"\0";function yd(r){return parseInt(r,10)==r?parseInt(r,10):r.charCodeAt(0)}function PA(r){return r.split("\\\\").join(Rf).split("\\{").join(If).split("\\}").join(bd).split("\\,").join(Pf).split("\\.").join(Lf)}function LA(r){return r.split(Rf).join("\\").split(If).join("{").split(bd).join("}").split(Pf).join(",").split(Lf).join(".")}function kf(r){if(!r)return[""];var e=[],t=Af("{","}",r);if(!t)return r.split(",");var n=t.pre,o=t.body,i=t.post,a=n.split(",");a[a.length-1]+="{"+o+"}";var s=kf(i);return i.length&&(a[a.length-1]+=s.shift(),a.push.apply(a,s)),e.push.apply(e,a),e}function kA(r){return r?(r.substr(0,2)==="{}"&&(r="\\{\\}"+r.substr(2)),na(PA(r),!0).map(LA)):[]}function OA(r){return"{"+r+"}"}function NA(r){return/^-?0\d/.test(r)}function MA(r,e){return r<=e}function _A(r,e){return r>=e}function na(r,e){var t=[],n=Af("{","}",r);if(!n)return[r];var o=n.pre,i=n.post.length?na(n.post,!1):[""];if(/\$$/.test(n.pre))for(var a=0;a<i.length;a++){var s=o+"{"+n.body+"}"+i[a];t.push(s)}else{var l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(n.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(n.body),p=l||c,d=n.body.indexOf(",")>=0;if(!p&&!d)return n.post.match(/,.*\}/)?(r=n.pre+"{"+n.body+bd+n.post,na(r)):[r];var m;if(p)m=n.body.split(/\.\./);else if(m=kf(n.body),m.length===1&&(m=na(m[0],!1).map(OA),m.length===1))return i.map(function(z){return n.pre+m[0]+z});var u;if(p){var h=yd(m[0]),g=yd(m[1]),f=Math.max(m[0].length,m[1].length),S=m.length==3?Math.abs(yd(m[2])):1,x=MA,v=g<h;v&&(S*=-1,x=_A);var b=m.some(NA);u=[];for(var E=h;x(E,g);E+=S){var C;if(c)C=String.fromCharCode(E),C==="\\"&&(C="");else if(C=String(E),b){var I=f-C.length;if(I>0){var M=new Array(I+1).join("0");E<0?C="-"+M+C.slice(1):C=M+C}}u.push(C)}}else{u=[];for(var L=0;L<m.length;L++)u.push.apply(u,na(m[L],!1))}for(var L=0;L<u.length;L++)for(var a=0;a<i.length;a++){var s=o+u[L]+i[a];(!e||p||s)&&t.push(s)}}return t}});var yi=(r,e)=>{},rc=!1;try{let r=await import("@sentry/node");yi=r.captureException,r.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME}),rc=!0}catch{}import{Command as VN,Option as on}from"@commander-js/extra-typings";import{execSync as qN}from"child_process";import xw from"body-parser";import vO from"cors";import xO from"dedent";import TO from"events";import Tw,{Router as EO}from"express";import{diff as AA}from"deep-object-diff";import Mt from"fs";import Ut from"path";import{z as Eu}from"zod";var iM=Eu.object({input:Eu.string()});import{z as ze}from"zod";var lM=ze.object({srcs:ze.array(ze.string()),urls:ze.array(ze.string()),desiredSrc:ze.string().optional(),desiredUrl:ze.string().optional()}),Cu=ze.object({srcRegex:ze.string().optional(),urlRegex:ze.string().optional()}),Au=ze.object({x:ze.number(),y:ze.number(),correlation:ze.number()}),cM=ze.object({searchImageBase64String:ze.string(),pageImageBase64String:ze.string(),id:ze.string().uuid(),timeoutMs:ze.number().max(1e4).min(0).optional()});import{z as O}from"zod";import{v4 as Re}from"uuid";import*as w from"zod";function ye(r){if(typeof r.ZodType.prototype.openapi<"u")return;r.ZodType.prototype.openapi=function(o){return new this.constructor({...this._def,openapi:o})};let e=r.ZodObject.prototype.extend;r.ZodObject.prototype.extend=function(...o){let i=e.apply(this,o);return i._def.extendMetadata={extends:this},delete i._def.openapi,i};let t=r.ZodObject.prototype.omit;r.ZodObject.prototype.omit=function(...o){let i=t.apply(this,o);return delete i._def.extendMetadata,delete i._def.openapi,i};let n=r.ZodObject.prototype.pick;r.ZodObject.prototype.pick=function(...o){let i=n.apply(this,o);return delete i._def.extendMetadata,delete i._def.openapi,i}}import{z as he}from"zod";ye(he);var Ru=he.object({plan:he.string().optional(),evidence:he.string().optional(),thoughts:he.string(),result:he.boolean(),relevantElements:he.array(he.number()).optional()}),co=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(co||{});var Zv=he.object({type:he.literal("ELEMENT_CONTENT"),negated:he.boolean().optional(),operation:he.nativeEnum(co),value:he.string()}).openapi({ref:"ElementContentAssertion"}),Qv=he.object({type:he.literal("ELEMENT_ATTRIBUTE"),negated:he.boolean().optional(),operation:he.nativeEnum(co),attr:he.string(),value:he.string()}).openapi({ref:"ElementAttributeValueAssertion"}),bi=(o=>(o.EXISTS="EXISTS",o.VISIBLE="VISIBLE",o.ENABLED="ENABLED",o.EDITABLE="EDITABLE",o))(bi||{}),ex=he.object({type:he.literal("ELEMENT_EXISTENCE"),negated:he.boolean().optional(),condition:he.nativeEnum(bi).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Iu=he.discriminatedUnion("type",[Zv,Qv,ex]).openapi({ref:"ManualElementAssertion"});var tx=he.object({type:he.literal("CONTENT"),negated:he.boolean().optional(),value:he.string()}).openapi({ref:"PageContentAssertion"}),Pu=he.discriminatedUnion("type",[tx]).openapi({ref:"ManualPageAssertion"});import*as K from"zod";ye(K);var Vn=(s=>(s.AI="AI",s.AI_HEALED="AI_HEALED",s.CLICK_TO_FIND="CLICK_TO_FIND",s.XY_PERCENT="XY_PERCENT",s.RECORDING="RECORDING",s.USER_CSS_SELECTOR="USER_CSS_SELECTOR",s.HEURISTIC_HEALED="HEURISTIC_HEALED",s))(Vn||{}),nx=K.object({mPathSelectorTokens:K.string().array(),frameSrcRegex:K.string().optional(),frameUrlRegex:K.string().optional(),indices:K.number().array()}),vr=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:nx.optional(),inputDescription:K.string().optional().describe("the description that generated this cache"),targetSource:K.nativeEnum(Vn).optional(),targetUpdateTime:K.string().optional()}).openapi({ref:"A11yTargetWithCache"});function Lu(r){return!!(r.name||r.role||r.content||r.serializedForm||r.serializedHtml||r.screenshotUrl)}var rx=K.object({type:K.literal("description"),elementDescriptor:K.string(),a11yData:vr.optional().describe("DEPRECATED: new a11y cache is stored in DB and resolved into the 'cache' field")}).openapi({ref:"DescriptionTarget"}),ox=K.object({x:K.number(),y:K.number()}),ix=K.object({type:K.literal("coordinates"),pixels:ox}).openapi({ref:"CoordinatesTarget"});function qn(r){return r.type==="description"}function yn(r){return r.type==="coordinates"}var ct=K.discriminatedUnion("type",[rx,ix]).openapi({ref:"ElementTarget"});function oc(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function dt(r){if(!r)return"";switch(r.type){case"description":return r.elementDescriptor;case"coordinates":return`x: ${r.pixels.x}, y: ${r.pixels.y}`}}import{z as ie}from"zod";var Na=ie.object({url:ie.string(),method:ie.union([ie.literal("GET"),ie.literal("POST"),ie.literal("PUT"),ie.literal("DELETE"),ie.literal("PATCH")]),headers:ie.record(ie.string(),ie.string()).optional(),params:ie.record(ie.string(),ie.string()).optional(),body:ie.string().optional(),timeout:ie.number().int().optional().describe("Max seconds to wait for the request to complete")}),ku=ie.object({url:ie.string(),headers:ie.record(ie.string(),ie.string()).optional(),query:ie.string(),variables:ie.record(ie.string(),ie.string()).optional(),timeout:ie.number().int().optional().describe("Max seconds to wait for the request to complete")}),Ma=ie.object({code:ie.string(),fragment:ie.boolean().optional(),environment:ie.union([ie.literal("NODE"),ie.literal("BROWSER")]).optional().describe("default NODE"),timeout:ie.number().int().max(60).optional().describe("Max seconds for the code to complete")});var Ue=(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))(Ue||{});ye(w);var Y=w.object({thoughts:w.string().optional(),id:w.string().uuid().describe("unique identifier to this step, used for step cache")}),Gt=w.object({useSelector:w.boolean().optional(),force:w.boolean().optional(),disableCache:w.boolean().optional().describe("disable element caching for this step"),iframeUrl:w.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),bn=w.object({target:vr}).optional().openapi({ref:"SingleTargetCache"}),Fa=w.object({loadTimeout:w.number().int().max(60).optional().describe("Max seconds for the page to load")}),ax=Y.merge(Fa).merge(w.object({type:w.literal("NAVIGATE"),url:w.string()})).openapi({ref:"NavigateCommand"}),Da=Gt.merge(w.object({cache:bn})),po=Y.merge(Da.merge(w.object({target:ct.optional(),type:w.literal("SCROLL_UP"),deltaY:w.number().optional()}))).openapi({ref:"ScrollUpCommand"}),uo=Y.merge(Da.merge(w.object({target:ct.optional(),type:w.literal("SCROLL_DOWN"),deltaY:w.number().optional()}))).openapi({ref:"ScrollDownCommand"}),mo=Y.merge(Da.merge(w.object({target:ct.optional(),type:w.literal("SCROLL_LEFT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),ho=Y.merge(Da.merge(w.object({target:ct.optional(),type:w.literal("SCROLL_RIGHT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollRightCommand"}),AM=w.discriminatedUnion("type",[po,uo,mo,ho]).openapi({ref:"AllScrollCommands"}),sx=Y.merge(w.object({type:w.literal("DIALOG"),action:w.union([w.literal("ACCEPT"),w.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),lx=Y.merge(w.object({type:w.literal("WAIT"),delay:w.number()})).openapi({ref:"WaitCommand"}),cx=w.discriminatedUnion("type",[w.object({type:w.literal("SUBSTRING"),url:w.string()}),w.object({type:w.literal("GLOB"),glob:w.string()}),w.object({type:w.literal("REGEX"),regex:w.string()})]),dx=w.object({caseInsensitive:w.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:w.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:w.number().int().optional().describe("Max seconds to wait for the URL to match")}),px=Y.extend({type:w.literal("WAIT_FOR_URL"),url:w.string().optional().describe("Deprecated: url or glob to wait for. New commands should use the discriminated matcher field."),matcher:cx.optional()}).merge(dx).openapi({ref:"WaitUrlCommand"}),ux=Y.merge(Fa).merge(w.object({type:w.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),mx=Y.merge(w.object({type:w.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),hx=Y.merge(w.object({type:w.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),gx=Y.extend({type:w.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),fx=Y.extend({type:w.literal("AUTH_LOAD"),storageState:w.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),ac=Y.merge(Gt).extend({type:w.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),Sx=Y.extend({type:w.literal("COPY"),value:w.string()}).openapi({ref:"CopyCommand"}),yx=Y.extend({type:w.literal("PASTE")}).openapi({ref:"PasteCommand"}),bx=Y.merge(Ma).extend({type:w.literal("JAVASCRIPT"),envKey:w.string().optional()}).openapi({ref:"JavaScriptCommand"}),wi=Y.merge(Gt).merge(w.object({type:w.literal("CLICK"),target:ct,doubleClick:w.boolean().optional(),rightClick:w.boolean().optional(),waitForUrl:w.string().optional().describe("Deprecated: wait for the click to trigger a page load or new tab that matches the provided URL or URL glob (e.g. https://google.com/**/*)."),waitForDownload:w.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:w.number().optional(),downloadTimeoutMs:w.number().optional(),cache:bn,relativePosition:w.object({x:w.number(),y:w.number()}).optional()})).openapi({ref:"ClickCommand"}),vi=Y.merge(Gt).merge(w.object({type:w.literal("DRAG"),fromTarget:ct,toTarget:ct,steps:w.number().optional(),hoverSeconds:w.number().optional().describe("Seconds to hover the object before dropping"),cache:w.object({fromTarget:vr.optional(),toTarget:vr.optional()}).optional()})).openapi({ref:"DragCommand"}),xi=Y.merge(Gt).merge(w.object({type:w.literal("MOUSE_DRAG"),target:ct.optional(),deltaX:w.string().describe("pixels to move horizontally, can be template"),deltaY:w.string().describe("pixels to move vertically, can be template"),steps:w.number().optional(),cache:bn})).openapi({ref:"MouseDragCommand"}),Ti=Y.merge(Gt).merge(w.object({type:w.literal("HOVER"),target:ct,cache:bn})).openapi({ref:"HoverCommand"}),Ei=Y.merge(Gt).merge(w.object({type:w.literal("FOCUS"),target:ct,cache:bn})).openapi({ref:"FocusCommand"}),Ci=Y.merge(Gt).extend({type:w.literal("BLUR"),target:ct.optional(),cache:bn}).openapi({ref:"BlurCommand"}),wx=w.object({type:w.literal("URL"),url:w.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),vx=w.object({type:w.literal("USER_FILE"),name:w.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),xx=Y.extend({type:w.literal("FILE_UPLOAD"),fileSource:w.discriminatedUnion("type",[wx,vx]),filename:w.string().optional()}).openapi({ref:"FileUploadCommand"}),Tx=w.discriminatedUnion("type",[w.object({type:w.literal("VALUE"),value:w.string()}),w.object({type:w.literal("LABEL"),label:w.string()}),w.object({type:w.literal("INDEX"),index:w.coerce.string()})]),Ai=Y.merge(Gt).extend({type:w.literal("SELECT_OPTION"),target:ct,cache:bn,option:w.string().describe("option value, deprecated old field").optional(),choice:Tx.optional().describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),sc=w.union([w.literal("MULTIMODAL"),w.literal("VISION_ONLY")]),lc=Y.merge(w.object({type:w.literal("AI_ASSERTION"),assertion:w.string(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional(),contextChoice:sc.optional(),timeout:w.number().int().optional().describe("Max seconds to wait for assertion to be true")})).openapi({ref:"AIAssertionCommand"}),Ex=lc.extend({type:w.literal("AI_WAIT")}).openapi({ref:"AIWaitCommand"}),wn=5,cc=600,Ri=Y.merge(Gt).extend({type:w.literal("ELEMENT_CHECK"),target:ct,assertion:Iu,cache:bn,timeout:w.number().int().min(0).max(cc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),Cx=Y.extend({type:w.literal("PAGE_CHECK"),assertion:Pu,iframeUrl:w.string().optional().describe("url or url regex for the iframe"),timeout:w.number().int().min(0).max(cc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),Ax=Y.merge(w.object({type:w.literal("AI_EXTRACT"),goal:w.string(),schema:w.string().optional(),envKey:w.string().optional(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional()})).openapi({ref:"AIExtractCommand"}),Rx=w.object({clearContent:w.boolean().optional(),forceClearContent:w.boolean().optional(),pressKeysSequentially:w.boolean().optional().describe("Deprecated: this is now the default. Please set delay to zero if you wish to achieve instant typing behavior."),delay:w.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:w.boolean().optional(),pressEnter:w.boolean().optional()}),Ou=25,Ii=Y.merge(Gt).merge(Rx).extend({type:w.literal("TYPE"),target:ct.optional(),value:w.string(),cache:bn}).openapi({ref:"TypeCommand"}),Ix=Y.merge(w.object({type:w.literal("PRESS"),value:w.string(),repeat:w.number().optional(),convertMeta:w.boolean().optional(),delayMs:w.number().optional()})).openapi({ref:"PressCommand"}),Px=w.object({type:w.literal("SUBSTRING"),substring:w.string()}),Lx=w.object({type:w.literal("REGEX"),pattern:w.string()}),kx=w.object({type:w.literal("INDEX"),index:w.coerce.string()}),Ox=w.discriminatedUnion("type",[Px,Lx,kx]),Nx=Y.merge(Fa).merge(w.object({type:w.literal("TAB"),url:w.string().optional().describe("deprecated field - new instances should use the discriminated union"),action:Ox.optional()})).openapi({ref:"TabCommand"}),Mx=Y.merge(Fa).merge(w.object({type:w.literal("NEW_TAB"),url:w.string()})).openapi({ref:"NewTabCommand"}),_x=Y.merge(w.object({type:w.literal("COOKIE"),value:w.string()})).openapi({ref:"CookieCommand"}),Fx=Y.merge(w.object({type:w.literal("LOCAL_STORAGE"),key:w.string(),value:w.string()})).openapi({ref:"LocalStorageCommand"}),Dx=Y.extend({type:w.literal("REQUEST")}).merge(Na).openapi({ref:"RequestCommand"}),Ux=Y.extend({type:w.literal("GRAPHQL_REQUEST")}).merge(ku).openapi({ref:"GraphQLRequestCommand"}),Bx=Y.merge(w.object({type:w.literal("SUCCESS"),condition:lc.optional()})).openapi({ref:"SuccessCommand"}),zx=Y.merge(w.object({type:w.literal("FAILURE")})).openapi({ref:"FailureCommand"}),jx=w.object({data:w.string().describe("location at which to find a jpg"),width:w.number(),height:w.number()}),Pi=Y.merge(Gt).merge(w.object({type:w.literal("VISUAL_DIFF"),threshold:w.number().optional().describe("default 0.1"),target:ct.optional(),screenshot:jx.optional(),cache:bn})).openapi({ref:"VisualDiffCommand"}),Hx=Y.merge(w.object({type:w.literal("REGISTER_REQUEST_LISTENER"),pattern:w.string(),key:w.string()})).openapi({ref:"RegisterRequestListenerCommand"}),$x=Y.merge(w.object({type:w.literal("AWAIT_LISTENER"),key:w.string(),timeout:w.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),Nu=w.discriminatedUnion("type",[wi,Ii,Ix,Ai,ax,uo,po,lc,Ti,lx,Bx]),Wx=w.discriminatedUnion("type",[Ex,Ax,fx,gx,ac,_x,Sx,sx,vi,Ri,xx,mx,hx,bx,Fx,xi,Mx,Cx,yx,ux,Dx,Ux,mo,ho,Nx,Pi,Ei,Ci,px,Hx,$x]),go=w.discriminatedUnion("type",[...Nu.options,...Wx.options]).openapi({ref:"Command"}),Ua=w.discriminatedUnion("type",[...Nu.options,zx]);function kn(r){let e;switch(r){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:Re(),type:r};break;case"AUTH_LOAD":{e={id:Re(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:Re(),type:r,goal:""};break;case"DIALOG":e={id:Re(),type:r,action:"DISMISS"};break;case"DRAG":e={id:Re(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Re(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Re(),type:r,url:""};break;case"WAIT":e={id:Re(),type:r,delay:1};break;case"BLUR":e={id:Re(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:Re(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:Re(),type:r,value:"",clearContent:!0};break;case"SELECT_OPTION":e={id:Re(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":case"TAB":e={id:Re(),type:r,url:""};break;case"REQUEST":e={id:Re(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:Re(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:Re(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:Re(),type:r,code:""};break;case"AI_WAIT":case"AI_ASSERTION":e={id:Re(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:Re(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Re(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Re(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:Re(),type:r,pattern:"",key:""};break}case"AWAIT_LISTENER":{e={id:Re(),type:r,key:""};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}function Mu(r){switch(r.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"})(r)}}import{z as Gx}from"zod";var kM=Gx.discriminatedUnion("type",[Ci,ac,wi,vi,Ei,Ti,xi,po,uo,mo,ho,Ai,Ii,Pi,Ri]);function _u(r){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(r)}import{z as Vx}from"zod";var Et={type:!0,cache:!0},xr=Vx.discriminatedUnion("type",[Ci.pick(Et),wi.pick(Et),vi.pick(Et),Ri.pick(Et),Ei.pick(Et),Ti.pick(Et),xi.pick(Et),po.pick(Et),uo.pick(Et),mo.pick(Et),ho.pick(Et),Ai.pick(Et),Ii.pick(Et),Pi.pick(Et)]),dc=Object.values(Ue).filter(r=>xr.options.some(e=>e.shape.type.safeParse(r).success));go.options.forEach(r=>{if("target"in r.shape&&!dc.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});import{z as uc}from"zod";import{z as pc}from"zod";import{z as fo}from"zod";var Ct=fo.object({index:fo.number().optional().describe("global index within a test (in-order traversal)"),id:fo.string(),skipped:fo.boolean().optional(),envKey:fo.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:fo.boolean().optional()});ye(pc);var At=Ct.extend({type:pc.literal("PRESET_ACTION"),command:go,skipped:pc.boolean().optional()}).openapi({ref:"PresetAction"});ye(uc);var Tr=Ct.extend({type:uc.literal("AI_ACTION"),text:uc.string(),steps:At.array().optional()}).openapi({ref:"AIAction"});import{z as ce}from"zod";var qx=ce.object({cacheKey:ce.string(),cacheExpiryMs:ce.number()}),mc=Ct.extend({id:ce.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ce.record(ce.string()).optional(),cacheConfig:qx.optional()}),On=mc.extend({type:ce.literal("MODULE"),moduleId:ce.string().uuid()}),Kx=ce.union([On.pick({type:!0,moduleId:!0}),ce.record(ce.unknown())]),Yx=ce.object({type:ce.literal("URL_REGEX"),regex:ce.string()}),Jx=ce.object({type:ce.literal("PAGE_CHECK"),substring:ce.string()}),hc=ce.object({cacheInvalidation:ce.discriminatedUnion("type",[Jx,Yx]).optional()}),Rt=ce.object({moduleId:ce.string().uuid(),name:ce.string(),description:ce.string().nullish(),enabled:ce.boolean().nullish(),parameters:ce.string().array().nullish(),defaultParameters:ce.record(ce.string(),ce.string()).nullish(),defaultCacheKey:ce.string().nullish(),defaultCacheTtl:ce.number().nullish(),defaultCacheAllInvocations:ce.boolean().nullish(),autoAuth:ce.boolean().nullish(),advanced:hc.nullish()});import{z as rt}from"zod";import{z as gc}from"zod";ye(gc);var So=Ct.extend({type:gc.literal("AI_ACTION_DYNAMIC"),text:gc.string()}).openapi({ref:"AIActionDynamic"});import{z as Fu}from"zod";var fc=Ct.extend({type:Fu.literal("CONDITIONAL"),skipped:Fu.boolean().optional()});import{z as Ba}from"zod";var Xx=Ba.object({type:Ba.literal("url"),url:Ba.string()}),Li=Ct.extend({type:Ba.literal("IFRAME"),identifier:Xx});import{z as Vt}from"zod";var Sc=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(Sc||{});var Zx=Vt.discriminatedUnion("type",[Vt.object({type:Vt.literal("NAVIGATE_URL"),url:Vt.string().url()}),Vt.object({type:Vt.literal("GO_TO_SECTION_START")})]),Qx=Vt.object({trigger:Vt.nativeEnum(Sc).optional(),attempts:Vt.number().int().optional(),restartBehavior:Zx}),ki=Ct.extend({type:Vt.literal("SECTION"),description:Vt.string().describe("user provided goal of what the section should accomplish"),plan:Vt.string().array().optional(),autohealingConfig:Qx.optional()});var Du=Rt.merge(mc).extend({type:rt.literal("RESOLVED_MODULE"),steps:rt.lazy(()=>ve.array())}),yc=Rt.extend({steps:rt.lazy(()=>ve.array())}),bc=Li.extend({steps:rt.lazy(()=>Je.array())}),eT=Li.extend({steps:rt.lazy(()=>ve.array())}),wc=ki.extend({steps:rt.lazy(()=>Je.array())}),tT=ki.extend({steps:rt.lazy(()=>ve.array())}),Er=fc.extend({blocks:rt.object({assertion:rt.lazy(()=>At),steps:rt.lazy(()=>Je.array())}).array(),elseSteps:rt.lazy(()=>Je.array().optional())}),nT=fc.extend({blocks:rt.object({assertion:rt.lazy(()=>At),steps:rt.lazy(()=>ve.array())}).array(),elseSteps:rt.lazy(()=>ve.array().optional())}),Je=rt.discriminatedUnion("type",[At,Tr,So,On,Er,bc,wc]),ve=rt.discriminatedUnion("type",[At,Tr,So,Du,nT,eT,tT]);import{z as qt}from"zod";var rT=qt.object({steps:Je.array(),beforeSteps:Je.array().nullish(),afterSteps:Je.array().nullish()}),yo=qt.object({steps:ve.array(),beforeSteps:ve.array().nullish(),afterSteps:ve.array().nullish()}),Cr=qt.object({steps:qt.record(qt.string(),qt.unknown()).array(),beforeSteps:qt.record(qt.string(),qt.unknown()).array().nullish(),afterSteps:qt.record(qt.string(),qt.unknown()).array().nullish()});var je="1.0.19";import{z as Ar}from"zod";var vc=Ar.object({key:Ar.string(),testId:Ar.string().optional(),moduleId:Ar.string().optional(),organizationId:Ar.string(),value:xr}),Uu=Ar.record(Ar.string(),vc);var Bu=O.object({phrase:O.string()}),xc=O.object({thoughts:O.string().optional(),result:O.union([O.literal("NOT_FOUND"),O.string(),O.number(),O.array(O.unknown()),O.record(O.unknown(),O.unknown()),O.unknown()])}),LF=O.object({text:O.string()}),zu=O.object({thoughts:O.string(),review:O.string().optional(),id:O.number().int()}),za=(m=>(m.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",m.FEW_WORDS="FEW_WORDS",m.STYLE_TAG="STYLE_TAG",m.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",m.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",m.NONE="NONE",m.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",m.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",m.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",m.PREFER_ASSERTION="PREFER_ASSERTION",m.HTML_ELEMENTS="HTML_ELEMENTS",m.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",m))(za||{});var ju=O.object({thoughts:O.string(),category:O.nativeEnum(za)}),oT=O.discriminatedUnion("op",[O.object({op:O.literal("replace"),path:O.string(),value:O.string()}),O.object({op:O.literal("add"),path:O.string(),value:O.string()}),O.object({op:O.literal("remove"),path:O.string()})]),kF=O.object({thoughts:O.string(),patches:oT.array()}),Hu=[O.literal("add"),O.literal("replace"),O.literal("remove")],iT=O.object({op:O.union(Hu),path:O.string(),value:ve.optional()}),$u=O.object({patches:iT.array(),thoughts:O.string()});var aT=O.object({thoughts:O.string(),op:O.union(Hu),value:O.union([O.null(),ve])}),Wu=O.object({reasoning:O.string(),scenario:O.string(),patch:aT.or(O.null())}),OF=O.object({thoughts:O.string(),evaluation:O.number().min(1).max(10)}),NF=O.object({observations:O.string(),reasoning:O.string(),command:Ua});var Tc=O.object({summary:O.string(),reasoning:O.string(),evaluation:O.discriminatedUnion("type",[O.object({type:O.literal("DONE")}),O.object({type:O.literal("RIGHT_TRACK")}),O.object({type:O.literal("WRONG_TRACK"),feedback:O.string()}),O.object({type:O.literal("IMPOSSIBLE")})])});import{z as F}from"zod";import*as te from"zod";var BF=te.object({thoughts:te.string().optional().describe("only provided if a description was provided"),target:vr.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")}),Gu=te.union([te.literal("NEGATED_CHECK"),te.literal("SELECT_OPTION"),te.literal("TYPE")]);function Oi(r){if(!("useSelector"in r&&r.useSelector)){if(r.type==="SELECT_OPTION")return"SELECT_OPTION";if(r.type==="TYPE")return"TYPE";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.negated)return"NEGATED_CHECK"}}var Ni=(a=>(a.A11Y_ID="A11Y_ID",a.USER_SELECTOR="USER_SELECTOR",a.CSS_SELECTOR="CSS_SELECTOR",a.HTML_DISTANCE="HTML_DISTANCE",a.TEMPLATE_MATCHING="TEMPLATE_MATCHING",a.AUTO_FRAME="AUTO_FRAME",a))(Ni||{}),bo=te.object({matched:te.boolean(),reason:te.string().optional().describe("Human understandable description"),logs:te.string().array().optional().describe("Logs for debugging")}),sT=bo.extend({type:te.literal("A11Y_ID")}),lT=bo.extend({type:te.literal("USER_SELECTOR")}),cT=bo.extend({type:te.literal("CSS_SELECTOR"),selectors:te.string().array()}),dT=bo.extend({type:te.literal("HTML_DISTANCE"),distance:te.number().optional(),closestElement:te.string().optional(),savedElement:te.string().optional()}),pT=bo.extend({type:te.literal("TEMPLATE_MATCHING"),elementImageUrl:te.string().url()}),uT=bo.extend({type:te.literal("AUTO_FRAME"),logs:te.string().array().optional()}),Vu=te.discriminatedUnion("type",[sT,lT,cT,dT,pT,uT]);import{z as Ui}from"zod";import{z as ME}from"zod";import*as J from"zod";import{cloneDeep as _i}from"lodash-es";var mT=r=>{let e=qu(r,0);if(e===void 0||!gT(r[e]))return;let t=qu(r,e+1);if(t!==void 0)return fT(r,e,t)},Ku=mT,qu=(r,e)=>{for(let t=e;t<r.length;t+=1){let n=r[t];if(!hT(n))return t}},hT=r=>r===" "||r===" "||r===`
|
|
5
|
+
`||r==="\r",gT=r=>r==="{"||r==="[",fT=(r,e,t)=>{let n;for(let o=t-1;o>e;o-=1){let i=r[o];if(i==="\r")return;if(i===`
|
|
6
|
+
`)return ST(n);if(n===void 0)n=i;else if(n[0]===i)n+=i;else return}},ST=r=>r===void 0?0:r[0]===" "?r.length:r;var Yu=(r,e)=>{let t=Ec(r,"toPrecision",e,e);return t===void 0?Ec(r,"toExponential",e,e):t},Ec=(r,e,t,n)=>{let i=r[e](n).replace(yT,"$1").replace(bT,"$1");return i.length<=t?i:n===1?void 0:Ec(r,e,t,n-1)},yT=/(e)\+/iu,bT=/\.?0*($|e)/iu;var Xu=(r,e)=>{if(typeof r!="string")throw new TypeError(`Input must be a JSON string: ${r}`);wT(e)},wT=r=>{if(vT(r),r<0)throw new TypeError(`"maxSize" argument must be positive: ${r}`);if(r<Ju)throw new TypeError(`"maxSize" argument must be at least ${Ju}: ${r}`)},vT=r=>{if(r===void 0)throw new TypeError('"maxSize" argument must be defined');if(!Number.isInteger(r))throw new TypeError(`"maxSize" argument must be an integer: ${r}`)},Ju=7;var ja=(r,e,t)=>{let n=Qu(e,t);return Zu(r,e,n)},Zu=(r,e,t)=>{if(t>=e)return t;let n=r[t];return n>=LT&&n<=kT?Zu(r,e,t+1):t},Ha=(r,e,t)=>{if(t===void 0)return t;let n=Qu(e,t);return xT(r,n)},xT=(r,e)=>TT(r,e)?e-3:ET(r,e)?e-2:CT(r,e)?e-1:e,TT=(r,e)=>e>=3&&r[e-3]>=AT&&r[e-3]<=RT,ET=(r,e)=>e>=2&&r[e-2]>=IT,CT=(r,e)=>e>=1&&r[e-1]>=PT,Qu=(r,e)=>e<0||Object.is(e,-0)?Math.max(r+e,0):e,AT=240,RT=244,IT=224,PT=194,LT=128,kT=191;var em=(r,e,t)=>{let n=globalThis.Buffer.from(r),o=ja(n,n.length,e),i=Ha(n,n.length,t);return o===0&&i>=n.length?n.toString():n.toString("utf8",o,i)};var tm=/[\uD800-\uDFFF]/gu,nm="\uFFFD";var $a=r=>OT(r)?r.replace(tm,nm):r,OT=r=>{for(let e=0;e<r.length;e+=1){let t=r.codePointAt(e);if(t>=55296&&t<=57343)return!0}return!1};var Rc=({input:r,targetByteCount:e,firstStartSurrogate:t,lastStartSurrogate:n,firstEndSurrogate:o,lastEndSurrogate:i,increment:a,canBacktrack:s,shift:l,charIndexInit:c})=>{let p=c,d=p,m=0;for(;m<e;p+=a){d=p;let h=r.charCodeAt(p);if(Number.isNaN(h))break;if(h<=127){m+=1;continue}if(h<=2047){m+=2;continue}if(m+=3,h<t||h>n)continue;let g=r.charCodeAt(p+a);Number.isNaN(g)||g<o||g>i||(m+=1,p+=a)}return(s&&m>e?d:p)+l};var Ic=(r,e,t)=>e<0||Object.is(e,-0)?UT(r,e,t):DT(r,e,t),DT=(r,e,t)=>Rc({input:r,targetByteCount:e,firstStartSurrogate:55296,lastStartSurrogate:56319,firstEndSurrogate:56320,lastEndSurrogate:57343,increment:1,canBacktrack:t,shift:0,charIndexInit:0}),UT=(r,e,t)=>Rc({input:r,targetByteCount:-e,firstStartSurrogate:56320,lastStartSurrogate:57343,firstEndSurrogate:55296,lastEndSurrogate:56319,increment:-1,canBacktrack:!t,shift:1,charIndexInit:r.length-1});var Wa=(r,e,t)=>{let n=Ic(r,e,!1),o=BT(r,t),i=n===0&&o===void 0?r:r.slice(n,o);return $a(i)},BT=(r,e)=>{if(e===void 0)return e;let t=Ic(r,e,!0);return t===r.length?void 0:t};var om=(r,e,t)=>{let{textEncoder:n,textDecoder:o}=zT(),i=jT(r),{written:a}=n.encodeInto(r,i),s=ja(i,a,e),l=Ha(i,a,t),c=l===void 0?a:Math.min(l,a),p=i.subarray(s,c);return o.decode(p)},zT=()=>(Pc===void 0&&(Pc=new globalThis.TextEncoder,rm=new globalThis.TextDecoder("utf8",{fatal:!1})),{textEncoder:Pc,textDecoder:rm}),Pc,rm,jT=r=>{let e=r.length*3;return e>HT?new Uint8Array(e):((Ga===void 0||Ga.length<e)&&(Ga=new Uint8Array(e)),Ga)},HT=1e5,Ga;var im=(r,e)=>{if(e===void 0)return e;let t=Lc(r,e);return t>=r.length*am?void 0:t},Lc=(r,e)=>e<=r.length*-am?0:e,am=4;var sm=(r,e,t)=>{if(typeof r!="string")throw new TypeError(`First argument must be a string: ${r}`);$T(e),WT(t)},$T=r=>{if(r===void 0)throw new TypeError("Second argument is required.");lm("Second",r)},WT=r=>{r!==void 0&&lm("Third",r)},lm=(r,e)=>{if(!Number.isInteger(e))throw new TypeError(`${r} argument must be an integer: ${e}`)};var cm=r=>{let e=!0,t=0;for(let n=0;n<kc;n+=1){let o=GT(r,n);o<=127||(e&&(e=!1),o>2047&&(t+=1))}return{asciiOnly:e,longCharsPercentage:t/kc}},GT=(r,e)=>{let t=kc-1,n=1-(t-e)/t,o=Math.round(n*(r.length-1));return r.charCodeAt(o)},kc=50;var VT=(r,e,t)=>{if(sm(r,e,t),r==="")return r;let n=Lc(r,e),o=im(r,t);return o===void 0&&Object.is(n,0)?$a(r):qT(r,n,o)},dm=VT,qT=(r,e,t)=>{if(r.length<=KT)return Wa(r,e,t);let{asciiOnly:n,longCharsPercentage:o}=cm(r);return n?JT(r,e,t):o>=YT?Wa(r,e,t):pm(r,e,t)},KT=200,YT=.4,JT=(r,e,t)=>"Buffer"in globalThis&&"from"in globalThis.Buffer?em(r,e,t):pm(r,e,t),pm=(r,e,t)=>"TextEncoder"in globalThis?om(r,e,t):Wa(r,e,t);var mm=(r,e)=>{let t=JSON.stringify(r),n=QT(t),o=dm(n,0,e-um.length-Mi.length*2),a=`${XT(o)}${um}`;return eE(a)},XT=r=>r.replace(ZT,""),ZT=/(\\|\\u[0-9a-fA-F]{0,3})$/u,QT=r=>r.slice(Mi.length,-Mi.length),eE=r=>`${Mi}${r}${Mi}`,Mi='"',um="...";var hm=r=>globalThis.Buffer.byteLength(r);var Oc=r=>{let e=r.length,t=e;for(let n=0;n<e;n+=1){let o=r.charCodeAt(n);if(o<=tE)continue;if(o<=nE){t+=1;continue}if(t+=2,o<rE||o>oE)continue;let i=r.charCodeAt(n+1);i<iE||i>aE||(n+=1)}return t},tE=127,nE=2047,rE=55296,oE=56319,iE=56320,aE=57343;var gm=()=>sE.bind(void 0,new TextEncoder),sE=(r,e)=>{let t=lE(e);return r.encodeInto(e,t).written},lE=r=>{let e=r.length*3;return e>cE?new Uint8Array(e):((Va===void 0||Va.length<e)&&(Va=new Uint8Array(e)),Va)},cE=1e5,Va;var pE=()=>"Buffer"in globalThis&&"byteLength"in globalThis.Buffer?hm:"TextEncoder"in globalThis?uE.bind(void 0,gm()):Oc,uE=(r,e)=>e.length<100?Oc(e):r(e),fm=pE();var Sm=r=>{if(r===null)return mE;if(r===!0)return hE;if(r===!1)return gE;let e=typeof r;return e==="object"?fE:e==="number"?JSON.stringify(r).length:Nc(r)},mE=4,hE=4,gE=5,fE=2,Nc=r=>fm(JSON.stringify(r));var qa=({size:r,increment:e,maxSize:t,truncatedProps:n,path:o,value:i})=>{let a=r+e,s=a>t;return s?{size:r,stop:s,truncatedProps:[...n,{path:o,value:i}]}:{size:a,stop:s,truncatedProps:n}},bm=r=>Sm(r),wm=(r,e,t)=>{let n=xm({empty:r,indent:e,depth:t,keySpaceSize:0}),o=Tm(r);return n+o},vm=({key:r,empty:e,indent:t,depth:n})=>{let o=xm({empty:e,indent:t,depth:n,keySpaceSize:1}),i=Nc(r),a=Tm(e);return o+i+SE+a},SE=1,xm=({empty:r,indent:e,depth:t,keySpaceSize:n})=>{if(e===void 0)return 0;let o=ym+e*(t+1),i=r?ym+e*t:0;return n+o+i},ym=1,Tm=r=>r?0:yE,yE=1;var Ka=({parent:r,truncatedProps:e,path:t,increment:n,maxSize:o,key:i,empty:a,size:s,truncateValue:l,indent:c,depth:p})=>{let d=r[i],m=[...t,i],{size:u,stop:h,truncatedProps:g}=qa({size:s,increment:n,maxSize:o,truncatedProps:e,path:m,value:d});return h?{empty:a,size:u,truncatedProps:g}:bE({value:d,truncatedProps:e,path:m,maxSize:o,empty:a,size:s,newSize:u,truncateValue:l,indent:c,depth:p})},bE=({value:r,truncatedProps:e,path:t,maxSize:n,empty:o,size:i,newSize:a,truncateValue:s,indent:l,depth:c})=>{let{value:p,size:d,truncatedProps:m}=s({value:r,truncatedProps:e,path:t,size:a,maxSize:n,indent:l,depth:c+1});return p===void 0?{empty:o,size:i,truncatedProps:m}:{empty:!1,size:d,value:p,truncatedProps:m}};var Em=({array:r,truncatedProps:e,path:t,size:n,maxSize:o,truncateValue:i,indent:a,depth:s})=>{let l=[],c={empty:!0,size:n,truncatedProps:e};for(let p=0;p<r.length;p+=1){let d=wm(c.empty,a,s);c=Ka({parent:r,truncatedProps:c.truncatedProps,path:t,increment:d,maxSize:o,key:p,empty:c.empty,size:c.size,truncateValue:i,indent:a,depth:s}),c.value!==void 0&&l.push(c.value)}return{value:l,size:c.size,truncatedProps:c.truncatedProps}};var Cm=({object:r,truncatedProps:e,path:t,size:n,maxSize:o,truncateValue:i,indent:a,depth:s})=>{let l={},c={empty:!0,size:n,truncatedProps:e};for(let p in r){let d=vm({key:p,empty:c.empty,indent:a,depth:s});c=Ka({parent:r,truncatedProps:c.truncatedProps,path:t,increment:d,maxSize:o,key:p,empty:c.empty,size:c.size,truncateValue:i,indent:a,depth:s}),c.value!==void 0&&(l[p]=c.value)}return{value:l,size:c.size,truncatedProps:c.truncatedProps}};var Ya=({value:r,truncatedProps:e,path:t,size:n,maxSize:o,indent:i,depth:a})=>{let s=bm(r),{size:l,stop:c,truncatedProps:p}=qa({size:n,increment:s,maxSize:o,truncatedProps:e,path:t,value:r});return c?{value:void 0,size:l,truncatedProps:p}:wE({value:r,truncatedProps:p,path:t,size:l,maxSize:o,indent:i,depth:a})},wE=({value:r,truncatedProps:e,path:t,size:n,maxSize:o,indent:i,depth:a})=>typeof r!="object"||r===null?{value:r,size:n,truncatedProps:e}:Array.isArray(r)?Em({array:r,truncatedProps:e,path:t,size:n,maxSize:o,truncateValue:Ya,indent:i,depth:a}):Cm({object:r,truncatedProps:e,path:t,size:n,maxSize:o,truncateValue:Ya,indent:i,depth:a});var vE=(r,e)=>{Xu(r,e);let t=xE(r),n=TE(r),{value:o,truncatedProps:i}=Ya({value:n,truncatedProps:[],path:[],size:0,maxSize:e,indent:t,depth:0});return{jsonString:EE({newValue:o,value:n,maxSize:e,indent:t}),truncatedProps:i}},wo=vE,xE=r=>{let e=Ku(r);return typeof e=="string"?e.length:e},TE=r=>{try{return JSON.parse(r)}catch(e){throw new TypeError(`Invalid JSON string: "${r}"
|
|
7
|
+
${e.message}`)}},EE=({newValue:r,value:e,maxSize:t,indent:n})=>r!==void 0?JSON.stringify(r,void 0,n):typeof e=="number"?Yu(e,t):mm(e,t);import*as Rr from"zod";import{z as Ne}from"zod";var Am=6e4,Ie="BASE_URL",Ja="CURRENT_URL",vo="ENV_NAME",qD={[Ie]:"https://www.google.com"},Rm=Ne.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Xa=Ne.object({name:Ne.string(),variables:Ne.record(Ne.string().describe("variable name"),Ne.string().describe("variable value"))}),xo=Ne.object({pageLoadTimeoutMs:Ne.number().optional().refine(r=>r===void 0||r<=Am&&r>=-1,{message:`Page load timeout must be between 0 and ${Am/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),localChromeExtensionPaths:Ne.string().array().optional(),extraHeaders:Ne.record(Ne.string(),Ne.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:Ne.string().optional(),disableGpu:Ne.boolean().optional(),ignoreHrefForCaching:Ne.boolean().optional().describe("When running locally often times <a> hrefs will be different every time, resulting in cache busting. This will ignore href in <a> matching when there is text content."),bustCacheOnBoundingBoxChange:Ne.boolean().optional().describe("Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed.")}),Za=Ne.object({name:Ne.string(),variables:Ne.record(Ne.string().describe("variable name"),Ne.unknown().describe("variable value")),browser:xo.optional()});ye(Rr);var Fi=Rr.object({env:Rr.record(Rr.unknown())}).openapi({ref:"TestContextSnapshot"}),CE="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",AE=[Ie,vo],Im=[Ja,Ie,vo],It=class r{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t={}){return new r({baseUrl:"about:blank",currentUrl:"about:blank",envName:e,variablesFromEnvironment:t})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[Ie]??"about:blank",o=e.env[Ja]??"about:blank",i=e.env[vo],a={};for(let[l,c]of Object.entries(e.env))Im.includes(l)||(t??{})[l]===void 0&&(a[l]=c);return new r({baseUrl:n,currentUrl:o,dynamicVariables:a,envName:i,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=_i(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){AE.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[vo]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return _i(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>Im.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,CE]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=wo(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=wo(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}setCurrentUrl(e){this.env[Ja]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=_i(e.variablesFromEnvironment),this.setMomenticSystemVariable(Ie,e.baseUrl),e.envName&&this.setMomenticSystemVariable(vo,e.envName)}getDynamicVariablesCopy(){return _i(this.env)}getVariablesFromEnvironmentCopy(){return _i(this.varsFromMomenticEnvironment)}};import{z as Ir}from"zod";ye(Ir);var pe=(c=>(c.AI_PROVIDER="AIProviderError",c.USER_INFRA="UserInfrastructureError",c.ACTION_FAILURE="ActionFailureError",c.ASSERTION_FAILURE="AssertionFailureError",c.CONFIG_ERROR="UserConfigurationError",c.WEB_AGENT_PLATFORM="InternalWebAgentError",c.UNKNOWN_PLATFORM="InternalPlatformError",c.JOB_TIMEOUT="JobTimeoutError",c.UNKNOWN="UnknownError",c))(pe||{});var Pm=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],Qa={ActionFailureError:"Action failure",AssertionFailureError:"Assertion failure",UserInfrastructureError:"Infrastructure failure",UserConfigurationError:"Configuration error",AIProviderError:"AI provider error",InternalWebAgentError:"Momentic AI agent error",JobTimeoutError:"Job timeout",InternalPlatformError:"Unknown Momentic platform error",UnknownError:"Unknown error"},To={ActionFailureError:"A browser action such as a click or type failed to execute because of the underlying page state is incorrect, suggesting a bug in the application itself.",AssertionFailureError:"An AI assertion or check failed for a legitimate reason, such as a missing element, a change in the page structure, or an unexpected state (e.g. loading state).",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",UserInfrastructureError:"The user's web application exhibited an infrastructure failure, such as a page load timeout, a 5XX status code, maintenance page, or session crash.",UserConfigurationError:"The error message suggests a user-caused misconfiguration in the test, such as an undefined variable, a missing base URL, an empty test/module input parameter, or an invalid step option",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself.",InternalWebAgentError:"The AI testing framework failed to find the correct element or evaluate the assertion correctly, even though the test steps and application state look valid. In other words, the AI agent failed to understand the page.",UnknownError:"An unknown error occurred. Please refer to the failure details in the run for more information or reach out to Momentic Support for assistance.",InternalPlatformError:"An unknown error occurred with the Momentic platform."},Mc=Ir.object({reason:Ir.nativeEnum(pe),summary:Ir.string()}).openapi({ref:"TestResultClassification"}),es=Ir.object({errorMessage:Ir.string(),errorStack:Ir.string().optional(),classification:Mc.optional()}).openapi({ref:"TestFailureDetails"});ye(J);var xe=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(xe||{}),_c=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(_c||{}),Fc=J.object({beforeUrl:J.string().optional(),afterUrl:J.string().optional(),message:J.string().optional(),beforeScreenshot:J.string().optional(),afterScreenshot:J.string().optional(),beforeSnapshot:J.string().optional(),afterSnapshot:J.string().optional(),startedAt:J.coerce.date(),finishedAt:J.coerce.date()}),RE=Fc.extend({viewport:J.object({height:J.number(),width:J.number()}),status:J.nativeEnum(_c),message:J.string().optional(),elementInteracted:J.string().optional()}),Kn=Fc.extend({status:J.nativeEnum(xe),message:J.string().optional(),data:J.unknown().optional(),beforeTestContext:Fi.optional(),afterTestContext:Fi.optional(),failureReason:J.nativeEnum(pe).optional(),details:J.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),ts=Kn.merge(At).extend({results:RE.array(),proposedStep:At.optional()}),IE=Kn.merge(Tr).extend({results:J.lazy(()=>ts.array())}),PE=Kn.merge(So).extend({results:J.lazy(()=>ts.array())}),LE=Kn.merge(On).extend({moduleName:J.string().optional(),results:J.lazy(()=>an.array())}),kE=Kn.merge(Er).extend({assertion:ts.optional(),results:J.lazy(()=>an.array()).describe("results for the block actually executed")}),OE=Kn.merge(Li).extend({results:J.lazy(()=>an.array())}),NE=Kn.merge(ki).extend({results:J.lazy(()=>an.array()),healingAttempts:J.lazy(()=>an.array().array()).optional()}),an=J.discriminatedUnion("type",[IE,PE,ts,LE,kE,OE,NE]),ns=Kn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),rs=Fc.extend({index:J.number().optional(),description:J.string(),pageState:J.string().optional()});var Dc=ME.object({results:an.array().describe("main results"),beforeResults:an.array().optional(),afterResults:an.array().optional()}),os=Dc.partial();import{z as H}from"zod";import{z as be}from"zod";var _E=be.object({type:be.literal("FAILURE_RECOVERY"),thoughts:be.string()}),FE=be.object({type:be.literal("DESCRIPTION_UPDATE"),thoughts:be.string()}),is=be.discriminatedUnion("type",[FE,_E]),as=(e=>(e.AUTO_HEALING="AUTO_HEALING",e))(as||{}),DE=be.object({testId:be.string(),name:be.string(),orgId:be.string(),runId:be.string(),purpose:be.nativeEnum(as).catch("AUTO_HEALING"),steps:ve.array(),details:is.or(is.array()).optional()}),b0=DE.pick({name:!0,orgId:!0}),Uc=be.object({id:be.string(),name:be.string().nullish(),createdAt:be.string().pipe(be.coerce.date()).or(be.date()),organizationId:be.string(),schemaVersion:be.string(),purpose:be.nativeEnum(as).catch("AUTO_HEALING"),runId:be.string().nullish(),details:is.or(is.array()).nullish(),applied:be.boolean().nullish(),appliedAt:be.coerce.date().nullish()}),Lm=Uc.extend({steps:ve.array()});import{isValidCron as UE}from"cron-validator";import{z as ne}from"zod";import{z as Bc}from"zod";var ss=Bc.object({width:Bc.number().min(200).max(1e4),height:Bc.number().min(200).max(1e4)}),km={"Desktop Large":{width:1920,height:1080},"Desktop Small":{width:1280,height:800},iPad:{width:768,height:1024},"Pixel 8":{width:448,height:998},"iPhone 15":{width:393,height:852}},x0=Object.keys(km);var Dt=km["Desktop Large"],Pr="en-US",Lr="America/Los_Angeles";var Om=1e4,Nm=2e3,kr=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(kr||{});var ls=xo.extend({browserType:ne.nativeEnum(kr).optional(),slowMoMs:ne.number().optional().refine(r=>r===void 0||r<=Nm&&r>=-1,{message:`Slow motion must be between 0 and ${Nm} milliseconds`}),smartWaitingTimeoutMs:ne.number().optional().refine(r=>r===void 0||r<=Om&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${Om/1e3} seconds`}),basicAuthorization:ne.object({username:ne.string().optional(),password:ne.string().optional()}).optional(),disableJavaScript:ne.boolean().optional(),disableGpu:ne.boolean().optional(),locale:ne.string().optional(),timezone:ne.string().optional()}),Mm=["extraHeaders","basicAuthorization","localChromeExtensionPaths"];var BE=ne.object({disableAICaching:ne.boolean().default(!1),failureRecovery:ne.boolean().optional().describe("undefined means inherit org settings")});var zE=ne.object({viewport:ss.optional()}),Eo=zE.merge(BE).merge(ls),Co=ne.object({cron:ne.string().refine(r=>UE(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:ne.boolean().default(!1),env:ne.string().optional(),timeZone:ne.string().default("America/Los_Angeles"),jobKey:ne.string().optional()}),Ao=ne.object({onSuccess:ne.boolean().default(!1),failureMessage:ne.string().optional(),onFailure:ne.boolean().default(!0),successMessage:ne.string().optional()}),jE=ne.object({name:ne.string(),required:ne.boolean().optional(),defaultValue:ne.string().describe("this is not optional because we need a value when the editor is first loaded")}),cs=jE.array(),HE=ne.object({name:ne.string(),value:ne.string()}),_m=HE.array(),ds=ne.object({name:ne.string(),default:ne.boolean().optional(),fixtures:Rm.array().optional()});ye(H);var Pt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},re=(s=>(s.PENDING="PENDING",s.RUNNING="RUNNING",s.PASSED="PASSED",s.FAILED="FAILED",s.CANCELLED="CANCELLED",s.RETRYING="RETRYING",s.WAITING_FOR_USER="WAITING_FOR_USER",s))(re||{}),ps=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(ps||{});var Be=H.string().pipe(H.coerce.date()).or(H.date()),Di=H.object({id:H.string(),runKey:H.string(),organizationId:H.string(),createdAt:Be,createdBy:H.string(),flake:H.boolean().nullish(),scheduledAt:Be.or(H.null()),startedAt:Be.or(H.null()),updatedAt:Be.nullish(),finishedAt:Be.or(H.null()),resolvedBaseUrl:H.string().nullish(),environmentName:H.string().nullish(),labels:H.array(H.string()).optional(),cliVersion:H.string().nullish(),section:H.nativeEnum(ps).nullish(),status:H.nativeEnum(re),trigger:H.nativeEnum(Pt),attempts:H.number(),runAttempts:H.array(H.object({id:H.string(),status:H.nativeEnum(re),startedAt:Be.or(H.null()),finishedAt:Be.or(H.null())})).optional(),videos:H.array(H.string()).optional(),failureReason:H.nativeEnum(pe).nullish(),failureDetails:es.nullish(),testFragments:H.array(Uc).nullish(),localTestId:H.string().nullish(),testId:H.string().nullish(),testName:H.string().nullish(),test:H.object({name:H.string(),id:H.string()}).nullish().default(null),suiteId:H.string().nullish()}).openapi({ref:"RunMetadata"}),$E={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},us=Di.pick({...$E,test:!0}),Fm=Di.omit({failureReason:!0,failureDetails:!0,test:!0}),zc=Di.extend({stepsSnapshot:H.array(H.record(H.unknown())).nullish(),resolvedInputs:H.record(H.string(),H.string()).nullish(),test:H.object({name:H.string(),id:H.string(),description:H.string().nullish(),baseUrl:H.string().nullish(),advanced:Eo.nullish()}).nullish()}).merge(Dc),Dm=r=>r.includes("PASSED")&&r.includes("FAILED");var WE=Ui.object({id:Ui.string().uuid(),startedAt:Be.or(Ui.null()),finishedAt:Be.or(Ui.null()),status:Ui.nativeEnum(re)}).merge(os),j0=WE.array();var Bi=(o=>(o.JUNIT="junit",o.ALLURE="allure",o.ALLURE_JSON="allure-json",o.PLAYWRIGHT_JSON="playwright-json",o))(Bi||{});import{z as He}from"zod";var GE=He.object({id:He.string(),status:He.nativeEnum(re),trigger:He.nativeEnum(Pt),createdAt:Be,startedAt:Be.nullish(),finishedAt:Be.nullish(),gitCommitSha:He.string().nullish(),gitCommitShaShort:He.string().nullish(),gitCommitTimestamp:Be.nullish(),gitBranchName:He.string().nullish(),gitOriginUrl:He.string().nullish(),gitCommitMessage:He.string().nullish(),gitCommitAuthorName:He.string().nullish(),githubRepository:He.string().nullish(),gitlabProjectPath:He.string().nullish(),pipelineId:He.string().nullish(),cliVersion:He.string().nullish(),suite:He.object({id:He.string(),name:He.string()}).nullish(),runs:He.object({status:He.nativeEnum(re)}).array()}).openapi({ref:"RunGroup"}),Um=GE.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:us.array()});import{z as Xe}from"zod";var VE=Xe.object({type:Xe.literal("TARGETING"),name:Xe.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:Vu.array(),pageState:Xe.string().optional(),targetSource:Xe.nativeEnum(Vn).optional(),targetUpdateTime:Xe.string().optional()}),qE=Xe.object({type:Xe.literal("AI_LOCATION"),matched:Xe.boolean(),pageState:Xe.string().optional(),ragUsed:Xe.boolean().optional(),thoughts:Xe.string().optional()}),KE=Xe.object({type:Xe.literal("ASSERTION"),relevantElementsSerialized:Xe.string().array().optional(),pageState:Xe.string().optional(),ragUsed:Xe.boolean().optional()}),Bm=Xe.discriminatedUnion("type",[VE,qE,KE]);function ms(){return{details:[]}}import{z as Me}from"zod";var YE=Me.object({id:Me.string(),name:Me.string()}),tU=YE.merge(Me.object({createdAt:Be,createdBy:Me.string(),schedule:Co,notification:Ao,environment:Me.object({name:Me.string()}).nullish(),beforeTests:Me.object({id:Me.string()}).array().nullish(),afterTests:Me.object({id:Me.string()}).array().nullish()})),zm=Me.object({id:Me.string().uuid(),orgId:Me.string(),createdAt:Be,startedAt:Be.or(Me.null()),finishedAt:Be.or(Me.null()),status:Me.nativeEnum(re),trigger:Me.nativeEnum(Pt),suite:Me.object({id:Me.string(),name:Me.string()}).nullish(),runs:Di.array()}),nU=zm.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),jm=zm.extend({runs:us.array()});var Kt=F.object({disableCache:F.boolean().optional(),loggerTags:F.record(F.string(),F.string()).optional(),langfuseSessionId:F.string().optional()}),JE=F.object({screenshotBase64AfterCommand:F.string(),urlAfterCommand:F.string(),serializedCommand:F.string(),elementInteracted:F.string().optional(),thoughts:F.string().optional()}),Hm=F.object({goal:F.string(),browserState:F.string(),screenshot:F.string(),source:Gu.optional()}),$m=F.object({target:F.string().or(F.number()),browserState:F.string().optional(),screenshot:F.string().optional(),boundingBox:F.object({x:F.number(),y:F.number(),height:F.number(),width:F.number()}).optional()}),Wm=F.object({goal:F.string(),browserState:F.string(),screenshot:F.string().optional(),returnSchema:F.string().optional()}),Gm=F.object({goal:F.string(),browserState:F.string(),screenshot:F.string(),url:F.string(),contextChoice:sc.optional()}),Vm=F.object({command:go}),jc=F.object({goal:F.string(),browserState:F.string(),startingScreenshot:F.string().optional(),screenshot:F.string(),url:F.string(),history:JE.array(),actionHint:F.string().optional(),lastError:F.string().optional()}),qm=F.object({results:rs.array(),errorMessage:F.string(),errorStack:F.string().optional()}),Km=F.object({results:rs.array(),goal:F.string(),errorMessage:F.string()}),Ym=F.object({failedResults:rs.array(),nextStepsSerialized:F.string().array(),currentUrl:F.string(),currentPageState:F.string(),currentScreenshot:F.string()}),xU=F.object({description:F.string(),type:F.union([F.literal("locator"),F.literal("assertion"),F.literal("ai-action")]),excerpt:F.string()});import{z as zi}from"zod";var CU=zi.object({goal:zi.string()}),Jm=zi.object({keywords:zi.array(zi.string())});import{z as St}from"zod";var Hc=St.object({content:St.string(),ids:St.string().array(),tokenLength:St.number()}),XE=St.object({chunks:Hc.array()}),IU=St.object({ids:St.string().array(),score:St.number(),tokenLength:St.number()}),PU=XE.extend({description:St.string().describe("Input to pass to RAG engine"),tokenLimit:St.number()}),Xm=St.object({ids:St.number().array()}),Zm=St.object({indices:St.number().array()});var Qm=r=>!(!r.org_id||!r.user_id||!r.platform);import{z as Or}from"zod";var eh=Or.object({id:Or.string().uuid(),skipped:Or.boolean().optional(),envKey:Or.string().optional().describe("key in the environment to save the result of this step to")}),$c=eh.merge(Na).extend({type:Or.literal("REQUEST")}),Wc=eh.merge(Ma).extend({type:Or.literal("JAVASCRIPT")}),Gc=Or.discriminatedUnion("type",[Wc,$c]);import{z as Yt}from"zod";import{z as Nr}from"zod";var ZE=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Pe=r=>{let e=r.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var hs=Nr.string().min(1).max(255).superRefine((r,e)=>{try{Ro(r)}catch(t){return e.addIssue({code:Nr.ZodIssueCode.custom,message:t.message,fatal:!0}),Nr.NEVER}});function Ro(r){if(r=r.toLowerCase().trim(),r.length===0||r.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(r))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(r.endsWith("-")||r.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(r.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(r))throw new Error(`"${r}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(r)||/^\s|\s$/.test(r))throw new Error("Name cannot start or end with a space or dot.");if(r.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(r==="none")throw new Error("Name cannot be 'none'.");if(r.match(ZE))throw new Error("Name cannot be a UUID. Please choose a different name.")}var gs=Nr.preprocess(r=>r===null?"":r,Nr.union([Nr.string().url(),Nr.literal("")])).optional();var th=Yt.object({id:Yt.string(),name:hs,description:Yt.string().optional().nullish(),baseUrl:gs.nullish(),schemaVersion:Yt.string(),advanced:Yt.unknown().optional(),retries:Yt.number(),envs:Yt.array(ds).nullish(),parameters:cs.nullish()}),QE=Yt.object({createdAt:Yt.coerce.date(),updatedAt:Yt.coerce.date(),schedule:Co.nullish(),notification:Ao.nullish(),createdBy:Yt.string(),organizationId:Yt.string()}),eC=th.merge(QE),YU=eC.extend({steps:Gc.array()}),JU=th.extend({steps:Gc.array()});import{z as Lt}from"zod";var nh=Lt.object({startedAt:Lt.coerce.date(),finishedAt:Lt.coerce.date(),status:Lt.nativeEnum(xe),message:Lt.string().optional(),data:Lt.unknown().optional()}),nC=nh.merge(Wc).extend({type:Lt.literal("JAVASCRIPT")}),rC=nh.merge($c).extend({type:Lt.literal("REQUEST")}),oC=Lt.discriminatedUnion("type",[nC,rC]),rh=Lt.object({startedAt:Lt.coerce.date(),finishedAt:Lt.coerce.date().nullish(),status:Lt.nativeEnum(re),results:oC.array(),failureReason:Lt.string().nullish(),failureDetails:es.nullish()});import{z as kt}from"zod";var iC=kt.object({id:kt.string(),organizationId:kt.string(),createdAt:kt.coerce.date(),updatedAt:kt.coerce.date(),createdBy:kt.string(),scheduledAt:kt.coerce.date().nullish(),startedAt:kt.coerce.date().nullish(),finishedAt:kt.coerce.date().nullish(),status:kt.nativeEnum(re),trigger:kt.nativeEnum(Pt),results:rh.array().nullish(),apiTestName:kt.string().nullish(),apiTestPath:kt.string().nullish(),apiTestId:kt.string().nullish()}),i1=iC.pick({status:!0,startedAt:!0,finishedAt:!0});var Mr=(t=>(t.TestRun="test-run",t.CreditsUsed="credits-used",t))(Mr||{}),oh=3;function aC(r){return r==="MODULE"||r==="IFRAME"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function ji(r){if(!aC(r))switch(r){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function Hi(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":case"AI_WAIT":return oh;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":return r.useSelector||!r.target||r.target.type!=="description"?0:1;case"DRAG":case"MOUSE_DRAG":return r.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":return 0;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var Io=class{async reportBillableEvent(e,t,n){}async reportCreditsUsed(e,t,n,o){}};function Vc(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}import{parseString as sC,splitCookiesString as lC}from"set-cookie-parser";import{z as me}from"zod";var qc=me.object({name:me.string(),value:me.string(),url:me.string().optional(),domain:me.string().optional(),path:me.string().optional(),expires:me.number().default(Date.now()/1e3+60*60*24*365),httpOnly:me.boolean().optional(),secure:me.boolean().default(!0),sameSite:me.union([me.literal("Strict"),me.literal("Lax"),me.literal("None")]).default("None")});function fs(r,e){let t=[],n=lC(r);for(let o of n){let i=sC(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let p=i.sameSite.trim().toLowerCase();if(p==="strict")a="Strict";else if(p==="lax")a="Lax";else if(p==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${p}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let s=qc.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(s);let l=[s.name,...Object.keys(s)].map(p=>p.toLowerCase()),c=o.match(/\b(\S+)=([^;]*)/g);if(c)for(let p of c){let[d,m]=p.split("=");if(!d||!m)throw new Error(`Invalid key-value pair in cookie: ${p}`);l.includes(d.toLowerCase())||t.push({...s,name:d,value:m})}}return t}var cC=me.object({origin:me.string(),localStorage:me.array(me.object({name:me.string(),value:me.string()}))}),dC=me.object({entries:me.record(me.string(),me.array(me.tuple([me.unknown(),me.unknown()]))),version:me.number().optional()}),Ss=me.object({cookies:qc.array().optional(),origins:cC.array().optional(),idb:me.record(me.string(),dC).optional().describe("key is db name")});function ys(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=qc.safeParse({name:n.key,...n});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),t.push(i)}),t}var R1=new Set(Object.values(Ue));var pC={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_WAIT:"AI wait",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"Local storage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",SUCCESS:"Done"},I1={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_WAIT:[],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],SUCCESS:[]},P1={AI_ACTION:"Ask AI achieve a specific goal. Caches the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI whether something is true on the page, retrying until a configurable timeout.",AI_WAIT:"Wait until AI considers a condition to be true.",CLICK:"Click on an element on the page based on a description.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page based on a description.",HOVER:"Hover over an element on the page based on a description.",FILE_UPLOAD:"Automatically upload a file when the next file chooser is activated.",FOCUS:"Focus an element on the page based on a description.",BLUR:"Remove focus from an element on the page based on a description.",SELECT_OPTION:"Select an option from an HTML Select <select> element based on a description.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session",LOCAL_STORAGE:"Set a local storage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JSON snapshot including cookies, local storage, and IndexDB entries.",AUTH_SAVE:"Save auth state (cookies, local storage) into a JavaScript object format usable by 'Load auth state'.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's state using pre-built conditions, including URL and content checks.",WAIT_FOR_URL:"Wait for the active page's URL to match a specific URL or glob pattern. If a new tab is opened, this command will wait for the new tab's URL to match instead.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."};import{Faker as O1,en as N1}from"@faker-js/faker";import{z as $}from"zod";var ih=55555,D1=$.object({body:$.string(),to:$.string(),from:$.string()}),U1=$.object({from:$.string().optional(),to:$.string(),timeout:$.number().optional(),beforeDate:$.string().pipe($.coerce.date()).or($.date()).optional(),afterDate:$.string().pipe($.coerce.date()).or($.date()).optional()}),B1=$.object({to:$.string(),from:$.string(),subject:$.string(),body:$.string()}),z1=$.object({inbox:$.string(),afterDate:$.string().pipe($.coerce.date()).or($.date()).optional(),timeout:$.number().optional(),trimWhitespace:$.boolean().optional()}),j1=$.object({inbox:$.string(),limit:$.number().optional(),afterDate:$.string().pipe($.coerce.date()).or($.date()).optional(),trimWhitespace:$.boolean().optional()});var ah=$.object({result:$.unknown(),variableUpdates:$.record($.string(),$.unknown()).optional(),persistentVariableUpdates:$.record($.string(),$.unknown()).optional(),error:$.string().optional(),success:$.boolean()}),H1=$.object({id:$.string().optional(),orgId:$.string(),momenticLambdaAuthHash:$.string(),code:$.string(),fragment:$.boolean(),state:Fi,timeoutMs:$.number().optional()}),Yn=15e3;import*as pt from"zod";ye(pt);var uC=pt.object({url:pt.string(),lineNumber:pt.number(),columnNumber:pt.number()}).openapi({ref:"CodeLocation"}),bs=pt.object({timestamp:pt.number(),text:pt.string(),type:pt.string(),tabIndex:pt.number(),args:pt.unknown().array().optional(),url:pt.string().optional(),location:uC.optional()}).openapi({ref:"ConsoleLog"}),sh=bs.array(),mC=sh.array();import*as Yc from"zod";import{z as R}from"zod";var hC=R.object({name:R.string(),version:R.string(),comment:R.string().optional()}),gC=R.object({name:R.string(),version:R.string(),comment:R.string().optional()}),fC=R.object({onContentLoad:R.number().optional(),onLoad:R.number().optional(),comment:R.string().optional()}),ch=R.object({startedDateTime:R.string(),id:R.string(),title:R.string().optional(),pageTimings:fC,comment:R.string().optional()}),SC=R.array(ch),yC=R.object({name:R.string(),value:R.string(),path:R.string().optional(),domain:R.string().optional(),expires:R.string().optional(),httpOnly:R.boolean().optional(),secure:R.boolean().optional(),comment:R.string().optional()}),dh=R.array(yC),bC=R.object({name:R.string(),value:R.string(),comment:R.string().optional()}),ph=R.array(bC),wC=R.object({name:R.string(),value:R.string(),comment:R.string().optional()}),vC=R.array(wC),xC=R.object({name:R.string(),value:R.string().optional(),fileName:R.string().optional(),contentType:R.string().optional(),comment:R.string().optional()}),TC=R.array(xC),EC=R.object({mimeType:R.string(),params:TC,text:R.string(),comment:R.string().optional()}),CC=R.object({method:R.string(),url:R.string(),httpVersion:R.string().optional(),cookies:dh,headers:ph,queryString:vC,postData:EC.optional(),headersSize:R.number().optional(),bodySize:R.number().optional(),comment:R.string().optional()}),AC=R.object({size:R.number().optional(),compression:R.number().optional(),mimeType:R.string().optional(),text:R.string().optional(),encoding:R.string().optional(),comment:R.string().optional()}),RC=R.object({status:R.number(),statusText:R.string(),httpVersion:R.string().optional(),cookies:dh,headers:ph,content:AC,redirectURL:R.string().optional(),headersSize:R.number().optional(),bodySize:R.number().optional(),comment:R.string().optional()}),lh=R.object({expires:R.string().optional(),lastAccess:R.string(),eTag:R.string(),hitCount:R.number(),comment:R.string().optional()}),IC=R.object({beforeRequest:lh.optional(),afterRequest:lh.optional(),comment:R.string().optional()}),PC=R.object({blocked:R.number().optional(),dns:R.number().optional(),connect:R.number().optional(),send:R.number(),wait:R.number(),receive:R.number(),ssl:R.number().optional(),comment:R.string().optional()}),uh=R.object({pageref:R.string().optional(),startedDateTime:R.string(),time:R.number().optional(),request:CC,response:RC.optional(),cache:IC.optional(),timings:PC,serverIPAddress:R.string().optional(),connection:R.string().optional(),comment:R.string().optional(),_resourceType:R.string().optional()}),LC=R.array(uh),kC=R.object({version:R.string().default("1.1"),creator:hC.optional(),browser:gC.optional(),pages:SC.optional(),entries:LC,comment:R.string().optional()}),OC=R.object({log:kC}),mh=R.record(R.string(),ch),hh=R.record(R.string(),uh);function Kc(r,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(r).sort((t,n)=>new Date(t.startedDateTime).getTime()-new Date(n.startedDateTime).getTime()),entries:Object.values(e).sort((t,n)=>new Date(t.startedDateTime).getTime()-new Date(n.startedDateTime).getTime())}}}ye(Yc);var NC=Yc.object({logsPerPage:bs.array().array(),harPages:mh.optional(),harEntries:hh.optional()}).openapi({ref:"DebugData"});var _r=class{async getConsoleLogsForRunAttempt(e,t,n){}async getNetworkLogsForRunAttempt(e,t,n){}async getHtmlSnapshot(e,t){}async getA11yTreeSnapshot(e,t){}async getScreenshot(e,t){}async storeConsoleLogsForRunAttempt(e,t,n,o){}async storeNetworkLogsForRunAttempt(e,t,n,o){}async storeScreenshot(e,t,n){}async storeHtmlSnapshot(e,t,n){}};var ws=class extends Error{constructor(e,t,n,o={}){super(`The ${n} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};function gh(r){for(let e of Object.values(pe))if(r.includes(e))return e}var A=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(pe))if(t.startsWith(i)){o=!0,e=i;break}if(n?.errOptions?.cause)super(o?t:`${e}: ${t}`,n?.errOptions);else{let i=o?t:`${e}${t?`: ${t}`:""}`;super(i,n?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e,Object.defineProperty(this,"lastScreenshotBuffer",{value:n?.lastScreenshotBuffer,enumerable:!1})}getLastScreenshotBuffer(){return"lastScreenshotBuffer"in this?this.lastScreenshotBuffer:void 0}toString(){return this.message}toJSON(){return{message:this.message}}},Jn=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundError"}toString(){return`${this.message}
|
|
8
8
|
Decisions:
|
|
9
9
|
${this.decisions.map(e=>e.toString()).join(`
|
|
10
|
-
`)}`}};function xh(n){return n instanceof Error?n.message.includes("Timeout")&&n.message.includes("exceeded")&&n.message.includes("waiting for locator"):!1}function Zc(n){return!(n instanceof Error)||n.message.includes("locator resolved to visible")?!1:!!(n.message.includes("Timeout")&&n.message.includes("exceeded")&&n.message.includes("body >")||n.message.includes("Element is not attached to the DOM"))}function Hi(n){return n instanceof Error?n.message.includes("Timeout")&&n.message.includes("exceeded")&&n.message.includes("waiting for locator")&&n.message.includes("data-momentic-id")&&!n.message.includes("locator resolved")&&!n.message.includes("waiting for element to be"):!1}var ji=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCssDataError"}};import{cloneDeep as XC}from"lodash-es";import{z as ut}from"zod";var Jt=(u=>(u.AutoExpandIframes="auto_expand_iframes",u.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",u.FakerConstantSeed="faker_constant_seed",u.FilterZeroOpacityElements="filter_zero_opacity_elements",u.GlobalLocatorRedirect="global_locator_redirect",u.IconKnowledgeBase="icon_knowledge_base",u.MiniModelInitialAssertion="mini_model_initial_assertion",u.MiniModelInitialLocator="mini_model_initial_locator",u.ShowTestPlans="show_test_plans",u.RagV2="rag_v2",u.UseNewHeadlessChromium="use_new_chrome_headless_chromium",u.VisualActions="visual_actions",u))(Jt||{});var wa=ut.union([ut.string(),ut.number(),ut.boolean(),ut.null(),ut.record(ut.string(),ut.lazy(()=>wa)),ut.array(ut.lazy(()=>wa))]),$i=class{flags;payloads;constructor(e,t){this.flags=e,this.payloads=t}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=XC(this.flags);return Object.entries(e).forEach(([t,r])=>{typeof r=="boolean"&&Object.values(Jt).includes(t)&&(e[t]=this.isBooleanFlagEnabled(t))}),e}getFlagPayload(e){let t=this.payloads[e];if(t!==void 0){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}refresh(){throw new Error("Not implemented")}},QB=new $i({},{}),ez=ut.object({globalOverrides:ut.record(ut.string()).optional(),agentConfig:ut.record(ut.string(),ut.string()).optional()});var Qc={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},Th=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],nz=Object.keys(Qc);import*as Eh from"zod";var oz=Eh.custom().refine(n=>n&&n.length>0).refine(n=>n&&n[0]instanceof File,{message:"Please upload a valid file."});import{z as Jn}from"zod";var az=Jn.object({id:Jn.string(),name:Jn.string(),createdAt:Jn.coerce.date(),createdBy:Jn.string(),updatedAt:Jn.coerce.date(),updatedBy:Jn.string().nullable(),organizationId:Jn.string()});import{z as V}from"zod";import{z as $e}from"zod";var kt=$e.object({id:$e.string(),name:ma,baseUrl:ha,description:$e.string().optional().nullish(),schemaVersion:$e.string(),advanced:wo,retries:$e.number(),envs:$e.array(ca).nullish(),parameters:la.nullish(),disabled:$e.boolean().optional(),labels:$e.array($e.string()).optional().catch([])}),hz=kt.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),ZC=$e.object({labels:$e.array($e.string()).optional(),outputs:jm.nullish()}),Xt=kt.merge(ZC),QC=$e.object({createdAt:$e.coerce.date(),updatedAt:$e.coerce.date(),updatedBy:$e.string().nullable(),schedule:vo,notification:xo,createdBy:$e.string(),organizationId:$e.string(),folderId:$e.string().nullable().optional()}),eR=kt.merge(QC),gz=eR.merge(go),Wi=kt.merge(go),fz=kt.merge(Er);var Ch=V.object({platformSep:V.string(),fullPathSegments:V.string().array(),relativePath:V.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:V.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:V.coerce.date(),createdAt:V.coerce.date()}),Cz=V.array(Ch.extend({id:V.string(),name:V.string(),description:V.string().optional(),labels:V.string().array().optional()})),Rz=V.array(Ch.extend({id:V.string(),name:V.string(),content:wc})),Az=Wi.merge(Xt),Rh=V.object({schemaVersion:V.string(),stepLists:go}),Ah=Xt.partial().merge(kt.pick({id:!0})),Ih=V.object({name:V.string(),description:V.string().optional(),baseUrl:V.string().url().optional(),environment:V.string().optional(),browserType:V.nativeEnum(Ir).optional(),viewport:sa.optional(),folderPath:V.string().optional()}),Iz=Wi.merge(V.object({relativeFilePath:V.string().describe("relative to project root")})),Ph=V.object({name:V.string()}),Pz=V.object({relativeFilePath:V.string()}),Lh=V.object({name:V.string(),description:V.string(),enabled:V.boolean(),steps:V.lazy(()=>ve.array()),testFilePath:V.string().describe("relative to the project root"),folderPath:V.string().optional().describe("user selected folder path")}),Oh=V.object({description:V.string()});var Lz=V.array(Xs),kh=V.object({defaultEnv:V.string().optional().describe("name of the default env, or undefined to unset")}),Nh=V.object({configFilePath:V.string().describe("full path on disk")}),Oz=V.string().array(),kz=V.object({message:V.string(),newRelativeTestPath:V.string().optional()});var Gi=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],_h=Gi.map(n=>`**/${n}/**`);import vn from"chalk";var tR=["app","version","env","namespace","host"];function We(n){let e=n.bindings()??{},t={};for(let r of Object.keys(e)){let o=e[r];!tR.includes(r)&&typeof o=="string"&&(t[r]=o)}return t}var ed=class n{minLogLevel;logBindings;constructor(e,t){this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...r){if(e<this.minLogLevel)return;let o;Array.isArray(r[0])?(o=r[0],r=r.slice(1)):typeof r[0]=="object"&&!(r[0]instanceof Error)&&Object.entries(r[0]).length&&(o={...r[0],...this.logBindings},r=r.slice(1));let i=[];if(i.push(...r),console.log(t(...i)),o&&!Array.isArray(o)){let s=Object.entries(o);for(let[a,l]of s){let c=l;l instanceof Error?c=l.message:typeof l=="object"&&(c=JSON.stringify(l,void 0,2),c=c.split(`
|
|
10
|
+
`)}`}};function fh(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function Jc(r){return!(r instanceof Error)||r.message.includes("locator resolved to visible")?!1:!!(r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("body >")||r.message.includes("Element is not attached to the DOM"))}function Wi(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator")&&r.message.includes("data-momentic-id")&&!r.message.includes("locator resolved")&&!r.message.includes("waiting for element to be"):!1}var $i=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCssDataError"}};import{cloneDeep as MC}from"lodash-es";import{z as ut}from"zod";var Jt=(m=>(m.AutoExpandIframes="auto_expand_iframes",m.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",m.FakerConstantSeed="faker_constant_seed",m.FilterZeroOpacityElements="filter_zero_opacity_elements",m.GlobalLocatorRedirect="global_locator_redirect",m.IconKnowledgeBase="icon_knowledge_base",m.MiniModelInitialAssertion="mini_model_initial_assertion",m.MiniModelInitialLocator="mini_model_initial_locator",m.ShowTestPlans="show_test_plans",m.RagV2="rag_v2",m.UseNewHeadlessChromium="use_new_chrome_headless_chromium",m.VisualActions="visual_actions",m))(Jt||{});var vs=ut.union([ut.string(),ut.number(),ut.boolean(),ut.null(),ut.record(ut.string(),ut.lazy(()=>vs)),ut.array(ut.lazy(()=>vs))]),Gi=class{flags;payloads;constructor(e,t){this.flags=e,this.payloads=t}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=MC(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(Jt).includes(t)&&(e[t]=this.isBooleanFlagEnabled(t))}),e}getFlagPayload(e){let t=this.payloads[e];if(t!==void 0){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}refresh(){throw new Error("Not implemented")}},LB=new Gi({},{}),kB=ut.object({globalOverrides:ut.record(ut.string()).optional(),agentConfig:ut.record(ut.string(),ut.string()).optional()});var Xc={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},Sh=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],NB=Object.keys(Xc);import*as yh from"zod";var _B=yh.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as Xn}from"zod";var UB=Xn.object({id:Xn.string(),name:Xn.string(),createdAt:Xn.coerce.date(),createdBy:Xn.string(),updatedAt:Xn.coerce.date(),updatedBy:Xn.string().nullable(),organizationId:Xn.string()});import{z as W}from"zod";import{z as $e}from"zod";var Ot=$e.object({id:$e.string(),name:hs,baseUrl:gs,description:$e.string().optional().nullish(),schemaVersion:$e.string(),advanced:Eo,retries:$e.number(),envs:$e.array(ds).nullish(),parameters:cs.nullish(),disabled:$e.boolean().optional(),labels:$e.array($e.string()).optional().catch([])}),GB=Ot.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),_C=$e.object({labels:$e.array($e.string()).optional(),outputs:_m.nullish()}),Xt=Ot.merge(_C),FC=$e.object({createdAt:$e.coerce.date(),updatedAt:$e.coerce.date(),updatedBy:$e.string().nullable(),schedule:Co,notification:Ao,createdBy:$e.string(),organizationId:$e.string(),folderId:$e.string().nullable().optional()}),DC=Ot.merge(FC),VB=DC.merge(yo),Vi=Ot.merge(yo),qB=Ot.merge(Cr);var bh=W.object({platformSep:W.string(),fullPathSegments:W.string().array(),relativePath:W.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:W.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:W.coerce.date(),createdAt:W.coerce.date()}),nz=W.array(bh.extend({id:W.string(),name:W.string(),description:W.string().optional(),labels:W.string().array().optional()})),rz=W.array(bh.extend({id:W.string(),name:W.string(),description:W.string().optional(),content:yc})),oz=Vi.merge(Xt),wh=W.object({schemaVersion:W.string(),stepLists:yo}),vh=Xt.partial().merge(Ot.pick({id:!0})),xh=W.object({name:W.string(),description:W.string().optional(),baseUrl:W.string().url().optional(),environment:W.string().optional(),browserType:W.nativeEnum(kr).optional(),viewport:ss.optional(),folderPath:W.string().optional()}),iz=Vi.merge(W.object({relativeFilePath:W.string().describe("relative to project root")})),Th=W.object({name:W.string()}),az=W.object({relativeFilePath:W.string()}),Eh=W.object({name:W.string(),description:W.string(),enabled:W.boolean(),steps:W.lazy(()=>ve.array()),testFilePath:W.string().describe("relative to the project root"),folderPath:W.string().optional().describe("user selected folder path")}),Ch=W.object({description:W.string(),enabled:W.boolean()}).partial();var sz=W.array(Za),Ah=W.object({defaultEnv:W.string().optional().describe("name of the default env, or undefined to unset")}),Rh=W.object({configFilePath:W.string().describe("full path on disk")}),lz=W.string().array(),cz=W.object({message:W.string(),newRelativeTestPath:W.string().optional()});var qi=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],Ih=qi.map(r=>`**/${r}/**`);import vn from"chalk";var UC=["app","version","env","namespace","host"];function We(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!UC.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var Zc=class r{minLogLevel;logBindings;constructor(e,t){this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...n){if(e<this.minLogLevel)return;let o;Array.isArray(n[0])?(o=n[0],n=n.slice(1)):typeof n[0]=="object"&&!(n[0]instanceof Error)&&Object.entries(n[0]).length&&(o={...n[0],...this.logBindings},n=n.slice(1));let i=[];if(i.push(...n),console.log(t(...i)),o&&!Array.isArray(o)){let a=Object.entries(o);for(let[s,l]of a){let c=l;l instanceof Error?c=l.message:typeof l=="object"&&(c=JSON.stringify(l,void 0,2),c=c.split(`
|
|
11
11
|
`).map((p,d)=>d>0?` ${p}`:p).join(`
|
|
12
|
-
`)),console.log(t(` ${
|
|
12
|
+
`)),console.log(t(` ${s}:`,c))}}else if(o)for(let a of o){let s=a;typeof a=="object"&&(s=JSON.stringify(a,void 0,2),s=s.split(`
|
|
13
13
|
`).map((l,c)=>c>0?` ${l}`:l).join(`
|
|
14
|
-
`)),console.log(" ",t(a))}}setMinLevel(e){this.minLogLevel=e}log(...e){this.logWithLevel(1,vn.reset,...e)}info(...e){this.logWithLevel(1,vn.blue,...e)}debug(...e){this.logWithLevel(0,vn.dim,...e)}warn(...e){this.logWithLevel(2,vn.yellow,...e)}error(...e){this.logWithLevel(3,vn.red,...e)}success(...e){this.logWithLevel(4,vn.green,...e)}dimmed(...e){this.logWithLevel(1,vn.dim,...e)}underline(...e){this.logWithLevel(2,vn.underline,...e)}bold(...e){this.logWithLevel(2,vn.bold,...e)}grey(...e){this.logWithLevel(0,vn.grey,...e)}child(e){return new n(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},y=new ed(1,{}),Nr={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Nr,flush:()=>{},bindings:()=>({})},va={},_r=({logger:n,logKey:e,maxCount:t,intervalMs:r},o,i,...s)=>{let a=va[e];a?clearTimeout(a.timer):(a={count:0,totalCount:0},va[e]=a),a.totalCount++,a.count<t&&(a.count++,n.debug(o,i,...s)),a.timer=setTimeout(()=>{let l=va[e];l?.totalCount!==l?.count&&n.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete va[e]},r)};import{z as Xe}from"zod";var Mh=Xe.object({id:Xe.string(),createdAt:Xe.coerce.date(),createdBy:Xe.string(),organizationId:Xe.string(),name:Xe.string(),description:Xe.string().nullish(),enabled:Xe.boolean(),schemaVersion:Xe.string().describe("Schema version for steps"),parameters:Xe.string().array().nullish().describe("Parameter list"),defaultParameters:Xe.record(Xe.string(),Xe.string()).nullish(),defaultCacheKey:Xe.string().nullish(),defaultCacheTtl:Xe.number().nullish(),defaultCacheAllInvocations:Xe.boolean().nullish(),autoAuth:Xe.boolean().nullish(),advanced:fc.nullish()}),Wz=Mh.extend({steps:Xe.lazy(()=>Ye.array())}),Fh=5*60*1e3,td=At.merge(Mh.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as qz}from"date-fns-tz";import{z as Zt}from"zod";var nd=Zt.object({failureRecovery:Zt.boolean().optional(),aiAction:Zt.boolean().optional(),stepLintSuggestions:Zt.boolean().optional()}),Dh=Zt.object({fakerConstantSeed:Zt.boolean().optional()}),Jz=Zt.object({ai:nd.optional(),githubAppInstallationId:Zt.number().nullish(),githubReleaseAppInstallationId:Zt.number().nullish(),gitlabAppAccessToken:Zt.string().nullish().optional(),gitlabAppBaseUrl:Zt.string().nullish().optional(),qaseAccessToken:Zt.string().nullish().optional()});import*as T from"zod";var uj=T.object({error:T.boolean(),reason:T.string(),message:T.string()}),mj=Kt.merge($c),Uh=Ds,hj=Kt.merge($c);var gj=Kt.merge(Xm).extend({useConsensus:T.boolean().optional(),attemptNumber:T.number().optional()}),rd=Nu,fj=Kt.merge(Zm),Bh=qu,Sj=Kt.merge(Km),zh=Vu,yj=Kt.merge(Ym),jh=Gu,bj=Kt.merge(Jm);var wj=T.object({testPaths:T.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:T.string().optional(),all:T.boolean().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional(),testInputMatrix:T.record(T.string(),T.string()).array().optional()}),Hh=T.object({queuedTests:T.unknown().array(),runIds:T.string().uuid().array(),runGroupId:T.string().optional()}),$h=Wi,Wh=T.string().array(),vj=T.union([T.object({paths:T.string().array().describe("run specific test paths (e.g. todo-test)"),all:T.boolean().describe("run all tests").optional()}),T.object({path:T.string().describe("deprecated; present for backcompat")})]),Gh=T.object({tests:T.record(T.string().describe("Test name"),T.string().describe("Test YAML")),modules:T.record(T.string().describe("Module name"),T.string().describe("Module YAML"))}),nR=T.object({test:T.string().describe("test YAML"),modules:T.record(T.string().describe("moduleId"),T.string().describe("module YAML"))}),xj=nR.array(),Tj=T.object({testId:T.string(),schemaVersion:T.string()}).merge(Er),Ej=T.object({entries:T.array(Tc),testId:T.string()}),Cj=T.object({steps:T.array(T.record(T.unknown())),testId:T.string(),schemaVersion:T.string(),organizationId:T.string()}),Vh=Wu,qh=T.object({trigger:T.nativeEnum(Pt),status:T.nativeEnum(ne),startedAt:T.coerce.date().optional(),gitCommitSha:T.string().optional(),gitCommitShaShort:T.string().optional(),gitCommitTimestamp:T.coerce.date().optional(),gitBranchName:T.string().optional(),gitOriginUrl:T.string().optional(),gitCommitMessage:T.string().optional(),gitCommitAuthorName:T.string().optional(),githubRepository:T.string().optional(),gitlabProjectPath:T.string().optional(),pipelineId:T.string().optional(),cliVersion:T.string().optional()}),Kh=T.object({id:T.string()}),Yh=T.object({status:T.nativeEnum(ne),updatedAt:T.coerce.date().optional(),finishedAt:T.coerce.date().optional()}),Jh=T.object({stepsSnapshot:T.array(T.record(T.unknown())).optional(),runGroupId:T.string().optional(),testId:T.string(),testName:T.string(),resolvedBaseUrl:T.string().optional(),environmentName:T.string().optional(),labels:T.array(T.string()).optional(),cliVersion:T.string().optional(),trigger:T.nativeEnum(Pt),schemaVersion:T.string().optional(),section:T.nativeEnum(da).optional()}),Xh=T.object({id:T.string()}),rR=Hc.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Zh=rR.array(),Qh=Hc.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),eg=T.object({id:T.string()}),tg=T.object({status:T.nativeEnum(ne),finishedAt:T.coerce.date().optional()}).merge(ra),Rj=T.object({screenshot:T.string()}),ng=T.object({key:T.string()}),rg=T.object({orgId:T.string(),userId:T.string()}),og=T.array(Js),ig=T.record(T.string(),T.union([T.string(),T.boolean()])),Aj=T.object({paths:T.string().array(),env:T.string().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional()}),sg=T.object({suiteRunIds:T.string().array(),runGroupIds:T.string().array()}),Ij=T.object({suiteRunIds:T.string().array()}),ag=qm.array(),Pj=T.object({runGroupIds:T.string().array()}),Co=T.object({uploadUrl:T.string()}),Lj=Kt.merge(Qm),Oj=Kt.merge(th),kj=Kt.merge(eh),oR=T.object({testId:T.string().optional().default(""),testName:T.string().optional().default(""),suiteId:T.string().optional().default(""),suiteName:T.string().optional().default(""),creditsUsed:T.number().optional(),usedBy:T.string().optional()}),iR=T.object({transactionId:T.string(),timestamp:T.string(),event:T.nativeEnum(Or),properties:oR}),Nj=iR.array(),lg=Fm.omit({steps:!0}).extend({steps:T.array(T.record(T.string(),T.unknown())).describe("unparsed ResolvedStep[]")}),_j=T.object({limit:T.number().max(10).optional(),afterTime:T.number().optional()}),cg=Hm.array(),Mj=T.object({applied:T.boolean().optional(),appliedAt:T.coerce.date().optional()}),Fj=Kt.extend({chunks:Wc.array(),description:T.string().describe("Input to pass to AI"),type:T.union([T.literal("locator"),T.literal("assertion"),T.literal("ai-action")]),softTokenLimit:T.number(),hardTokenLimit:T.number()}),dg=Co.extend({id:T.string()}),pg=T.object({runGroupId:T.string()}),ug=T.object({featureFlags:T.record(T.string(),T.boolean().or(T.string())).optional(),featureFlagPayloads:T.record(T.string(),wa).optional()});import{z as Te}from"zod";var mg=Te.object({orgId:Te.string(),cacheKeys:Te.string().array()}),Bj=Te.object({keyParams:mg,clientMetadata:Te.string(),lockAcquisitionTimeoutMs:Te.number().optional()}),hg=Te.object({acquired:Te.boolean(),acquiredByMetadata:Te.string(),keyPrefix:Te.string()}),zj=Te.object({keyPrefix:Te.string(),result:Te.string(),ttlMs:Te.number()}),jj=Te.union([Te.object({keyPrefix:Te.string()}),mg]),sR=Te.object({remainingTtlMs:Te.number(),value:Te.string().nullish()}),Hj=Te.object({results:Te.record(Te.string(),sR),activeLocks:Te.string().array()}),gg=0,fg=5*60*1e3;import{z as an}from"zod";var Sg="test",yg="module",Nt=(t=>(t.TEST=`${Sg}.yaml`,t.MODULE=`${yg}.yaml`,t))(Nt||{}),fe=(o=>(o.TEST=`momentic/${Sg}`,o.MODULE=`momentic/${yg}`,o.FIXTURE="momentic/fixture",o.ENVIRONMENT="momentic/environment",o))(fe||{}),Jj=kt.merge(Er),od=At.extend({steps:an.array(an.record(an.string(),an.unknown())),schemaVersion:an.string()}),Xj=od.extend({fileType:an.literal(fe.MODULE)}),Zj=an.object({test:an.string().describe("YAML for the test, including metadata and steps"),modules:an.record(an.string(),an.string()).describe("Map of module name to YAML for the module")});import{z as ot}from"zod";var aR=ot.object({version:ot.string(),json:ot.record(ot.unknown()),hash:ot.string()}),bg=ot.record(ot.unknown()),nH=ot.object({newSvgs:ot.array(aR),metadata:bg.optional()}),lR=ot.object({version:ot.string(),json:ot.record(ot.unknown()).nullish(),hash:ot.string(),description:ot.string().nullish(),metadata:bg.nullish()}),wg=ot.record(ot.string().describe("icon hash"),lR);import{validator as aH}from"@exodus/schemasafe";var vg=n=>{n.extraHeaders&&(n.extraHeaders=Object.fromEntries(Object.entries(n.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as bH}from"zod";import{z as Xn}from"zod";var xH=Xn.object({repositoriesIndexed:Xn.boolean(),indexingInProgress:Xn.boolean(),indexesOutdated:Xn.boolean()}),xg=(s=>(s.Queued="queued",s.InProgress="in_progress",s.Completed="completed",s.Waiting="waiting",s.Requested="requested",s.Pending="pending",s))(xg||{}),Tg=(a=>(a.Success="success",a.Failure="failure",a.Neutral="neutral",a.Cancelled="cancelled",a.Skipped="skipped",a.TimedOut="timed_out",a.ActionRequired="action_required",a))(Tg||{}),TH=Xn.object({name:Xn.string(),status:Xn.nativeEnum(xg),conclusion:Xn.nativeEnum(Tg).nullable()});import{z as Le}from"zod";var id=Le.object({assertion:Le.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),cR=Le.object({instruction:Le.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:id.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),Eg=cR.extend({subSteps:Le.lazy(()=>Eg.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Cg=Le.object({name:Le.string().describe("Short name describing the test plan"),description:Le.string().nullish().transform(n=>n??void 0).describe("Longer form description of the high level goal of the test plan")}),Rg=Cg.extend({id:Le.string(),createdAt:Le.coerce.date(),updatedAt:Le.coerce.date(),updatedBy:Le.string(),createdBy:Le.string(),test:Le.object({id:Le.string(),name:Le.string()}).nullish().transform(n=>n??void 0)}),AH=Rg.extend({testGenRuns:Le.tuple([]).or(Le.tuple([Le.object({id:Le.string(),startedAt:Le.coerce.date(),status:Le.nativeEnum(ne)})]))}),Ag=Le.object({preConditions:id.array().nullish().transform(n=>n??[]),postConditions:id.array().nullish().transform(n=>n??[]),steps:Eg.array().nullish().transform(n=>n??[])}),IH=Rg.extend({plan:Ag.nullish().transform(n=>n??{preConditions:[],postConditions:[],steps:[]})}),dR=Cg.extend({plan:Ag.nullish().transform(n=>n??{preConditions:[],postConditions:[],steps:[]})}),PH=dR.array().nullish().transform(n=>n??[]);import{z as Ee}from"zod";var pR=Ee.object({step:ve,status:Ee.nativeEnum(ne),startedAt:Ee.coerce.date(),finishedAt:Ee.coerce.date().optional(),healMetadata:Ee.object({healType:Ee.nativeEnum(Li).or(Ee.literal("AI")),healedAt:Ee.coerce.date()}).optional(),beforeSnapshotId:Ee.string().uuid().optional(),afterSnapshotId:Ee.string().uuid().optional(),message:Ee.string().optional()}),UH=pR.extend({status:Ee.nativeEnum(xe),finishedAt:Ee.coerce.date()}),uR=Ee.object({startedAt:Ee.coerce.date()}).merge(tg),BH=uR.extend({finishedAt:Ee.coerce.date()}),mR=Qh.merge(Jh).extend({startedAt:Ee.coerce.date(),attempts:Ee.number()}),zH=mR.extend({status:Ee.nativeEnum(ne),finishedAt:Ee.coerce.date()}),hR=qh.merge(Yh).extend({startedAt:Ee.coerce.date(),cliVersion:Ee.string()}),sd=hR.extend({updatedAt:Ee.coerce.date(),finishedAt:Ee.coerce.date()});function ad(n){let e={parentChain:[]};return xa(n,e),e}function xa(n,e){let{onPresetAction:t,onSimpleStepContainer:r,onConditional:o,earlyStop:i}=n;for(let s of n.steps)switch(s.type){case"PRESET_ACTION":if(t(s,e)&&i)return!0;break;case"CONDITIONAL":if(o?.(s,e)&&i)return!0;e.parentChain.push(s);for(let l of s.blocks)if(t(l.assertion,e)&&i||xa({...n,steps:l.steps},e)&&i)return!0;if(xa({...n,steps:s.elseSteps??[]},e)&&i)return!0;e.parentChain.pop();break;case"RESOLVED_MODULE":case"IFRAME":case"SECTION":case"AI_ACTION":if(r?.(s,e)&&i)return!0;if(s.steps){if(e.parentChain.push(s),xa({...n,steps:s.steps},e)&&i)return!0;e.parentChain.pop()}break;case"AI_ACTION_DYNAMIC":{if(r?.(s,e)&&i)return!0;break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(s)}}function Ig(n,e,t,r){let o=Array.from(e),i=Array.from(r);for(let a=0;a<o.length;a++){if(o[a]!==i[a])return!1;i.shift()}return!!gR([n],t,i).result}function gR(n,e,t=[]){let r,o=[],i=(s,a)=>{let l=JSON.stringify(a.parentChain.map(p=>p.id)),c=t.length===0?!0:JSON.stringify(t)===l;return s.id===e&&c?(r=s,o=a.parentChain,!0):!1};return ad({steps:n,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:r,parentChain:o}}function Pg(n,e){e(n);for(let t in n){let r=n[t];r&&(Array.isArray(r)?Ta(r,e):typeof r=="object"&&Pg(r,e))}}function Ta(n,e){for(let t of n)t&&(Array.isArray(t)?Ta(t,e):typeof t=="object"&&Pg(t,e))}function Ro({steps:n,topLevel:e=!0,...t}){let{stepCacheEntries:r,logger:o,keyPrefix:i}=t,s=[],a=[],l=0,c=(d,u)=>{try{let m=vr.parse(u.value);if(m.type!==d.type){o.warn({parsedCacheEntry:m,command:d},"Not using step cache due to type mismatch"),a.push(u.key);return}d.cache=m.cache,s.push(u.key)}catch(m){a.push(u.key),o.error({err:m,cacheEntry:u},"Not using step cache due to parsing error")}},p=(d,u)=>{let m=fR(d.id,u),h=m.find(g=>!!r[g]);h?c(d,r[h]):a.push(m[0])};for(let d of n)switch(d.type){case"RESOLVED_MODULE":{l+=d.steps.length;let{hits:m,misses:h}=Ro({...t,steps:d.steps,keyPrefix:i?`${i}:${d.id}`:d.id,topLevel:!1});s=s.concat(m),a=a.concat(h);break}case"IFRAME":case"SECTION":case"AI_ACTION":{if(l+=d.steps?.length??0,!d.steps?.length)break;let{hits:m,misses:h}=Ro({...t,steps:d.steps,topLevel:!1});s=s.concat(m),a=a.concat(h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!uc.includes(d.command.type)||(d.command.type==="TYPE"||d.command.type==="MOUSE_DRAG"||d.command.type==="VISUAL_DIFF"||d.command.type==="SCROLL_DOWN"||d.command.type==="SCROLL_UP"||d.command.type==="SCROLL_LEFT"||d.command.type==="SCROLL_RIGHT")&&!d.command.target||"cache"in d.command&&d.command.cache)continue;l++,p(d.command,i);break}case"CONDITIONAL":{for(let m of d.blocks){l++,p(m.assertion.command,i),l+=m.steps.length;let{hits:h,misses:g}=Ro({...t,steps:m.steps,topLevel:!1});s=s.concat(h),a=a.concat(g);break}if(d.elseSteps){l+=d.elseSteps.length;let{hits:m,misses:h}=Ro({...t,steps:d.elseSteps,topLevel:!1});s=s.concat(m),a=a.concat(h)}break}default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(d)}return e&&l&&a.length>0&&o.warn({totalSteps:l,cacheMisses:a,cacheHits:s,cacheEntries:r.length},"Step cache did not fully resolve"),{hits:s,misses:a}}function Lg(n,e){return e?`${e}:${n}`:n}function fR(n,e){let t=[],r=e?.split(":")??[];for(let o=r.length;o>=0;o--){let i=[...r.slice(o),n];t.push(i.join(":"))}return t.reverse(),t}function Og(n){let{moduleStepParents:e=[],moduleIdParents:t=[]}=n;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
15
|
-
${JSON.stringify(t)}`);let r=[];if(!n.skipIntermediateEntries)for(let o=e.length;o>0;o--){let i=t[o-1],s=e.slice(o,e.length).join(":");r.push({key:Lg(n.id,s),moduleId:i,organizationId:n.orgId,value:n.value})}return r.push({key:Lg(n.id,e.join(":")),organizationId:n.orgId,value:n.value,testId:n.testId}),r}function kg(n){switch(n.type){case"DRAG":{if(n.fromTarget.type==="coordinates"||n.toTarget.type==="coordinates"||!n.fromTarget?.a11yData||!n.toTarget?.a11yData)return;n.cache={fromTarget:n.fromTarget.a11yData,toTarget:n.toTarget.a11yData},delete n.fromTarget.a11yData,delete n.toTarget.a11yData;return}case"MOUSE_DRAG":case"HOVER":case"SCROLL_UP":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SELECT_OPTION":case"TYPE":case"VISUAL_DIFF":case"CLICK":case"FOCUS":case"ELEMENT_CHECK":case"BLUR":{if(n.target?.type==="coordinates"||!n.target?.a11yData)return;n.cache={target:n.target.a11yData},delete n.target.a11yData;return}default:return}}function Ng(n){let e=new Set;return Ta(n,t=>{if("type"in t&&t.type==="RESOLVED_MODULE"&&"moduleId"in t){let r=t.moduleId;typeof r=="string"&&!e.has(r)&&e.add(r)}}),e}function _g(n,e,t){e.length&&(n.type==="DRAG"?e.length!==2||!e.every(r=>r.cache)?t.warn({newTargets:e,cmd:n},"New targets for step are incorrect"):n.fromTarget.type==="description"&&n.toTarget.type==="description"&&(n.cache={fromTarget:e[0].cache,toTarget:e[1].cache}):e.length!==1||!e[0]?.cache?t.warn({newTargets:e,cmd:n},"New targets for step are incorrect"):"target"in n&&n.target&&n.target.type==="description"&&(n.cache={target:e[0].cache}))}function Me(n,e,t=!1){return n.length<e?n:n.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var Zn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},Qn={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},ld={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable"},cd={EXISTS:"does not exists",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable"};function SR(n){switch(n.type){case"ELEMENT_CONTENT":return`${n.negated?Qn[n.operation]:Zn[n.operation]} '${n.value}'`;case"ELEMENT_ATTRIBUTE":{let t=n.negated?Qn[n.operation]:Zn[n.operation];return n.operation==="EXISTS"?`attribute '${n.attr}' ${t}`:`attribute '${n.attr}' ${t} '${n.value}'`}case"ELEMENT_EXISTENCE":return n.negated?cd[n.condition]:ld[n.condition];default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}var mW={CONTENT:"The page"};function yR(n){switch(n.type){case"VALUE":return`the option with value ${n.value}`;case"LABEL":return`the option with label ${n.label}`;case"INDEX":return`the option at index ${n.index}`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function dd(n){switch(n.type){case"SUBSTRING":return`match substring '${n.url}'`;case"REGEX":return`match regex '${n.regex}'`;case"GLOB":return`match glob '${n.glob}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function bR(n){switch(n.type){case"CONTENT":return`${n.negated?Qn.CONTAINS:Zn.CONTAINS} '${n.value}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.type)}}function Mr(n){switch(n.type){case"SUCCESS":return n.condition?.assertion?`Check success condition: ${n.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${n.goal}`;case"NAVIGATE":return`Go to URL: ${Me(n.url,30)}`;case"DIALOG":return`Automatically ${n.action.toLowerCase()} the next dialog`;case"CAPTCHA":return"Solve captchas on the page";case"GO_BACK":return"Go back to the previous page";case"GO_FORWARD":return"Go forward to the next page";case"SCROLL_DOWN":return`Scroll down ${n.deltaY?`${n.deltaY}px`:"1 page height"}${n.target?` in the container of: ${dt(n.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${n.deltaY?`${n.deltaY}px`:"1 page height"}${n.target?` in the container of: ${dt(n.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${n.deltaX?`${n.deltaX}px`:"1 page width"}${n.target?` in the container of: ${dt(n.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${n.deltaX?`${n.deltaX}px`:"1 page width"}${n.target?` in the container of: ${dt(n.target)}`:""}`;case"WAIT":return`Wait for ${n.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(n.target?.type==="coordinates")return`Click at coordinates: ${dt(n.target)}`;let t="";return n.target?.elementDescriptor.length?t=` on element: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` on element: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Click${t}`}case"FOCUS":return`Focus ${dt(n.target)}`;case"BLUR":return`Focus ${dt(n.target)}`;case"DRAG":return`Drag ${dt(n.fromTarget)} onto ${dt(n.toTarget)}`;case"MOUSE_DRAG":return n.target?.type==="description"&&n.target.elementDescriptor?`Click and drag ${dt(n.target)} by ${n.deltaX}px horizontally, ${n.deltaY}px vertically`:`Click and drag mouse by ${n.deltaX}px horizontally, ${n.deltaY}px vertically`;case"TYPE":{let t="";return n.target?.type==="coordinates"?t=` in element at coordinates: ${dt(n.target)}`:n.target?.elementDescriptor.length?t=` in element: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` in element: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Type '${n.value}'${t||""}`}case"HOVER":{let t="";return n.target.type==="coordinates"?t=` over coordinates: ${dt(n.target)}`:n.target.elementDescriptor.length>0?t=` over element: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` over element: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Hover${t}`}case"PRESS":return`Press ${n.value}`;case"SELECT_OPTION":{let t="",r=n.option??yR(n.choice);return n.target.type==="coordinates"?t=` from element at coordinates: ${dt(n.target)}`:n.target.elementDescriptor.length>0?t=` from: '${n.target.elementDescriptor}'`:n.cache?.target.nodeOnlySerializedHtml&&(t=` from: '${n.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${r}'${t}`}case"TAB":if(n.url)return`Switch to tab with substring: ${n.url}`;if(n.action)switch(n.action.type){case"SUBSTRING":return`Switch to tab with substring: ${n.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${n.action.pattern}`;case"INDEX":return`Switch to tab at index: ${n.action.index}`;default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${n.url}`;case"REQUEST":return`Send ${n.method} request to ${n.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${n.url}`;case"COOKIE":return`Set cookie: ${n.value}`;case"LOCAL_STORAGE":return`Set local storage: ${n.key}: ${n.value}`;case"JAVASCRIPT":return`Run JavaScript: ${Me(n.code,30)}`;case"AI_ASSERTION":return`Assertion: '${n.assertion}'`;case"AI_WAIT":return`Wait until assertion is true: '${n.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${n.target?`for element: ${dt(n.target)}`:"for entire page"}`;case"FILE_UPLOAD":return n.fileSource.type==="URL"?`Upload file: ${n.fileSource.url}`:`Upload file: ${n.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Assert the element ${dt(n.target)} ${SR(n.assertion)}`;case"PAGE_CHECK":return`Assert the page ${bR(n.assertion)}`;case"WAIT_FOR_URL":return n.url?`Wait for page URL to match: ${n.url}`:n.matcher?`Wait for page URL to ${dd(n.matcher)}`:"Wait for page URL to match";case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return n.pattern?`Register a listener for network requests that match ${n.pattern}`:"Register a listener for network requests";case"AWAIT_LISTENER":return n.key?`Wait for the listener ${n.key} to resolve`:"Wait for a listener to resolve";default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function Mg(n){let e=[];for(let t of n){t.sort((s,a)=>s.timestamp-a.timestamp);let r=[],o,i=1;for(let s of t)o&&o.text===s.text&&o.type===s.type&&JSON.stringify(o.args??null)===JSON.stringify(s.args??null)?i++:(o&&(i>1?o.args&&o.args.length?o.args.push(`(repeated ${i} times)`):o.text+=` (repeated ${i} times)`:r.push(o)),o=s,i=1);o&&r.push(o),e.push(r)}return e}import{cloneDeep as SW,unset as yW}from"lodash-es";function ln(n){switch(n.type){case"AI_ACTION":return`AI action: ${Me(n.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${Me(n.text,100)}`;case"PRESET_ACTION":return Mr(n.command);case"MODULE":return`Module: ${n.id}`;case"RESOLVED_MODULE":return`Module: ${n.name}`;case"CONDITIONAL":return"Conditional step";case"IFRAME":return"Frame step";case"SECTION":return`Section${n.description?`with goal: ${Me(n.description,100)}`:""}`;default:return(t=>{throw new Error("You missed a case in the switch above")})(n)}}var wR="[FAILED]";async function Fg(n,e,t,r){if(t)if(t.startsWith("http")){let i=await(await fetch(t)).arrayBuffer();return`data:image/jpeg;base64,${Buffer.from(i).toString("base64")}`}else return t.startsWith("data:")?t:`data:image/jpeg;base64,${t}`;else if(r){let o=await e.getScreenshot(n,r);if(o)return`data:image/jpeg;base64,${Buffer.from(o).toString("base64")}`}}async function Ea(n,e,t,{numScreenshots:r=1,addIndices:o=!0,includeBeforeScreenshots:i=!1,includeDomState:s=!1,recursive:a=!0}){let l=[],c;for(let p=0;p<t.length;p++){let d=t[p],u=a?Fr(d):ln(d),m={description:`Step ${p}: ${u}`,startedAt:d.startedAt,finishedAt:d.finishedAt,beforeUrl:d.beforeUrl,afterUrl:d.afterUrl,message:d.message!=="Successfully executed preset action."?d.message:void 0,index:o?p:void 0};if(d.status==="FAILED"){m.description=`${wR} ${m.description}`,o&&(c=p);try{let h=Gm.array().parse(d.details);for(let g of h)"pageState"in g&&s&&(m.pageState=g.pageState)}catch{}}r>0&&p>=t.length-r&&(m.afterScreenshot=await Fg(n,e,d.afterScreenshot,d.afterSnapshot),i&&(m.beforeScreenshot=await Fg(n,e,d.beforeScreenshot,d.beforeSnapshot))),l.push(m)}return{results:l,failureIndex:c}}function Fr(n){let e=ln(n);switch(n.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":e+=`
|
|
16
|
-
`;for(let t=0;t<
|
|
17
|
-
`,2),e+=`${Ge(
|
|
14
|
+
`)),console.log(" ",t(s))}}setMinLevel(e){this.minLogLevel=e}log(...e){this.logWithLevel(1,vn.reset,...e)}info(...e){this.logWithLevel(1,vn.white,...e)}debug(...e){this.logWithLevel(0,vn.dim,...e)}warn(...e){this.logWithLevel(2,vn.yellow,...e)}error(...e){this.logWithLevel(3,vn.red,...e)}success(...e){this.logWithLevel(4,vn.green,...e)}dimmed(...e){this.logWithLevel(1,vn.dim,...e)}underline(...e){this.logWithLevel(2,vn.underline,...e)}bold(...e){this.logWithLevel(2,vn.bold,...e)}grey(...e){this.logWithLevel(0,vn.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},y=new Zc(1,{}),Fr={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Fr,flush:()=>{},bindings:()=>({})},xs={},Dr=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let s=xs[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},xs[e]=s),s.totalCount++,s.count<t&&(s.count++,r.debug(o,i,...a)),s.timer=setTimeout(()=>{let l=xs[e];l?.totalCount!==l?.count&&r.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete xs[e]},n)};import{z as Ze}from"zod";var Ph=Ze.object({id:Ze.string(),createdAt:Ze.coerce.date(),createdBy:Ze.string(),organizationId:Ze.string(),name:Ze.string(),description:Ze.string().nullish(),enabled:Ze.boolean(),schemaVersion:Ze.string().describe("Schema version for steps"),parameters:Ze.string().array().nullish().describe("Parameter list"),defaultParameters:Ze.record(Ze.string(),Ze.string()).nullish(),defaultCacheKey:Ze.string().nullish(),defaultCacheTtl:Ze.number().nullish(),defaultCacheAllInvocations:Ze.boolean().nullish(),autoAuth:Ze.boolean().nullish(),advanced:hc.nullish()}),xz=Ph.extend({steps:Ze.lazy(()=>Je.array())}),Lh=5*60*1e3,Qc=Rt.merge(Ph.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as Cz}from"date-fns-tz";import{z as Zt}from"zod";var ed=Zt.object({failureRecovery:Zt.boolean().optional(),aiAction:Zt.boolean().optional(),stepLintSuggestions:Zt.boolean().optional()}),kh=Zt.object({fakerConstantSeed:Zt.boolean().optional()}),Iz=Zt.object({ai:ed.optional(),githubAppInstallationId:Zt.number().nullish(),githubReleaseAppInstallationId:Zt.number().nullish(),gitlabAppAccessToken:Zt.string().nullish().optional(),gitlabAppBaseUrl:Zt.string().nullish().optional(),qaseAccessToken:Zt.string().nullish().optional()});import*as T from"zod";var Wz=T.object({error:T.boolean(),reason:T.string(),message:T.string()}),Gz=Kt.merge(jc),Oh=Ua,Vz=Kt.merge(jc);var qz=Kt.merge(Gm).extend({useConsensus:T.boolean().optional(),attemptNumber:T.number().optional()}),td=Ru,Kz=Kt.merge(Vm),Nh=ju,Yz=Kt.merge(Hm),Mh=zu,Jz=Kt.merge($m),_h=Bu,Xz=Kt.merge(Wm);var Zz=T.object({testPaths:T.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:T.string().optional(),all:T.boolean().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional(),testInputMatrix:T.record(T.string(),T.string()).array().optional()}),Fh=T.object({queuedTests:T.unknown().array(),runIds:T.string().uuid().array(),runGroupId:T.string().optional()}),Dh=Vi,Uh=T.string().array(),Qz=T.union([T.object({paths:T.string().array().describe("run specific test paths (e.g. todo-test)"),all:T.boolean().describe("run all tests").optional()}),T.object({path:T.string().describe("deprecated; present for backcompat")})]),Bh=T.object({tests:T.record(T.string().describe("Test name"),T.string().describe("Test YAML")),modules:T.record(T.string().describe("Module name"),T.string().describe("Module YAML"))}),BC=T.object({test:T.string().describe("test YAML"),modules:T.record(T.string().describe("moduleId"),T.string().describe("module YAML"))}),ej=BC.array(),tj=T.object({testId:T.string(),schemaVersion:T.string()}).merge(Cr),nj=T.object({entries:T.array(vc),testId:T.string()}),rj=T.object({steps:T.array(T.record(T.unknown())),testId:T.string(),schemaVersion:T.string(),organizationId:T.string()}),zh=Uu,jh=T.object({trigger:T.nativeEnum(Pt),status:T.nativeEnum(re),startedAt:T.coerce.date().optional(),gitCommitSha:T.string().optional(),gitCommitShaShort:T.string().optional(),gitCommitTimestamp:T.coerce.date().optional(),gitBranchName:T.string().optional(),gitOriginUrl:T.string().optional(),gitCommitMessage:T.string().optional(),gitCommitAuthorName:T.string().optional(),githubRepository:T.string().optional(),gitlabProjectPath:T.string().optional(),pipelineId:T.string().optional(),cliVersion:T.string().optional()}),Hh=T.object({id:T.string()}),$h=T.object({status:T.nativeEnum(re),updatedAt:T.coerce.date().optional(),finishedAt:T.coerce.date().optional()}),Wh=T.object({stepsSnapshot:T.array(T.record(T.unknown())).optional(),runGroupId:T.string().optional(),testId:T.string(),testName:T.string(),resolvedBaseUrl:T.string().optional(),environmentName:T.string().optional(),labels:T.array(T.string()).optional(),cliVersion:T.string().optional(),trigger:T.nativeEnum(Pt),schemaVersion:T.string().optional(),section:T.nativeEnum(ps).optional()}),Gh=T.object({id:T.string()}),zC=zc.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Vh=zC.array(),qh=zc.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),Kh=T.object({id:T.string()}),Yh=T.object({status:T.nativeEnum(re),finishedAt:T.coerce.date().optional()}).merge(os),oj=T.object({screenshot:T.string()}),Jh=T.object({key:T.string()}),Xh=T.object({orgId:T.string(),userId:T.string()}),Zh=T.array(Xa),Qh=T.record(T.string(),T.union([T.string(),T.boolean()])),ij=T.object({paths:T.string().array(),env:T.string().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional()}),eg=T.object({suiteRunIds:T.string().array(),runGroupIds:T.string().array()}),aj=T.object({suiteRunIds:T.string().array()}),tg=jm.array(),sj=T.object({runGroupIds:T.string().array()}),Po=T.object({uploadUrl:T.string()}),lj=Kt.merge(qm),cj=Kt.merge(Ym),dj=Kt.merge(Km),jC=T.object({testId:T.string().optional().default(""),testName:T.string().optional().default(""),suiteId:T.string().optional().default(""),suiteName:T.string().optional().default(""),creditsUsed:T.number().optional(),usedBy:T.string().optional()}),HC=T.object({transactionId:T.string(),timestamp:T.string(),event:T.nativeEnum(Mr),properties:jC}),pj=HC.array(),ng=Lm.omit({steps:!0}).extend({steps:T.array(T.record(T.string(),T.unknown())).describe("unparsed ResolvedStep[]")}),uj=T.object({limit:T.number().max(10).optional(),afterTime:T.number().optional()}),rg=Fm.array(),mj=T.object({applied:T.boolean().optional(),appliedAt:T.coerce.date().optional()}),hj=Kt.extend({chunks:Hc.array(),description:T.string().describe("Input to pass to AI"),type:T.union([T.literal("locator"),T.literal("assertion"),T.literal("ai-action")]),softTokenLimit:T.number(),hardTokenLimit:T.number()}),og=Po.extend({id:T.string()}),ig=T.object({runGroupId:T.string()}),ag=T.object({featureFlags:T.record(T.string(),T.boolean().or(T.string())).optional(),featureFlagPayloads:T.record(T.string(),vs).optional()});import{z as Te}from"zod";var sg=Te.object({orgId:Te.string(),cacheKeys:Te.string().array()}),Sj=Te.object({keyParams:sg,clientMetadata:Te.string(),lockAcquisitionTimeoutMs:Te.number().optional()}),lg=Te.object({acquired:Te.boolean(),acquiredByMetadata:Te.string(),keyPrefix:Te.string()}),yj=Te.object({keyPrefix:Te.string(),result:Te.string(),ttlMs:Te.number()}),bj=Te.union([Te.object({keyPrefix:Te.string()}),sg]),$C=Te.object({remainingTtlMs:Te.number(),value:Te.string().nullish()}),wj=Te.object({results:Te.record(Te.string(),$C),activeLocks:Te.string().array()}),cg=0,dg=5*60*1e3;import{z as sn}from"zod";var pg="test",ug="module",Nt=(t=>(t.TEST=`${pg}.yaml`,t.MODULE=`${ug}.yaml`,t))(Nt||{}),fe=(o=>(o.TEST=`momentic/${pg}`,o.MODULE=`momentic/${ug}`,o.FIXTURE="momentic/fixture",o.ENVIRONMENT="momentic/environment",o))(fe||{}),Ij=Ot.merge(Cr),nd=Rt.extend({steps:sn.array(sn.record(sn.string(),sn.unknown())),schemaVersion:sn.string()}),Pj=nd.extend({fileType:sn.literal(fe.MODULE)}),Lj=sn.object({test:sn.string().describe("YAML for the test, including metadata and steps"),modules:sn.record(sn.string(),sn.string()).describe("Map of module name to YAML for the module")});import{z as ot}from"zod";var WC=ot.object({version:ot.string(),json:ot.record(ot.unknown()),hash:ot.string()}),mg=ot.record(ot.unknown()),Mj=ot.object({newSvgs:ot.array(WC),metadata:mg.optional()}),GC=ot.object({version:ot.string(),json:ot.record(ot.unknown()).nullish(),hash:ot.string(),description:ot.string().nullish(),metadata:mg.nullish()}),hg=ot.record(ot.string().describe("icon hash"),GC);import{validator as zj}from"@exodus/schemasafe";var gg=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as Zj}from"zod";import{z as Zn}from"zod";var tH=Zn.object({repositoriesIndexed:Zn.boolean(),indexingInProgress:Zn.boolean(),indexesOutdated:Zn.boolean()}),fg=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(fg||{}),Sg=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(Sg||{}),nH=Zn.object({name:Zn.string(),status:Zn.nativeEnum(fg),conclusion:Zn.nativeEnum(Sg).nullable()});import{z as Le}from"zod";var rd=Le.object({assertion:Le.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),VC=Le.object({instruction:Le.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:rd.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),yg=VC.extend({subSteps:Le.lazy(()=>yg.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),bg=Le.object({name:Le.string().describe("Short name describing the test plan"),description:Le.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),wg=bg.extend({id:Le.string(),createdAt:Le.coerce.date(),updatedAt:Le.coerce.date(),updatedBy:Le.string(),createdBy:Le.string(),test:Le.object({id:Le.string(),name:Le.string()}).nullish().transform(r=>r??void 0)}),aH=wg.extend({testGenRuns:Le.tuple([]).or(Le.tuple([Le.object({id:Le.string(),startedAt:Le.coerce.date(),status:Le.nativeEnum(re)})]))}),vg=Le.object({preConditions:rd.array().nullish().transform(r=>r??[]),postConditions:rd.array().nullish().transform(r=>r??[]),steps:yg.array().nullish().transform(r=>r??[])}),sH=wg.extend({plan:vg.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),qC=bg.extend({plan:vg.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),lH=qC.array().nullish().transform(r=>r??[]);import{z as Ee}from"zod";var KC=Ee.object({step:ve,status:Ee.nativeEnum(re),startedAt:Ee.coerce.date(),finishedAt:Ee.coerce.date().optional(),healMetadata:Ee.object({healType:Ee.nativeEnum(Ni).or(Ee.literal("AI")),healedAt:Ee.coerce.date()}).optional(),beforeSnapshotId:Ee.string().uuid().optional(),afterSnapshotId:Ee.string().uuid().optional(),message:Ee.string().optional()}),SH=KC.extend({status:Ee.nativeEnum(xe),finishedAt:Ee.coerce.date()}),YC=Ee.object({startedAt:Ee.coerce.date()}).merge(Yh),yH=YC.extend({finishedAt:Ee.coerce.date()}),JC=qh.merge(Wh).extend({startedAt:Ee.coerce.date(),attempts:Ee.number()}),bH=JC.extend({status:Ee.nativeEnum(re),finishedAt:Ee.coerce.date()}),XC=jh.merge($h).extend({startedAt:Ee.coerce.date(),cliVersion:Ee.string()}),od=XC.extend({updatedAt:Ee.coerce.date(),finishedAt:Ee.coerce.date()});function id(r){let e={parentChain:[]};return Ts(r,e),e}function Ts(r,e){let{onPresetAction:t,onSimpleStepContainer:n,onConditional:o,earlyStop:i}=r;for(let a of r.steps)switch(a.type){case"PRESET_ACTION":if(t(a,e)&&i)return!0;break;case"CONDITIONAL":if(o?.(a,e)&&i)return!0;e.parentChain.push(a);for(let l of a.blocks)if(t(l.assertion,e)&&i||Ts({...r,steps:l.steps},e)&&i)return!0;if(Ts({...r,steps:a.elseSteps??[]},e)&&i)return!0;e.parentChain.pop();break;case"RESOLVED_MODULE":case"IFRAME":case"SECTION":case"AI_ACTION":if(n?.(a,e)&&i)return!0;if(a.steps){if(e.parentChain.push(a),Ts({...r,steps:a.steps},e)&&i)return!0;e.parentChain.pop()}break;case"AI_ACTION_DYNAMIC":{if(n?.(a,e)&&i)return!0;break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(a)}}function xg(r,e,t,n){let o=Array.from(e),i=Array.from(n);for(let s=0;s<o.length;s++){if(o[s]!==i[s])return!1;i.shift()}return!!ZC([r],t,i).result}function ZC(r,e,t=[]){let n,o=[],i=(a,s)=>{let l=JSON.stringify(s.parentChain.map(p=>p.id)),c=t.length===0?!0:JSON.stringify(t)===l;return a.id===e&&c?(n=a,o=s.parentChain,!0):!1};return id({steps:r,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:n,parentChain:o}}function Tg(r,e){e(r);for(let t in r){let n=r[t];n&&(Array.isArray(n)?Es(n,e):typeof n=="object"&&Tg(n,e))}}function Es(r,e){for(let t of r)t&&(Array.isArray(t)?Es(t,e):typeof t=="object"&&Tg(t,e))}function Lo({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],s=[],l=0,c=(d,m)=>{try{let u=xr.parse(m.value);if(u.type!==d.type){o.warn({parsedCacheEntry:u,command:d},"Not using step cache due to type mismatch"),s.push(m.key);return}d.cache=u.cache,a.push(m.key)}catch(u){s.push(m.key),o.error({err:u,cacheEntry:m},"Not using step cache due to parsing error")}},p=(d,m)=>{let u=QC(d.id,m),h=u.find(g=>!!n[g]);h?c(d,n[h]):s.push(u[0])};for(let d of r)switch(d.type){case"RESOLVED_MODULE":{l+=d.steps.length;let{hits:u,misses:h}=Lo({...t,steps:d.steps,keyPrefix:i?`${i}:${d.id}`:d.id,topLevel:!1});a=a.concat(u),s=s.concat(h);break}case"IFRAME":case"SECTION":case"AI_ACTION":{if(l+=d.steps?.length??0,!d.steps?.length)break;let{hits:u,misses:h}=Lo({...t,steps:d.steps,topLevel:!1});a=a.concat(u),s=s.concat(h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!dc.includes(d.command.type)||(d.command.type==="TYPE"||d.command.type==="MOUSE_DRAG"||d.command.type==="VISUAL_DIFF"||d.command.type==="SCROLL_DOWN"||d.command.type==="SCROLL_UP"||d.command.type==="SCROLL_LEFT"||d.command.type==="SCROLL_RIGHT")&&!d.command.target||"cache"in d.command&&d.command.cache)continue;l++,p(d.command,i);break}case"CONDITIONAL":{for(let u of d.blocks){l++,p(u.assertion.command,i),l+=u.steps.length;let{hits:h,misses:g}=Lo({...t,steps:u.steps,topLevel:!1});a=a.concat(h),s=s.concat(g);break}if(d.elseSteps){l+=d.elseSteps.length;let{hits:u,misses:h}=Lo({...t,steps:d.elseSteps,topLevel:!1});a=a.concat(u),s=s.concat(h)}break}default:return(u=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(d)}return e&&l&&s.length>0&&o.warn({totalSteps:l,cacheMisses:s,cacheHits:a,cacheEntries:n.length},"Step cache did not fully resolve"),{hits:a,misses:s}}function Eg(r,e){return e?`${e}:${r}`:r}function QC(r,e){let t=[],n=e?.split(":")??[];for(let o=n.length;o>=0;o--){let i=[...n.slice(o),r];t.push(i.join(":"))}return t.reverse(),t}function Cg(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
15
|
+
${JSON.stringify(t)}`);let n=[];if(!r.skipIntermediateEntries)for(let o=e.length;o>0;o--){let i=t[o-1],a=e.slice(o,e.length).join(":");n.push({key:Eg(r.id,a),moduleId:i,organizationId:r.orgId,value:r.value})}return n.push({key:Eg(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function Ag(r){switch(r.type){case"DRAG":{if(r.fromTarget.type==="coordinates"||r.toTarget.type==="coordinates"||!r.fromTarget?.a11yData||!r.toTarget?.a11yData)return;r.cache={fromTarget:r.fromTarget.a11yData,toTarget:r.toTarget.a11yData},delete r.fromTarget.a11yData,delete r.toTarget.a11yData;return}case"MOUSE_DRAG":case"HOVER":case"SCROLL_UP":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SELECT_OPTION":case"TYPE":case"VISUAL_DIFF":case"CLICK":case"FOCUS":case"ELEMENT_CHECK":case"BLUR":{if(r.target?.type==="coordinates"||!r.target?.a11yData)return;r.cache={target:r.target.a11yData},delete r.target.a11yData;return}default:return}}function Rg(r){let e=new Set;return Es(r,t=>{if("type"in t&&t.type==="RESOLVED_MODULE"&&"moduleId"in t){let n=t.moduleId;typeof n=="string"&&!e.has(n)&&e.add(n)}}),e}function Ig(r,e,t){e.length&&(r.type==="DRAG"?e.length!==2||!e.every(n=>n.cache)?t.warn({newTargets:e,cmd:r},"New targets for step are incorrect"):r.fromTarget.type==="description"&&r.toTarget.type==="description"&&(r.cache={fromTarget:e[0].cache,toTarget:e[1].cache}):e.length!==1||!e[0]?.cache?t.warn({newTargets:e,cmd:r},"New targets for step are incorrect"):"target"in r&&r.target&&r.target.type==="description"&&(r.cache={target:e[0].cache}))}function _e(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var Qn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},er={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},ad={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable"},sd={EXISTS:"does not exists",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable"};function eA(r){switch(r.type){case"ELEMENT_CONTENT":return`${r.negated?er[r.operation]:Qn[r.operation]} '${r.value}'`;case"ELEMENT_ATTRIBUTE":{let t=r.negated?er[r.operation]:Qn[r.operation];return r.operation==="EXISTS"?`attribute '${r.attr}' ${t}`:`attribute '${r.attr}' ${t} '${r.value}'`}case"ELEMENT_EXISTENCE":return r.negated?sd[r.condition]:ad[r.condition];default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var K$={CONTENT:"The page"};function tA(r){switch(r.type){case"VALUE":return`the option with value ${r.value}`;case"LABEL":return`the option with label ${r.label}`;case"INDEX":return`the option at index ${r.index}`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function ld(r){switch(r.type){case"SUBSTRING":return`match substring '${r.url}'`;case"REGEX":return`match regex '${r.regex}'`;case"GLOB":return`match glob '${r.glob}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function nA(r){switch(r.type){case"CONTENT":return`${r.negated?er.CONTAINS:Qn.CONTAINS} '${r.value}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function Ur(r){switch(r.type){case"SUCCESS":return r.condition?.assertion?`Check success condition: ${r.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${r.goal}`;case"NAVIGATE":return`Go to URL: ${_e(r.url,30)}`;case"DIALOG":return`Automatically ${r.action.toLowerCase()} the next dialog`;case"CAPTCHA":return"Solve captchas on the page";case"GO_BACK":return"Go back to the previous page";case"GO_FORWARD":return"Go forward to the next page";case"SCROLL_DOWN":return`Scroll down ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${dt(r.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${dt(r.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${dt(r.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${dt(r.target)}`:""}`;case"WAIT":return`Wait for ${r.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(r.target?.type==="coordinates")return`Click at coordinates: ${dt(r.target)}`;let t="";return r.target?.elementDescriptor.length?t=` on element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(t=` on element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Click${t}`}case"FOCUS":return`Focus ${dt(r.target)}`;case"BLUR":return`Focus ${dt(r.target)}`;case"DRAG":return`Drag ${dt(r.fromTarget)} onto ${dt(r.toTarget)}`;case"MOUSE_DRAG":return r.target?.type==="description"&&r.target.elementDescriptor?`Click and drag ${dt(r.target)} by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`:`Click and drag mouse by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`;case"TYPE":{let t="";return r.target?.type==="coordinates"?t=` in element at coordinates: ${dt(r.target)}`:r.target?.elementDescriptor.length?t=` in element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(t=` in element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Type '${r.value}'${t||""}`}case"HOVER":{let t="";return r.target.type==="coordinates"?t=` over coordinates: ${dt(r.target)}`:r.target.elementDescriptor.length>0?t=` over element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(t=` over element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Hover${t}`}case"PRESS":return`Press ${r.value}`;case"SELECT_OPTION":{let t="",n=r.option??tA(r.choice);return r.target.type==="coordinates"?t=` from element at coordinates: ${dt(r.target)}`:r.target.elementDescriptor.length>0?t=` from: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(t=` from: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${n}'${t}`}case"TAB":if(r.url)return`Switch to tab with substring: ${r.url}`;if(r.action)switch(r.action.type){case"SUBSTRING":return`Switch to tab with substring: ${r.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${r.action.pattern}`;case"INDEX":return`Switch to tab at index: ${r.action.index}`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${r.url}`;case"REQUEST":return`Send ${r.method} request to ${r.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${r.url}`;case"COOKIE":return`Set cookie: ${r.value}`;case"LOCAL_STORAGE":return`Set local storage: ${r.key}: ${r.value}`;case"JAVASCRIPT":return`Run JavaScript: ${_e(r.code,30)}`;case"AI_ASSERTION":return`Assertion: '${r.assertion}'`;case"AI_WAIT":return`Wait until assertion is true: '${r.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${r.target?`for element: ${dt(r.target)}`:"for entire page"}`;case"FILE_UPLOAD":return r.fileSource.type==="URL"?`Upload file: ${r.fileSource.url}`:`Upload file: ${r.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Assert the element ${dt(r.target)} ${eA(r.assertion)}`;case"PAGE_CHECK":return`Assert the page ${nA(r.assertion)}`;case"WAIT_FOR_URL":return r.url?`Wait for page URL to match: ${r.url}`:r.matcher?`Wait for page URL to ${ld(r.matcher)}`:"Wait for page URL to match";case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return r.pattern?`Register a listener for network requests that match ${r.pattern}`:"Register a listener for network requests";case"AWAIT_LISTENER":return r.key?`Wait for the listener ${r.key} to resolve`:"Wait for a listener to resolve";default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function Pg(r){let e=[];for(let t of r){t.sort((a,s)=>a.timestamp-s.timestamp);let n=[],o,i=1;for(let a of t)o&&o.text===a.text&&o.type===a.type&&JSON.stringify(o.args??null)===JSON.stringify(a.args??null)?i++:(o&&(i>1?o.args&&o.args.length?o.args.push(`(repeated ${i} times)`):o.text+=` (repeated ${i} times)`:n.push(o)),o=a,i=1);o&&n.push(o),e.push(n)}return e}import{cloneDeep as rA}from"lodash-es";import{cloneDeep as Z$,unset as Q$}from"lodash-es";function ln(r){switch(r.type){case"AI_ACTION":return`AI action: ${_e(r.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${_e(r.text,100)}`;case"PRESET_ACTION":return Ur(r.command);case"MODULE":return`Module: ${r.id}`;case"RESOLVED_MODULE":return`Module: ${r.name}`;case"CONDITIONAL":return"Conditional step";case"IFRAME":return"Frame step";case"SECTION":return`Section${r.description?`with goal: ${_e(r.description,100)}`:""}`;default:return(t=>{throw new Error("You missed a case in the switch above")})(r)}}var Lg=1e3,kg=3e6,oA="[FAILED]";async function Og(r,e,t,n){if(t)if(t.startsWith("http")){let i=await(await fetch(t)).arrayBuffer();return`data:image/jpeg;base64,${Buffer.from(i).toString("base64")}`}else return t.startsWith("data:")?t:`data:image/jpeg;base64,${t}`;else if(n){let o=await e.getScreenshot(r,n);if(o)return`data:image/jpeg;base64,${Buffer.from(o).toString("base64")}`}}async function Cs(r,e,t,{numScreenshots:n=1,addIndices:o=!0,includeBeforeScreenshots:i=!1,includeDomState:a=!1,recursive:s=!0}){let l=[],c;for(let p=0;p<t.length;p++){let d=t[p],m=s?Br(d):ln(d),u={description:`Step ${p}: ${m}`,startedAt:d.startedAt,finishedAt:d.finishedAt,beforeUrl:d.beforeUrl,afterUrl:d.afterUrl,message:d.message!=="Successfully executed preset action."?d.message:void 0,index:o?p:void 0};if(d.status==="FAILED"){u.description=`${oA} ${u.description}`,o&&(c=p);try{let h=Bm.array().parse(d.details);for(let g of h)"pageState"in g&&a&&(u.pageState=g.pageState)}catch{}}n>0&&p>=t.length-n&&(u.afterScreenshot=await Og(r,e,d.afterScreenshot,d.afterSnapshot),i&&(u.beforeScreenshot=await Og(r,e,d.beforeScreenshot,d.beforeSnapshot))),l.push(u)}return{results:l,failureIndex:c}}function Br(r){let e=ln(r);switch(r.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":e+=`
|
|
16
|
+
`;for(let t=0;t<r.results.length;t++)e+=Ge(`Sub-step ${t} in AI action:
|
|
17
|
+
`,2),e+=`${Ge(Br(r.results[t]),2)}
|
|
18
18
|
`,e+=Ge(`${"=".repeat(10)}
|
|
19
19
|
`,2);return e;case"PRESET_ACTION":return e;case"MODULE":{e+=`
|
|
20
|
-
`;for(let t=0;t<
|
|
21
|
-
`,2),e+=`${Ge(
|
|
20
|
+
`;for(let t=0;t<r.results.length;t++)e+=Ge(`Sub-step ${t} in module:
|
|
21
|
+
`,2),e+=`${Ge(Br(r.results[t]),2)}
|
|
22
22
|
`,e+=Ge(`${"=".repeat(10)}
|
|
23
23
|
`,2);return e}case"CONDITIONAL":{e+=`
|
|
24
|
-
`,
|
|
25
|
-
`,2),e+=`${Ge(
|
|
24
|
+
`,r.assertion&&(e+=Ge(`Conditional check:
|
|
25
|
+
`,2),e+=`${Ge(Br(r.assertion),2)}
|
|
26
26
|
`,e+=Ge(`${"=".repeat(10)}
|
|
27
|
-
`,2)),e+=Ge(`${
|
|
28
|
-
`,2);for(let t=0;t<
|
|
29
|
-
`,2),e+=`${Ge(
|
|
27
|
+
`,2)),e+=Ge(`${r.assertion?"Branch steps":"Else branch steps"}
|
|
28
|
+
`,2);for(let t=0;t<r.results.length;t++)e+=Ge(`Sub-step ${t} in conditional branch:
|
|
29
|
+
`,2),e+=`${Ge(Br(r.results[t]),2)}
|
|
30
30
|
`,e+=Ge(`${"=".repeat(10)}
|
|
31
31
|
`,2);return e}case"IFRAME":{e+=`
|
|
32
|
-
`;for(let t=0;t<
|
|
33
|
-
`,2),e+=`${Ge(
|
|
32
|
+
`;for(let t=0;t<r.results.length;t++)e+=Ge(`Sub-step ${t} in frame step:
|
|
33
|
+
`,2),e+=`${Ge(Br(r.results[t]),2)}
|
|
34
34
|
`,e+=Ge(`${"=".repeat(10)}
|
|
35
35
|
`,2);return e}case"SECTION":{e+=`
|
|
36
|
-
`;for(let t=0;t<
|
|
37
|
-
`,2),e+=`${Ge(
|
|
36
|
+
`;for(let t=0;t<r.results.length;t++)e+=Ge(`Sub-step ${t} in section:
|
|
37
|
+
`,2),e+=`${Ge(Br(r.results[t]),2)}
|
|
38
38
|
`,e+=Ge(`${"=".repeat(10)}
|
|
39
|
-
`,2);return e}default:return(
|
|
39
|
+
`,2);return e}default:return(n=>{throw new Error("You missed a case in the switch above")})(r)}}function Ge(r,e){return r.split(`
|
|
40
40
|
`).map(t=>" ".repeat(e)+t).join(`
|
|
41
|
-
`)}function Dg(n,e){try{if(!n)return n;if(typeof n=="string")return Me(n,3e4);if(typeof n=="object"){let{jsonString:t}=ki(JSON.stringify(n,(r,o)=>e?.includes(r)||typeof o=="string"&&o.length>3e4?"REDACTED":o),2e4);return JSON.parse(t)}return n}catch{return n}}import{cloneDeep as FW}from"lodash-es";var vR=/^(?!.*\S+\s+\S+).*$/,xR=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,TR=/style="([^"]*)/g,ER=/data-[\w-]+/g,CR=n=>{switch(n.type){case"AI_WAIT":case"AI_ASSERTION":return{type:n.type,assertion:n.assertion};case"DRAG":if(n.fromTarget.type==="description")return{type:n.type,description:n.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(n.target?.type==="description")return{type:n.type,description:n.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function Ug(n){let e=CR(n),t=e.type==="AI_ASSERTION"||e.type==="AI_WAIT"?e.assertion:e.description;return!t||t==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:vR.test(t)&&xR.test(t)?{thoughts:"Too few words in the command description. Please add more words to the description.",category:"FEW_WORDS"}:TR.test(t)?{thoughts:"Style tag is not allowed in the command description. Please remove it and describe the command in a different way.",category:"STYLE_TAG"}:ER.test(t)?{thoughts:"Hardcoded data attributes are not recommend in the command description. If the attribute doesn't directly match the quotes, autohealing will fail.",category:"HARDCODED_ATTRIBUTE"}:new RegExp(`\\b${e.type}\\b`,"gi").test(t)?{thoughts:"The description contains the same word as the command type. Please remove it since the type of command is already known.",category:"TYPE_IN_DESCRIPTION"}:{thoughts:"NONE",category:"NONE"}}function Bg(n,e){if(!(!n.envs||!n.envs.length)){for(let t of n.envs){let r=t;e in t&&(r[e]&&(t.default=!0),delete r.defaultOnCloud,delete r.defaultOnLocal)}n.envs.some(t=>t.default)||(n.envs[0].default=!0)}}import{cloneDeep as pf}from"lodash-es";import LR from"diff-lines";import Ra,{gte as OR}from"semver";var zg={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async n=>(n=n.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),n=n.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),n)};var jg={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,r=t[t.length-1];return r&&r.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var RR=["target","fromTarget","toTarget"];function Hg(n){for(let e of RR){if(n[e]===void 0)continue;let t=n[e];t.elementDescriptor!==void 0?t.type="description":n[e]={type:"description",elementDescriptor:""}}}var $g={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":return Hg(e.command),e;case"AI_ACTION":{let t=e.commands;for(let r of t??[])Hg(r);return e}default:return e}})};import{v4 as AR}from"uuid";var Wg={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=AR()),e;default:return e}})};import{v4 as Gg}from"uuid";var Vg={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??Gg(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??Gg()}})),delete e.commands),e;default:return e}})};var qg={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as IR}from"uuid";var Kg={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>("id"in e&&typeof e.id=="string"||(e.id=IR()),e))};import{v4 as Yg}from"uuid";var Jg={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=Yg())}return e.id=Yg(),e})};var Xg={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as PR}from"uuid";var Zg={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=PR()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var Qg={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var ef={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&tf(t),e})};function tf(n){n&&Object.keys(n).forEach(e=>{if(typeof n[e]=="object"&&n[e]){tf(n[e]);return}if(typeof n[e]!="string")return;let t=n[e];e==="code"?n[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(n[e]=t.replace(/inputs\./g,"env."))})}var nf={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||t.url===void 0||(t.action={type:"SUBSTRING",substring:t.url},t.url=void 0),e})};var rf={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TYPE"?e:t.pressKeysSequentially===void 0?(t.delay=0,e):(t.pressKeysSequentially&&(t.pressKeysSequentially=void 0,t.delay=50),e)})};var of={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="WAIT_FOR_URL"||t.url===void 0||(t.matcher={type:"GLOB",glob:t.url},t.url=void 0),e})};var sf={name:"Migrate AI assertions to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async n=>n.map(e=>{if(e.type!=="AI_ASSERTION")return e;let r={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...r};return delete o.text,o}),stopOnFailure:!0};var Ca=new Set(["CLICK","TYPE","SELECT_OPTION"]),af={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e.command,r=t?.type,o=t?.elementDescriptor;return(o!==void 0||Ca.has(r))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(s=>{let a=s?.elementDescriptor,l=s?.type;(a!==void 0||Ca.has(l))&&(s.target={elementDescriptor:a??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(s=>{let a=s.command,l=a?.elementDescriptor,c=a?.type;(l!==void 0||Ca.has(c))&&(a.target={elementDescriptor:l??""}),s.commands&&Array.isArray(s.commands)&&s.commands.forEach(d=>{let u=d?.elementDescriptor,m=d?.type;(u!==void 0||Ca.has(m))&&(d.target={elementDescriptor:u??""})})}),e}),stopOnFailure:!0};var lf={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(r=>{if(r&&typeof r=="object"){let o=r;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var cf={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e.command,r=t?.type;return r?.startsWith("PRESET_")&&(t.type=r.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let s=i.type;s?.startsWith("PRESET_")&&(i.type=s.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let s=i.command,a=s?.type;a?.startsWith("PRESET_")&&(s.type=a.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(c=>{let p=c.type;p?.startsWith("PRESET_")&&(c.type=p.slice(7))})}),e}),stopOnFailure:!0};var Dr=[sf,lf,cf,af,zg,jg,$g,Wg,Vg,qg,Kg,Jg,Xg,Zg,Qg,ef,nf,rf,of];if(je!==Dr[Dr.length-1].toVersion)throw new Error("Please bump LATEST_VERSION in types package after adding a migration");Dr.forEach((n,e)=>{if(!Ra.valid(n.toVersion)||!Ra.valid(n.fromVersion))throw new Error(`Migration '${n.name}' has invalid version`);if(!Ra.gt(n.toVersion,n.fromVersion))throw new Error(`Migration '${n.name}' has toVersion <= fromVersion`);if(e===0)return;if(Dr[e-1].toVersion!==n.fromVersion)throw new Error(`Migration '${n.name}' at index ${e} is not contiguous with previous migration`)});function kR(n){return n.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var Vi=async({metadata:n,steps:e,logger:t,toVersion:r})=>{let o=e,{schemaVersion:i,id:s}=n,a=Dr.findIndex(p=>Ra.gt(p.toVersion,i));if(a===-1)return{steps:o,newVersion:i};let l=i;for(let p=a;p<Dr.length;p++){if(r&&OR(l,r)){t.debug("Stopping migration early because toVersion was reached");break}let d=Dr[p],u={id:s,migration:d.name,toVersion:d.toVersion};try{o=await df(o,d),l=d.toVersion}catch(m){throw t.error({err:m,...u},"Migration failed"),new Error(`Step migration ${d.name} failed: ${m}`)}}let c=LR(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return c.trim()&&t.debug({diffs:c,id:s},"Migration diffs"),{newVersion:l,steps:o}};async function df(n,e){let t=await e.execute(n);for(let r of t)for(let o of Object.keys(r)){if(!e.recursiveKeys.has(o))continue;let i=r[o];!i||!Array.isArray(i)||kR(i)&&(r[o]=await df(i,e))}return t}async function uf({rawSteps:n,metadata:e,logger:t,callbacks:r}){Bg(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:s}=await Aa({rawSteps:n.steps,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o}),a={...e,steps:i,schemaVersion:s};for(let l of["beforeSteps","afterSteps"]){let c=n[l];if(!c)continue;let{resolvedSteps:p}=await Aa({rawSteps:c,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o});a[l]=p}return{resolvedTest:a,moduleIds:Array.from(Object.keys(o))}}async function pd(n,e,t){let{newVersion:r,steps:o}=await Vi({metadata:n,steps:e,logger:t});try{return{steps:Ye.array().parse(o),newVersion:r}}catch(i){throw t.error({type:"zod",err:i,newVersion:r,id:n.id,steps:o},"Failed to parse test steps while migrating test"),new ba(`Failed to parse test steps while migrating test: ${i}`,n.id,"entity",{cause:i})}}async function Aa({rawSteps:n,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o={}}){let{newVersion:i,steps:s}=await pd(e,n,t),a=[];for(let l of s)a.push(await qi({step:l,callbacks:r,logger:t,resolvedModuleCache:o}));return{resolvedSteps:a,newSchemaVersion:i}}async function qi({step:n,callbacks:e,logger:t,resolvedModuleCache:r}){switch(n.type){case"AI_ACTION":return n;case"AI_ACTION_DYNAMIC":return n;case"PRESET_ACTION":return n;case"MODULE":{let l=n.moduleId,c=r[l];if(c)return{...pf(c),...n,type:"RESOLVED_MODULE"};let p=await e.onFetchModule({id:l,logger:t});if(!p)throw new Error(`Could not find module with id ${l}`);let{newVersion:d,steps:u}=await Vi({metadata:{id:l,schemaVersion:p.schemaVersion},steps:p.steps,logger:t}),m;try{m=Ye.array().parse(u)}catch(f){throw t.error({type:"zod",err:f,steps:u,newVersion:d,id:l},"Module failed to parse"),f}let h;try{h=await Promise.all(m.map(f=>qi({step:f,callbacks:e,logger:t,resolvedModuleCache:r})))}catch(f){throw t.error({err:f,...n},`Failed to recursively resolve module '${p.name}': ${f}`),f}let g={...p,steps:h};return r[l]=pf(g),{...g,...n,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let l of n.blocks){let c=[];for(let p of l.steps)c.push(await qi({step:p,callbacks:e,logger:t,resolvedModuleCache:r}));o.push({...l,steps:c})}let i;if(n.elseSteps){i=[];for(let l of n.elseSteps)i.push(await qi({step:l,callbacks:e,logger:t,resolvedModuleCache:r}))}return{...n,blocks:o,elseSteps:i};case"SECTION":case"IFRAME":let s=[];for(let l of n.steps)s.push(await qi({step:l,callbacks:e,logger:t,resolvedModuleCache:r}));return{...n,steps:s};default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function NR(n){return typeof n=="object"&&n!==null}function _n(n){if(Array.isArray(n))return n.map(_n);if(NR(n)){let e={};return Object.entries(n).forEach(([t,r])=>{r!==void 0&&(e[t]=_n(r))}),e}return n}import{cloneDeep as mf}from"lodash-es";import{v4 as ud}from"uuid";async function Ze(n){let e=new Map,t=new Set,r=mf(n.stepLists.steps),o=await Ur({...n,steps:r,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t}),i={stepsToSave:{steps:o.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates};for(let s of["beforeSteps","afterSteps"]){let a=mf(n.stepLists[s]);if(!a)continue;let l=await Ur({...n,steps:a,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});i.cachesToSave.push(...l.cachesToSave),i.moduleUpdates.push(...l.moduleUpdates),i.stepsToSave[s]=l.stepsToSave}return i}async function Ur({steps:n,...e}){let{seenModules:t,cacheCreationParams:r,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:s,shouldCreateNewModuleId:a}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let c of n)switch(delete c.index,delete c.aiSuggested,c.id=e.createNewStepIds?ud():c.id,c.type){case"PRESET_ACTION":{let d=c.command;d.id=r?.createNewCacheIds?ud():d.id,kg(d),"cache"in d&&d.cache&&(r&&(l.cachesToSave=l.cachesToSave.concat(Og({id:d.id,orgId:r.orgId,testId:r.testId,value:vr.parse(d),moduleIdParents:o,moduleStepParents:i,skipIntermediateEntries:e.skipCacheIntermediateEntries}))),delete d.cache),d.thoughts&&delete d.thoughts,l.stepsToSave.push({...c,command:d});break}case"RESOLVED_MODULE":{let d=r?.createNewCacheIds?ud():c.id,u=c.moduleId;s.has(u)?u=s.get(u):a!==void 0&&(u=await a(c),s.set(c.moduleId,u));let{cachesToSave:m,stepsToSave:h,moduleUpdates:g}=await Ur({...e,steps:c.steps,cacheCreationParams:r?{...r,createNewCacheIds:!1}:void 0,moduleStepParents:[...i,d],moduleIdParents:[...o,u],skipCacheIntermediateEntries:r?.createNewCacheIds});l.moduleUpdates=l.moduleUpdates.concat(g),l.cachesToSave=l.cachesToSave.concat(m),t.has(u)||(t.add(u),l.moduleUpdates.push({...At.parse(c),steps:Ye.array().parse(h),moduleId:u}));let f={type:"MODULE",moduleId:u,inputs:c.inputs,id:d,skipped:c.skipped,cacheConfig:c.cacheConfig,envKey:c.envKey};l.stepsToSave.push(f);break}case"AI_ACTION":{if(!c.steps){l.stepsToSave.push(c);break}let{stepsToSave:d,cachesToSave:u}=await Ur({...e,steps:c.steps});try{c.steps=Rt.array().parse(d)}catch(m){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${m}`)}l.stepsToSave.push(c),l.cachesToSave=l.cachesToSave.concat(u);break}case"AI_ACTION_DYNAMIC":{l.stepsToSave.push(c);break}case"CONDITIONAL":{let d=[];for(let m of c.blocks){let{stepsToSave:h,cachesToSave:g,moduleUpdates:f}=await Ur({...e,steps:m.steps});d.push({...m,steps:h}),l.cachesToSave=l.cachesToSave.concat(g),l.moduleUpdates=l.moduleUpdates.concat(f)}let u={...c,elseSteps:void 0,blocks:d};if(c.elseSteps){let{stepsToSave:m,cachesToSave:h,moduleUpdates:g}=await Ur({...e,steps:c.elseSteps});u.elseSteps=m,l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(g)}l.stepsToSave.push(u);break}case"IFRAME":case"SECTION":{let{stepsToSave:d,cachesToSave:u,moduleUpdates:m}=await Ur({...e,steps:c.steps}),h={...c,steps:d};l.moduleUpdates=l.moduleUpdates.concat(m),l.stepsToSave.push(h),l.cachesToSave=l.cachesToSave.concat(u);break}default:return(d=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(c)}return l}import{cloneDeep as _R}from"lodash-es";import{stringify as hf}from"yaml";async function gf(n,e=new Set){let t={id:n.id,name:n.name,description:n.description,baseUrl:n.baseUrl,schemaVersion:n.schemaVersion,advanced:n.advanced,retries:n.retries,envs:n.envs,disabled:n.disabled,labels:n.labels},r={},o=await MR({originalStepLists:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},modules:r,processedModuleNames:e}),i={fileType:fe.TEST,...t,beforeSteps:o.beforeSteps&&o.beforeSteps.length>0?o.beforeSteps:void 0,steps:o.steps,afterSteps:o.afterSteps&&o.afterSteps.length>0?o.afterSteps:void 0};return{test:hf(i),modules:r}}async function MR({originalStepLists:n,modules:e,processedModuleNames:t}){let r=_R(n);Object.values(r).forEach(s=>{FR(s??[])});let{stepsToSave:o,moduleUpdates:i}=await Ze({stepLists:r});for(let s of i)t.has(s.name)||(e[s.name]=DR(s),t.add(s.name));return o}function FR(n){ad({steps:n,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function DR(n){let e=At.parse(n),t={fileType:fe.MODULE,...e,schemaVersion:je,steps:n.steps};return hf(t)}async function te(n,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},n);function i(){clearTimeout(o),e?.removeEventListener("abort",i),r(e?.reason)}})}async function Ki({promiseGenerator:n,signal:e,codePath:t,logger:r}){let i=Date.now(),s=setInterval(()=>{if(e?.aborted){clearInterval(s);return}r?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((a,l)=>{function c(){clearInterval(s),e?.removeEventListener("abort",c),l(e?.reason)}if(e?.aborted){l(e?.reason),clearInterval(s);return}e?.addEventListener("abort",c),(async()=>{try{a(await n())}catch(p){l(p)}finally{clearInterval(s),e?.removeEventListener("abort",c)}})()})}async function Br({promiseGenerator:n,timeoutMs:e,codePath:t,logger:r,signal:o}){let i=!1,s=new AbortController,a=()=>{s.abort()},l=setTimeout(()=>{i||s.abort()},e);o?.addEventListener("abort",a);try{return await Ki({promiseGenerator:n,signal:s.signal,codePath:t,logger:r})}finally{i=!0,o?.removeEventListener("abort",a),clearTimeout(l)}}function Ia(n){let e=[];for(let t of n)switch(t.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(t);break;case"RESOLVED_MODULE":{let r={...t,type:"MODULE"};e.push(kn.parse(r));break}case"IFRAME":case"SECTION":{let r={...t,steps:Ia(t.steps)};e.push(Ye.parse(r));break}case"CONDITIONAL":{let r={...t,blocks:t.blocks.map(o=>({assertion:o.assertion,steps:Ia(o.steps)})),elseSteps:t.elseSteps?Ia(t.elseSteps):void 0};e.push(Tr.parse(r));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function Pa(n){return Ia([n])[0]}import UR from"picomatch";var md=(n,e,t)=>{t?.caseInsensitive&&(n=n.toLowerCase());let r;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;r=n.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;r=n===e.glob||UR(o)(n);break}case"REGEX":{r=new RegExp(e.regex).test(n);break}}return t?.negated?!r:r};import jr from"yaml";import{execSync as BR}from"child_process";function zr(n,e){let t=e.hooks?.postSave;if(!t)return;let r;t.includes("$1")?r=t.replaceAll("$1",n):r=`${t} ${n}`,y.debug({postSaveCommand:r},"Executing post-save hook command");try{BR(r,{encoding:"utf-8"})}catch(o){y.warn({err:o,postSaveCommand:r},"Failed to execute post-save hook command, continuing...")}}import{diff as ff}from"deep-object-diff";import er from"fs";import{cloneDeep as zR}from"lodash-es";import hd from"path";import{v4 as jR}from"uuid";import Yi from"yaml";function gd({content:n,schemaVersion:e,momenticFiles:t,project:r}){let o=t.modules[n.moduleId]?.fullFilePath;if(!o||!er.existsSync(o))throw new Error(`Tried to update module ${n.moduleId} that could not be found on disk`);let i=er.readFileSync(o,"utf-8"),s=Yi.parse(i),a;if(n.name&&n.name!==s.name){let u=`${Pe(n.name)}.${Nt.MODULE}`;if(a=hd.join(hd.dirname(o),u),er.existsSync(a))throw new Error(`Test with name '${n.name}' already exists at path '${a}'`)}let l={...n,schemaVersion:e},c=_n({fileType:fe.MODULE,...td.parse(l),steps:n.steps}),p=ff(c,s);if(p&&Object.keys(p).length===0){y.debug(`Skipping save for module ${n.moduleId} since there are no changes`);return}let d=Yi.stringify(c);er.writeFileSync(o,d,"utf-8"),a&&er.renameSync(o,a),zr(a||o,r.config)}function Sf({moduleId:n,content:e,momenticFiles:t,project:r,logger:o}){let i=t.modules[n]?.fullFilePath;if(!i)throw new Error(`Tried to update module ${n} that could not be found on disk`);let s=Ji(i,o),a={...s,...e},l=_n({fileType:fe.MODULE,...td.parse(a),steps:s.steps}),c=ff(l,s);if(c&&Object.keys(c).length===0){y.debug(`Skipping save for module ${n} since there are no changes`);return}let p=Yi.stringify(l);er.writeFileSync(i,p,"utf-8"),zr(i,r.config)}async function yf({name:n,description:e,enabled:t,steps:r,folder:o,project:i}){let s=Pe(n),a=hd.join(o,`${s}.module.yaml`),l=jR(),{stepsToSave:c}=await Ze({stepLists:{steps:r}}),p={fileType:fe.MODULE,schemaVersion:je,moduleId:l,name:n,description:e,enabled:t,steps:c.steps},d=Yi.stringify(p);return er.writeFileSync(a,d,"utf-8"),zr(a,i.config),{moduleId:l,name:n,description:e,enabled:t,steps:r}}function Ji(n,e){let t=er.readFileSync(n,"utf-8"),r=Yi.parse(t);try{return od.parse(r)}catch(o){throw e.error({err:o,moduleFilePath:n,moduleContents:t},`${n} does not parse as a valid Momentic module`),o}}async function fd(n,e,t,r){let o=Ji(n.fullFilePath,t),{resolvedSteps:i}=await Aa({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:r,logger:t,callbacks:{onFetchModule:async({id:a})=>{let l=e.modules[a]?.fullFilePath;if(l)return Ji(l,t)}}}),s={...o,steps:i};return r&&(r[n.id]=zR(s)),s}async function La(n,e){let t={};return await Promise.all(Object.values(n.modules).map(async r=>{await fd(r,n,e,t)})),Array.from(Object.values(t))}async function bf({test:n,name:e,folder:t}){let r=await gf(n);if(Object.keys(r.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${Pe(e)}.${Nt.TEST}`,s=Bt.join(t,i);return _t.writeFileSync(s,r.test,"utf-8"),s}function Sd(n,e,t){let r=Bt.join(t.rootDir,n);if(!_t.existsSync(r))throw new Error(`Test not found at path '${n}' in project '${t.rootDir}'`);let o=_t.readFileSync(r,"utf-8"),i=jr.parse(o),s,a;if(e.name&&e.name!==i.name){let u=`${Pe(e.name)}.${Nt.TEST}`;if(s=Bt.join(Bt.dirname(n),u),a=Bt.join(t.rootDir,s),_t.existsSync(a))throw new Error(`Test with name '${e.name}' already exists at path '${a}'`)}let l={...i,...e},c=Xt.parse(l),p={fileType:fe.TEST,...Xt.parse(c),beforeSteps:i.beforeSteps??void 0,steps:i.steps,afterSteps:i.afterSteps??void 0},d=jr.stringify(p);return _t.writeFileSync(r,d,"utf-8"),a&&_t.renameSync(r,a),zr(r,t.config),{newRelativeTestPath:s}}function Hr(n,e,t,r){let o=Bt.join(r.rootDir,n);if(!_t.existsSync(o))throw new Error(`Test not found at path '${n}' in project '${r.rootDir}'`);let i=_t.readFileSync(o,"utf-8"),s=jr.parse(i),a=Xt.parse({...s,schemaVersion:t}),l=_n({fileType:fe.TEST,...a,beforeSteps:e.beforeSteps??void 0,steps:e.steps,afterSteps:e.afterSteps??void 0}),c=HR(l,s);if(c&&Object.keys(c).length===0){y.debug(`Skipping save for test ${a.name} since there are no changes`);return}let p=jr.stringify(l);_t.writeFileSync(o,p,"utf-8"),y.debug(`Saving test ${a.name} to ${o}`),zr(o,r.config)}function yd(n,e,t=n){let r=n.split(Bt.sep).pop()??"";if(Gi.includes(r))return e.warn(`Skipping directory '${n}' because it is likely an artifact folder.`),[];let o=_t.readdirSync(n),i=[];return o.forEach(s=>{let a=Bt.join(n,s),l;try{l=_t.statSync(a)}catch(c){e.warn({err:c},`Skipping path '${a}' because it could not be read.`);return}if(l.isDirectory())i=i.concat(yd(a,e,t));else if(s.endsWith(".yaml")){let c=_t.readFileSync(a,"utf-8"),p=Bt.relative(Bt.resolve(t),Bt.resolve(a));try{let d=jr.parse(c),u=kt.parse(d);i.push({id:u.id,name:u.name,fullPathSegments:a.split(Bt.sep),testPath:p,fileName:s,lastModified:l.mtime,createdAt:l.ctime})}catch{e.warn(`Skipping file '${a}' because it does not parse as a valid Momentic test.`)}}}),i}function Oa(n,e){let t=Bt.join(e.rootDir,n);if(!t)throw new Error(`Could not find test with path ${n} in Momentic project (${e.rootDir})`);let r;try{r=_t.readFileSync(t,"utf8"),r=r.replace(/\r\n|\r/g,`
|
|
42
|
-
`)}catch(i){throw new Error(`Could not read test file ${t}: ${i}`)}let o;try{o=jr.parse(r)}catch(i){throw new Error(`Could not parse test file ${t} as YAML: ${i}`)}return kt.parse(o)}function Xi(n,e,t){let r=t.project.rootDir,o;try{o=_t.readFileSync(n,"utf-8")}catch(s){throw e.error({err:s,projectRoot:r},s.message),new Error(s.message)}let i=jr.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${n} is missing steps`);return i}async function Zi(n,e,t){let r=Xi(n,e,t),o;try{o=Xt.parse(r)}catch(s){throw new Error(`Test ${n} is missing metadata or has invalid metadata: ${s}`)}let{resolvedTest:i}=await uf({rawSteps:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:s,logger:a})=>{let l=t.modules[s]?.fullFilePath;if(l)return Ji(l,a)}}});return i}import $R from"@dotenvx/dotenvx";import WR from"fs";import wf from"path";function xf(n,e){return(n.config.environments??[]).map(t=>Qi(t.name,n,e))}function vf(n){return n.includes("${")?n.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[r,o]=t.split(/:-|-/,2),i=process.env[r];return t.includes(":-")?i&&i!==""?i:o||"":t.includes("-")?i!==void 0?i:o||"":i||""}):n}function Qi(n,e,t){let r=(e.config.environments??[]).find(s=>s.name===n);if(!r)throw new Error(`Environment ${n} not found in local project configuration file`);let o={[Ie]:vf(r.baseUrl)};if(r.envVariables){let s={};for(let[a,l]of Object.entries(r.envVariables))if(typeof l=="string"){let c=vf(l);c&&(s[a]=c)}else{let c=l.fromFile,p;try{p=WR.readFileSync(wf.resolve(e.rootDir,c),"utf-8")}catch(d){throw new Error(`Failed to read environment variable '${a}' from file '${c}': ${d}`)}if(l.json)try{s[a]=JSON.parse(p)}catch(d){throw new Error(`Failed to parse environment variable '${a}' from file '${c}' as JSON: ${d}`)}else s[a]=p}Object.keys(s).length>0&&y.debug(s,"Set environment variables with interpolation from project configuration"),Object.assign(o,s)}if(r.envFile){let s={},a=$R.config({path:wf.resolve(e.rootDir,r.envFile),processEnv:s,logLevel:"error",quiet:!0});if(a.error)throw new Error(`Failed to load .env file: ${a.error.message}`);t.debug(s,"Set environment variables from .env file"),Object.assign(o,s)}return r.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:n,variables:o,browser:r.browser}}import{existsSync as vI,readFileSync as xI,readdirSync as TI,writeFileSync as EI}from"fs";var $f=Pu(Mf(),1);var ts=n=>{if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>65536)throw new TypeError("pattern is too long")};var ZR={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},ns=n=>n.replace(/[[\]\\-]/g,"\\$&"),QR=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ff=n=>n.join(""),Df=(n,e)=>{let t=e;if(n.charAt(t)!=="[")throw new Error("not in a brace expression");let r=[],o=[],i=t+1,s=!1,a=!1,l=!1,c=!1,p=t,d="";e:for(;i<n.length;){let g=n.charAt(i);if((g==="!"||g==="^")&&i===t+1){c=!0,i++;continue}if(g==="]"&&s&&!l){p=i+1;break}if(s=!0,g==="\\"&&!l){l=!0,i++;continue}if(g==="["&&!l){for(let[f,[S,x,v]]of Object.entries(ZR))if(n.startsWith(f,i)){if(d)return["$.",!1,n.length-t,!0];i+=f.length,v?o.push(S):r.push(S),a=a||x;continue e}}if(l=!1,d){g>d?r.push(ns(d)+"-"+ns(g)):g===d&&r.push(ns(g)),d="",i++;continue}if(n.startsWith("-]",i+1)){r.push(ns(g+"-")),i+=2;continue}if(n.startsWith("-",i+1)){d=g,i+=2;continue}r.push(ns(g)),i++}if(p<i)return["",!1,0,!1];if(!r.length&&!o.length)return["$.",!1,n.length-t,!0];if(o.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!c){let g=r[0].length===2?r[0].slice(-1):r[0];return[QR(g),!1,p-t,!1]}let u="["+(c?"^":"")+Ff(r)+"]",m="["+(c?"":"^")+Ff(o)+"]";return[r.length&&o.length?"("+u+"|"+m+")":r.length?u:m,a,p-t,!0]};var cn=(n,{windowsPathsNoEscape:e=!1}={})=>e?n.replace(/\[([^\/\\])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var eA=new Set(["!","?","+","*","@"]),Uf=n=>eA.has(n),tA="(?!(?:^|/)\\.\\.?(?:$|/))",ka="(?!\\.)",nA=new Set(["[","."]),rA=new Set(["..","."]),oA=new Set("().*{}+?[]^$\\!"),iA=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),vd="[^/]",Bf=vd+"*?",zf=vd+"+?",Ao=class n{type;#e;#t;#i=!1;#r=[];#s;#w;#c;#p=!1;#a;#l;#o=!1;constructor(e,t,r={}){this.type=e,e&&(this.#t=!0),this.#s=t,this.#e=this.#s?this.#s.#e:this,this.#a=this.#e===this?r:this.#e.#a,this.#c=this.#e===this?[]:this.#e.#c,e==="!"&&!this.#e.#p&&this.#c.push(this),this.#w=this.#s?this.#s.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l!==void 0?this.#l:this.type?this.#l=this.type+"("+this.#r.map(e=>String(e)).join("|")+")":this.#l=this.#r.map(e=>String(e)).join("")}#f(){if(this!==this.#e)throw new Error("should only call on root");if(this.#p)return this;this.toString(),this.#p=!0;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let t=e,r=t.#s;for(;r;){for(let o=t.#w+1;!r.type&&o<r.#r.length;o++)for(let i of e.#r){if(typeof i=="string")throw new Error("string part in extglob AST??");i.copyIn(r.#r[o])}t=r,r=t.#s}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof n&&t.#s===this))throw new Error("invalid part: "+t);this.#r.push(t)}}toJSON(){let e=this.type===null?this.#r.slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...this.#r.map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#p&&this.#s?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#s?.isStart())return!1;if(this.#w===0)return!0;let e=this.#s;for(let t=0;t<this.#w;t++){let r=e.#r[t];if(!(r instanceof n&&r.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#s?.type==="!")return!0;if(!this.#s?.isEnd())return!1;if(!this.type)return this.#s?.isEnd();let e=this.#s?this.#s.#r.length:0;return this.#w===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let t=new n(this.type,e);for(let r of this.#r)t.copyIn(r);return t}static#S(e,t,r,o){let i=!1,s=!1,a=-1,l=!1;if(t.type===null){let m=r,h="";for(;m<e.length;){let g=e.charAt(m++);if(i||g==="\\"){i=!i,h+=g;continue}if(s){m===a+1?(g==="^"||g==="!")&&(l=!0):g==="]"&&!(m===a+2&&l)&&(s=!1),h+=g;continue}else if(g==="["){s=!0,a=m,l=!1,h+=g;continue}if(!o.noext&&Uf(g)&&e.charAt(m)==="("){t.push(h),h="";let f=new n(g,t);m=n.#S(e,f,m,o),t.push(f);continue}h+=g}return t.push(h),m}let c=r+1,p=new n(null,t),d=[],u="";for(;c<e.length;){let m=e.charAt(c++);if(i||m==="\\"){i=!i,u+=m;continue}if(s){c===a+1?(m==="^"||m==="!")&&(l=!0):m==="]"&&!(c===a+2&&l)&&(s=!1),u+=m;continue}else if(m==="["){s=!0,a=c,l=!1,u+=m;continue}if(Uf(m)&&e.charAt(c)==="("){p.push(u),u="";let h=new n(m,p);p.push(h),c=n.#S(e,h,c,o);continue}if(m==="|"){p.push(u),u="",d.push(p),p=new n(null,t);continue}if(m===")")return u===""&&t.#r.length===0&&(t.#o=!0),p.push(u),u="",t.push(...d,p),c;u+=m}return t.type=null,t.#t=void 0,t.#r=[e.substring(r-1)],c}static fromGlob(e,t={}){let r=new n(null,void 0,t);return n.#S(e,r,0,t),r}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,r,o,i]=this.toRegExpSource();if(!(o||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return r;let a=(this.#a.nocase?"i":"")+(i?"u":"");return Object.assign(new RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#a}toRegExpSource(e){let t=e??!!this.#a.dot;if(this.#e===this&&this.#f(),!this.type){let l=this.isStart()&&this.isEnd(),c=this.#r.map(m=>{let[h,g,f,S]=typeof m=="string"?n.#u(m,this.#t,l):m.toRegExpSource(e);return this.#t=this.#t||f,this.#i=this.#i||S,h}).join(""),p="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&rA.has(this.#r[0]))){let h=nA,g=t&&h.has(c.charAt(0))||c.startsWith("\\.")&&h.has(c.charAt(2))||c.startsWith("\\.\\.")&&h.has(c.charAt(4)),f=!t&&!e&&h.has(c.charAt(0));p=g?tA:f?ka:""}let d="";return this.isEnd()&&this.#e.#p&&this.#s?.type==="!"&&(d="(?:$|\\/)"),[p+c+d,cn(c),this.#t=!!this.#t,this.#i]}let r=this.type==="*"||this.type==="+",o=this.type==="!"?"(?:(?!(?:":"(?:",i=this.#m(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!=="!"){let l=this.toString();return this.#r=[l],this.type=null,this.#t=void 0,[l,cn(this.toString()),!1,!1]}let s=!r||e||t||!ka?"":this.#m(!0);s===i&&(s=""),s&&(i=`(?:${i})(?:${s})*?`);let a="";if(this.type==="!"&&this.#o)a=(this.isStart()&&!t?ka:"")+zf;else{let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?ka:"")+Bf+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&s?")":this.type==="*"&&s?")?":`)${this.type}`;a=o+i+l}return[a,cn(i),this.#t=!!this.#t,this.#i]}#m(e){return this.#r.map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[r,o,i,s]=t.toRegExpSource(e);return this.#i=this.#i||s,r}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#u(e,t,r=!1){let o=!1,i="",s=!1;for(let a=0;a<e.length;a++){let l=e.charAt(a);if(o){o=!1,i+=(oA.has(l)?"\\":"")+l;continue}if(l==="\\"){a===e.length-1?i+="\\\\":o=!0;continue}if(l==="["){let[c,p,d,u]=Df(e,a);if(d){i+=c,s=s||p,a+=d-1,t=t||u;continue}}if(l==="*"){r&&e==="*"?i+=zf:i+=Bf,t=!0;continue}if(l==="?"){i+=vd,t=!0;continue}i+=iA(l)}return[i,cn(e),!!t,s]}};var Io=(n,{windowsPathsNoEscape:e=!1}={})=>e?n.replace(/[?*()[\]]/g,"[$&]"):n.replace(/[?*()[\]\\]/g,"\\$&");var yt=(n,e,t={})=>(ts(e),!t.nocomment&&e.charAt(0)==="#"?!1:new zt(e,t).match(n)),sA=/^\*+([^+@!?\*\[\(]*)$/,aA=n=>e=>!e.startsWith(".")&&e.endsWith(n),lA=n=>e=>e.endsWith(n),cA=n=>(n=n.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(n)),dA=n=>(n=n.toLowerCase(),e=>e.toLowerCase().endsWith(n)),pA=/^\*+\.\*+$/,uA=n=>!n.startsWith(".")&&n.includes("."),mA=n=>n!=="."&&n!==".."&&n.includes("."),hA=/^\.\*+$/,gA=n=>n!=="."&&n!==".."&&n.startsWith("."),fA=/^\*+$/,SA=n=>n.length!==0&&!n.startsWith("."),yA=n=>n.length!==0&&n!=="."&&n!=="..",bA=/^\?+([^+@!?\*\[\(]*)?$/,wA=([n,e=""])=>{let t=Wf([n]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},vA=([n,e=""])=>{let t=Gf([n]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},xA=([n,e=""])=>{let t=Gf([n]);return e?r=>t(r)&&r.endsWith(e):t},TA=([n,e=""])=>{let t=Wf([n]);return e?r=>t(r)&&r.endsWith(e):t},Wf=([n])=>{let e=n.length;return t=>t.length===e&&!t.startsWith(".")},Gf=([n])=>{let e=n.length;return t=>t.length===e&&t!=="."&&t!==".."},Vf=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",jf={win32:{sep:"\\"},posix:{sep:"/"}},EA=Vf==="win32"?jf.win32.sep:jf.posix.sep;yt.sep=EA;var it=Symbol("globstar **");yt.GLOBSTAR=it;var CA="[^/]",RA=CA+"*?",AA="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",IA="(?:(?!(?:\\/|^)\\.).)*?",PA=(n,e={})=>t=>yt(t,n,e);yt.filter=PA;var Qt=(n,e={})=>Object.assign({},n,e),LA=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return yt;let e=yt;return Object.assign((r,o,i={})=>e(r,o,Qt(n,i)),{Minimatch:class extends e.Minimatch{constructor(o,i={}){super(o,Qt(n,i))}static defaults(o){return e.defaults(Qt(n,o)).Minimatch}},AST:class extends e.AST{constructor(o,i,s={}){super(o,i,Qt(n,s))}static fromGlob(o,i={}){return e.AST.fromGlob(o,Qt(n,i))}},unescape:(r,o={})=>e.unescape(r,Qt(n,o)),escape:(r,o={})=>e.escape(r,Qt(n,o)),filter:(r,o={})=>e.filter(r,Qt(n,o)),defaults:r=>e.defaults(Qt(n,r)),makeRe:(r,o={})=>e.makeRe(r,Qt(n,o)),braceExpand:(r,o={})=>e.braceExpand(r,Qt(n,o)),match:(r,o,i={})=>e.match(r,o,Qt(n,i)),sep:e.sep,GLOBSTAR:it})};yt.defaults=LA;var qf=(n,e={})=>(ts(n),e.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:(0,$f.default)(n));yt.braceExpand=qf;var OA=(n,e={})=>new zt(n,e).makeRe();yt.makeRe=OA;var kA=(n,e,t={})=>{let r=new zt(e,t);return n=n.filter(o=>r.match(o)),r.options.nonull&&!n.length&&n.push(e),n};yt.match=kA;var Hf=/[?*]|[+@!]\(.*?\)|\[|\]/,NA=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),zt=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){ts(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||Vf,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let o=this.globParts.map((i,s,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=i[0]===""&&i[1]===""&&(i[2]==="?"||!Hf.test(i[2]))&&!Hf.test(i[3]),c=/^[a-z]:/i.test(i[0]);if(l)return[...i.slice(0,4),...i.slice(4).map(p=>this.parse(p))];if(c)return[i[0],...i.slice(1).map(p=>this.parse(p))]}return i.map(l=>this.parse(l))});if(this.debug(this.pattern,o),this.set=o.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let s=this.set[i];s[0]===""&&s[1]===""&&this.globParts[i][2]==="?"&&typeof s[3]=="string"&&/^[a-z]:$/i.test(s[3])&&(s[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let r=0;r<e.length;r++)for(let o=0;o<e[r].length;o++)e[r][o]==="**"&&(e[r][o]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let r=-1;for(;(r=t.indexOf("**",r+1))!==-1;){let o=r;for(;t[o+1]==="**";)o++;o!==r&&t.splice(r,o-r)}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((r,o)=>{let i=r[r.length-1];return o==="**"&&i==="**"?r:o===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(r.pop(),r):(r.push(o),r)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let o=1;o<e.length-1;o++){let i=e[o];o===1&&i===""&&e[0]===""||(i==="."||i==="")&&(t=!0,e.splice(o,1),o--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=!0,e.pop())}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let o=e[r-1];o&&o!=="."&&o!==".."&&o!=="**"&&(t=!0,e.splice(r-1,2),r-=2)}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let r of e){let o=-1;for(;(o=r.indexOf("**",o+1))!==-1;){let s=o;for(;r[s+1]==="**";)s++;s>o&&r.splice(o+1,s-o);let a=r[o+1],l=r[o+2],c=r[o+3];if(a!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;t=!0,r.splice(o,1);let p=r.slice(0);p[o]="**",e.push(p),o--}if(!this.preserveMultipleSlashes){for(let s=1;s<r.length-1;s++){let a=r[s];s===1&&a===""&&r[0]===""||(a==="."||a==="")&&(t=!0,r.splice(s,1),s--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(t=!0,r.pop())}let i=0;for(;(i=r.indexOf("..",i+1))!==-1;){let s=r[i-1];if(s&&s!=="."&&s!==".."&&s!=="**"){t=!0;let l=i===1&&r[i+1]==="**"?["."]:[];r.splice(i-1,2,...l),r.length===0&&r.push(""),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let r=t+1;r<e.length;r++){let o=this.partsMatch(e[t],e[r],!this.preserveMultipleSlashes);if(o){e[t]=[],e[r]=o;break}}return e.filter(t=>t.length)}partsMatch(e,t,r=!1){let o=0,i=0,s=[],a="";for(;o<e.length&&i<t.length;)if(e[o]===t[i])s.push(a==="b"?t[i]:e[o]),o++,i++;else if(r&&e[o]==="**"&&t[i]===e[o+1])s.push(e[o]),o++;else if(r&&t[i]==="**"&&e[o]===t[i+1])s.push(t[i]),i++;else if(e[o]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(a==="b")return!1;a="a",s.push(e[o]),o++,i++}else if(t[i]==="*"&&e[o]&&(this.options.dot||!e[o].startsWith("."))&&e[o]!=="**"){if(a==="a")return!1;a="b",s.push(t[i]),o++,i++}else return!1;return e.length===t.length&&s}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,r=0;for(let o=0;o<e.length&&e.charAt(o)==="!";o++)t=!t,r++;r&&(this.pattern=e.slice(r)),this.negate=t}matchOne(e,t,r=!1){let o=this.options;if(this.isWindows){let g=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),f=!g&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),S=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),x=!S&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),v=f?3:g?0:void 0,b=x?3:S?0:void 0;if(typeof v=="number"&&typeof b=="number"){let[E,C]=[e[v],t[b]];E.toLowerCase()===C.toLowerCase()&&(t[b]=E,b>v?t=t.slice(b):v>b&&(e=e.slice(v)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var s=0,a=0,l=e.length,c=t.length;s<l&&a<c;s++,a++){this.debug("matchOne loop");var p=t[a],d=e[s];if(this.debug(t,p,d),p===!1)return!1;if(p===it){this.debug("GLOBSTAR",[t,p,d]);var u=s,m=a+1;if(m===c){for(this.debug("** at the end");s<l;s++)if(e[s]==="."||e[s]===".."||!o.dot&&e[s].charAt(0)===".")return!1;return!0}for(;u<l;){var h=e[u];if(this.debug(`
|
|
43
|
-
globstar while`,e,
|
|
44
|
-
>>> no match, partial?`,e,u,t,m),u===l))}let g;if(typeof p=="string"?(g=d===p,this.debug("string match",p,d,g)):(g=p.test(d),this.debug("pattern match",p,d,g)),!g)return!1}if(s===l&&a===c)return!0;if(s===l)return r;if(a===c)return s===l-1&&e[s]==="";throw new Error("wtf?")}braceExpand(){return qf(this.pattern,this.options)}parse(e){ts(e);let t=this.options;if(e==="**")return it;if(e==="")return"";let r,o=null;(r=e.match(fA))?o=t.dot?yA:SA:(r=e.match(sA))?o=(t.nocase?t.dot?dA:cA:t.dot?lA:aA)(r[1]):(r=e.match(bA))?o=(t.nocase?t.dot?vA:wA:t.dot?xA:TA)(r):(r=e.match(pA))?o=t.dot?mA:uA:(r=e.match(hA))&&(o=gA);let i=Ao.fromGlob(e,this.options).toMMPattern();return o&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:o}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,r=t.noglobstar?RA:t.dot?AA:IA,o=new Set(t.nocase?["i"]:[]),i=e.map(l=>{let c=l.map(p=>{if(p instanceof RegExp)for(let d of p.flags.split(""))o.add(d);return typeof p=="string"?NA(p):p===it?it:p._src});return c.forEach((p,d)=>{let u=c[d+1],m=c[d-1];p!==it||m===it||(m===void 0?u!==void 0&&u!==it?c[d+1]="(?:\\/|"+r+"\\/)?"+u:c[d]=r:u===void 0?c[d-1]=m+"(?:\\/|"+r+")?":u!==it&&(c[d-1]=m+"(?:\\/|\\/"+r+"\\/)"+u,c[d+1]=it))}),c.filter(p=>p!==it).join("/")}).join("|"),[s,a]=e.length>1?["(?:",")"]:["",""];i="^"+s+i+a+"$",this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...o].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&t)return!0;let r=this.options;this.isWindows&&(e=e.split("\\").join("/"));let o=this.slashSplit(e);this.debug(this.pattern,"split",o);let i=this.set;this.debug(this.pattern,"set",i);let s=o[o.length-1];if(!s)for(let a=o.length-2;!s&&a>=0;a--)s=o[a];for(let a=0;a<i.length;a++){let l=i[a],c=o;if(r.matchBase&&l.length===1&&(c=[s]),this.matchOne(c,l,t))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return yt.defaults(e).Minimatch}};yt.AST=Ao;yt.Minimatch=zt;yt.escape=Io;yt.unescape=cn;import{fileURLToPath as pI}from"node:url";var Po=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Yf=new Set,xd=typeof process=="object"&&process?process:{},Jf=(n,e,t,r)=>{typeof xd.emitWarning=="function"?xd.emitWarning(n,e,t,r):console.error(`[${t}] ${e}: ${n}`)},Na=globalThis.AbortController,Kf=globalThis.AbortSignal;if(typeof Na>"u"){Kf=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},Na=class{constructor(){e()}signal=new Kf;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let o of this.signal._onabort)o(r);this.signal.onabort?.(r)}}};let n=xd.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{n&&(n=!1,Jf("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var _A=n=>!Yf.has(n),xq=Symbol("type"),tr=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),Xf=n=>tr(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?Lo:null:null,Lo=class extends Array{constructor(e){super(e),this.fill(0)}},Td=class n{heap;length;static#e=!1;static create(e){let t=Xf(e);if(!t)return[];n.#e=!0;let r=new n(e,t);return n.#e=!1,r}constructor(e,t){if(!n.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},rs=class n{#e;#t;#i;#r;#s;#w;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#p;#a;#l;#o;#f;#S;#m;#u;#T;#g;#E;#C;#b;#v;#x;#h;static unsafeExposeInternals(e){return{starts:e.#C,ttls:e.#b,sizes:e.#E,keyMap:e.#a,keyList:e.#l,valList:e.#o,next:e.#f,prev:e.#S,get head(){return e.#m},get tail(){return e.#u},free:e.#T,isBackgroundFetch:t=>e.#d(t),backgroundFetch:(t,r,o,i)=>e.#U(t,r,o,i),moveToTail:t=>e.#z(t),indexes:t=>e.#A(t),rindexes:t=>e.#I(t),isStale:t=>e.#y(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#p}get size(){return this.#c}get fetchMethod(){return this.#s}get memoMethod(){return this.#w}get dispose(){return this.#i}get disposeAfter(){return this.#r}constructor(e){let{max:t=0,ttl:r,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:l,dispose:c,disposeAfter:p,noDisposeOnSet:d,noUpdateTTL:u,maxSize:m=0,maxEntrySize:h=0,sizeCalculation:g,fetchMethod:f,memoMethod:S,noDeleteOnFetchRejection:x,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:b,allowStaleOnFetchAbort:E,ignoreFetchAbort:C}=e;if(t!==0&&!tr(t))throw new TypeError("max option must be a nonnegative integer");let I=t?Xf(t):Array;if(!I)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=m,this.maxEntrySize=h||this.#t,this.sizeCalculation=g,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(S!==void 0&&typeof S!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=S,f!==void 0&&typeof f!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#s=f,this.#x=!!f,this.#a=new Map,this.#l=new Array(t).fill(void 0),this.#o=new Array(t).fill(void 0),this.#f=new I(t),this.#S=new I(t),this.#m=0,this.#u=0,this.#T=Td.create(t),this.#c=0,this.#p=0,typeof c=="function"&&(this.#i=c),typeof p=="function"?(this.#r=p,this.#g=[]):(this.#r=void 0,this.#g=void 0),this.#v=!!this.#i,this.#h=!!this.#r,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!x,this.allowStaleOnFetchRejection=!!b,this.allowStaleOnFetchAbort=!!E,this.ignoreFetchAbort=!!C,this.maxEntrySize!==0){if(this.#t!==0&&!tr(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!tr(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#L()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!v,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=tr(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=r||0,this.ttl){if(!tr(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#t){let _="LRU_CACHE_UNBOUNDED";_A(_)&&(Yf.add(_),Jf("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",_,n))}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#P(){let e=new Lo(this.#e),t=new Lo(this.#e);this.#b=e,this.#C=t,this.#k=(i,s,a=Po.now())=>{if(t[i]=s!==0?a:0,e[i]=s,s!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#y(i)&&this.#O(this.#l[i],"expire")},s+1);l.unref&&l.unref()}},this.#R=i=>{t[i]=e[i]!==0?Po.now():0},this.#n=(i,s)=>{if(e[s]){let a=e[s],l=t[s];if(!a||!l)return;i.ttl=a,i.start=l,i.now=r||o();let c=i.now-l;i.remainingTTL=a-c}};let r=0,o=()=>{let i=Po.now();if(this.ttlResolution>0){r=i;let s=setTimeout(()=>r=0,this.ttlResolution);s.unref&&s.unref()}return i};this.getRemainingTTL=i=>{let s=this.#a.get(i);if(s===void 0)return 0;let a=e[s],l=t[s];if(!a||!l)return 1/0;let c=(r||o())-l;return a-c},this.#y=i=>{let s=t[i],a=e[i];return!!a&&!!s&&(r||o())-s>a}}#R=()=>{};#n=()=>{};#k=()=>{};#y=()=>!1;#L(){let e=new Lo(this.#e);this.#p=0,this.#E=e,this.#N=t=>{this.#p-=e[t],e[t]=0},this.#M=(t,r,o,i)=>{if(this.#d(r))return 0;if(!tr(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(r,t),!tr(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#_=(t,r,o)=>{if(e[t]=r,this.#t){let i=this.#t-e[t];for(;this.#p>i;)this.#D(!0)}this.#p+=e[t],o&&(o.entrySize=r,o.totalCalculatedSize=this.#p)}}#N=e=>{};#_=(e,t,r)=>{};#M=(e,t,r,o)=>{if(r||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#u;!(!this.#F(t)||((e||!this.#y(t))&&(yield t),t===this.#m));)t=this.#S[t]}*#I({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#F(t)||((e||!this.#y(t))&&(yield t),t===this.#u));)t=this.#f[t]}#F(e){return e!==void 0&&this.#a.get(this.#l[e])===e}*entries(){for(let e of this.#A())this.#o[e]!==void 0&&this.#l[e]!==void 0&&!this.#d(this.#o[e])&&(yield[this.#l[e],this.#o[e]])}*rentries(){for(let e of this.#I())this.#o[e]!==void 0&&this.#l[e]!==void 0&&!this.#d(this.#o[e])&&(yield[this.#l[e],this.#o[e]])}*keys(){for(let e of this.#A()){let t=this.#l[e];t!==void 0&&!this.#d(this.#o[e])&&(yield t)}}*rkeys(){for(let e of this.#I()){let t=this.#l[e];t!==void 0&&!this.#d(this.#o[e])&&(yield t)}}*values(){for(let e of this.#A())this.#o[e]!==void 0&&!this.#d(this.#o[e])&&(yield this.#o[e])}*rvalues(){for(let e of this.#I())this.#o[e]!==void 0&&!this.#d(this.#o[e])&&(yield this.#o[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let r of this.#A()){let o=this.#o[r],i=this.#d(o)?o.__staleWhileFetching:o;if(i!==void 0&&e(i,this.#l[r],this))return this.get(this.#l[r],t)}}forEach(e,t=this){for(let r of this.#A()){let o=this.#o[r],i=this.#d(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#l[r],this)}}rforEach(e,t=this){for(let r of this.#I()){let o=this.#o[r],i=this.#d(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#l[r],this)}}purgeStale(){let e=!1;for(let t of this.#I({allowStale:!0}))this.#y(t)&&(this.#O(this.#l[t],"expire"),e=!0);return e}info(e){let t=this.#a.get(e);if(t===void 0)return;let r=this.#o[t],o=this.#d(r)?r.__staleWhileFetching:r;if(o===void 0)return;let i={value:o};if(this.#b&&this.#C){let s=this.#b[t],a=this.#C[t];if(s&&a){let l=s-(Po.now()-a);i.ttl=l,i.start=Date.now()}}return this.#E&&(i.size=this.#E[t]),i}dump(){let e=[];for(let t of this.#A({allowStale:!0})){let r=this.#l[t],o=this.#o[t],i=this.#d(o)?o.__staleWhileFetching:o;if(i===void 0||r===void 0)continue;let s={value:i};if(this.#b&&this.#C){s.ttl=this.#b[t];let a=Po.now()-this.#C[t];s.start=Math.floor(Date.now()-a)}this.#E&&(s.size=this.#E[t]),e.unshift([r,s])}return e}load(e){this.clear();for(let[t,r]of e){if(r.start){let o=Date.now()-r.start;r.start=Po.now()-o}this.set(t,r.value,r)}}set(e,t,r={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=r,{noUpdateTTL:c=this.noUpdateTTL}=r,p=this.#M(e,t,r.size||0,a);if(this.maxEntrySize&&p>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#O(e,"set"),this;let d=this.#c===0?void 0:this.#a.get(e);if(d===void 0)d=this.#c===0?this.#u:this.#T.length!==0?this.#T.pop():this.#c===this.#e?this.#D(!1):this.#c,this.#l[d]=e,this.#o[d]=t,this.#a.set(e,d),this.#f[this.#u]=d,this.#S[d]=this.#u,this.#u=d,this.#c++,this.#_(d,p,l),l&&(l.set="add"),c=!1;else{this.#z(d);let u=this.#o[d];if(t!==u){if(this.#x&&this.#d(u)){u.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:m}=u;m!==void 0&&!s&&(this.#v&&this.#i?.(m,e,"set"),this.#h&&this.#g?.push([m,e,"set"]))}else s||(this.#v&&this.#i?.(u,e,"set"),this.#h&&this.#g?.push([u,e,"set"]));if(this.#N(d),this.#_(d,p,l),this.#o[d]=t,l){l.set="replace";let m=u&&this.#d(u)?u.__staleWhileFetching:u;m!==void 0&&(l.oldValue=m)}}else l&&(l.set="update")}if(o!==0&&!this.#b&&this.#P(),this.#b&&(c||this.#k(d,o,i),l&&this.#n(l,d)),!s&&this.#h&&this.#g){let u=this.#g,m;for(;m=u?.shift();)this.#r?.(...m)}return this}pop(){try{for(;this.#c;){let e=this.#o[this.#m];if(this.#D(!0),this.#d(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#h&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}}#D(e){let t=this.#m,r=this.#l[t],o=this.#o[t];return this.#x&&this.#d(o)?o.__abortController.abort(new Error("evicted")):(this.#v||this.#h)&&(this.#v&&this.#i?.(o,r,"evict"),this.#h&&this.#g?.push([o,r,"evict"])),this.#N(t),e&&(this.#l[t]=void 0,this.#o[t]=void 0,this.#T.push(t)),this.#c===1?(this.#m=this.#u=0,this.#T.length=0):this.#m=this.#f[t],this.#a.delete(r),this.#c--,t}has(e,t={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=t,i=this.#a.get(e);if(i!==void 0){let s=this.#o[i];if(this.#d(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#y(i))o&&(o.has="stale",this.#n(o,i));else return r&&this.#R(i),o&&(o.has="hit",this.#n(o,i)),!0}else o&&(o.has="miss");return!1}peek(e,t={}){let{allowStale:r=this.allowStale}=t,o=this.#a.get(e);if(o===void 0||!r&&this.#y(o))return;let i=this.#o[o];return this.#d(i)?i.__staleWhileFetching:i}#U(e,t,r,o){let i=t===void 0?void 0:this.#o[t];if(this.#d(i))return i;let s=new Na,{signal:a}=r;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let l={signal:s.signal,options:r,context:o},c=(g,f=!1)=>{let{aborted:S}=s.signal,x=r.ignoreFetchAbort&&g!==void 0;if(r.status&&(S&&!f?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,x&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),S&&!x&&!f)return d(s.signal.reason);let v=m;return this.#o[t]===m&&(g===void 0?v.__staleWhileFetching?this.#o[t]=v.__staleWhileFetching:this.#O(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,g,l.options))),g},p=g=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=g),d(g)),d=g=>{let{aborted:f}=s.signal,S=f&&r.allowStaleOnFetchAbort,x=S||r.allowStaleOnFetchRejection,v=x||r.noDeleteOnFetchRejection,b=m;if(this.#o[t]===m&&(!v||b.__staleWhileFetching===void 0?this.#O(e,"fetch"):S||(this.#o[t]=b.__staleWhileFetching)),x)return r.status&&b.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),b.__staleWhileFetching;if(b.__returned===b)throw g},u=(g,f)=>{let S=this.#s?.(e,i,l);S&&S instanceof Promise&&S.then(x=>g(x===void 0?void 0:x),f),s.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(g(void 0),r.allowStaleOnFetchAbort&&(g=x=>c(x,!0)))})};r.status&&(r.status.fetchDispatched=!0);let m=new Promise(u).then(c,p),h=Object.assign(m,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,h,{...l.options,status:void 0}),t=this.#a.get(e)):this.#o[t]=h,h}#d(e){if(!this.#x)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof Na}async fetch(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:p=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:u=this.allowStaleOnFetchRejection,ignoreFetchAbort:m=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:g,forceRefresh:f=!1,status:S,signal:x}=t;if(!this.#x)return S&&(S.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:S});let v={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:p,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:h,ignoreFetchAbort:m,status:S,signal:x},b=this.#a.get(e);if(b===void 0){S&&(S.fetch="miss");let E=this.#U(e,b,v,g);return E.__returned=E}else{let E=this.#o[b];if(this.#d(E)){let z=r&&E.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",z&&(S.returnedStale=!0)),z?E.__staleWhileFetching:E.__returned=E}let C=this.#y(b);if(!f&&!C)return S&&(S.fetch="hit"),this.#z(b),o&&this.#R(b),S&&this.#n(S,b),E;let I=this.#U(e,b,v,g),L=I.__staleWhileFetching!==void 0&&r;return S&&(S.fetch=C?"stale":"refresh",L&&C&&(S.returnedStale=!0)),L?I.__staleWhileFetching:I.__returned=I}}async forceFetch(e,t={}){let r=await this.fetch(e,t);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,t={}){let r=this.#w;if(!r)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:i,...s}=t,a=this.get(e,s);if(!i&&a!==void 0)return a;let l=r(e,a,{options:s,context:o});return this.set(e,l,s),l}get(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=t,a=this.#a.get(e);if(a!==void 0){let l=this.#o[a],c=this.#d(l);return s&&this.#n(s,a),this.#y(a)?(s&&(s.get="stale"),c?(s&&r&&l.__staleWhileFetching!==void 0&&(s.returnedStale=!0),r?l.__staleWhileFetching:void 0):(i||this.#O(e,"expire"),s&&r&&(s.returnedStale=!0),r?l:void 0)):(s&&(s.get="hit"),c?l.__staleWhileFetching:(this.#z(a),o&&this.#R(a),l))}else s&&(s.get="miss")}#B(e,t){this.#S[t]=e,this.#f[e]=t}#z(e){e!==this.#u&&(e===this.#m?this.#m=this.#f[e]:this.#B(this.#S[e],this.#f[e]),this.#B(this.#u,e),this.#u=e)}delete(e){return this.#O(e,"delete")}#O(e,t){let r=!1;if(this.#c!==0){let o=this.#a.get(e);if(o!==void 0)if(r=!0,this.#c===1)this.#j(t);else{this.#N(o);let i=this.#o[o];if(this.#d(i)?i.__abortController.abort(new Error("deleted")):(this.#v||this.#h)&&(this.#v&&this.#i?.(i,e,t),this.#h&&this.#g?.push([i,e,t])),this.#a.delete(e),this.#l[o]=void 0,this.#o[o]=void 0,o===this.#u)this.#u=this.#S[o];else if(o===this.#m)this.#m=this.#f[o];else{let s=this.#S[o];this.#f[s]=this.#f[o];let a=this.#f[o];this.#S[a]=this.#S[o]}this.#c--,this.#T.push(o)}}if(this.#h&&this.#g?.length){let o=this.#g,i;for(;i=o?.shift();)this.#r?.(...i)}return r}clear(){return this.#j("delete")}#j(e){for(let t of this.#I({allowStale:!0})){let r=this.#o[t];if(this.#d(r))r.__abortController.abort(new Error("deleted"));else{let o=this.#l[t];this.#v&&this.#i?.(r,o,e),this.#h&&this.#g?.push([r,o,e])}}if(this.#a.clear(),this.#o.fill(void 0),this.#l.fill(void 0),this.#b&&this.#C&&(this.#b.fill(0),this.#C.fill(0)),this.#E&&this.#E.fill(0),this.#m=0,this.#u=0,this.#T.length=0,this.#p=0,this.#c=0,this.#h&&this.#g){let t=this.#g,r;for(;r=t?.shift();)this.#r?.(...r)}}};import{posix as GA,win32 as Nd}from"node:path";import{fileURLToPath as VA}from"node:url";import{lstatSync as qA,readdir as KA,readdirSync as YA,readlinkSync as JA,realpathSync as XA}from"fs";import*as ZA from"node:fs";import{lstat as eI,readdir as tI,readlink as nI,realpath as rI}from"node:fs/promises";import{EventEmitter as Ld}from"node:events";import nS from"node:stream";import{StringDecoder as MA}from"node:string_decoder";var Zf=typeof process=="object"&&process?process:{stdout:null,stderr:null},FA=n=>!!n&&typeof n=="object"&&(n instanceof rr||n instanceof nS||DA(n)||UA(n)),DA=n=>!!n&&typeof n=="object"&&n instanceof Ld&&typeof n.pipe=="function"&&n.pipe!==nS.Writable.prototype.pipe,UA=n=>!!n&&typeof n=="object"&&n instanceof Ld&&typeof n.write=="function"&&typeof n.end=="function",Mn=Symbol("EOF"),Fn=Symbol("maybeEmitEnd"),nr=Symbol("emittedEnd"),_a=Symbol("emittingEnd"),os=Symbol("emittedError"),Ma=Symbol("closed"),Qf=Symbol("read"),Fa=Symbol("flush"),eS=Symbol("flushChunk"),dn=Symbol("encoding"),Oo=Symbol("decoder"),Qe=Symbol("flowing"),is=Symbol("paused"),ko=Symbol("resume"),et=Symbol("buffer"),bt=Symbol("pipes"),tt=Symbol("bufferLength"),Ed=Symbol("bufferPush"),Da=Symbol("bufferShift"),mt=Symbol("objectMode"),Fe=Symbol("destroyed"),Cd=Symbol("error"),Rd=Symbol("emitData"),tS=Symbol("emitEnd"),Ad=Symbol("emitEnd2"),xn=Symbol("async"),Id=Symbol("abort"),Ua=Symbol("aborted"),ss=Symbol("signal"),$r=Symbol("dataListeners"),jt=Symbol("discarded"),as=n=>Promise.resolve().then(n),BA=n=>n(),zA=n=>n==="end"||n==="finish"||n==="prefinish",jA=n=>n instanceof ArrayBuffer||!!n&&typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,HA=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),Ba=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[ko](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Pd=class extends Ba{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,r){super(e,t,r),this.proxyErrors=o=>t.emit("error",o),e.on("error",this.proxyErrors)}},$A=n=>!!n.objectMode,WA=n=>!n.objectMode&&!!n.encoding&&n.encoding!=="buffer",rr=class extends Ld{[Qe]=!1;[is]=!1;[bt]=[];[et]=[];[mt];[dn];[xn];[Oo];[Mn]=!1;[nr]=!1;[_a]=!1;[Ma]=!1;[os]=null;[tt]=0;[Fe]=!1;[ss];[Ua]=!1;[$r]=0;[jt]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");$A(t)?(this[mt]=!0,this[dn]=null):WA(t)?(this[dn]=t.encoding,this[mt]=!1):(this[mt]=!1,this[dn]=null),this[xn]=!!t.async,this[Oo]=this[dn]?new MA(this[dn]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[et]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[bt]});let{signal:r}=t;r&&(this[ss]=r,r.aborted?this[Id]():r.addEventListener("abort",()=>this[Id]()))}get bufferLength(){return this[tt]}get encoding(){return this[dn]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[mt]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[xn]}set async(e){this[xn]=this[xn]||!!e}[Id](){this[Ua]=!0,this.emit("abort",this[ss]?.reason),this.destroy(this[ss]?.reason)}get aborted(){return this[Ua]}set aborted(e){}write(e,t,r){if(this[Ua])return!1;if(this[Mn])throw new Error("write after end");if(this[Fe])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(r=t,t="utf8"),t||(t="utf8");let o=this[xn]?as:BA;if(!this[mt]&&!Buffer.isBuffer(e)){if(HA(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(jA(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[mt]?(this[Qe]&&this[tt]!==0&&this[Fa](!0),this[Qe]?this.emit("data",e):this[Ed](e),this[tt]!==0&&this.emit("readable"),r&&o(r),this[Qe]):e.length?(typeof e=="string"&&!(t===this[dn]&&!this[Oo]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[dn]&&(e=this[Oo].write(e)),this[Qe]&&this[tt]!==0&&this[Fa](!0),this[Qe]?this.emit("data",e):this[Ed](e),this[tt]!==0&&this.emit("readable"),r&&o(r),this[Qe]):(this[tt]!==0&&this.emit("readable"),r&&o(r),this[Qe])}read(e){if(this[Fe])return null;if(this[jt]=!1,this[tt]===0||e===0||e&&e>this[tt])return this[Fn](),null;this[mt]&&(e=null),this[et].length>1&&!this[mt]&&(this[et]=[this[dn]?this[et].join(""):Buffer.concat(this[et],this[tt])]);let t=this[Qf](e||null,this[et][0]);return this[Fn](),t}[Qf](e,t){if(this[mt])this[Da]();else{let r=t;e===r.length||e===null?this[Da]():typeof r=="string"?(this[et][0]=r.slice(e),t=r.slice(0,e),this[tt]-=e):(this[et][0]=r.subarray(e),t=r.subarray(0,e),this[tt]-=e)}return this.emit("data",t),!this[et].length&&!this[Mn]&&this.emit("drain"),t}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t="utf8"),e!==void 0&&this.write(e,t),r&&this.once("end",r),this[Mn]=!0,this.writable=!1,(this[Qe]||!this[is])&&this[Fn](),this}[ko](){this[Fe]||(!this[$r]&&!this[bt].length&&(this[jt]=!0),this[is]=!1,this[Qe]=!0,this.emit("resume"),this[et].length?this[Fa]():this[Mn]?this[Fn]():this.emit("drain"))}resume(){return this[ko]()}pause(){this[Qe]=!1,this[is]=!0,this[jt]=!1}get destroyed(){return this[Fe]}get flowing(){return this[Qe]}get paused(){return this[is]}[Ed](e){this[mt]?this[tt]+=1:this[tt]+=e.length,this[et].push(e)}[Da](){return this[mt]?this[tt]-=1:this[tt]-=this[et][0].length,this[et].shift()}[Fa](e=!1){do;while(this[eS](this[Da]())&&this[et].length);!e&&!this[et].length&&!this[Mn]&&this.emit("drain")}[eS](e){return this.emit("data",e),this[Qe]}pipe(e,t){if(this[Fe])return e;this[jt]=!1;let r=this[nr];return t=t||{},e===Zf.stdout||e===Zf.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[bt].push(t.proxyErrors?new Pd(this,e,t):new Ba(this,e,t)),this[xn]?as(()=>this[ko]()):this[ko]()),e}unpipe(e){let t=this[bt].find(r=>r.dest===e);t&&(this[bt].length===1?(this[Qe]&&this[$r]===0&&(this[Qe]=!1),this[bt]=[]):this[bt].splice(this[bt].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let r=super.on(e,t);if(e==="data")this[jt]=!1,this[$r]++,!this[bt].length&&!this[Qe]&&this[ko]();else if(e==="readable"&&this[tt]!==0)super.emit("readable");else if(zA(e)&&this[nr])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[os]){let o=t;this[xn]?as(()=>o.call(this,this[os])):o.call(this,this[os])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[$r]=this.listeners("data").length,this[$r]===0&&!this[jt]&&!this[bt].length&&(this[Qe]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[$r]=0,!this[jt]&&!this[bt].length&&(this[Qe]=!1)),t}get emittedEnd(){return this[nr]}[Fn](){!this[_a]&&!this[nr]&&!this[Fe]&&this[et].length===0&&this[Mn]&&(this[_a]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ma]&&this.emit("close"),this[_a]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==Fe&&this[Fe])return!1;if(e==="data")return!this[mt]&&!r?!1:this[xn]?(as(()=>this[Rd](r)),!0):this[Rd](r);if(e==="end")return this[tS]();if(e==="close"){if(this[Ma]=!0,!this[nr]&&!this[Fe])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[os]=r,super.emit(Cd,r);let i=!this[ss]||this.listeners("error").length?super.emit("error",r):!1;return this[Fn](),i}else if(e==="resume"){let i=super.emit("resume");return this[Fn](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let o=super.emit(e,...t);return this[Fn](),o}[Rd](e){for(let r of this[bt])r.dest.write(e)===!1&&this.pause();let t=this[jt]?!1:super.emit("data",e);return this[Fn](),t}[tS](){return this[nr]?!1:(this[nr]=!0,this.readable=!1,this[xn]?(as(()=>this[Ad]()),!0):this[Ad]())}[Ad](){if(this[Oo]){let t=this[Oo].end();if(t){for(let r of this[bt])r.dest.write(t);this[jt]||super.emit("data",t)}}for(let t of this[bt])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[mt]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[mt]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[mt])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[dn]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(Fe,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[jt]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();let o=this.read();if(o!==null)return Promise.resolve({done:!1,value:o});if(this[Mn])return t();let i,s,a=d=>{this.off("data",l),this.off("end",c),this.off(Fe,p),t(),s(d)},l=d=>{this.off("error",a),this.off("end",c),this.off(Fe,p),this.pause(),i({value:d,done:!!this[Mn]})},c=()=>{this.off("error",a),this.off("data",l),this.off(Fe,p),t(),i({done:!0,value:void 0})},p=()=>a(new Error("stream destroyed"));return new Promise((d,u)=>{s=u,i=d,this.once(Fe,p),this.once("error",a),this.once("end",c),this.once("data",l)})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[jt]=!1;let e=!1,t=()=>(this.pause(),this.off(Cd,t),this.off(Fe,t),this.off("end",t),e=!0,{done:!0,value:void 0}),r=()=>{if(e)return t();let o=this.read();return o===null?t():{done:!1,value:o}};return this.once("end",t),this.once(Cd,t),this.once(Fe,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[Fe])return e?this.emit("error",e):this.emit(Fe),this;this[Fe]=!0,this[jt]=!0,this[et].length=0,this[tt]=0;let t=this;return typeof t.close=="function"&&!this[Ma]&&t.close(),e?this.emit("error",e):this.emit(Fe),this}static get isStream(){return FA}};var QA=XA.native,cs={lstatSync:qA,readdir:KA,readdirSync:YA,readlinkSync:JA,realpathSync:QA,promises:{lstat:eI,readdir:tI,readlink:nI,realpath:rI}},aS=n=>!n||n===cs||n===ZA?cs:{...cs,...n,promises:{...cs.promises,...n.promises||{}}},lS=/^\\\\\?\\([a-z]:)\\?$/i,oI=n=>n.replace(/\//g,"\\").replace(lS,"$1\\"),iI=/[\\\/]/,tn=0,cS=1,dS=2,Tn=4,pS=6,uS=8,Wr=10,mS=12,en=15,ls=~en,Od=16,rS=32,ds=64,pn=128,za=256,Ha=512,oS=ds|pn|Ha,sI=1023,kd=n=>n.isFile()?uS:n.isDirectory()?Tn:n.isSymbolicLink()?Wr:n.isCharacterDevice()?dS:n.isBlockDevice()?pS:n.isSocket()?mS:n.isFIFO()?cS:tn,iS=new Map,ps=n=>{let e=iS.get(n);if(e)return e;let t=n.normalize("NFKD");return iS.set(n,t),t},sS=new Map,ja=n=>{let e=sS.get(n);if(e)return e;let t=ps(n.toLowerCase());return sS.set(n,t),t},$a=class extends rs{constructor(){super({max:256})}},_d=class extends rs{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},hS=Symbol("PathScurry setAsCwd"),ht=class{name;root;roots;parent;nocase;isCWD=!1;#e;#t;get dev(){return this.#t}#i;get mode(){return this.#i}#r;get nlink(){return this.#r}#s;get uid(){return this.#s}#w;get gid(){return this.#w}#c;get rdev(){return this.#c}#p;get blksize(){return this.#p}#a;get ino(){return this.#a}#l;get size(){return this.#l}#o;get blocks(){return this.#o}#f;get atimeMs(){return this.#f}#S;get mtimeMs(){return this.#S}#m;get ctimeMs(){return this.#m}#u;get birthtimeMs(){return this.#u}#T;get atime(){return this.#T}#g;get mtime(){return this.#g}#E;get ctime(){return this.#E}#C;get birthtime(){return this.#C}#b;#v;#x;#h;#P;#R;#n;#k;#y;#L;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=tn,r,o,i,s,a){this.name=e,this.#b=i?ja(e):ps(e),this.#n=t&sI,this.nocase=i,this.roots=o,this.root=r||this,this.#k=s,this.#x=a.fullpath,this.#P=a.relative,this.#R=a.relativePosix,this.parent=a.parent,this.parent?this.#e=this.parent.#e:this.#e=aS(a.fs)}depth(){return this.#v!==void 0?this.#v:this.parent?this.#v=this.parent.depth()+1:this.#v=0}childrenCache(){return this.#k}resolve(e){if(!e)return this;let t=this.getRootString(e),o=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#N(o):this.#N(o)}#N(e){let t=this;for(let r of e)t=t.child(r);return t}children(){let e=this.#k.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#k.set(this,t),this.#n&=~Od,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),o=this.nocase?ja(e):ps(e);for(let l of r)if(l.#b===o)return l;let i=this.parent?this.sep:"",s=this.#x?this.#x+i+e:void 0,a=this.newChild(e,tn,{...t,parent:this,fullpath:s});return this.canReaddir()||(a.#n|=pn),r.push(a),a}relative(){if(this.isCWD)return"";if(this.#P!==void 0)return this.#P;let e=this.name,t=this.parent;if(!t)return this.#P=this.name;let r=t.relative();return r+(!r||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#R!==void 0)return this.#R;let e=this.name,t=this.parent;if(!t)return this.#R=this.fullpathPosix();let r=t.relativePosix();return r+(!r||!t.parent?"":"/")+e}fullpath(){if(this.#x!==void 0)return this.#x;let e=this.name,t=this.parent;if(!t)return this.#x=this.name;let o=t.fullpath()+(t.parent?this.sep:"")+e;return this.#x=o}fullpathPosix(){if(this.#h!==void 0)return this.#h;if(this.sep==="/")return this.#h=this.fullpath();if(!this.parent){let o=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(o)?this.#h=`//?/${o}`:this.#h=o}let e=this.parent,t=e.fullpathPosix(),r=t+(!t||!e.parent?"":"/")+this.name;return this.#h=r}isUnknown(){return(this.#n&en)===tn}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#n&en)===uS}isDirectory(){return(this.#n&en)===Tn}isCharacterDevice(){return(this.#n&en)===dS}isBlockDevice(){return(this.#n&en)===pS}isFIFO(){return(this.#n&en)===cS}isSocket(){return(this.#n&en)===mS}isSymbolicLink(){return(this.#n&Wr)===Wr}lstatCached(){return this.#n&rS?this:void 0}readlinkCached(){return this.#y}realpathCached(){return this.#L}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#y)return!0;if(!this.parent)return!1;let e=this.#n&en;return!(e!==tn&&e!==Wr||this.#n&za||this.#n&pn)}calledReaddir(){return!!(this.#n&Od)}isENOENT(){return!!(this.#n&pn)}isNamed(e){return this.nocase?this.#b===ja(e):this.#b===ps(e)}async readlink(){let e=this.#y;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#e.promises.readlink(this.fullpath()),r=(await this.parent.realpath())?.resolve(t);if(r)return this.#y=r}catch(t){this.#d(t.code);return}}readlinkSync(){let e=this.#y;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#e.readlinkSync(this.fullpath()),r=this.parent.realpathSync()?.resolve(t);if(r)return this.#y=r}catch(t){this.#d(t.code);return}}#_(e){this.#n|=Od;for(let t=e.provisional;t<e.length;t++){let r=e[t];r&&r.#M()}}#M(){this.#n&pn||(this.#n=(this.#n|pn)&ls,this.#A())}#A(){let e=this.children();e.provisional=0;for(let t of e)t.#M()}#I(){this.#n|=Ha,this.#F()}#F(){if(this.#n&ds)return;let e=this.#n;(e&en)===Tn&&(e&=ls),this.#n=e|ds,this.#A()}#D(e=""){e==="ENOTDIR"||e==="EPERM"?this.#F():e==="ENOENT"?this.#M():this.children().provisional=0}#U(e=""){e==="ENOTDIR"?this.parent.#F():e==="ENOENT"&&this.#M()}#d(e=""){let t=this.#n;t|=za,e==="ENOENT"&&(t|=pn),(e==="EINVAL"||e==="UNKNOWN")&&(t&=ls),this.#n=t,e==="ENOTDIR"&&this.parent&&this.parent.#F()}#B(e,t){return this.#O(e,t)||this.#z(e,t)}#z(e,t){let r=kd(e),o=this.newChild(e.name,r,{parent:this}),i=o.#n&en;return i!==Tn&&i!==Wr&&i!==tn&&(o.#n|=ds),t.unshift(o),t.provisional++,o}#O(e,t){for(let r=t.provisional;r<t.length;r++){let o=t[r];if((this.nocase?ja(e.name):ps(e.name))===o.#b)return this.#j(e,o,r,t)}}#j(e,t,r,o){let i=t.name;return t.#n=t.#n&ls|kd(e),i!==e.name&&(t.name=e.name),r!==o.provisional&&(r===o.length-1?o.pop():o.splice(r,1),o.unshift(t)),o.provisional++,t}async lstat(){if(!(this.#n&pn))try{return this.#G(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#U(e.code)}}lstatSync(){if(!(this.#n&pn))try{return this.#G(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#U(e.code)}}#G(e){let{atime:t,atimeMs:r,birthtime:o,birthtimeMs:i,blksize:s,blocks:a,ctime:l,ctimeMs:c,dev:p,gid:d,ino:u,mode:m,mtime:h,mtimeMs:g,nlink:f,rdev:S,size:x,uid:v}=e;this.#T=t,this.#f=r,this.#C=o,this.#u=i,this.#p=s,this.#o=a,this.#E=l,this.#m=c,this.#t=p,this.#w=d,this.#a=u,this.#i=m,this.#g=h,this.#S=g,this.#r=f,this.#c=S,this.#l=x,this.#s=v;let b=kd(e);this.#n=this.#n&ls|b|rS,b!==tn&&b!==Tn&&b!==Wr&&(this.#n|=ds)}#$=[];#W=!1;#V(e){this.#W=!1;let t=this.#$.slice();this.#$.length=0,t.forEach(r=>r(null,e))}readdirCB(e,t=!1){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let r=this.children();if(this.calledReaddir()){let i=r.slice(0,r.provisional);t?e(null,i):queueMicrotask(()=>e(null,i));return}if(this.#$.push(e),this.#W)return;this.#W=!0;let o=this.fullpath();this.#e.readdir(o,{withFileTypes:!0},(i,s)=>{if(i)this.#D(i.code),r.provisional=0;else{for(let a of s)this.#B(a,r);this.#_(r)}this.#V(r.slice(0,r.provisional))})}#H;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(this.#H)await this.#H;else{let r=()=>{};this.#H=new Promise(o=>r=o);try{for(let o of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#B(o,e);this.#_(e)}catch(o){this.#D(o.code),e.provisional=0}this.#H=void 0,r()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let r of this.#e.readdirSync(t,{withFileTypes:!0}))this.#B(r,e);this.#_(e)}catch(r){this.#D(r.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#n&oS)return!1;let e=en&this.#n;return e===tn||e===Tn||e===Wr}shouldWalk(e,t){return(this.#n&Tn)===Tn&&!(this.#n&oS)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#L)return this.#L;if(!((Ha|za|pn)&this.#n))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#L=this.resolve(e)}catch{this.#I()}}realpathSync(){if(this.#L)return this.#L;if(!((Ha|za|pn)&this.#n))try{let e=this.#e.realpathSync(this.fullpath());return this.#L=this.resolve(e)}catch{this.#I()}}[hS](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),r=[],o=this;for(;o&&o.parent;)t.add(o),o.#P=r.join(this.sep),o.#R=r.join("/"),o=o.parent,r.push("..");for(o=e;o&&o.parent&&!t.has(o);)o.#P=void 0,o.#R=void 0,o=o.parent}},Wa=class n extends ht{sep="\\";splitSep=iI;constructor(e,t=tn,r,o,i,s,a){super(e,t,r,o,i,s,a)}newChild(e,t=tn,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return Nd.parse(e).root}getRoot(e){if(e=oI(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,r]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=r;return this.roots[e]=new No(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(lS,"$1\\"),e===t}},Ga=class n extends ht{splitSep="/";sep="/";constructor(e,t=tn,r,o,i,s,a){super(e,t,r,o,i,s,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=tn,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}},Va=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#r;constructor(e=process.cwd(),t,r,{nocase:o,childrenCacheSize:i=16*1024,fs:s=cs}={}){this.#r=aS(s),(e instanceof URL||e.startsWith("file://"))&&(e=VA(e));let a=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#e=new $a,this.#t=new $a,this.#i=new _d(i);let l=a.substring(this.rootPath.length).split(r);if(l.length===1&&!l[0]&&l.pop(),o===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=o,this.root=this.newRoot(this.#r),this.roots[this.rootPath]=this.root;let c=this.root,p=l.length-1,d=t.sep,u=this.rootPath,m=!1;for(let h of l){let g=p--;c=c.child(h,{relative:new Array(g).fill("..").join(d),relativePosix:new Array(g).fill("..").join("/"),fullpath:u+=(m?"":d)+h}),m=!0}this.cwd=c}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#i}resolve(...e){let t="";for(let i=e.length-1;i>=0;i--){let s=e[i];if(!(!s||s===".")&&(t=t?`${s}/${t}`:s,this.isAbsolute(s)))break}let r=this.#e.get(t);if(r!==void 0)return r;let o=this.cwd.resolve(t).fullpath();return this.#e.set(t,o),o}resolvePosix(...e){let t="";for(let i=e.length-1;i>=0;i--){let s=e[i];if(!(!s||s===".")&&(t=t?`${s}/${t}`:s,this.isAbsolute(s)))break}let r=this.#t.get(t);if(r!==void 0)return r;let o=this.cwd.resolve(t).fullpathPosix();return this.#t.set(t,o),o}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:r}=t;if(e.canReaddir()){let o=await e.readdir();return r?o:o.map(i=>i.name)}else return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:r=!0}=t;return e.canReaddir()?r?e.readdirSync():e.readdirSync().map(o=>o.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e.withFileTypes,e=this.cwd);let r=await e.readlink();return t?r:r?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e.withFileTypes,e=this.cwd);let r=e.readlinkSync();return t?r:r?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e.withFileTypes,e=this.cwd);let r=await e.realpath();return t?r:r?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e.withFileTypes,e=this.cwd);let r=e.realpathSync();return t?r:r?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=[];(!i||i(e))&&a.push(r?e:e.fullpath());let l=new Set,c=(d,u)=>{l.add(d),d.readdirCB((m,h)=>{if(m)return u(m);let g=h.length;if(!g)return u();let f=()=>{--g===0&&u()};for(let S of h)(!i||i(S))&&a.push(r?S:S.fullpath()),o&&S.isSymbolicLink()?S.realpath().then(x=>x?.isUnknown()?x.lstat():x).then(x=>x?.shouldWalk(l,s)?c(x,f):f()):S.shouldWalk(l,s)?c(S,f):f()},!0)},p=e;return new Promise((d,u)=>{c(p,m=>{if(m)return u(m);d(a)})})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=[];(!i||i(e))&&a.push(r?e:e.fullpath());let l=new Set([e]);for(let c of l){let p=c.readdirSync();for(let d of p){(!i||i(d))&&a.push(r?d:d.fullpath());let u=d;if(d.isSymbolicLink()){if(!(o&&(u=d.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(l,s)&&l.add(u)}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t;(!i||i(e))&&(yield r?e:e.fullpath());let a=new Set([e]);for(let l of a){let c=l.readdirSync();for(let p of c){(!i||i(p))&&(yield r?p:p.fullpath());let d=p;if(p.isSymbolicLink()){if(!(o&&(d=p.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(a,s)&&a.add(d)}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=new rr({objectMode:!0});(!i||i(e))&&a.write(r?e:e.fullpath());let l=new Set,c=[e],p=0,d=()=>{let u=!1;for(;!u;){let m=c.shift();if(!m){p===0&&a.end();return}p++,l.add(m);let h=(f,S,x=!1)=>{if(f)return a.emit("error",f);if(o&&!x){let v=[];for(let b of S)b.isSymbolicLink()&&v.push(b.realpath().then(E=>E?.isUnknown()?E.lstat():E));if(v.length){Promise.all(v).then(()=>h(null,S,!0));return}}for(let v of S)v&&(!i||i(v))&&(a.write(r?v:v.fullpath())||(u=!0));p--;for(let v of S){let b=v.realpathCached()||v;b.shouldWalk(l,s)&&c.push(b)}u&&!a.flowing?a.once("drain",d):g||d()},g=!0;m.readdirCB(h,!0),g=!1}};return d(),a}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:s}=t,a=new rr({objectMode:!0}),l=new Set;(!i||i(e))&&a.write(r?e:e.fullpath());let c=[e],p=0,d=()=>{let u=!1;for(;!u;){let m=c.shift();if(!m){p===0&&a.end();return}p++,l.add(m);let h=m.readdirSync();for(let g of h)(!i||i(g))&&(a.write(r?g:g.fullpath())||(u=!0));p--;for(let g of h){let f=g;if(g.isSymbolicLink()){if(!(o&&(f=g.realpathSync())))continue;f.isUnknown()&&f.lstatSync()}f.shouldWalk(l,s)&&c.push(f)}}u&&!a.flowing&&a.once("drain",d)};return d(),a}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[hS](t)}},No=class extends Va{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,Nd,"\\",{...t,nocase:r}),this.nocase=r;for(let o=this.cwd;o;o=o.parent)o.nocase=this.nocase}parseRootPath(e){return Nd.parse(e).root.toUpperCase()}newRoot(e){return new Wa(this.rootPath,Tn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},_o=class extends Va{sep="/";constructor(e=process.cwd(),t={}){let{nocase:r=!1}=t;super(e,GA,"/",{...t,nocase:r}),this.nocase=r}parseRootPath(e){return"/"}newRoot(e){return new Ga(this.rootPath,Tn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},us=class extends _o{constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,{...t,nocase:r})}},_q=process.platform==="win32"?Wa:Ga,gS=process.platform==="win32"?No:process.platform==="darwin"?us:_o;var aI=n=>n.length>=1,lI=n=>n.length>=1,Mo=class n{#e;#t;#i;length;#r;#s;#w;#c;#p;#a;#l=!0;constructor(e,t,r,o){if(!aI(e))throw new TypeError("empty pattern list");if(!lI(t))throw new TypeError("empty glob list");if(t.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,r<0||r>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#t=t,this.#i=r,this.#r=o,this.#i===0){if(this.isUNC()){let[i,s,a,l,...c]=this.#e,[p,d,u,m,...h]=this.#t;c[0]===""&&(c.shift(),h.shift());let g=[i,s,a,l,""].join("/"),f=[p,d,u,m,""].join("/");this.#e=[g,...c],this.#t=[f,...h],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[i,...s]=this.#e,[a,...l]=this.#t;s[0]===""&&(s.shift(),l.shift());let c=i+"/",p=a+"/";this.#e=[c,...s],this.#t=[p,...l],this.length=this.#e.length}}}pattern(){return this.#e[this.#i]}isString(){return typeof this.#e[this.#i]=="string"}isGlobstar(){return this.#e[this.#i]===it}isRegExp(){return this.#e[this.#i]instanceof RegExp}globString(){return this.#w=this.#w||(this.#i===0?this.isAbsolute()?this.#t[0]+this.#t.slice(1).join("/"):this.#t.join("/"):this.#t.slice(this.#i).join("/"))}hasMore(){return this.length>this.#i+1}rest(){return this.#s!==void 0?this.#s:this.hasMore()?(this.#s=new n(this.#e,this.#t,this.#i+1,this.#r),this.#s.#a=this.#a,this.#s.#p=this.#p,this.#s.#c=this.#c,this.#s):this.#s=null}isUNC(){let e=this.#e;return this.#p!==void 0?this.#p:this.#p=this.#r==="win32"&&this.#i===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#c!==void 0?this.#c:this.#c=this.#r==="win32"&&this.#i===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#i===0?e:""}checkFollowGlobstar(){return!(this.#i===0||!this.isGlobstar()||!this.#l)}markFollowGlobstar(){return this.#i===0||!this.isGlobstar()||!this.#l?!1:(this.#l=!1,!0)}};var cI=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Fo=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:r,noext:o,noglobstar:i,platform:s=cI}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=s,this.mmopts={dot:!0,nobrace:t,nocase:r,noext:o,noglobstar:i,optimizationLevel:2,platform:s,nocomment:!0,nonegate:!0};for(let a of e)this.add(a)}add(e){let t=new zt(e,this.mmopts);for(let r=0;r<t.set.length;r++){let o=t.set[r],i=t.globParts[r];if(!o||!i)throw new Error("invalid pattern object");for(;o[0]==="."&&i[0]===".";)o.shift(),i.shift();let s=new Mo(o,i,0,this.platform),a=new zt(s.globString(),this.mmopts),l=i[i.length-1]==="**",c=s.isAbsolute();c?this.absolute.push(a):this.relative.push(a),l&&(c?this.absoluteChildren.push(a):this.relativeChildren.push(a))}}ignored(e){let t=e.fullpath(),r=`${t}/`,o=e.relative()||".",i=`${o}/`;for(let s of this.relative)if(s.match(o)||s.match(i))return!0;for(let s of this.absolute)if(s.match(t)||s.match(r))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+"/",r=(e.relative()||".")+"/";for(let o of this.relativeChildren)if(o.match(r))return!0;for(let o of this.absoluteChildren)if(o.match(t))return!0;return!1}};var Md=class n{store;constructor(e=new Map){this.store=e}copy(){return new n(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let r=e.fullpath(),o=this.store.get(r);o?o.add(t.globString()):this.store.set(r,new Set([t.globString()]))}},Fd=class{store=new Map;add(e,t,r){let o=(t?2:0)|(r?1:0),i=this.store.get(e);this.store.set(e,i===void 0?o:o&i)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},Dd=class{store=new Map;add(e,t){if(!e.canReaddir())return;let r=this.store.get(e);r?r.find(o=>o.globString()===t.globString())||r.push(t):this.store.set(e,[t])}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},ms=class n{hasWalkedCache;matches=new Fd;subwalks=new Dd;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new Md}processPatterns(e,t){this.patterns=t;let r=t.map(o=>[e,o]);for(let[o,i]of r){this.hasWalkedCache.storeWalked(o,i);let s=i.root(),a=i.isAbsolute()&&this.opts.absolute!==!1;if(s){o=o.resolve(s==="/"&&this.opts.root!==void 0?this.opts.root:s);let d=i.rest();if(d)i=d;else{this.matches.add(o,!0,!1);continue}}if(o.isENOENT())continue;let l,c,p=!1;for(;typeof(l=i.pattern())=="string"&&(c=i.rest());)o=o.resolve(l),i=c,p=!0;if(l=i.pattern(),c=i.rest(),p){if(this.hasWalkedCache.hasWalked(o,i))continue;this.hasWalkedCache.storeWalked(o,i)}if(typeof l=="string"){let d=l===".."||l===""||l===".";this.matches.add(o.resolve(l),a,d);continue}else if(l===it){(!o.isSymbolicLink()||this.follow||i.checkFollowGlobstar())&&this.subwalks.add(o,i);let d=c?.pattern(),u=c?.rest();if(!c||(d===""||d===".")&&!u)this.matches.add(o,a,d===""||d===".");else if(d===".."){let m=o.parent||o;u?this.hasWalkedCache.hasWalked(m,u)||this.subwalks.add(m,u):this.matches.add(m,a,!0)}}else l instanceof RegExp&&this.subwalks.add(o,i)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new n(this.opts,this.hasWalkedCache)}filterEntries(e,t){let r=this.subwalks.get(e),o=this.child();for(let i of t)for(let s of r){let a=s.isAbsolute(),l=s.pattern(),c=s.rest();l===it?o.testGlobstar(i,s,c,a):l instanceof RegExp?o.testRegExp(i,l,c,a):o.testString(i,l,c,a)}return o}testGlobstar(e,t,r,o){if((this.dot||!e.name.startsWith("."))&&(t.hasMore()||this.matches.add(e,o,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(r&&t.checkFollowGlobstar()?this.subwalks.add(e,r):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),r){let i=r.pattern();if(typeof i=="string"&&i!==".."&&i!==""&&i!==".")this.testString(e,i,r.rest(),o);else if(i===".."){let s=e.parent||e;this.subwalks.add(s,r)}else i instanceof RegExp&&this.testRegExp(e,i,r.rest(),o)}}testRegExp(e,t,r,o){t.test(e.name)&&(r?this.subwalks.add(e,r):this.matches.add(e,o,!1))}testString(e,t,r,o){e.isNamed(t)&&(r?this.subwalks.add(e,r):this.matches.add(e,o,!1))}};var dI=(n,e)=>typeof n=="string"?new Fo([n],e):Array.isArray(n)?new Fo(n,e):n,qa=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#t;#i;signal;maxDepth;includeChildMatches;constructor(e,t,r){if(this.patterns=e,this.path=t,this.opts=r,this.#i=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#t=dI(r.ignore??[],r),!this.includeChildMatches&&typeof this.#t.add!="function")){let o="cannot ignore child matches, ignore lacks add() method.";throw new Error(o)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#r(e){return this.seen.has(e)||!!this.#t?.ignored?.(e)}#s(e){return!!this.#t?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#e.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e())}async matchCheck(e,t){if(t&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||await e.realpath(),!r)return;e=r}let i=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let s=await i.realpath();s&&(s.isUnknown()||this.opts.stat)&&await s.lstat()}return this.matchCheckTest(i,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#r(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||e.realpathSync(),!r)return;e=r}let i=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let s=i.realpathSync();s&&(s?.isUnknown()||this.opts.stat)&&s.lstatSync()}return this.matchCheckTest(i,t)}matchFinish(e,t){if(this.#r(e))return;if(!this.includeChildMatches&&this.#t?.add){let i=`${e.relativePosix()}/**`;this.#t.add(i)}let r=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let o=this.opts.mark&&e.isDirectory()?this.#i:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(r){let i=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(i+o)}else{let i=this.opts.posix?e.relativePosix():e.relative(),s=this.opts.dotRelative&&!i.startsWith(".."+this.#i)?"."+this.#i:"";this.matchEmit(i?s+i+o:"."+o)}}async match(e,t,r){let o=await this.matchCheck(e,r);o&&this.matchFinish(o,t)}matchSync(e,t,r){let o=this.matchCheckSync(e,r);o&&this.matchFinish(o,t)}walkCB(e,t,r){this.signal?.aborted&&r(),this.walkCB2(e,t,new ms(this.opts),r)}walkCB2(e,t,r,o){if(this.#s(e))return o();if(this.signal?.aborted&&o(),this.paused){this.onResume(()=>this.walkCB2(e,t,r,o));return}r.processPatterns(e,t);let i=1,s=()=>{--i===0&&o()};for(let[a,l,c]of r.matches.entries())this.#r(a)||(i++,this.match(a,l,c).then(()=>s()));for(let a of r.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;i++;let l=a.readdirCached();a.calledReaddir()?this.walkCB3(a,l,r,s):a.readdirCB((c,p)=>this.walkCB3(a,p,r,s),!0)}s()}walkCB3(e,t,r,o){r=r.filterEntries(e,t);let i=1,s=()=>{--i===0&&o()};for(let[a,l,c]of r.matches.entries())this.#r(a)||(i++,this.match(a,l,c).then(()=>s()));for(let[a,l]of r.subwalks.entries())i++,this.walkCB2(a,l,r.child(),s);s()}walkCBSync(e,t,r){this.signal?.aborted&&r(),this.walkCB2Sync(e,t,new ms(this.opts),r)}walkCB2Sync(e,t,r,o){if(this.#s(e))return o();if(this.signal?.aborted&&o(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,r,o));return}r.processPatterns(e,t);let i=1,s=()=>{--i===0&&o()};for(let[a,l,c]of r.matches.entries())this.#r(a)||this.matchSync(a,l,c);for(let a of r.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;i++;let l=a.readdirSync();this.walkCB3Sync(a,l,r,s)}s()}walkCB3Sync(e,t,r,o){r=r.filterEntries(e,t);let i=1,s=()=>{--i===0&&o()};for(let[a,l,c]of r.matches.entries())this.#r(a)||this.matchSync(a,l,c);for(let[a,l]of r.subwalks.entries())i++,this.walkCB2Sync(a,l,r.child(),s);s()}},hs=class extends qa{matches=new Set;constructor(e,t,r){super(e,t,r)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},gs=class extends qa{results;constructor(e,t,r){super(e,t,r),this.results=new rr({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};var uI=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",un=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,t){if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=pI(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==!1,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(l=>l.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(l=>l.includes("/")?l:`./**/${l}`)}if(this.pattern=e,this.platform=t.platform||uI,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let l=t.platform==="win32"?No:t.platform==="darwin"?us:t.platform?_o:gS;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",o={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:r,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(l=>new zt(l,o)),[s,a]=i.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=s.map((l,c)=>{let p=a[c];if(!p)throw new Error("invalid pattern object");return new Mo(l,p,0,this.platform)})}async walk(){return[...await new hs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new hs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new gs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new gs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};var Ud=(n,e={})=>{Array.isArray(n)||(n=[n]);for(let t of n)if(new zt(t,e).hasMagic())return!0;return!1};function Ka(n,e={}){return new un(n,e).streamSync()}function yS(n,e={}){return new un(n,e).stream()}function Do(n,e={}){return new un(n,e).walkSync()}async function fS(n,e={}){return new un(n,e).walk()}function Ya(n,e={}){return new un(n,e).iterateSync()}function bS(n,e={}){return new un(n,e).iterate()}var mI=Ka,hI=Object.assign(yS,{sync:Ka}),gI=Ya,fI=Object.assign(bS,{sync:Ya}),SI=Object.assign(Do,{stream:Ka,iterate:Ya}),SS=Object.assign(fS,{glob:fS,globSync:Do,sync:SI,globStream:yS,stream:hI,globStreamSync:Ka,streamSync:mI,globIterate:bS,iterate:fI,globIterateSync:Ya,iterateSync:gI,Glob:un,hasMagic:Ud,escape:Io,unescape:cn});SS.glob=SS;import CI from"os";import or,{dirname as TS}from"path";import{cwd as Hd}from"process";import ES from"yaml";import{z as pe}from"zod";import wS from"fs";import Ja from"path";import yI from"yaml";import{z as Bd}from"zod";var vS=!1,fs=[`**/*.${Nt.TEST}`,`**/*.${Nt.MODULE}`],zd=Bd.string().refine(n=>/^[a-zA-Z0-9-]+$/.test(n)),jd=50,bI=Bd.object({fileType:Bd.nativeEnum(fe)});function Oe(n,e){let t={project:n,tests:{},modules:{}},r=n.config.include??fs,o=Array.from(n.config.exclude??[]).concat(_h),i=Do(r,{absolute:!1,cwd:n.rootDir,ignore:o,dotRelative:!1,maxDepth:jd,nodir:!0});for(let s of i)wI(n.rootDir,s,t,e);return vS=!0,t}function wI(n,e,t,r){let o=Ja.join(n,e),i;try{i=wS.readFileSync(o,"utf-8")}catch(d){r.warn(`Could not read possible Momentic file at ${o}, skipping: ${d}`);return}let s;try{if(s=yI.parse(i),typeof s!="object"||s===null)throw new Error("The YAML document should parse as a map with key-value pairs")}catch(d){r.warn(`Could not parse possible Momentic file at ${o}, skipping: ${d}`);return}let a=bI.safeParse(s);if(a.error){r.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${a.error}`);return}let l=a.data.fileType,c;try{c=wS.statSync(o)}catch(d){r.warn(`Skipping path '${o}' because it could not be stat, skipping: ${d}`);return}let p={relativePath:e,fullFilePath:o,platformSep:Ja.sep,fullPathSegments:o.split(Ja.sep),fileName:Ja.basename(o),lastModified:c.mtime,createdAt:c.birthtime};switch(l){case fe.TEST:try{let d=Xt.parse(s);if(t.tests[d.id]){let u=t.tests[d.id].fullFilePath;y.error(`Two tests with the same ID (${d.id}) were found in the same project. Please ensure that all test IDs are unique and avoid copying tests manually. Momentic will ignore the first test when resolving tests.
|
|
41
|
+
`)}function _g(r,e){try{if(!r)return r;if(typeof r=="string")return _e(r,3e4);if(typeof r=="object"){let{jsonString:t}=wo(JSON.stringify(r,(n,o)=>e?.includes(n)||typeof o=="string"&&o.length>3e4?"REDACTED":o),2e4);return JSON.parse(t)}return r}catch{return r}}function cd(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=wo(JSON.stringify(n.data),1e3);n.data=JSON.parse(o)}}catch(o){e.error({err:o},"Failed to serialize individual result output data"),n.data=`Result output data could not be serialized: ${o}`}switch(n.details&&(n.details=void 0),n.type){case"PRESET_ACTION":Ng(n);break;case"CONDITIONAL":n.assertion&&Ng(n.assertion),cd(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"IFRAME":case"MODULE":case"SECTION":{cd(n.results,e);break}default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}}function Ng(r){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}function Mg(r,e){let t=JSON.stringify(r),n=t.replaceAll("\\u0000","");if(t.length!==n.length){let o=t.indexOf("\\u0000");e.warn({input:t.slice(Math.max(0,o-500),Math.min(t.length,o+500))},"Database content violation: stripped unicode character from input")}return n}function As(r,e){let t=rA(r);if(cd(t,e),t.length>Lg)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,Lg);let n=Mg(t,e);if(n.length>kg)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>kg;)t.pop(),n=Mg(t,e);try{return an.array().parse(JSON.parse(n))}catch(o){throw e.error({serialized:n,err:o},"Could not parse serialized results into JSON structure after processing"),o}}import{cloneDeep as yW}from"lodash-es";var iA=/^(?!.*\S+\s+\S+).*$/,aA=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,sA=/style="([^"]*)/g,lA=/data-[\w-]+/g,cA=r=>{switch(r.type){case"AI_WAIT":case"AI_ASSERTION":return{type:r.type,assertion:r.assertion};case"DRAG":if(r.fromTarget.type==="description")return{type:r.type,description:r.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(r.target?.type==="description")return{type:r.type,description:r.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function Fg(r){let e=cA(r),t=e.type==="AI_ASSERTION"||e.type==="AI_WAIT"?e.assertion:e.description;return!t||t==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:iA.test(t)&&aA.test(t)?{thoughts:"Too few words in the command description. Please add more words to the description.",category:"FEW_WORDS"}:sA.test(t)?{thoughts:"Style tag is not allowed in the command description. Please remove it and describe the command in a different way.",category:"STYLE_TAG"}:lA.test(t)?{thoughts:"Hardcoded data attributes are not recommend in the command description. If the attribute doesn't directly match the quotes, autohealing will fail.",category:"HARDCODED_ATTRIBUTE"}:new RegExp(`\\b${e.type}\\b`,"gi").test(t)?{thoughts:"The description contains the same word as the command type. Please remove it since the type of command is already known.",category:"TYPE_IN_DESCRIPTION"}:{thoughts:"NONE",category:"NONE"}}function Dg(r,e){if(!(!r.envs||!r.envs.length)){for(let t of r.envs){let n=t;e in t&&(n[e]&&(t.default=!0),delete n.defaultOnCloud,delete n.defaultOnLocal)}r.envs.some(t=>t.default)||(r.envs[0].default=!0)}}import{cloneDeep as cf}from"lodash-es";import hA from"diff-lines";import Is,{gte as gA}from"semver";var Ug={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>(r=r.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),r=r.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),r)};var Bg={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,n=t[t.length-1];return n&&n.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var dA=["target","fromTarget","toTarget"];function zg(r){for(let e of dA){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var jg={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":return zg(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])zg(n);return e}default:return e}})};import{v4 as pA}from"uuid";var Hg={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=pA()),e;default:return e}})};import{v4 as $g}from"uuid";var Wg={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??$g(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??$g()}})),delete e.commands),e;default:return e}})};var Gg={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as uA}from"uuid";var Vg={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>("id"in e&&typeof e.id=="string"||(e.id=uA()),e))};import{v4 as qg}from"uuid";var Kg={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=qg())}return e.id=qg(),e})};var Yg={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as mA}from"uuid";var Jg={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=mA()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var Xg={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var Zg={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&Qg(t),e})};function Qg(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){Qg(r[e]);return}if(typeof r[e]!="string")return;let t=r[e];e==="code"?r[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(r[e]=t.replace(/inputs\./g,"env."))})}var ef={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||t.url===void 0||(t.action={type:"SUBSTRING",substring:t.url},t.url=void 0),e})};var tf={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TYPE"?e:t.pressKeysSequentially===void 0?(t.delay=0,e):(t.pressKeysSequentially&&(t.pressKeysSequentially=void 0,t.delay=50),e)})};var nf={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="WAIT_FOR_URL"||t.url===void 0||(t.matcher={type:"GLOB",glob:t.url},t.url=void 0),e})};var rf={name:"Migrate AI assertions to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async r=>r.map(e=>{if(e.type!=="AI_ASSERTION")return e;let n={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...n};return delete o.text,o}),stopOnFailure:!0};var Rs=new Set(["CLICK","TYPE","SELECT_OPTION"]),of={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type,o=t?.elementDescriptor;return(o!==void 0||Rs.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let s=a?.elementDescriptor,l=a?.type;(s!==void 0||Rs.has(l))&&(a.target={elementDescriptor:s??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let s=a.command,l=s?.elementDescriptor,c=s?.type;(l!==void 0||Rs.has(c))&&(s.target={elementDescriptor:l??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let m=d?.elementDescriptor,u=d?.type;(m!==void 0||Rs.has(u))&&(d.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var af={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var sf={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.type=n.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,s=a?.type;s?.startsWith("PRESET_")&&(a.type=s.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(c=>{let p=c.type;p?.startsWith("PRESET_")&&(c.type=p.slice(7))})}),e}),stopOnFailure:!0};var zr=[rf,af,sf,of,Ug,Bg,jg,Hg,Wg,Gg,Vg,Kg,Yg,Jg,Xg,Zg,ef,tf,nf];if(je!==zr[zr.length-1].toVersion)throw new Error("Please bump LATEST_VERSION in types package after adding a migration");zr.forEach((r,e)=>{if(!Is.valid(r.toVersion)||!Is.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!Is.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(zr[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});function fA(r){return r.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var Ki=async({metadata:r,steps:e,logger:t,toVersion:n})=>{let o=e,{schemaVersion:i,id:a}=r,s=zr.findIndex(p=>Is.gt(p.toVersion,i));if(s===-1)return{steps:o,newVersion:i};let l=i;for(let p=s;p<zr.length;p++){if(n&&gA(l,n)){t.debug("Stopping migration early because toVersion was reached");break}let d=zr[p],m={id:a,migration:d.name,toVersion:d.toVersion};try{o=await lf(o,d),l=d.toVersion}catch(u){throw t.error({err:u,...m},"Migration failed"),new Error(`Step migration ${d.name} failed: ${u}`)}}let c=hA(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return c.trim()&&t.debug({diffs:c,id:a},"Migration diffs"),{newVersion:l,steps:o}};async function lf(r,e){let t=await e.execute(r);for(let n of t)for(let o of Object.keys(n)){if(!e.recursiveKeys.has(o))continue;let i=n[o];!i||!Array.isArray(i)||fA(i)&&(n[o]=await lf(i,e))}return t}async function df({rawSteps:r,metadata:e,logger:t,callbacks:n}){Dg(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await Ps({rawSteps:r.steps,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o}),s={...e,steps:i,schemaVersion:a};for(let l of["beforeSteps","afterSteps"]){let c=r[l];if(!c)continue;let{resolvedSteps:p}=await Ps({rawSteps:c,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o});s[l]=p}return{resolvedTest:s,moduleIds:Array.from(Object.keys(o))}}async function dd(r,e,t){let{newVersion:n,steps:o}=await Ki({metadata:r,steps:e,logger:t});try{return{steps:Je.array().parse(o),newVersion:n}}catch(i){throw t.error({type:"zod",err:i,newVersion:n,id:r.id,steps:o},"Failed to parse test steps while migrating test"),new ws(`Failed to parse test steps while migrating test: ${i}`,r.id,"entity",{cause:i})}}async function Ps({rawSteps:r,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await dd(e,r,t),s=[];for(let l of a)s.push(await Yi({step:l,callbacks:n,logger:t,resolvedModuleCache:o}));return{resolvedSteps:s,newSchemaVersion:i}}async function Yi({step:r,callbacks:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"AI_ACTION":return r;case"AI_ACTION_DYNAMIC":return r;case"PRESET_ACTION":return r;case"MODULE":{let l=r.moduleId,c=n[l];if(c)return{...cf(c),...r,type:"RESOLVED_MODULE"};let p=await e.onFetchModule({id:l,logger:t});if(!p)throw new Error(`Could not find module with id ${l}`);let{newVersion:d,steps:m}=await Ki({metadata:{id:l,schemaVersion:p.schemaVersion},steps:p.steps,logger:t}),u;try{u=Je.array().parse(m)}catch(f){throw t.error({type:"zod",err:f,steps:m,newVersion:d,id:l},"Module failed to parse"),f}let h;try{h=await Promise.all(u.map(f=>Yi({step:f,callbacks:e,logger:t,resolvedModuleCache:n})))}catch(f){throw t.error({err:f,...r},`Failed to recursively resolve module '${p.name}': ${f}`),f}let g={...p,steps:h};return n[l]=cf(g),{...g,...r,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let l of r.blocks){let c=[];for(let p of l.steps)c.push(await Yi({step:p,callbacks:e,logger:t,resolvedModuleCache:n}));o.push({...l,steps:c})}let i;if(r.elseSteps){i=[];for(let l of r.elseSteps)i.push(await Yi({step:l,callbacks:e,logger:t,resolvedModuleCache:n}))}return{...r,blocks:o,elseSteps:i};case"SECTION":case"IFRAME":let a=[];for(let l of r.steps)a.push(await Yi({step:l,callbacks:e,logger:t,resolvedModuleCache:n}));return{...r,steps:a};default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function SA(r){return typeof r=="object"&&r!==null}function Nn(r){if(Array.isArray(r))return r.map(Nn);if(SA(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=Nn(n))}),e}return r}import{cloneDeep as pf}from"lodash-es";import{v4 as pd}from"uuid";async function Qe(r){let e=new Map,t=new Set,n=pf(r.stepLists.steps),o=await jr({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t}),i={stepsToSave:{steps:o.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates};for(let a of["beforeSteps","afterSteps"]){let s=pf(r.stepLists[a]);if(!s)continue;let l=await jr({...r,steps:s,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});i.cachesToSave.push(...l.cachesToSave),i.moduleUpdates.push(...l.moduleUpdates),i.stepsToSave[a]=l.stepsToSave}return i}async function jr({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:s}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let c of r)switch(delete c.index,delete c.aiSuggested,c.id=e.createNewStepIds?pd():c.id,c.type){case"PRESET_ACTION":{let d=c.command;d.id=n?.createNewCacheIds?pd():d.id,Ag(d),"cache"in d&&d.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(Cg({id:d.id,orgId:n.orgId,testId:n.testId,value:xr.parse(d),moduleIdParents:o,moduleStepParents:i,skipIntermediateEntries:e.skipCacheIntermediateEntries}))),delete d.cache),d.thoughts&&delete d.thoughts,l.stepsToSave.push({...c,command:d});break}case"RESOLVED_MODULE":{let d=n?.createNewCacheIds?pd():c.id,m=c.moduleId;a.has(m)?m=a.get(m):s!==void 0&&(m=await s(c),a.set(c.moduleId,m));let{cachesToSave:u,stepsToSave:h,moduleUpdates:g}=await jr({...e,steps:c.steps,cacheCreationParams:n?{...n,createNewCacheIds:!1}:void 0,moduleStepParents:[...i,d],moduleIdParents:[...o,m],skipCacheIntermediateEntries:n?.createNewCacheIds});l.moduleUpdates=l.moduleUpdates.concat(g),l.cachesToSave=l.cachesToSave.concat(u),t.has(m)||(t.add(m),l.moduleUpdates.push({...Rt.parse(c),steps:Je.array().parse(h),moduleId:m}));let f={type:"MODULE",moduleId:m,inputs:c.inputs,id:d,skipped:c.skipped,cacheConfig:c.cacheConfig,envKey:c.envKey};l.stepsToSave.push(f);break}case"AI_ACTION":{if(!c.steps){l.stepsToSave.push(c);break}let{stepsToSave:d,cachesToSave:m}=await jr({...e,steps:c.steps});try{c.steps=At.array().parse(d)}catch(u){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${u}`)}l.stepsToSave.push(c),l.cachesToSave=l.cachesToSave.concat(m);break}case"AI_ACTION_DYNAMIC":{l.stepsToSave.push(c);break}case"CONDITIONAL":{let d=[];for(let u of c.blocks){let{stepsToSave:h,cachesToSave:g,moduleUpdates:f}=await jr({...e,steps:u.steps});d.push({...u,steps:h}),l.cachesToSave=l.cachesToSave.concat(g),l.moduleUpdates=l.moduleUpdates.concat(f)}let m={...c,elseSteps:void 0,blocks:d};if(c.elseSteps){let{stepsToSave:u,cachesToSave:h,moduleUpdates:g}=await jr({...e,steps:c.elseSteps});m.elseSteps=u,l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(g)}l.stepsToSave.push(m);break}case"IFRAME":case"SECTION":{let{stepsToSave:d,cachesToSave:m,moduleUpdates:u}=await jr({...e,steps:c.steps}),h={...c,steps:d};l.moduleUpdates=l.moduleUpdates.concat(u),l.stepsToSave.push(h),l.cachesToSave=l.cachesToSave.concat(m);break}default:return(d=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(c)}return l}import{cloneDeep as yA}from"lodash-es";import{stringify as uf}from"yaml";async function mf(r,e=new Set){let t={id:r.id,name:r.name,description:r.description,baseUrl:r.baseUrl,schemaVersion:r.schemaVersion,advanced:r.advanced,retries:r.retries,envs:r.envs,disabled:r.disabled,labels:r.labels},n={},o=await bA({originalStepLists:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},modules:n,processedModuleNames:e}),i={fileType:fe.TEST,...t,beforeSteps:o.beforeSteps&&o.beforeSteps.length>0?o.beforeSteps:void 0,steps:o.steps,afterSteps:o.afterSteps&&o.afterSteps.length>0?o.afterSteps:void 0};return{test:uf(i),modules:n}}async function bA({originalStepLists:r,modules:e,processedModuleNames:t}){let n=yA(r);Object.values(n).forEach(a=>{wA(a??[])});let{stepsToSave:o,moduleUpdates:i}=await Qe({stepLists:n});for(let a of i)t.has(a.name)||(e[a.name]=vA(a),t.add(a.name));return o}function wA(r){id({steps:r,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function vA(r){let e=Rt.parse(r),t={fileType:fe.MODULE,...e,schemaVersion:je,steps:r.steps};return uf(t)}async function Q(r,e){return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function Ji({promiseGenerator:r,signal:e,codePath:t,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((s,l)=>{function c(){clearInterval(a),e?.removeEventListener("abort",c),l(e?.reason)}if(e?.aborted){l(e?.reason),clearInterval(a);return}e?.addEventListener("abort",c),(async()=>{try{s(await r())}catch(p){l(p)}finally{clearInterval(a),e?.removeEventListener("abort",c)}})()})}async function Hr({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,s=()=>{a.abort()},l=setTimeout(()=>{i||a.abort()},e);o?.addEventListener("abort",s);try{return await Ji({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(l)}}function Ls(r){let e=[];for(let t of r)switch(t.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(t);break;case"RESOLVED_MODULE":{let n={...t,type:"MODULE"};e.push(On.parse(n));break}case"IFRAME":case"SECTION":{let n={...t,steps:Ls(t.steps)};e.push(Je.parse(n));break}case"CONDITIONAL":{let n={...t,blocks:t.blocks.map(o=>({assertion:o.assertion,steps:Ls(o.steps)})),elseSteps:t.elseSteps?Ls(t.elseSteps):void 0};e.push(Er.parse(n));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function ks(r){return Ls([r])[0]}import xA from"picomatch";var ud=(r,e,t)=>{t?.caseInsensitive&&(r=r.toLowerCase());let n;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;n=r.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;n=r===e.glob||xA(o)(r);break}case"REGEX":{n=new RegExp(e.regex).test(r);break}}return t?.negated?!n:n};import Wr from"yaml";import{execSync as TA}from"child_process";function $r(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,y.debug({postSaveCommand:n},"Executing post-save hook command");try{TA(n,{encoding:"utf-8"})}catch(o){y.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as hf}from"deep-object-diff";import tr from"fs";import{cloneDeep as EA}from"lodash-es";import md from"path";import{v4 as CA}from"uuid";import Xi from"yaml";function hd({content:r,schemaVersion:e,momenticFiles:t,project:n}){let o=t.modules[r.moduleId]?.fullFilePath;if(!o||!tr.existsSync(o))throw new Error(`Tried to update module ${r.moduleId} that could not be found on disk`);let i=tr.readFileSync(o,"utf-8"),a=Xi.parse(i),s;if(r.name&&r.name!==a.name){let m=`${Pe(r.name)}.${Nt.MODULE}`;if(s=md.join(md.dirname(o),m),tr.existsSync(s))throw new Error(`Test with name '${r.name}' already exists at path '${s}'`)}let l={...r,schemaVersion:e},c=Nn({fileType:fe.MODULE,...Qc.parse(l),steps:r.steps}),p=hf(c,a);if(p&&Object.keys(p).length===0){y.debug(`Skipping save for module ${r.moduleId} since there are no changes`);return}let d=Xi.stringify(c);tr.writeFileSync(o,d,"utf-8"),s&&tr.renameSync(o,s),$r(s||o,n.config)}function gf({moduleId:r,content:e,momenticFiles:t,project:n,logger:o}){let i=t.modules[r]?.fullFilePath;if(!i)throw new Error(`Tried to update module ${r} that could not be found on disk`);let a=Zi(i,o),s={...a,...e},l=Nn({fileType:fe.MODULE,...Qc.parse(s),steps:a.steps}),c=hf(l,a);if(c&&Object.keys(c).length===0){y.debug(`Skipping save for module ${r} since there are no changes`);return}let p=Xi.stringify(l);tr.writeFileSync(i,p,"utf-8"),$r(i,n.config)}async function ff({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=Pe(r),s=md.join(o,`${a}.module.yaml`),l=CA(),{stepsToSave:c}=await Qe({stepLists:{steps:n}}),p={fileType:fe.MODULE,schemaVersion:je,moduleId:l,name:r,description:e,enabled:t,steps:c.steps},d=Xi.stringify(p);return tr.writeFileSync(s,d,"utf-8"),$r(s,i.config),{moduleId:l,name:r,description:e,enabled:t,steps:n}}function Zi(r,e){let t=tr.readFileSync(r,"utf-8"),n=Xi.parse(t);try{return nd.parse(n)}catch(o){throw e.error({err:o,moduleFilePath:r,moduleContents:t},`${r} does not parse as a valid Momentic module`),o}}async function gd(r,e,t,n){let o=Zi(r.fullFilePath,t),{resolvedSteps:i}=await Ps({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:n,logger:t,callbacks:{onFetchModule:async({id:s})=>{let l=e.modules[s]?.fullFilePath;if(l)return Zi(l,t)}}}),a={...o,steps:i};return n&&(n[r.id]=EA(a)),a}async function Os(r,e){let t={};return await Promise.all(Object.values(r.modules).map(async n=>{await gd(n,r,e,t)})),Array.from(Object.values(t))}async function Sf({test:r,name:e,folder:t}){let n=await mf(r);if(Object.keys(n.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${Pe(e)}.${Nt.TEST}`,a=Ut.join(t,i);return Mt.writeFileSync(a,n.test,"utf-8"),a}function fd(r,e,t){let n=Ut.join(t.rootDir,r);if(!Mt.existsSync(n))throw new Error(`Test not found at path '${r}' in project '${t.rootDir}'`);let o=Mt.readFileSync(n,"utf-8"),i=Wr.parse(o),a,s;if(e.name&&e.name!==i.name){let m=`${Pe(e.name)}.${Nt.TEST}`;if(a=Ut.join(Ut.dirname(r),m),s=Ut.join(t.rootDir,a),Mt.existsSync(s))throw new Error(`Test with name '${e.name}' already exists at path '${s}'`)}let l={...i,...e},c=Xt.parse(l),p={fileType:fe.TEST,...Xt.parse(c),beforeSteps:i.beforeSteps??void 0,steps:i.steps,afterSteps:i.afterSteps??void 0},d=Wr.stringify(p);return Mt.writeFileSync(n,d,"utf-8"),s&&Mt.renameSync(n,s),$r(n,t.config),{newRelativeTestPath:a}}function Gr(r,e,t,n){let o=Ut.join(n.rootDir,r);if(!Mt.existsSync(o))throw new Error(`Test not found at path '${r}' in project '${n.rootDir}'`);let i=Mt.readFileSync(o,"utf-8"),a=Wr.parse(i),s=Xt.parse({...a,schemaVersion:t}),l=Nn({fileType:fe.TEST,...s,beforeSteps:e.beforeSteps??void 0,steps:e.steps,afterSteps:e.afterSteps??void 0}),c=AA(l,a);if(c&&Object.keys(c).length===0){y.debug(`Skipping save for test ${s.name} since there are no changes`);return}let p=Wr.stringify(l);Mt.writeFileSync(o,p,"utf-8"),y.debug(`Saving test ${s.name} to ${o}`),$r(o,n.config)}function Sd(r,e,t=r){let n=r.split(Ut.sep).pop()??"";if(qi.includes(n))return e.warn(`Skipping directory '${r}' because it is likely an artifact folder.`),[];let o=Mt.readdirSync(r),i=[];return o.forEach(a=>{let s=Ut.join(r,a),l;try{l=Mt.statSync(s)}catch(c){e.warn({err:c},`Skipping path '${s}' because it could not be read.`);return}if(l.isDirectory())i=i.concat(Sd(s,e,t));else if(a.endsWith(".yaml")){let c=Mt.readFileSync(s,"utf-8"),p=Ut.relative(Ut.resolve(t),Ut.resolve(s));try{let d=Wr.parse(c),m=Ot.parse(d);i.push({id:m.id,name:m.name,fullPathSegments:s.split(Ut.sep),testPath:p,fileName:a,lastModified:l.mtime,createdAt:l.ctime})}catch{e.warn(`Skipping file '${s}' because it does not parse as a valid Momentic test.`)}}}),i}function Ns(r,e){let t=Ut.join(e.rootDir,r);if(!t)throw new Error(`Could not find test with path ${r} in Momentic project (${e.rootDir})`);let n;try{n=Mt.readFileSync(t,"utf8"),n=n.replace(/\r\n|\r/g,`
|
|
42
|
+
`)}catch(i){throw new Error(`Could not read test file ${t}: ${i}`)}let o;try{o=Wr.parse(n)}catch(i){throw new Error(`Could not parse test file ${t} as YAML: ${i}`)}return Ot.parse(o)}function Qi(r,e,t){let n=t.project.rootDir,o;try{o=Mt.readFileSync(r,"utf-8")}catch(a){throw e.error({err:a,projectRoot:n},a.message),new Error(a.message)}let i=Wr.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${r} is missing steps`);return i}async function ea(r,e,t){let n=Qi(r,e,t),o;try{o=Xt.parse(n)}catch(a){throw new Error(`Test ${r} is missing metadata or has invalid metadata: ${a}`)}let{resolvedTest:i}=await df({rawSteps:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:a,logger:s})=>{let l=t.modules[a]?.fullFilePath;if(l)return Zi(l,s)}}});return i}import RA from"@dotenvx/dotenvx";import IA from"fs";import yf from"path";function wf(r,e){return(r.config.environments??[]).map(t=>ta(t.name,r,e))}function bf(r){return r.includes("${")?r.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[n,o]=t.split(/:-|-/,2),i=process.env[n];return t.includes(":-")?i&&i!==""?i:o||"":t.includes("-")?i!==void 0?i:o||"":i||""}):r}function ta(r,e,t){let n=(e.config.environments??[]).find(a=>a.name===r);if(!n)throw new Error(`Environment ${r} not found in local project configuration file`);let o={[Ie]:bf(n.baseUrl)};if(n.envVariables){let a={};for(let[s,l]of Object.entries(n.envVariables))if(typeof l=="string"){let c=bf(l);c&&(a[s]=c)}else{let c=l.fromFile,p;try{p=IA.readFileSync(yf.resolve(e.rootDir,c),"utf-8")}catch(d){throw new Error(`Failed to read environment variable '${s}' from file '${c}': ${d}`)}if(l.json)try{a[s]=JSON.parse(p)}catch(d){throw new Error(`Failed to parse environment variable '${s}' from file '${c}' as JSON: ${d}`)}else a[s]=p}Object.keys(a).length>0&&y.debug(a,"Set environment variables with interpolation from project configuration"),Object.assign(o,a)}if(n.envFile){let a={},s=RA.config({path:yf.resolve(e.rootDir,n.envFile),processEnv:a,logLevel:"error",quiet:!0});if(s.error)throw new Error(`Failed to load .env file: ${s.error.message}`);t.debug(a,"Set environment variables from .env file"),Object.assign(o,a)}return n.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:r,variables:o,browser:n.browser}}import{existsSync as iI,readFileSync as aI,readdirSync as sI,writeFileSync as lI}from"fs";var jf=Xv(Nf(),1);var ra=r=>{if(typeof r!="string")throw new TypeError("invalid pattern");if(r.length>65536)throw new TypeError("pattern is too long")};var FA={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},oa=r=>r.replace(/[[\]\\-]/g,"\\$&"),DA=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Mf=r=>r.join(""),_f=(r,e)=>{let t=e;if(r.charAt(t)!=="[")throw new Error("not in a brace expression");let n=[],o=[],i=t+1,a=!1,s=!1,l=!1,c=!1,p=t,d="";e:for(;i<r.length;){let g=r.charAt(i);if((g==="!"||g==="^")&&i===t+1){c=!0,i++;continue}if(g==="]"&&a&&!l){p=i+1;break}if(a=!0,g==="\\"&&!l){l=!0,i++;continue}if(g==="["&&!l){for(let[f,[S,x,v]]of Object.entries(FA))if(r.startsWith(f,i)){if(d)return["$.",!1,r.length-t,!0];i+=f.length,v?o.push(S):n.push(S),s=s||x;continue e}}if(l=!1,d){g>d?n.push(oa(d)+"-"+oa(g)):g===d&&n.push(oa(g)),d="",i++;continue}if(r.startsWith("-]",i+1)){n.push(oa(g+"-")),i+=2;continue}if(r.startsWith("-",i+1)){d=g,i+=2;continue}n.push(oa(g)),i++}if(p<i)return["",!1,0,!1];if(!n.length&&!o.length)return["$.",!1,r.length-t,!0];if(o.length===0&&n.length===1&&/^\\?.$/.test(n[0])&&!c){let g=n[0].length===2?n[0].slice(-1):n[0];return[DA(g),!1,p-t,!1]}let m="["+(c?"^":"")+Mf(n)+"]",u="["+(c?"":"^")+Mf(o)+"]";return[n.length&&o.length?"("+m+"|"+u+")":n.length?m:u,s,p-t,!0]};var cn=(r,{windowsPathsNoEscape:e=!1}={})=>e?r.replace(/\[([^\/\\])\]/g,"$1"):r.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var UA=new Set(["!","?","+","*","@"]),Ff=r=>UA.has(r),BA="(?!(?:^|/)\\.\\.?(?:$|/))",Ms="(?!\\.)",zA=new Set(["[","."]),jA=new Set(["..","."]),HA=new Set("().*{}+?[]^$\\!"),$A=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),wd="[^/]",Df=wd+"*?",Uf=wd+"+?",ko=class r{type;#e;#t;#i=!1;#r=[];#a;#w;#c;#p=!1;#s;#l;#o=!1;constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#a=t,this.#e=this.#a?this.#a.#e:this,this.#s=this.#e===this?n:this.#e.#s,this.#c=this.#e===this?[]:this.#e.#c,e==="!"&&!this.#e.#p&&this.#c.push(this),this.#w=this.#a?this.#a.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l!==void 0?this.#l:this.type?this.#l=this.type+"("+this.#r.map(e=>String(e)).join("|")+")":this.#l=this.#r.map(e=>String(e)).join("")}#f(){if(this!==this.#e)throw new Error("should only call on root");if(this.#p)return this;this.toString(),this.#p=!0;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let t=e,n=t.#a;for(;n;){for(let o=t.#w+1;!n.type&&o<n.#r.length;o++)for(let i of e.#r){if(typeof i=="string")throw new Error("string part in extglob AST??");i.copyIn(n.#r[o])}t=n,n=t.#a}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof r&&t.#a===this))throw new Error("invalid part: "+t);this.#r.push(t)}}toJSON(){let e=this.type===null?this.#r.slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...this.#r.map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#p&&this.#a?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#a?.isStart())return!1;if(this.#w===0)return!0;let e=this.#a;for(let t=0;t<this.#w;t++){let n=e.#r[t];if(!(n instanceof r&&n.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#a?.type==="!")return!0;if(!this.#a?.isEnd())return!1;if(!this.type)return this.#a?.isEnd();let e=this.#a?this.#a.#r.length:0;return this.#w===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let t=new r(this.type,e);for(let n of this.#r)t.copyIn(n);return t}static#S(e,t,n,o){let i=!1,a=!1,s=-1,l=!1;if(t.type===null){let u=n,h="";for(;u<e.length;){let g=e.charAt(u++);if(i||g==="\\"){i=!i,h+=g;continue}if(a){u===s+1?(g==="^"||g==="!")&&(l=!0):g==="]"&&!(u===s+2&&l)&&(a=!1),h+=g;continue}else if(g==="["){a=!0,s=u,l=!1,h+=g;continue}if(!o.noext&&Ff(g)&&e.charAt(u)==="("){t.push(h),h="";let f=new r(g,t);u=r.#S(e,f,u,o),t.push(f);continue}h+=g}return t.push(h),u}let c=n+1,p=new r(null,t),d=[],m="";for(;c<e.length;){let u=e.charAt(c++);if(i||u==="\\"){i=!i,m+=u;continue}if(a){c===s+1?(u==="^"||u==="!")&&(l=!0):u==="]"&&!(c===s+2&&l)&&(a=!1),m+=u;continue}else if(u==="["){a=!0,s=c,l=!1,m+=u;continue}if(Ff(u)&&e.charAt(c)==="("){p.push(m),m="";let h=new r(u,p);p.push(h),c=r.#S(e,h,c,o);continue}if(u==="|"){p.push(m),m="",d.push(p),p=new r(null,t);continue}if(u===")")return m===""&&t.#r.length===0&&(t.#o=!0),p.push(m),m="",t.push(...d,p),c;m+=u}return t.type=null,t.#t=void 0,t.#r=[e.substring(n-1)],c}static fromGlob(e,t={}){let n=new r(null,void 0,t);return r.#S(e,n,0,t),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,n,o,i]=this.toRegExpSource();if(!(o||this.#t||this.#s.nocase&&!this.#s.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let s=(this.#s.nocase?"i":"")+(i?"u":"");return Object.assign(new RegExp(`^${t}$`,s),{_src:t,_glob:e})}get options(){return this.#s}toRegExpSource(e){let t=e??!!this.#s.dot;if(this.#e===this&&this.#f(),!this.type){let l=this.isStart()&&this.isEnd(),c=this.#r.map(u=>{let[h,g,f,S]=typeof u=="string"?r.#u(u,this.#t,l):u.toRegExpSource(e);return this.#t=this.#t||f,this.#i=this.#i||S,h}).join(""),p="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&jA.has(this.#r[0]))){let h=zA,g=t&&h.has(c.charAt(0))||c.startsWith("\\.")&&h.has(c.charAt(2))||c.startsWith("\\.\\.")&&h.has(c.charAt(4)),f=!t&&!e&&h.has(c.charAt(0));p=g?BA:f?Ms:""}let d="";return this.isEnd()&&this.#e.#p&&this.#a?.type==="!"&&(d="(?:$|\\/)"),[p+c+d,cn(c),this.#t=!!this.#t,this.#i]}let n=this.type==="*"||this.type==="+",o=this.type==="!"?"(?:(?!(?:":"(?:",i=this.#m(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!=="!"){let l=this.toString();return this.#r=[l],this.type=null,this.#t=void 0,[l,cn(this.toString()),!1,!1]}let a=!n||e||t||!Ms?"":this.#m(!0);a===i&&(a=""),a&&(i=`(?:${i})(?:${a})*?`);let s="";if(this.type==="!"&&this.#o)s=(this.isStart()&&!t?Ms:"")+Uf;else{let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?Ms:"")+Df+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&a?")":this.type==="*"&&a?")?":`)${this.type}`;s=o+i+l}return[s,cn(i),this.#t=!!this.#t,this.#i]}#m(e){return this.#r.map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[n,o,i,a]=t.toRegExpSource(e);return this.#i=this.#i||a,n}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#u(e,t,n=!1){let o=!1,i="",a=!1;for(let s=0;s<e.length;s++){let l=e.charAt(s);if(o){o=!1,i+=(HA.has(l)?"\\":"")+l;continue}if(l==="\\"){s===e.length-1?i+="\\\\":o=!0;continue}if(l==="["){let[c,p,d,m]=_f(e,s);if(d){i+=c,a=a||p,s+=d-1,t=t||m;continue}}if(l==="*"){n&&e==="*"?i+=Uf:i+=Df,t=!0;continue}if(l==="?"){i+=wd,t=!0;continue}i+=$A(l)}return[i,cn(e),!!t,a]}};var Oo=(r,{windowsPathsNoEscape:e=!1}={})=>e?r.replace(/[?*()[\]]/g,"[$&]"):r.replace(/[?*()[\]\\]/g,"\\$&");var yt=(r,e,t={})=>(ra(e),!t.nocomment&&e.charAt(0)==="#"?!1:new Bt(e,t).match(r)),WA=/^\*+([^+@!?\*\[\(]*)$/,GA=r=>e=>!e.startsWith(".")&&e.endsWith(r),VA=r=>e=>e.endsWith(r),qA=r=>(r=r.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(r)),KA=r=>(r=r.toLowerCase(),e=>e.toLowerCase().endsWith(r)),YA=/^\*+\.\*+$/,JA=r=>!r.startsWith(".")&&r.includes("."),XA=r=>r!=="."&&r!==".."&&r.includes("."),ZA=/^\.\*+$/,QA=r=>r!=="."&&r!==".."&&r.startsWith("."),eR=/^\*+$/,tR=r=>r.length!==0&&!r.startsWith("."),nR=r=>r.length!==0&&r!=="."&&r!=="..",rR=/^\?+([^+@!?\*\[\(]*)?$/,oR=([r,e=""])=>{let t=Hf([r]);return e?(e=e.toLowerCase(),n=>t(n)&&n.toLowerCase().endsWith(e)):t},iR=([r,e=""])=>{let t=$f([r]);return e?(e=e.toLowerCase(),n=>t(n)&&n.toLowerCase().endsWith(e)):t},aR=([r,e=""])=>{let t=$f([r]);return e?n=>t(n)&&n.endsWith(e):t},sR=([r,e=""])=>{let t=Hf([r]);return e?n=>t(n)&&n.endsWith(e):t},Hf=([r])=>{let e=r.length;return t=>t.length===e&&!t.startsWith(".")},$f=([r])=>{let e=r.length;return t=>t.length===e&&t!=="."&&t!==".."},Wf=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Bf={win32:{sep:"\\"},posix:{sep:"/"}},lR=Wf==="win32"?Bf.win32.sep:Bf.posix.sep;yt.sep=lR;var it=Symbol("globstar **");yt.GLOBSTAR=it;var cR="[^/]",dR=cR+"*?",pR="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",uR="(?:(?!(?:\\/|^)\\.).)*?",mR=(r,e={})=>t=>yt(t,r,e);yt.filter=mR;var Qt=(r,e={})=>Object.assign({},r,e),hR=r=>{if(!r||typeof r!="object"||!Object.keys(r).length)return yt;let e=yt;return Object.assign((n,o,i={})=>e(n,o,Qt(r,i)),{Minimatch:class extends e.Minimatch{constructor(o,i={}){super(o,Qt(r,i))}static defaults(o){return e.defaults(Qt(r,o)).Minimatch}},AST:class extends e.AST{constructor(o,i,a={}){super(o,i,Qt(r,a))}static fromGlob(o,i={}){return e.AST.fromGlob(o,Qt(r,i))}},unescape:(n,o={})=>e.unescape(n,Qt(r,o)),escape:(n,o={})=>e.escape(n,Qt(r,o)),filter:(n,o={})=>e.filter(n,Qt(r,o)),defaults:n=>e.defaults(Qt(r,n)),makeRe:(n,o={})=>e.makeRe(n,Qt(r,o)),braceExpand:(n,o={})=>e.braceExpand(n,Qt(r,o)),match:(n,o,i={})=>e.match(n,o,Qt(r,i)),sep:e.sep,GLOBSTAR:it})};yt.defaults=hR;var Gf=(r,e={})=>(ra(r),e.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:(0,jf.default)(r));yt.braceExpand=Gf;var gR=(r,e={})=>new Bt(r,e).makeRe();yt.makeRe=gR;var fR=(r,e,t={})=>{let n=new Bt(e,t);return r=r.filter(o=>n.match(o)),n.options.nonull&&!r.length&&r.push(e),r};yt.match=fR;var zf=/[?*]|[+@!]\(.*?\)|\[|\]/,SR=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Bt=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){ra(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||Wf,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let o=this.globParts.map((i,a,s)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=i[0]===""&&i[1]===""&&(i[2]==="?"||!zf.test(i[2]))&&!zf.test(i[3]),c=/^[a-z]:/i.test(i[0]);if(l)return[...i.slice(0,4),...i.slice(4).map(p=>this.parse(p))];if(c)return[i[0],...i.slice(1).map(p=>this.parse(p))]}return i.map(l=>this.parse(l))});if(this.debug(this.pattern,o),this.set=o.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let a=this.set[i];a[0]===""&&a[1]===""&&this.globParts[i][2]==="?"&&typeof a[3]=="string"&&/^[a-z]:$/i.test(a[3])&&(a[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let n=0;n<e.length;n++)for(let o=0;o<e[n].length;o++)e[n][o]==="**"&&(e[n][o]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let n=-1;for(;(n=t.indexOf("**",n+1))!==-1;){let o=n;for(;t[o+1]==="**";)o++;o!==n&&t.splice(n,o-n)}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((n,o)=>{let i=n[n.length-1];return o==="**"&&i==="**"?n:o===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(n.pop(),n):(n.push(o),n)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let o=1;o<e.length-1;o++){let i=e[o];o===1&&i===""&&e[0]===""||(i==="."||i==="")&&(t=!0,e.splice(o,1),o--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=!0,e.pop())}let n=0;for(;(n=e.indexOf("..",n+1))!==-1;){let o=e[n-1];o&&o!=="."&&o!==".."&&o!=="**"&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let o=-1;for(;(o=n.indexOf("**",o+1))!==-1;){let a=o;for(;n[a+1]==="**";)a++;a>o&&n.splice(o+1,a-o);let s=n[o+1],l=n[o+2],c=n[o+3];if(s!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;t=!0,n.splice(o,1);let p=n.slice(0);p[o]="**",e.push(p),o--}if(!this.preserveMultipleSlashes){for(let a=1;a<n.length-1;a++){let s=n[a];a===1&&s===""&&n[0]===""||(s==="."||s==="")&&(t=!0,n.splice(a,1),a--)}n[0]==="."&&n.length===2&&(n[1]==="."||n[1]==="")&&(t=!0,n.pop())}let i=0;for(;(i=n.indexOf("..",i+1))!==-1;){let a=n[i-1];if(a&&a!=="."&&a!==".."&&a!=="**"){t=!0;let l=i===1&&n[i+1]==="**"?["."]:[];n.splice(i-1,2,...l),n.length===0&&n.push(""),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let o=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(o){e[t]=[],e[n]=o;break}}return e.filter(t=>t.length)}partsMatch(e,t,n=!1){let o=0,i=0,a=[],s="";for(;o<e.length&&i<t.length;)if(e[o]===t[i])a.push(s==="b"?t[i]:e[o]),o++,i++;else if(n&&e[o]==="**"&&t[i]===e[o+1])a.push(e[o]),o++;else if(n&&t[i]==="**"&&e[o]===t[i+1])a.push(t[i]),i++;else if(e[o]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(s==="b")return!1;s="a",a.push(e[o]),o++,i++}else if(t[i]==="*"&&e[o]&&(this.options.dot||!e[o].startsWith("."))&&e[o]!=="**"){if(s==="a")return!1;s="b",a.push(t[i]),o++,i++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,n=0;for(let o=0;o<e.length&&e.charAt(o)==="!";o++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){let o=this.options;if(this.isWindows){let g=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),f=!g&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),S=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),x=!S&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),v=f?3:g?0:void 0,b=x?3:S?0:void 0;if(typeof v=="number"&&typeof b=="number"){let[E,C]=[e[v],t[b]];E.toLowerCase()===C.toLowerCase()&&(t[b]=E,b>v?t=t.slice(b):v>b&&(e=e.slice(v)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var a=0,s=0,l=e.length,c=t.length;a<l&&s<c;a++,s++){this.debug("matchOne loop");var p=t[s],d=e[a];if(this.debug(t,p,d),p===!1)return!1;if(p===it){this.debug("GLOBSTAR",[t,p,d]);var m=a,u=s+1;if(u===c){for(this.debug("** at the end");a<l;a++)if(e[a]==="."||e[a]===".."||!o.dot&&e[a].charAt(0)===".")return!1;return!0}for(;m<l;){var h=e[m];if(this.debug(`
|
|
43
|
+
globstar while`,e,m,t,u,h),this.matchOne(e.slice(m),t.slice(u),n))return this.debug("globstar found match!",m,l,h),!0;if(h==="."||h===".."||!o.dot&&h.charAt(0)==="."){this.debug("dot detected!",e,m,t,u);break}this.debug("globstar swallow a segment, and continue"),m++}return!!(n&&(this.debug(`
|
|
44
|
+
>>> no match, partial?`,e,m,t,u),m===l))}let g;if(typeof p=="string"?(g=d===p,this.debug("string match",p,d,g)):(g=p.test(d),this.debug("pattern match",p,d,g)),!g)return!1}if(a===l&&s===c)return!0;if(a===l)return n;if(s===c)return a===l-1&&e[a]==="";throw new Error("wtf?")}braceExpand(){return Gf(this.pattern,this.options)}parse(e){ra(e);let t=this.options;if(e==="**")return it;if(e==="")return"";let n,o=null;(n=e.match(eR))?o=t.dot?nR:tR:(n=e.match(WA))?o=(t.nocase?t.dot?KA:qA:t.dot?VA:GA)(n[1]):(n=e.match(rR))?o=(t.nocase?t.dot?iR:oR:t.dot?aR:sR)(n):(n=e.match(YA))?o=t.dot?XA:JA:(n=e.match(ZA))&&(o=QA);let i=ko.fromGlob(e,this.options).toMMPattern();return o&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:o}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,n=t.noglobstar?dR:t.dot?pR:uR,o=new Set(t.nocase?["i"]:[]),i=e.map(l=>{let c=l.map(p=>{if(p instanceof RegExp)for(let d of p.flags.split(""))o.add(d);return typeof p=="string"?SR(p):p===it?it:p._src});return c.forEach((p,d)=>{let m=c[d+1],u=c[d-1];p!==it||u===it||(u===void 0?m!==void 0&&m!==it?c[d+1]="(?:\\/|"+n+"\\/)?"+m:c[d]=n:m===void 0?c[d-1]=u+"(?:\\/|"+n+")?":m!==it&&(c[d-1]=u+"(?:\\/|\\/"+n+"\\/)"+m,c[d+1]=it))}),c.filter(p=>p!==it).join("/")}).join("|"),[a,s]=e.length>1?["(?:",")"]:["",""];i="^"+a+i+s+"$",this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...o].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&t)return!0;let n=this.options;this.isWindows&&(e=e.split("\\").join("/"));let o=this.slashSplit(e);this.debug(this.pattern,"split",o);let i=this.set;this.debug(this.pattern,"set",i);let a=o[o.length-1];if(!a)for(let s=o.length-2;!a&&s>=0;s--)a=o[s];for(let s=0;s<i.length;s++){let l=i[s],c=o;if(n.matchBase&&l.length===1&&(c=[a]),this.matchOne(c,l,t))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(e){return yt.defaults(e).Minimatch}};yt.AST=ko;yt.Minimatch=Bt;yt.escape=Oo;yt.unescape=cn;import{fileURLToPath as YR}from"node:url";var No=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,qf=new Set,vd=typeof process=="object"&&process?process:{},Kf=(r,e,t,n)=>{typeof vd.emitWarning=="function"?vd.emitWarning(r,e,t,n):console.error(`[${t}] ${e}: ${r}`)},_s=globalThis.AbortController,Vf=globalThis.AbortSignal;if(typeof _s>"u"){Vf=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,o){this._onabort.push(o)}},_s=class{constructor(){e()}signal=new Vf;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let o of this.signal._onabort)o(n);this.signal.onabort?.(n)}}};let r=vd.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{r&&(r=!1,Kf("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var yR=r=>!qf.has(r),oq=Symbol("type"),nr=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),Yf=r=>nr(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?Mo:null:null,Mo=class extends Array{constructor(e){super(e),this.fill(0)}},xd=class r{heap;length;static#e=!1;static create(e){let t=Yf(e);if(!t)return[];r.#e=!0;let n=new r(e,t);return r.#e=!1,n}constructor(e,t){if(!r.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},ia=class r{#e;#t;#i;#r;#a;#w;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#p;#s;#l;#o;#f;#S;#m;#u;#T;#g;#E;#C;#b;#v;#x;#h;static unsafeExposeInternals(e){return{starts:e.#C,ttls:e.#b,sizes:e.#E,keyMap:e.#s,keyList:e.#l,valList:e.#o,next:e.#f,prev:e.#S,get head(){return e.#m},get tail(){return e.#u},free:e.#T,isBackgroundFetch:t=>e.#d(t),backgroundFetch:(t,n,o,i)=>e.#U(t,n,o,i),moveToTail:t=>e.#z(t),indexes:t=>e.#R(t),rindexes:t=>e.#I(t),isStale:t=>e.#y(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#p}get size(){return this.#c}get fetchMethod(){return this.#a}get memoMethod(){return this.#w}get dispose(){return this.#i}get disposeAfter(){return this.#r}constructor(e){let{max:t=0,ttl:n,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:a,updateAgeOnHas:s,allowStale:l,dispose:c,disposeAfter:p,noDisposeOnSet:d,noUpdateTTL:m,maxSize:u=0,maxEntrySize:h=0,sizeCalculation:g,fetchMethod:f,memoMethod:S,noDeleteOnFetchRejection:x,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:b,allowStaleOnFetchAbort:E,ignoreFetchAbort:C}=e;if(t!==0&&!nr(t))throw new TypeError("max option must be a nonnegative integer");let I=t?Yf(t):Array;if(!I)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=u,this.maxEntrySize=h||this.#t,this.sizeCalculation=g,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(S!==void 0&&typeof S!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=S,f!==void 0&&typeof f!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#a=f,this.#x=!!f,this.#s=new Map,this.#l=new Array(t).fill(void 0),this.#o=new Array(t).fill(void 0),this.#f=new I(t),this.#S=new I(t),this.#m=0,this.#u=0,this.#T=xd.create(t),this.#c=0,this.#p=0,typeof c=="function"&&(this.#i=c),typeof p=="function"?(this.#r=p,this.#g=[]):(this.#r=void 0,this.#g=void 0),this.#v=!!this.#i,this.#h=!!this.#r,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!m,this.noDeleteOnFetchRejection=!!x,this.allowStaleOnFetchRejection=!!b,this.allowStaleOnFetchAbort=!!E,this.ignoreFetchAbort=!!C,this.maxEntrySize!==0){if(this.#t!==0&&!nr(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!nr(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#L()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!v,this.updateAgeOnGet=!!a,this.updateAgeOnHas=!!s,this.ttlResolution=nr(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=n||0,this.ttl){if(!nr(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#t){let M="LRU_CACHE_UNBOUNDED";yR(M)&&(qf.add(M),Kf("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",M,r))}}getRemainingTTL(e){return this.#s.has(e)?1/0:0}#P(){let e=new Mo(this.#e),t=new Mo(this.#e);this.#b=e,this.#C=t,this.#O=(i,a,s=No.now())=>{if(t[i]=a!==0?s:0,e[i]=a,a!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#y(i)&&this.#k(this.#l[i],"expire")},a+1);l.unref&&l.unref()}},this.#A=i=>{t[i]=e[i]!==0?No.now():0},this.#n=(i,a)=>{if(e[a]){let s=e[a],l=t[a];if(!s||!l)return;i.ttl=s,i.start=l,i.now=n||o();let c=i.now-l;i.remainingTTL=s-c}};let n=0,o=()=>{let i=No.now();if(this.ttlResolution>0){n=i;let a=setTimeout(()=>n=0,this.ttlResolution);a.unref&&a.unref()}return i};this.getRemainingTTL=i=>{let a=this.#s.get(i);if(a===void 0)return 0;let s=e[a],l=t[a];if(!s||!l)return 1/0;let c=(n||o())-l;return s-c},this.#y=i=>{let a=t[i],s=e[i];return!!s&&!!a&&(n||o())-a>s}}#A=()=>{};#n=()=>{};#O=()=>{};#y=()=>!1;#L(){let e=new Mo(this.#e);this.#p=0,this.#E=e,this.#N=t=>{this.#p-=e[t],e[t]=0},this.#_=(t,n,o,i)=>{if(this.#d(n))return 0;if(!nr(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(n,t),!nr(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#M=(t,n,o)=>{if(e[t]=n,this.#t){let i=this.#t-e[t];for(;this.#p>i;)this.#D(!0)}this.#p+=e[t],o&&(o.entrySize=n,o.totalCalculatedSize=this.#p)}}#N=e=>{};#M=(e,t,n)=>{};#_=(e,t,n,o)=>{if(n||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#R({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#u;!(!this.#F(t)||((e||!this.#y(t))&&(yield t),t===this.#m));)t=this.#S[t]}*#I({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#F(t)||((e||!this.#y(t))&&(yield t),t===this.#u));)t=this.#f[t]}#F(e){return e!==void 0&&this.#s.get(this.#l[e])===e}*entries(){for(let e of this.#R())this.#o[e]!==void 0&&this.#l[e]!==void 0&&!this.#d(this.#o[e])&&(yield[this.#l[e],this.#o[e]])}*rentries(){for(let e of this.#I())this.#o[e]!==void 0&&this.#l[e]!==void 0&&!this.#d(this.#o[e])&&(yield[this.#l[e],this.#o[e]])}*keys(){for(let e of this.#R()){let t=this.#l[e];t!==void 0&&!this.#d(this.#o[e])&&(yield t)}}*rkeys(){for(let e of this.#I()){let t=this.#l[e];t!==void 0&&!this.#d(this.#o[e])&&(yield t)}}*values(){for(let e of this.#R())this.#o[e]!==void 0&&!this.#d(this.#o[e])&&(yield this.#o[e])}*rvalues(){for(let e of this.#I())this.#o[e]!==void 0&&!this.#d(this.#o[e])&&(yield this.#o[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let n of this.#R()){let o=this.#o[n],i=this.#d(o)?o.__staleWhileFetching:o;if(i!==void 0&&e(i,this.#l[n],this))return this.get(this.#l[n],t)}}forEach(e,t=this){for(let n of this.#R()){let o=this.#o[n],i=this.#d(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#l[n],this)}}rforEach(e,t=this){for(let n of this.#I()){let o=this.#o[n],i=this.#d(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#l[n],this)}}purgeStale(){let e=!1;for(let t of this.#I({allowStale:!0}))this.#y(t)&&(this.#k(this.#l[t],"expire"),e=!0);return e}info(e){let t=this.#s.get(e);if(t===void 0)return;let n=this.#o[t],o=this.#d(n)?n.__staleWhileFetching:n;if(o===void 0)return;let i={value:o};if(this.#b&&this.#C){let a=this.#b[t],s=this.#C[t];if(a&&s){let l=a-(No.now()-s);i.ttl=l,i.start=Date.now()}}return this.#E&&(i.size=this.#E[t]),i}dump(){let e=[];for(let t of this.#R({allowStale:!0})){let n=this.#l[t],o=this.#o[t],i=this.#d(o)?o.__staleWhileFetching:o;if(i===void 0||n===void 0)continue;let a={value:i};if(this.#b&&this.#C){a.ttl=this.#b[t];let s=No.now()-this.#C[t];a.start=Math.floor(Date.now()-s)}this.#E&&(a.size=this.#E[t]),e.unshift([n,a])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let o=Date.now()-n.start;n.start=No.now()-o}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:l}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,p=this.#_(e,t,n.size||0,s);if(this.maxEntrySize&&p>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#k(e,"set"),this;let d=this.#c===0?void 0:this.#s.get(e);if(d===void 0)d=this.#c===0?this.#u:this.#T.length!==0?this.#T.pop():this.#c===this.#e?this.#D(!1):this.#c,this.#l[d]=e,this.#o[d]=t,this.#s.set(e,d),this.#f[this.#u]=d,this.#S[d]=this.#u,this.#u=d,this.#c++,this.#M(d,p,l),l&&(l.set="add"),c=!1;else{this.#z(d);let m=this.#o[d];if(t!==m){if(this.#x&&this.#d(m)){m.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:u}=m;u!==void 0&&!a&&(this.#v&&this.#i?.(u,e,"set"),this.#h&&this.#g?.push([u,e,"set"]))}else a||(this.#v&&this.#i?.(m,e,"set"),this.#h&&this.#g?.push([m,e,"set"]));if(this.#N(d),this.#M(d,p,l),this.#o[d]=t,l){l.set="replace";let u=m&&this.#d(m)?m.__staleWhileFetching:m;u!==void 0&&(l.oldValue=u)}}else l&&(l.set="update")}if(o!==0&&!this.#b&&this.#P(),this.#b&&(c||this.#O(d,o,i),l&&this.#n(l,d)),!a&&this.#h&&this.#g){let m=this.#g,u;for(;u=m?.shift();)this.#r?.(...u)}return this}pop(){try{for(;this.#c;){let e=this.#o[this.#m];if(this.#D(!0),this.#d(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#h&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}}#D(e){let t=this.#m,n=this.#l[t],o=this.#o[t];return this.#x&&this.#d(o)?o.__abortController.abort(new Error("evicted")):(this.#v||this.#h)&&(this.#v&&this.#i?.(o,n,"evict"),this.#h&&this.#g?.push([o,n,"evict"])),this.#N(t),e&&(this.#l[t]=void 0,this.#o[t]=void 0,this.#T.push(t)),this.#c===1?(this.#m=this.#u=0,this.#T.length=0):this.#m=this.#f[t],this.#s.delete(n),this.#c--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:o}=t,i=this.#s.get(e);if(i!==void 0){let a=this.#o[i];if(this.#d(a)&&a.__staleWhileFetching===void 0)return!1;if(this.#y(i))o&&(o.has="stale",this.#n(o,i));else return n&&this.#A(i),o&&(o.has="hit",this.#n(o,i)),!0}else o&&(o.has="miss");return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,o=this.#s.get(e);if(o===void 0||!n&&this.#y(o))return;let i=this.#o[o];return this.#d(i)?i.__staleWhileFetching:i}#U(e,t,n,o){let i=t===void 0?void 0:this.#o[t];if(this.#d(i))return i;let a=new _s,{signal:s}=n;s?.addEventListener("abort",()=>a.abort(s.reason),{signal:a.signal});let l={signal:a.signal,options:n,context:o},c=(g,f=!1)=>{let{aborted:S}=a.signal,x=n.ignoreFetchAbort&&g!==void 0;if(n.status&&(S&&!f?(n.status.fetchAborted=!0,n.status.fetchError=a.signal.reason,x&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),S&&!x&&!f)return d(a.signal.reason);let v=u;return this.#o[t]===u&&(g===void 0?v.__staleWhileFetching?this.#o[t]=v.__staleWhileFetching:this.#k(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,g,l.options))),g},p=g=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=g),d(g)),d=g=>{let{aborted:f}=a.signal,S=f&&n.allowStaleOnFetchAbort,x=S||n.allowStaleOnFetchRejection,v=x||n.noDeleteOnFetchRejection,b=u;if(this.#o[t]===u&&(!v||b.__staleWhileFetching===void 0?this.#k(e,"fetch"):S||(this.#o[t]=b.__staleWhileFetching)),x)return n.status&&b.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),b.__staleWhileFetching;if(b.__returned===b)throw g},m=(g,f)=>{let S=this.#a?.(e,i,l);S&&S instanceof Promise&&S.then(x=>g(x===void 0?void 0:x),f),a.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(g(void 0),n.allowStaleOnFetchAbort&&(g=x=>c(x,!0)))})};n.status&&(n.status.fetchDispatched=!0);let u=new Promise(m).then(c,p),h=Object.assign(u,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,h,{...l.options,status:void 0}),t=this.#s.get(e)):this.#o[t]=h,h}#d(e){if(!this.#x)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof _s}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:p=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:m=this.allowStaleOnFetchRejection,ignoreFetchAbort:u=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:g,forceRefresh:f=!1,status:S,signal:x}=t;if(!this.#x)return S&&(S.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:S});let v={allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:a,noDisposeOnSet:s,size:l,sizeCalculation:c,noUpdateTTL:p,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:h,ignoreFetchAbort:u,status:S,signal:x},b=this.#s.get(e);if(b===void 0){S&&(S.fetch="miss");let E=this.#U(e,b,v,g);return E.__returned=E}else{let E=this.#o[b];if(this.#d(E)){let z=n&&E.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",z&&(S.returnedStale=!0)),z?E.__staleWhileFetching:E.__returned=E}let C=this.#y(b);if(!f&&!C)return S&&(S.fetch="hit"),this.#z(b),o&&this.#A(b),S&&this.#n(S,b),E;let I=this.#U(e,b,v,g),L=I.__staleWhileFetching!==void 0&&n;return S&&(S.fetch=C?"stale":"refresh",L&&C&&(S.returnedStale=!0)),L?I.__staleWhileFetching:I.__returned=I}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,t={}){let n=this.#w;if(!n)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:i,...a}=t,s=this.get(e,a);if(!i&&s!==void 0)return s;let l=n(e,s,{options:a,context:o});return this.set(e,l,a),l}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:a}=t,s=this.#s.get(e);if(s!==void 0){let l=this.#o[s],c=this.#d(l);return a&&this.#n(a,s),this.#y(s)?(a&&(a.get="stale"),c?(a&&n&&l.__staleWhileFetching!==void 0&&(a.returnedStale=!0),n?l.__staleWhileFetching:void 0):(i||this.#k(e,"expire"),a&&n&&(a.returnedStale=!0),n?l:void 0)):(a&&(a.get="hit"),c?l.__staleWhileFetching:(this.#z(s),o&&this.#A(s),l))}else a&&(a.get="miss")}#B(e,t){this.#S[t]=e,this.#f[e]=t}#z(e){e!==this.#u&&(e===this.#m?this.#m=this.#f[e]:this.#B(this.#S[e],this.#f[e]),this.#B(this.#u,e),this.#u=e)}delete(e){return this.#k(e,"delete")}#k(e,t){let n=!1;if(this.#c!==0){let o=this.#s.get(e);if(o!==void 0)if(n=!0,this.#c===1)this.#j(t);else{this.#N(o);let i=this.#o[o];if(this.#d(i)?i.__abortController.abort(new Error("deleted")):(this.#v||this.#h)&&(this.#v&&this.#i?.(i,e,t),this.#h&&this.#g?.push([i,e,t])),this.#s.delete(e),this.#l[o]=void 0,this.#o[o]=void 0,o===this.#u)this.#u=this.#S[o];else if(o===this.#m)this.#m=this.#f[o];else{let a=this.#S[o];this.#f[a]=this.#f[o];let s=this.#f[o];this.#S[s]=this.#S[o]}this.#c--,this.#T.push(o)}}if(this.#h&&this.#g?.length){let o=this.#g,i;for(;i=o?.shift();)this.#r?.(...i)}return n}clear(){return this.#j("delete")}#j(e){for(let t of this.#I({allowStale:!0})){let n=this.#o[t];if(this.#d(n))n.__abortController.abort(new Error("deleted"));else{let o=this.#l[t];this.#v&&this.#i?.(n,o,e),this.#h&&this.#g?.push([n,o,e])}}if(this.#s.clear(),this.#o.fill(void 0),this.#l.fill(void 0),this.#b&&this.#C&&(this.#b.fill(0),this.#C.fill(0)),this.#E&&this.#E.fill(0),this.#m=0,this.#u=0,this.#T.length=0,this.#p=0,this.#c=0,this.#h&&this.#g){let t=this.#g,n;for(;n=t?.shift();)this.#r?.(...n)}}};import{posix as PR,win32 as Od}from"node:path";import{fileURLToPath as LR}from"node:url";import{lstatSync as kR,readdir as OR,readdirSync as NR,readlinkSync as MR,realpathSync as _R}from"fs";import*as FR from"node:fs";import{lstat as UR,readdir as BR,readlink as zR,realpath as jR}from"node:fs/promises";import{EventEmitter as Pd}from"node:events";import eS from"node:stream";import{StringDecoder as bR}from"node:string_decoder";var Jf=typeof process=="object"&&process?process:{stdout:null,stderr:null},wR=r=>!!r&&typeof r=="object"&&(r instanceof or||r instanceof eS||vR(r)||xR(r)),vR=r=>!!r&&typeof r=="object"&&r instanceof Pd&&typeof r.pipe=="function"&&r.pipe!==eS.Writable.prototype.pipe,xR=r=>!!r&&typeof r=="object"&&r instanceof Pd&&typeof r.write=="function"&&typeof r.end=="function",Mn=Symbol("EOF"),_n=Symbol("maybeEmitEnd"),rr=Symbol("emittedEnd"),Fs=Symbol("emittingEnd"),aa=Symbol("emittedError"),Ds=Symbol("closed"),Xf=Symbol("read"),Us=Symbol("flush"),Zf=Symbol("flushChunk"),dn=Symbol("encoding"),_o=Symbol("decoder"),et=Symbol("flowing"),sa=Symbol("paused"),Fo=Symbol("resume"),tt=Symbol("buffer"),bt=Symbol("pipes"),nt=Symbol("bufferLength"),Td=Symbol("bufferPush"),Bs=Symbol("bufferShift"),mt=Symbol("objectMode"),Fe=Symbol("destroyed"),Ed=Symbol("error"),Cd=Symbol("emitData"),Qf=Symbol("emitEnd"),Ad=Symbol("emitEnd2"),xn=Symbol("async"),Rd=Symbol("abort"),zs=Symbol("aborted"),la=Symbol("signal"),Vr=Symbol("dataListeners"),zt=Symbol("discarded"),ca=r=>Promise.resolve().then(r),TR=r=>r(),ER=r=>r==="end"||r==="finish"||r==="prefinish",CR=r=>r instanceof ArrayBuffer||!!r&&typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,AR=r=>!Buffer.isBuffer(r)&&ArrayBuffer.isView(r),js=class{src;dest;opts;ondrain;constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[Fo](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Id=class extends js{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,n){super(e,t,n),this.proxyErrors=o=>t.emit("error",o),e.on("error",this.proxyErrors)}},RR=r=>!!r.objectMode,IR=r=>!r.objectMode&&!!r.encoding&&r.encoding!=="buffer",or=class extends Pd{[et]=!1;[sa]=!1;[bt]=[];[tt]=[];[mt];[dn];[xn];[_o];[Mn]=!1;[rr]=!1;[Fs]=!1;[Ds]=!1;[aa]=null;[nt]=0;[Fe]=!1;[la];[zs]=!1;[Vr]=0;[zt]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");RR(t)?(this[mt]=!0,this[dn]=null):IR(t)?(this[dn]=t.encoding,this[mt]=!1):(this[mt]=!1,this[dn]=null),this[xn]=!!t.async,this[_o]=this[dn]?new bR(this[dn]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[tt]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[bt]});let{signal:n}=t;n&&(this[la]=n,n.aborted?this[Rd]():n.addEventListener("abort",()=>this[Rd]()))}get bufferLength(){return this[nt]}get encoding(){return this[dn]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[mt]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[xn]}set async(e){this[xn]=this[xn]||!!e}[Rd](){this[zs]=!0,this.emit("abort",this[la]?.reason),this.destroy(this[la]?.reason)}get aborted(){return this[zs]}set aborted(e){}write(e,t,n){if(this[zs])return!1;if(this[Mn])throw new Error("write after end");if(this[Fe])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(n=t,t="utf8"),t||(t="utf8");let o=this[xn]?ca:TR;if(!this[mt]&&!Buffer.isBuffer(e)){if(AR(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(CR(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[mt]?(this[et]&&this[nt]!==0&&this[Us](!0),this[et]?this.emit("data",e):this[Td](e),this[nt]!==0&&this.emit("readable"),n&&o(n),this[et]):e.length?(typeof e=="string"&&!(t===this[dn]&&!this[_o]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[dn]&&(e=this[_o].write(e)),this[et]&&this[nt]!==0&&this[Us](!0),this[et]?this.emit("data",e):this[Td](e),this[nt]!==0&&this.emit("readable"),n&&o(n),this[et]):(this[nt]!==0&&this.emit("readable"),n&&o(n),this[et])}read(e){if(this[Fe])return null;if(this[zt]=!1,this[nt]===0||e===0||e&&e>this[nt])return this[_n](),null;this[mt]&&(e=null),this[tt].length>1&&!this[mt]&&(this[tt]=[this[dn]?this[tt].join(""):Buffer.concat(this[tt],this[nt])]);let t=this[Xf](e||null,this[tt][0]);return this[_n](),t}[Xf](e,t){if(this[mt])this[Bs]();else{let n=t;e===n.length||e===null?this[Bs]():typeof n=="string"?(this[tt][0]=n.slice(e),t=n.slice(0,e),this[nt]-=e):(this[tt][0]=n.subarray(e),t=n.subarray(0,e),this[nt]-=e)}return this.emit("data",t),!this[tt].length&&!this[Mn]&&this.emit("drain"),t}end(e,t,n){return typeof e=="function"&&(n=e,e=void 0),typeof t=="function"&&(n=t,t="utf8"),e!==void 0&&this.write(e,t),n&&this.once("end",n),this[Mn]=!0,this.writable=!1,(this[et]||!this[sa])&&this[_n](),this}[Fo](){this[Fe]||(!this[Vr]&&!this[bt].length&&(this[zt]=!0),this[sa]=!1,this[et]=!0,this.emit("resume"),this[tt].length?this[Us]():this[Mn]?this[_n]():this.emit("drain"))}resume(){return this[Fo]()}pause(){this[et]=!1,this[sa]=!0,this[zt]=!1}get destroyed(){return this[Fe]}get flowing(){return this[et]}get paused(){return this[sa]}[Td](e){this[mt]?this[nt]+=1:this[nt]+=e.length,this[tt].push(e)}[Bs](){return this[mt]?this[nt]-=1:this[nt]-=this[tt][0].length,this[tt].shift()}[Us](e=!1){do;while(this[Zf](this[Bs]())&&this[tt].length);!e&&!this[tt].length&&!this[Mn]&&this.emit("drain")}[Zf](e){return this.emit("data",e),this[et]}pipe(e,t){if(this[Fe])return e;this[zt]=!1;let n=this[rr];return t=t||{},e===Jf.stdout||e===Jf.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,n?t.end&&e.end():(this[bt].push(t.proxyErrors?new Id(this,e,t):new js(this,e,t)),this[xn]?ca(()=>this[Fo]()):this[Fo]()),e}unpipe(e){let t=this[bt].find(n=>n.dest===e);t&&(this[bt].length===1?(this[et]&&this[Vr]===0&&(this[et]=!1),this[bt]=[]):this[bt].splice(this[bt].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let n=super.on(e,t);if(e==="data")this[zt]=!1,this[Vr]++,!this[bt].length&&!this[et]&&this[Fo]();else if(e==="readable"&&this[nt]!==0)super.emit("readable");else if(ER(e)&&this[rr])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[aa]){let o=t;this[xn]?ca(()=>o.call(this,this[aa])):o.call(this,this[aa])}return n}removeListener(e,t){return this.off(e,t)}off(e,t){let n=super.off(e,t);return e==="data"&&(this[Vr]=this.listeners("data").length,this[Vr]===0&&!this[zt]&&!this[bt].length&&(this[et]=!1)),n}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Vr]=0,!this[zt]&&!this[bt].length&&(this[et]=!1)),t}get emittedEnd(){return this[rr]}[_n](){!this[Fs]&&!this[rr]&&!this[Fe]&&this[tt].length===0&&this[Mn]&&(this[Fs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ds]&&this.emit("close"),this[Fs]=!1)}emit(e,...t){let n=t[0];if(e!=="error"&&e!=="close"&&e!==Fe&&this[Fe])return!1;if(e==="data")return!this[mt]&&!n?!1:this[xn]?(ca(()=>this[Cd](n)),!0):this[Cd](n);if(e==="end")return this[Qf]();if(e==="close"){if(this[Ds]=!0,!this[rr]&&!this[Fe])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[aa]=n,super.emit(Ed,n);let i=!this[la]||this.listeners("error").length?super.emit("error",n):!1;return this[_n](),i}else if(e==="resume"){let i=super.emit("resume");return this[_n](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let o=super.emit(e,...t);return this[_n](),o}[Cd](e){for(let n of this[bt])n.dest.write(e)===!1&&this.pause();let t=this[zt]?!1:super.emit("data",e);return this[_n](),t}[Qf](){return this[rr]?!1:(this[rr]=!0,this.readable=!1,this[xn]?(ca(()=>this[Ad]()),!0):this[Ad]())}[Ad](){if(this[_o]){let t=this[_o].end();if(t){for(let n of this[bt])n.dest.write(t);this[zt]||super.emit("data",t)}}for(let t of this[bt])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[mt]||(e.dataLength=0);let t=this.promise();return this.on("data",n=>{e.push(n),this[mt]||(e.dataLength+=n.length)}),await t,e}async concat(){if(this[mt])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[dn]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(Fe,()=>t(new Error("stream destroyed"))),this.on("error",n=>t(n)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[zt]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();let o=this.read();if(o!==null)return Promise.resolve({done:!1,value:o});if(this[Mn])return t();let i,a,s=d=>{this.off("data",l),this.off("end",c),this.off(Fe,p),t(),a(d)},l=d=>{this.off("error",s),this.off("end",c),this.off(Fe,p),this.pause(),i({value:d,done:!!this[Mn]})},c=()=>{this.off("error",s),this.off("data",l),this.off(Fe,p),t(),i({done:!0,value:void 0})},p=()=>s(new Error("stream destroyed"));return new Promise((d,m)=>{a=m,i=d,this.once(Fe,p),this.once("error",s),this.once("end",c),this.once("data",l)})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[zt]=!1;let e=!1,t=()=>(this.pause(),this.off(Ed,t),this.off(Fe,t),this.off("end",t),e=!0,{done:!0,value:void 0}),n=()=>{if(e)return t();let o=this.read();return o===null?t():{done:!1,value:o}};return this.once("end",t),this.once(Ed,t),this.once(Fe,t),{next:n,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[Fe])return e?this.emit("error",e):this.emit(Fe),this;this[Fe]=!0,this[zt]=!0,this[tt].length=0,this[nt]=0;let t=this;return typeof t.close=="function"&&!this[Ds]&&t.close(),e?this.emit("error",e):this.emit(Fe),this}static get isStream(){return wR}};var DR=_R.native,pa={lstatSync:kR,readdir:OR,readdirSync:NR,readlinkSync:MR,realpathSync:DR,promises:{lstat:UR,readdir:BR,readlink:zR,realpath:jR}},iS=r=>!r||r===pa||r===FR?pa:{...pa,...r,promises:{...pa.promises,...r.promises||{}}},aS=/^\\\\\?\\([a-z]:)\\?$/i,HR=r=>r.replace(/\//g,"\\").replace(aS,"$1\\"),$R=/[\\\/]/,tn=0,sS=1,lS=2,Tn=4,cS=6,dS=8,qr=10,pS=12,en=15,da=~en,Ld=16,tS=32,ua=64,pn=128,Hs=256,Ws=512,nS=ua|pn|Ws,WR=1023,kd=r=>r.isFile()?dS:r.isDirectory()?Tn:r.isSymbolicLink()?qr:r.isCharacterDevice()?lS:r.isBlockDevice()?cS:r.isSocket()?pS:r.isFIFO()?sS:tn,rS=new Map,ma=r=>{let e=rS.get(r);if(e)return e;let t=r.normalize("NFKD");return rS.set(r,t),t},oS=new Map,$s=r=>{let e=oS.get(r);if(e)return e;let t=ma(r.toLowerCase());return oS.set(r,t),t},Gs=class extends ia{constructor(){super({max:256})}},Nd=class extends ia{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},uS=Symbol("PathScurry setAsCwd"),ht=class{name;root;roots;parent;nocase;isCWD=!1;#e;#t;get dev(){return this.#t}#i;get mode(){return this.#i}#r;get nlink(){return this.#r}#a;get uid(){return this.#a}#w;get gid(){return this.#w}#c;get rdev(){return this.#c}#p;get blksize(){return this.#p}#s;get ino(){return this.#s}#l;get size(){return this.#l}#o;get blocks(){return this.#o}#f;get atimeMs(){return this.#f}#S;get mtimeMs(){return this.#S}#m;get ctimeMs(){return this.#m}#u;get birthtimeMs(){return this.#u}#T;get atime(){return this.#T}#g;get mtime(){return this.#g}#E;get ctime(){return this.#E}#C;get birthtime(){return this.#C}#b;#v;#x;#h;#P;#A;#n;#O;#y;#L;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=tn,n,o,i,a,s){this.name=e,this.#b=i?$s(e):ma(e),this.#n=t&WR,this.nocase=i,this.roots=o,this.root=n||this,this.#O=a,this.#x=s.fullpath,this.#P=s.relative,this.#A=s.relativePosix,this.parent=s.parent,this.parent?this.#e=this.parent.#e:this.#e=iS(s.fs)}depth(){return this.#v!==void 0?this.#v:this.parent?this.#v=this.parent.depth()+1:this.#v=0}childrenCache(){return this.#O}resolve(e){if(!e)return this;let t=this.getRootString(e),o=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#N(o):this.#N(o)}#N(e){let t=this;for(let n of e)t=t.child(n);return t}children(){let e=this.#O.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#O.set(this,t),this.#n&=~Ld,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let n=this.children(),o=this.nocase?$s(e):ma(e);for(let l of n)if(l.#b===o)return l;let i=this.parent?this.sep:"",a=this.#x?this.#x+i+e:void 0,s=this.newChild(e,tn,{...t,parent:this,fullpath:a});return this.canReaddir()||(s.#n|=pn),n.push(s),s}relative(){if(this.isCWD)return"";if(this.#P!==void 0)return this.#P;let e=this.name,t=this.parent;if(!t)return this.#P=this.name;let n=t.relative();return n+(!n||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#A!==void 0)return this.#A;let e=this.name,t=this.parent;if(!t)return this.#A=this.fullpathPosix();let n=t.relativePosix();return n+(!n||!t.parent?"":"/")+e}fullpath(){if(this.#x!==void 0)return this.#x;let e=this.name,t=this.parent;if(!t)return this.#x=this.name;let o=t.fullpath()+(t.parent?this.sep:"")+e;return this.#x=o}fullpathPosix(){if(this.#h!==void 0)return this.#h;if(this.sep==="/")return this.#h=this.fullpath();if(!this.parent){let o=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(o)?this.#h=`//?/${o}`:this.#h=o}let e=this.parent,t=e.fullpathPosix(),n=t+(!t||!e.parent?"":"/")+this.name;return this.#h=n}isUnknown(){return(this.#n&en)===tn}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#n&en)===dS}isDirectory(){return(this.#n&en)===Tn}isCharacterDevice(){return(this.#n&en)===lS}isBlockDevice(){return(this.#n&en)===cS}isFIFO(){return(this.#n&en)===sS}isSocket(){return(this.#n&en)===pS}isSymbolicLink(){return(this.#n&qr)===qr}lstatCached(){return this.#n&tS?this:void 0}readlinkCached(){return this.#y}realpathCached(){return this.#L}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#y)return!0;if(!this.parent)return!1;let e=this.#n&en;return!(e!==tn&&e!==qr||this.#n&Hs||this.#n&pn)}calledReaddir(){return!!(this.#n&Ld)}isENOENT(){return!!(this.#n&pn)}isNamed(e){return this.nocase?this.#b===$s(e):this.#b===ma(e)}async readlink(){let e=this.#y;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#e.promises.readlink(this.fullpath()),n=(await this.parent.realpath())?.resolve(t);if(n)return this.#y=n}catch(t){this.#d(t.code);return}}readlinkSync(){let e=this.#y;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#e.readlinkSync(this.fullpath()),n=this.parent.realpathSync()?.resolve(t);if(n)return this.#y=n}catch(t){this.#d(t.code);return}}#M(e){this.#n|=Ld;for(let t=e.provisional;t<e.length;t++){let n=e[t];n&&n.#_()}}#_(){this.#n&pn||(this.#n=(this.#n|pn)&da,this.#R())}#R(){let e=this.children();e.provisional=0;for(let t of e)t.#_()}#I(){this.#n|=Ws,this.#F()}#F(){if(this.#n&ua)return;let e=this.#n;(e&en)===Tn&&(e&=da),this.#n=e|ua,this.#R()}#D(e=""){e==="ENOTDIR"||e==="EPERM"?this.#F():e==="ENOENT"?this.#_():this.children().provisional=0}#U(e=""){e==="ENOTDIR"?this.parent.#F():e==="ENOENT"&&this.#_()}#d(e=""){let t=this.#n;t|=Hs,e==="ENOENT"&&(t|=pn),(e==="EINVAL"||e==="UNKNOWN")&&(t&=da),this.#n=t,e==="ENOTDIR"&&this.parent&&this.parent.#F()}#B(e,t){return this.#k(e,t)||this.#z(e,t)}#z(e,t){let n=kd(e),o=this.newChild(e.name,n,{parent:this}),i=o.#n&en;return i!==Tn&&i!==qr&&i!==tn&&(o.#n|=ua),t.unshift(o),t.provisional++,o}#k(e,t){for(let n=t.provisional;n<t.length;n++){let o=t[n];if((this.nocase?$s(e.name):ma(e.name))===o.#b)return this.#j(e,o,n,t)}}#j(e,t,n,o){let i=t.name;return t.#n=t.#n&da|kd(e),i!==e.name&&(t.name=e.name),n!==o.provisional&&(n===o.length-1?o.pop():o.splice(n,1),o.unshift(t)),o.provisional++,t}async lstat(){if(!(this.#n&pn))try{return this.#G(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#U(e.code)}}lstatSync(){if(!(this.#n&pn))try{return this.#G(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#U(e.code)}}#G(e){let{atime:t,atimeMs:n,birthtime:o,birthtimeMs:i,blksize:a,blocks:s,ctime:l,ctimeMs:c,dev:p,gid:d,ino:m,mode:u,mtime:h,mtimeMs:g,nlink:f,rdev:S,size:x,uid:v}=e;this.#T=t,this.#f=n,this.#C=o,this.#u=i,this.#p=a,this.#o=s,this.#E=l,this.#m=c,this.#t=p,this.#w=d,this.#s=m,this.#i=u,this.#g=h,this.#S=g,this.#r=f,this.#c=S,this.#l=x,this.#a=v;let b=kd(e);this.#n=this.#n&da|b|tS,b!==tn&&b!==Tn&&b!==qr&&(this.#n|=ua)}#$=[];#W=!1;#V(e){this.#W=!1;let t=this.#$.slice();this.#$.length=0,t.forEach(n=>n(null,e))}readdirCB(e,t=!1){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let n=this.children();if(this.calledReaddir()){let i=n.slice(0,n.provisional);t?e(null,i):queueMicrotask(()=>e(null,i));return}if(this.#$.push(e),this.#W)return;this.#W=!0;let o=this.fullpath();this.#e.readdir(o,{withFileTypes:!0},(i,a)=>{if(i)this.#D(i.code),n.provisional=0;else{for(let s of a)this.#B(s,n);this.#M(n)}this.#V(n.slice(0,n.provisional))})}#H;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(this.#H)await this.#H;else{let n=()=>{};this.#H=new Promise(o=>n=o);try{for(let o of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#B(o,e);this.#M(e)}catch(o){this.#D(o.code),e.provisional=0}this.#H=void 0,n()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let n of this.#e.readdirSync(t,{withFileTypes:!0}))this.#B(n,e);this.#M(e)}catch(n){this.#D(n.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#n&nS)return!1;let e=en&this.#n;return e===tn||e===Tn||e===qr}shouldWalk(e,t){return(this.#n&Tn)===Tn&&!(this.#n&nS)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#L)return this.#L;if(!((Ws|Hs|pn)&this.#n))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#L=this.resolve(e)}catch{this.#I()}}realpathSync(){if(this.#L)return this.#L;if(!((Ws|Hs|pn)&this.#n))try{let e=this.#e.realpathSync(this.fullpath());return this.#L=this.resolve(e)}catch{this.#I()}}[uS](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),n=[],o=this;for(;o&&o.parent;)t.add(o),o.#P=n.join(this.sep),o.#A=n.join("/"),o=o.parent,n.push("..");for(o=e;o&&o.parent&&!t.has(o);)o.#P=void 0,o.#A=void 0,o=o.parent}},Vs=class r extends ht{sep="\\";splitSep=$R;constructor(e,t=tn,n,o,i,a,s){super(e,t,n,o,i,a,s)}newChild(e,t=tn,n={}){return new r(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}getRootString(e){return Od.parse(e).root}getRoot(e){if(e=HR(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,n]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=n;return this.roots[e]=new Do(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(aS,"$1\\"),e===t}},qs=class r extends ht{splitSep="/";sep="/";constructor(e,t=tn,n,o,i,a,s){super(e,t,n,o,i,a,s)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=tn,n={}){return new r(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}},Ks=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#r;constructor(e=process.cwd(),t,n,{nocase:o,childrenCacheSize:i=16*1024,fs:a=pa}={}){this.#r=iS(a),(e instanceof URL||e.startsWith("file://"))&&(e=LR(e));let s=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(s),this.#e=new Gs,this.#t=new Gs,this.#i=new Nd(i);let l=s.substring(this.rootPath.length).split(n);if(l.length===1&&!l[0]&&l.pop(),o===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=o,this.root=this.newRoot(this.#r),this.roots[this.rootPath]=this.root;let c=this.root,p=l.length-1,d=t.sep,m=this.rootPath,u=!1;for(let h of l){let g=p--;c=c.child(h,{relative:new Array(g).fill("..").join(d),relativePosix:new Array(g).fill("..").join("/"),fullpath:m+=(u?"":d)+h}),u=!0}this.cwd=c}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#i}resolve(...e){let t="";for(let i=e.length-1;i>=0;i--){let a=e[i];if(!(!a||a===".")&&(t=t?`${a}/${t}`:a,this.isAbsolute(a)))break}let n=this.#e.get(t);if(n!==void 0)return n;let o=this.cwd.resolve(t).fullpath();return this.#e.set(t,o),o}resolvePosix(...e){let t="";for(let i=e.length-1;i>=0;i--){let a=e[i];if(!(!a||a===".")&&(t=t?`${a}/${t}`:a,this.isAbsolute(a)))break}let n=this.#t.get(t);if(n!==void 0)return n;let o=this.cwd.resolve(t).fullpathPosix();return this.#t.set(t,o),o}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:n}=t;if(e.canReaddir()){let o=await e.readdir();return n?o:o.map(i=>i.name)}else return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:n=!0}=t;return e.canReaddir()?n?e.readdirSync():e.readdirSync().map(o=>o.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e.withFileTypes,e=this.cwd);let n=await e.readlink();return t?n:n?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e.withFileTypes,e=this.cwd);let n=e.readlinkSync();return t?n:n?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e.withFileTypes,e=this.cwd);let n=await e.realpath();return t?n:n?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e.withFileTypes,e=this.cwd);let n=e.realpathSync();return t?n:n?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:i,walkFilter:a}=t,s=[];(!i||i(e))&&s.push(n?e:e.fullpath());let l=new Set,c=(d,m)=>{l.add(d),d.readdirCB((u,h)=>{if(u)return m(u);let g=h.length;if(!g)return m();let f=()=>{--g===0&&m()};for(let S of h)(!i||i(S))&&s.push(n?S:S.fullpath()),o&&S.isSymbolicLink()?S.realpath().then(x=>x?.isUnknown()?x.lstat():x).then(x=>x?.shouldWalk(l,a)?c(x,f):f()):S.shouldWalk(l,a)?c(S,f):f()},!0)},p=e;return new Promise((d,m)=>{c(p,u=>{if(u)return m(u);d(s)})})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:i,walkFilter:a}=t,s=[];(!i||i(e))&&s.push(n?e:e.fullpath());let l=new Set([e]);for(let c of l){let p=c.readdirSync();for(let d of p){(!i||i(d))&&s.push(n?d:d.fullpath());let m=d;if(d.isSymbolicLink()){if(!(o&&(m=d.realpathSync())))continue;m.isUnknown()&&m.lstatSync()}m.shouldWalk(l,a)&&l.add(m)}}return s}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:i,walkFilter:a}=t;(!i||i(e))&&(yield n?e:e.fullpath());let s=new Set([e]);for(let l of s){let c=l.readdirSync();for(let p of c){(!i||i(p))&&(yield n?p:p.fullpath());let d=p;if(p.isSymbolicLink()){if(!(o&&(d=p.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(s,a)&&s.add(d)}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:i,walkFilter:a}=t,s=new or({objectMode:!0});(!i||i(e))&&s.write(n?e:e.fullpath());let l=new Set,c=[e],p=0,d=()=>{let m=!1;for(;!m;){let u=c.shift();if(!u){p===0&&s.end();return}p++,l.add(u);let h=(f,S,x=!1)=>{if(f)return s.emit("error",f);if(o&&!x){let v=[];for(let b of S)b.isSymbolicLink()&&v.push(b.realpath().then(E=>E?.isUnknown()?E.lstat():E));if(v.length){Promise.all(v).then(()=>h(null,S,!0));return}}for(let v of S)v&&(!i||i(v))&&(s.write(n?v:v.fullpath())||(m=!0));p--;for(let v of S){let b=v.realpathCached()||v;b.shouldWalk(l,a)&&c.push(b)}m&&!s.flowing?s.once("drain",d):g||d()},g=!0;u.readdirCB(h,!0),g=!1}};return d(),s}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ht||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:i,walkFilter:a}=t,s=new or({objectMode:!0}),l=new Set;(!i||i(e))&&s.write(n?e:e.fullpath());let c=[e],p=0,d=()=>{let m=!1;for(;!m;){let u=c.shift();if(!u){p===0&&s.end();return}p++,l.add(u);let h=u.readdirSync();for(let g of h)(!i||i(g))&&(s.write(n?g:g.fullpath())||(m=!0));p--;for(let g of h){let f=g;if(g.isSymbolicLink()){if(!(o&&(f=g.realpathSync())))continue;f.isUnknown()&&f.lstatSync()}f.shouldWalk(l,a)&&c.push(f)}}m&&!s.flowing&&s.once("drain",d)};return d(),s}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[uS](t)}},Do=class extends Ks{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:n=!0}=t;super(e,Od,"\\",{...t,nocase:n}),this.nocase=n;for(let o=this.cwd;o;o=o.parent)o.nocase=this.nocase}parseRootPath(e){return Od.parse(e).root.toUpperCase()}newRoot(e){return new Vs(this.rootPath,Tn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},Uo=class extends Ks{sep="/";constructor(e=process.cwd(),t={}){let{nocase:n=!1}=t;super(e,PR,"/",{...t,nocase:n}),this.nocase=n}parseRootPath(e){return"/"}newRoot(e){return new qs(this.rootPath,Tn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},ha=class extends Uo{constructor(e=process.cwd(),t={}){let{nocase:n=!0}=t;super(e,{...t,nocase:n})}},fq=process.platform==="win32"?Vs:qs,mS=process.platform==="win32"?Do:process.platform==="darwin"?ha:Uo;var GR=r=>r.length>=1,VR=r=>r.length>=1,Bo=class r{#e;#t;#i;length;#r;#a;#w;#c;#p;#s;#l=!0;constructor(e,t,n,o){if(!GR(e))throw new TypeError("empty pattern list");if(!VR(t))throw new TypeError("empty glob list");if(t.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,n<0||n>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#t=t,this.#i=n,this.#r=o,this.#i===0){if(this.isUNC()){let[i,a,s,l,...c]=this.#e,[p,d,m,u,...h]=this.#t;c[0]===""&&(c.shift(),h.shift());let g=[i,a,s,l,""].join("/"),f=[p,d,m,u,""].join("/");this.#e=[g,...c],this.#t=[f,...h],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[i,...a]=this.#e,[s,...l]=this.#t;a[0]===""&&(a.shift(),l.shift());let c=i+"/",p=s+"/";this.#e=[c,...a],this.#t=[p,...l],this.length=this.#e.length}}}pattern(){return this.#e[this.#i]}isString(){return typeof this.#e[this.#i]=="string"}isGlobstar(){return this.#e[this.#i]===it}isRegExp(){return this.#e[this.#i]instanceof RegExp}globString(){return this.#w=this.#w||(this.#i===0?this.isAbsolute()?this.#t[0]+this.#t.slice(1).join("/"):this.#t.join("/"):this.#t.slice(this.#i).join("/"))}hasMore(){return this.length>this.#i+1}rest(){return this.#a!==void 0?this.#a:this.hasMore()?(this.#a=new r(this.#e,this.#t,this.#i+1,this.#r),this.#a.#s=this.#s,this.#a.#p=this.#p,this.#a.#c=this.#c,this.#a):this.#a=null}isUNC(){let e=this.#e;return this.#p!==void 0?this.#p:this.#p=this.#r==="win32"&&this.#i===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#c!==void 0?this.#c:this.#c=this.#r==="win32"&&this.#i===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#s!==void 0?this.#s:this.#s=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#i===0?e:""}checkFollowGlobstar(){return!(this.#i===0||!this.isGlobstar()||!this.#l)}markFollowGlobstar(){return this.#i===0||!this.isGlobstar()||!this.#l?!1:(this.#l=!1,!0)}};var qR=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",zo=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:n,noext:o,noglobstar:i,platform:a=qR}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=a,this.mmopts={dot:!0,nobrace:t,nocase:n,noext:o,noglobstar:i,optimizationLevel:2,platform:a,nocomment:!0,nonegate:!0};for(let s of e)this.add(s)}add(e){let t=new Bt(e,this.mmopts);for(let n=0;n<t.set.length;n++){let o=t.set[n],i=t.globParts[n];if(!o||!i)throw new Error("invalid pattern object");for(;o[0]==="."&&i[0]===".";)o.shift(),i.shift();let a=new Bo(o,i,0,this.platform),s=new Bt(a.globString(),this.mmopts),l=i[i.length-1]==="**",c=a.isAbsolute();c?this.absolute.push(s):this.relative.push(s),l&&(c?this.absoluteChildren.push(s):this.relativeChildren.push(s))}}ignored(e){let t=e.fullpath(),n=`${t}/`,o=e.relative()||".",i=`${o}/`;for(let a of this.relative)if(a.match(o)||a.match(i))return!0;for(let a of this.absolute)if(a.match(t)||a.match(n))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+"/",n=(e.relative()||".")+"/";for(let o of this.relativeChildren)if(o.match(n))return!0;for(let o of this.absoluteChildren)if(o.match(t))return!0;return!1}};var Md=class r{store;constructor(e=new Map){this.store=e}copy(){return new r(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let n=e.fullpath(),o=this.store.get(n);o?o.add(t.globString()):this.store.set(n,new Set([t.globString()]))}},_d=class{store=new Map;add(e,t,n){let o=(t?2:0)|(n?1:0),i=this.store.get(e);this.store.set(e,i===void 0?o:o&i)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},Fd=class{store=new Map;add(e,t){if(!e.canReaddir())return;let n=this.store.get(e);n?n.find(o=>o.globString()===t.globString())||n.push(t):this.store.set(e,[t])}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},ga=class r{hasWalkedCache;matches=new _d;subwalks=new Fd;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new Md}processPatterns(e,t){this.patterns=t;let n=t.map(o=>[e,o]);for(let[o,i]of n){this.hasWalkedCache.storeWalked(o,i);let a=i.root(),s=i.isAbsolute()&&this.opts.absolute!==!1;if(a){o=o.resolve(a==="/"&&this.opts.root!==void 0?this.opts.root:a);let d=i.rest();if(d)i=d;else{this.matches.add(o,!0,!1);continue}}if(o.isENOENT())continue;let l,c,p=!1;for(;typeof(l=i.pattern())=="string"&&(c=i.rest());)o=o.resolve(l),i=c,p=!0;if(l=i.pattern(),c=i.rest(),p){if(this.hasWalkedCache.hasWalked(o,i))continue;this.hasWalkedCache.storeWalked(o,i)}if(typeof l=="string"){let d=l===".."||l===""||l===".";this.matches.add(o.resolve(l),s,d);continue}else if(l===it){(!o.isSymbolicLink()||this.follow||i.checkFollowGlobstar())&&this.subwalks.add(o,i);let d=c?.pattern(),m=c?.rest();if(!c||(d===""||d===".")&&!m)this.matches.add(o,s,d===""||d===".");else if(d===".."){let u=o.parent||o;m?this.hasWalkedCache.hasWalked(u,m)||this.subwalks.add(u,m):this.matches.add(u,s,!0)}}else l instanceof RegExp&&this.subwalks.add(o,i)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new r(this.opts,this.hasWalkedCache)}filterEntries(e,t){let n=this.subwalks.get(e),o=this.child();for(let i of t)for(let a of n){let s=a.isAbsolute(),l=a.pattern(),c=a.rest();l===it?o.testGlobstar(i,a,c,s):l instanceof RegExp?o.testRegExp(i,l,c,s):o.testString(i,l,c,s)}return o}testGlobstar(e,t,n,o){if((this.dot||!e.name.startsWith("."))&&(t.hasMore()||this.matches.add(e,o,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(n&&t.checkFollowGlobstar()?this.subwalks.add(e,n):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),n){let i=n.pattern();if(typeof i=="string"&&i!==".."&&i!==""&&i!==".")this.testString(e,i,n.rest(),o);else if(i===".."){let a=e.parent||e;this.subwalks.add(a,n)}else i instanceof RegExp&&this.testRegExp(e,i,n.rest(),o)}}testRegExp(e,t,n,o){t.test(e.name)&&(n?this.subwalks.add(e,n):this.matches.add(e,o,!1))}testString(e,t,n,o){e.isNamed(t)&&(n?this.subwalks.add(e,n):this.matches.add(e,o,!1))}};var KR=(r,e)=>typeof r=="string"?new zo([r],e):Array.isArray(r)?new zo(r,e):r,Ys=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#t;#i;signal;maxDepth;includeChildMatches;constructor(e,t,n){if(this.patterns=e,this.path=t,this.opts=n,this.#i=!n.posix&&n.platform==="win32"?"\\":"/",this.includeChildMatches=n.includeChildMatches!==!1,(n.ignore||!this.includeChildMatches)&&(this.#t=KR(n.ignore??[],n),!this.includeChildMatches&&typeof this.#t.add!="function")){let o="cannot ignore child matches, ignore lacks add() method.";throw new Error(o)}this.maxDepth=n.maxDepth||1/0,n.signal&&(this.signal=n.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#r(e){return this.seen.has(e)||!!this.#t?.ignored?.(e)}#a(e){return!!this.#t?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#e.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e())}async matchCheck(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||await e.realpath(),!n)return;e=n}let i=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let a=await i.realpath();a&&(a.isUnknown()||this.opts.stat)&&await a.lstat()}return this.matchCheckTest(i,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#r(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||e.realpathSync(),!n)return;e=n}let i=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let a=i.realpathSync();a&&(a?.isUnknown()||this.opts.stat)&&a.lstatSync()}return this.matchCheckTest(i,t)}matchFinish(e,t){if(this.#r(e))return;if(!this.includeChildMatches&&this.#t?.add){let i=`${e.relativePosix()}/**`;this.#t.add(i)}let n=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let o=this.opts.mark&&e.isDirectory()?this.#i:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(n){let i=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(i+o)}else{let i=this.opts.posix?e.relativePosix():e.relative(),a=this.opts.dotRelative&&!i.startsWith(".."+this.#i)?"."+this.#i:"";this.matchEmit(i?a+i+o:"."+o)}}async match(e,t,n){let o=await this.matchCheck(e,n);o&&this.matchFinish(o,t)}matchSync(e,t,n){let o=this.matchCheckSync(e,n);o&&this.matchFinish(o,t)}walkCB(e,t,n){this.signal?.aborted&&n(),this.walkCB2(e,t,new ga(this.opts),n)}walkCB2(e,t,n,o){if(this.#a(e))return o();if(this.signal?.aborted&&o(),this.paused){this.onResume(()=>this.walkCB2(e,t,n,o));return}n.processPatterns(e,t);let i=1,a=()=>{--i===0&&o()};for(let[s,l,c]of n.matches.entries())this.#r(s)||(i++,this.match(s,l,c).then(()=>a()));for(let s of n.subwalkTargets()){if(this.maxDepth!==1/0&&s.depth()>=this.maxDepth)continue;i++;let l=s.readdirCached();s.calledReaddir()?this.walkCB3(s,l,n,a):s.readdirCB((c,p)=>this.walkCB3(s,p,n,a),!0)}a()}walkCB3(e,t,n,o){n=n.filterEntries(e,t);let i=1,a=()=>{--i===0&&o()};for(let[s,l,c]of n.matches.entries())this.#r(s)||(i++,this.match(s,l,c).then(()=>a()));for(let[s,l]of n.subwalks.entries())i++,this.walkCB2(s,l,n.child(),a);a()}walkCBSync(e,t,n){this.signal?.aborted&&n(),this.walkCB2Sync(e,t,new ga(this.opts),n)}walkCB2Sync(e,t,n,o){if(this.#a(e))return o();if(this.signal?.aborted&&o(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,n,o));return}n.processPatterns(e,t);let i=1,a=()=>{--i===0&&o()};for(let[s,l,c]of n.matches.entries())this.#r(s)||this.matchSync(s,l,c);for(let s of n.subwalkTargets()){if(this.maxDepth!==1/0&&s.depth()>=this.maxDepth)continue;i++;let l=s.readdirSync();this.walkCB3Sync(s,l,n,a)}a()}walkCB3Sync(e,t,n,o){n=n.filterEntries(e,t);let i=1,a=()=>{--i===0&&o()};for(let[s,l,c]of n.matches.entries())this.#r(s)||this.matchSync(s,l,c);for(let[s,l]of n.subwalks.entries())i++,this.walkCB2Sync(s,l,n.child(),a);a()}},fa=class extends Ys{matches=new Set;constructor(e,t,n){super(e,t,n)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Sa=class extends Ys{results;constructor(e,t,n){super(e,t,n),this.results=new or({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};var JR=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",un=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,t){if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=YR(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==!1,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(l=>l.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(l=>l.includes("/")?l:`./**/${l}`)}if(this.pattern=e,this.platform=t.platform||JR,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let l=t.platform==="win32"?Do:t.platform==="darwin"?ha:t.platform?Uo:mS;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;let n=this.platform==="darwin"||this.platform==="win32",o={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:n,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(l=>new Bt(l,o)),[a,s]=i.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=a.map((l,c)=>{let p=s[c];if(!p)throw new Error("invalid pattern object");return new Bo(l,p,0,this.platform)})}async walk(){return[...await new fa(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new fa(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new Sa(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new Sa(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};var Dd=(r,e={})=>{Array.isArray(r)||(r=[r]);for(let t of r)if(new Bt(t,e).hasMagic())return!0;return!1};function Js(r,e={}){return new un(r,e).streamSync()}function fS(r,e={}){return new un(r,e).stream()}function jo(r,e={}){return new un(r,e).walkSync()}async function hS(r,e={}){return new un(r,e).walk()}function Xs(r,e={}){return new un(r,e).iterateSync()}function SS(r,e={}){return new un(r,e).iterate()}var XR=Js,ZR=Object.assign(fS,{sync:Js}),QR=Xs,eI=Object.assign(SS,{sync:Xs}),tI=Object.assign(jo,{stream:Js,iterate:Xs}),gS=Object.assign(hS,{glob:hS,globSync:jo,sync:tI,globStream:fS,stream:ZR,globStreamSync:Js,streamSync:XR,globIterate:SS,iterate:eI,globIterateSync:Xs,iterateSync:QR,Glob:un,hasMagic:Dd,escape:Oo,unescape:cn});gS.glob=gS;import cI from"os";import ir,{dirname as vS}from"path";import{cwd as jd}from"process";import xS from"yaml";import{z as ue}from"zod";import yS from"fs";import Zs from"path";import nI from"yaml";import{z as Ud}from"zod";var bS=!1,ya=[`**/*.${Nt.TEST}`,`**/*.${Nt.MODULE}`],Bd=Ud.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),zd=50,rI=Ud.object({fileType:Ud.nativeEnum(fe)});function ke(r,e){let t={project:r,tests:{},modules:{}},n=r.config.include??ya,o=Array.from(r.config.exclude??[]).concat(Ih),i=jo(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:zd,nodir:!0});for(let a of i)oI(r.rootDir,a,t,e);return bS=!0,t}function oI(r,e,t,n){let o=Zs.join(r,e),i;try{i=yS.readFileSync(o,"utf-8")}catch(d){n.warn(`Could not read possible Momentic file at ${o}, skipping: ${d}`);return}let a;try{if(a=nI.parse(i),typeof a!="object"||a===null)throw new Error("The YAML document should parse as a map with key-value pairs")}catch(d){n.warn(`Could not parse possible Momentic file at ${o}, skipping: ${d}`);return}let s=rI.safeParse(a);if(s.error){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let l=s.data.fileType,c;try{c=yS.statSync(o)}catch(d){n.warn(`Skipping path '${o}' because it could not be stat, skipping: ${d}`);return}let p={relativePath:e,fullFilePath:o,platformSep:Zs.sep,fullPathSegments:o.split(Zs.sep),fileName:Zs.basename(o),lastModified:c.mtime,createdAt:c.birthtime};switch(l){case fe.TEST:try{let d=Xt.parse(a);if(t.tests[d.id]){let m=t.tests[d.id].fullFilePath;y.error(`Two tests with the same ID (${d.id}) were found in the same project. Please ensure that all test IDs are unique and avoid copying tests manually. Momentic will ignore the first test when resolving tests.
|
|
45
45
|
|
|
46
|
-
First test path: ${
|
|
46
|
+
First test path: ${m}
|
|
47
47
|
|
|
48
|
-
Second test path: ${o}`)}t.tests[d.id]={type:fe.TEST,name:d.name,id:d.id,description:d.description??void 0,labels:d.labels,...p};return}catch(d){
|
|
49
|
-
${r.map(o=>o.configFilePath)}`);if(r.length===0)throw new Error("No valid Momentic project file available.");return y.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}function NI(n){let e=OI(n);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${Uo}`)),r=Do(t,{absolute:!1,cwd:Hd(),dotRelative:!1,maxDepth:jd,nodir:!0}),o=[];for(let i of r){let s=or.join(Hd(),i),a=$d(s);a&&o.push({configFilePath:s,config:a,rootDir:TS(s)})}return o}function Wd(n){if(n){n=or.resolve(n);let t=$d(n);return t||(console.error(`No valid Momentic project file found at ${n}.`),process.exit(1)),[{config:t,configFilePath:n,rootDir:or.dirname(n)}]}if(vI(xS)){let t=NI(xS);if(t)return t}return kI()}function Bo(n,e){let t=ES.stringify(n);EI(e,t)}import zo from"fs";import Gd from"path";import{z as Vd}from"zod";var _I=Vd.object({width:Vd.number(),height:Vd.number()}),jo=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let r=Gd.join(e.rootDir,e.config.goldenFileDir??"golden/visual-diff");this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=t}async prepareGoldenScreenshotForComparison(e,t,r){if(t.screenshot?.data?.startsWith("https://")){let s=await fetch(t.screenshot.data);return{buffer:Buffer.from(await s.arrayBuffer()),width:t.screenshot.width,height:t.screenshot.height}}let o=t.screenshot?.data;o||(o=Gd.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return zo.mkdirSync(Gd.dirname(o),{recursive:!0}),zo.writeFileSync(o,r.buffer),zo.writeFileSync(i,JSON.stringify({width:r.width,height:r.height})),{buffer:Buffer.from(r.buffer),width:r.width,height:r.height};if(zo.existsSync(o)){let s=zo.readFileSync(o),a=_I.parse(JSON.parse(zo.readFileSync(i,"utf-8")));return{buffer:s,width:a.width,height:a.height}}else throw new R("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};var Ho=class n{flags;constructor(e){this.flags={auto_expand_iframes:e.browser?.autoExpandIframes??!1,use_new_chrome_headless_chromium:e.browser?.useNewHeadlessChromium??!1,rag_v2:e.ai?.ragV2??!1,faker_constant_seed:e.advanced?.fakerConstantSeed??!1,disable_secondary_cache_resolution:e.browser?.disableSecondaryCacheResolution??!1,filter_zero_opacity_elements:e.browser?.filterZeroOpacityElements??!1,global_locator_redirect:e.browser?.globalLocatorRedirect??!1,visual_actions:e.browser?.visualActions??!1,mini_model_initial_assertion:!1,mini_model_initial_locator:!1,show_test_plans:!1,icon_knowledge_base:!1}}static initIfConfigHasOverrides(e,t){let r;if(t.ai&&"ragV2"in t.ai&&(r=new n(t)),t.browser&&("autoExpandIframes"in t.browser||"useNewHeadlessChromium"in t.browser||"disableSecondaryCacheResolution"in t.browser||"filterZeroOpacityElements"in t.browser||"globalLocatorRedirect"in t.browser||"visualActions"in t.browser)&&(r=new n(t)),t.advanced&&"fakerConstantSeed"in t.advanced&&(r=new n(t)),r)return e.debug({flags:r.flags},"using config-based feature flags because overrides have been set"),r;e.debug("using Posthog feature flags because no overrides have been set")}async getAllFlagsAndPayloads(e){return{featureFlags:this.flags,featureFlagPayloads:{}}}};import qk from"http";var M="v1",Ss="1.4.0";var MI=9e4,FI=15e3,hn=class extends Error{status;rawError;constructor(e,t,r,o={}){super(r,o),this.status=e,this.rawError=t}};async function DI(n){return n.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var qd=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Ss&&(e["X-MOMENTIC-CLI-VERSION"]=Ss),e}async sendRequest(e,t,r=3,o=MI){let i=r,s,a={path:e,baseUrl:this.baseUrl,method:t.method};for(;r>0;)try{return r--,await this.sendSingleRequestHelper(e,t,o)}catch(l){if(s=l,l instanceof hn&&l.status>=400&&l.status<500||r===0)throw l;let c=1500,p=i-r,d=Math.min(c*Math.pow(2,p-1),FI);await new Promise(u=>setTimeout(u,d))}throw this.logger.warn({...a,err:s},"Got fatal error response from Momentic server"),s}async sendSingleRequestHelper(e,t,r){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,s=setTimeout(()=>i.abort(),r),a=()=>i.abort();t.signal&&t.signal.addEventListener("abort",a);let l=this.getHeaders();try{let c=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!c.ok){let d=await DI(c);throw new hn(c.status,d,`Request to ${e} failed with status ${c.status}: ${d}`)}let p;if(c.status===204)p={};else{let d=await c.text();try{p=JSON.parse(d)}catch{p=d}}return this.logger&&!t.noLog&&p&&this.logger.debug({result:p,status:c.status,...o},"Got response from Momentic server"),p}finally{clearTimeout(s),t.signal&&t.signal.removeEventListener("abort",a)}}},Mt=class extends qd{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var st=class extends Mt{constructor(e){super(e)}getAppUrl(){return this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${M}/auth/check`,{method:"GET",noLog:!0},10,5e3),{orgId:t,userId:r}=rg.parse(e);return{orgId:t,userId:r}}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${M}/runs/status`,{method:"POST",body:e,noLog:!0});return Zh.parse(t)}async createRunGroup(e){let t=await this.sendRequest(`/${M}/run-groups`,{method:"POST",body:e,noLog:!0},10);return Kh.parse(t)}async updateRunGroup(e,t){await this.sendRequest(`/${M}/run-groups/${e}`,{method:"PATCH",body:t,noLog:!0},5)}async createRun(e){let t=await this.sendRequest(`/${M}/runs`,{method:"POST",body:e,noLog:!0},10);return Xh.parse(t)}async updateRun(e,t){await this.sendRequest(`/${M}/runs/${e}`,{method:"PATCH",body:t,noLog:!0},5)}async createRunAttempt(e){let t=await this.sendRequest(`/${M}/runs/${e}/attempts`,{method:"POST",noLog:!0},10);return eg.parse(t)}async updateRunAttempt(e,t,r){await this.sendRequest(`/${M}/runs/${e}/attempts/${t}`,{method:"PATCH",body:r,noLog:!0},5)}async getTest(e){let t=await this.sendRequest(`/${M}/tests/${e}`,{method:"GET"});return $h.parse(t)}async getAllTestIds(){let e=await this.sendRequest(`/${M}/tests`,{method:"GET"});return Wh.parse(e)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${M}/tests/export`,{method:"POST",body:e});return Gh.parse(t)}async updateTestWithYAML(e){await this.sendRequest(`/${M}/tests/update`,{method:"POST",body:e})}async updateStepCaches(e){await this.sendRequest(`/${M}/cache`,{method:"PATCH",body:e})}async getStepCacheForTest(e){let t=await this.sendRequest(`/${M}/cache`,{method:"POST",body:e},10);return Vh.parse(t)}async queueTests(e){let t=await this.sendRequest(`/${M}/tests/queue`,{method:"POST",body:e});return Hh.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${M}/screenshots`,{method:"POST",body:e,noLog:!0},3,5e3);return ng.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${M}/environments`,{method:"GET"});return og.parse(e)}async getEnvironment(e){let t=await this.sendRequest(`/${M}/environments/${e}`,{method:"GET"});return Js.parse(t)}async getAllFeatureFlags(){let e=await this.sendRequest(`/${M}/auth/flags`,{method:"GET",noLog:!0},10);return ig.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${M}/result-cache/lock`,{method:"POST",body:e,signal:t});return hg.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${M}/result-cache/lock`,{method:"DELETE",body:{key:e}})}async deleteCacheResult(e){await this.sendRequest(`/${M}/result-cache/entry`,{method:"DELETE",body:e})}async setCacheResult(e){await this.sendRequest(`/${M}/result-cache/entry`,{method:"PATCH",body:e})}async getCacheResult(e){try{return await this.sendRequest(`/${M}/result-cache/entry`,{method:"POST",body:e})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${M}/suites/queue`,{method:"POST",body:e});return sg.parse(t)}async bulkGetSuiteStatus(e){let t={suiteRunIds:e},r=await this.sendRequest(`/${M}/suites/status`,{method:"POST",body:t,noLog:!0});return ag.parse(r)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${M}/run-groups/status`,{method:"POST",body:t,noLog:!0});return Wm.array().parse(r)}async updateCacheLastUsedDate(e,t){try{await this.sendRequest(`/${M}/cache/lastUsedAt`,{method:"PATCH",body:e,noLog:!0})}catch(r){t.error({err:r},"Failed to update cache last used date")}}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${M}/test-fragments/`,{method:"POST",body:e})}catch(r){t.error({err:r},"Failed to upload proposed steps")}}async uploadSnapshotScreenshot(e,t,r){try{await this.sendRequest(`/${M}/snapshots/${t}/screenshot`,{method:"POST",body:r,noLog:!0})}catch(o){e.error({err:o},"Failed to upload screenshot")}}async generateConsoleLogsForRunAttemptUploadUrl(e,t,r){let o=await this.sendRequest(`/${M}/runs/${t}/attempts/${r}/console-logs`,{method:"POST",noLog:!0});return Co.parse(o)}async generateNetworkLogsForRunAttemptUploadUrl(e,t,r){let o=await this.sendRequest(`/${M}/runs/${t}/attempts/${r}/network-logs`,{method:"POST",noLog:!0});return Co.parse(o)}async generateHtmlSnapshotUploadUrl(e,t){let r=await this.sendRequest(`/${M}/snapshots/${t}/html`,{method:"POST",noLog:!0});return Co.parse(r)}async generateA11yTreeSnapshotUploadUrl(e,t){let r=await this.sendRequest(`/${M}/snapshots/${t}/a11y`,{method:"POST",noLog:!0});return Co.parse(r)}async reportBillableEvents(e,t){try{await this.sendRequest(`/${M}/billing/events`,{method:"POST",body:t,noLog:!0},10,5e3)}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${M}/test-fragments/${e}`,{method:"GET",noLog:!0});return lg.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${M}/test-fragments/${e}`,{method:"PATCH",body:t})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${M}/results/tests/${e}`,{method:"POST",body:t});return cg.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${M}/results/uploads`,{method:"POST",noLog:!0});return dg.parse(e)}async startProcessingResultsUpload(e){let t=await this.sendRequest(`/${M}/results/uploads/${e}/process`,{method:"POST",noLog:!0});return pg.parse(t)}async fetchIconKnowledgeBase(e,t){try{let r=await this.sendRequest(`/${M}/knowledge-base/icons`,{method:"GET",noLog:!0});return wg.parse(r)}catch(r){return t.error({err:r},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t,r){try{await this.sendRequest(`/${M}/icon-knowledge-base/icons`,{method:"POST",body:t,noLog:!0},3,5e3)}catch(o){r.error({err:o},"Failed to save new icons to icon knowledge base")}}async getAllFlagsAndPayloads(){let e=await this.sendRequest(`/${M}/feature-flags`,{method:"GET",noLog:!0},3,5e3);return ug.parse(e)}};import{randomUUID as RS}from"crypto";var Xa=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvent(e,t,r){try{return await this.apiClient.reportBillableEvents(e,[{event:t,timestamp:new Date().toISOString(),transactionId:r?.eventId??RS(),properties:Kc({},r)}])}catch(o){e.error({err:o},"Failed to report billable event")}}async reportCreditsUsed(e,t,r,o){if(r)try{return await this.apiClient.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:o?.eventId??RS(),properties:Kc({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};function $o(n,e,t){return fetch(n,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Za=class{constructor(e){this.client=e}async storeConsoleLogsForRunAttempt(e,t,r,o){try{let i=JSON.stringify(o),{uploadUrl:s}=await this.client.generateConsoleLogsForRunAttemptUploadUrl(e,t,r),a=await $o(s,"application/json",i);if(!a.ok)throw new Error(`Failed to upload network logs: ${a.statusText}`)}catch(i){e.error({err:i},"Failed to upload console logs")}}async storeNetworkLogsForRunAttempt(e,t,r,o){let i=JSON.stringify(o);try{let{uploadUrl:s}=await this.client.generateNetworkLogsForRunAttemptUploadUrl(e,t,r),a=await $o(s,"application/json",i);if(!a.ok)throw new Error(`Failed to upload network logs: ${a.statusText}`)}catch(s){e.error({err:s},"Failed to upload network logs")}}async storeHtmlSnapshot(e,t,r){try{let{uploadUrl:o}=await this.client.generateHtmlSnapshotUploadUrl(e,t),i=await $o(o,"text/html",r);if(!i.ok)throw new Error(`Failed to upload network logs: ${i.statusText}`)}catch(o){e.error({err:o},"Failed to upload html snapshot")}}async storeScreenshot(e,t,r){try{await this.client.uploadSnapshotScreenshot(e,t,{screenshot:r.toString("base64")})}catch(o){e.error({err:o},"Failed to upload screenshot")}}async storeA11yTreeSnapshot(e,t,r){return Promise.resolve()}async getConsoleLogsForRunAttempt(e,t,r){}async getNetworkLogsForRunAttempt(e,t,r){}async getHtmlSnapshot(e,t){}async getA11yTreeSnapshot(e,t){}async getScreenshot(e,t){}};var Wo=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}async saveStepCacheEntries(e,t,r){try{await this.client.updateStepCaches({entries:e,testId:t})}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let t=await this.client.getStepCacheForTest({testId:e.testId,organizationId:e.organizationId,steps:e.steps,schemaVersion:e.schemaVersion}),{hits:r}=Ro({steps:e.steps,stepCacheEntries:t,logger:e.logger});this.client.updateCacheLastUsedDate(r,e.logger)}fetchIconKnowledgeBase(e,t){return this.client.fetchIconKnowledgeBase(e,t)}saveNewIcons(e,t,r){return this.client.saveNewIcons(e,t,r)}};import{Faker as UI,en as BI}from"@faker-js/faker";var Go="v1",ir=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new UI({locale:BI}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Go}/tools/ai/generate`,{method:"POST",body:t}).catch(r=>{throw r instanceof hn?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Go}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof hn?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Go}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof hn?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Go}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof hn?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Go}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof hn?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Go}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof hn?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as zI}from"zod";var Vo=class extends Mt{constructor(e){super(e)}async rankChunksWithAi(e,t){let r={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:t.abortSignal});return oh.parse(o)}async rankChunksWithRag(e,t){let r=await this.sendRequest(`/${M}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Ss,...e},signal:t.abortSignal});return rh.parse(r)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${M}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return zI.string().parse(t)}async getElementLocation(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/locate-element`,{method:"POST",body:r,signal:t.abortSignal});return zh.parse(o)}async getAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/assertion`,{method:"POST",body:r,signal:t.abortSignal});return rd.parse(o)}async getLintStepResult(e,t){let r={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/lint/step`,{method:"POST",body:r,signal:t.abortSignal});return Bh.parse(o)}async getVisualAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/visual-assertion`,{method:"POST",body:r,signal:t.abortSignal});return rd.parse(o)}async getAiActionCommand(e,t){let r=await this.sendRequest(`/${M}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Uh.parse(r)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${M}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let r=await this.sendRequest(`/${M}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Cc.parse(r)}async getReverseMappedDescription(e,t){let r=await this.sendRequest(`/${M}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return jh.parse(r)}async getTextExtraction(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${M}/web-agent/text-extraction`,{method:"POST",body:r,signal:t.abortSignal});return Ec.parse(o)}async getTestResultClassification(e,t){let r=await this.sendRequest(`/${M}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Fc.parse(r)}async getExtractedKeywords(e,t){let r=await this.sendRequest(`/${M}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return nh.parse(r)}async getAutohealingProposal(e,t){let r=await this.sendRequest(`/${M}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Yu.parse(r)}async getFailureRecoveryProposal(e,t){let r=await this.sendRequest(`/${M}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Ju.parse(r)}async getIframeRegex(e,t){let r=await this.sendRequest(`/${M}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Ou.parse(r)}};var Gr=class extends Mt{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let r=await this.sendRequest(`/${M}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return ku.parse(r)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var Qa=class{constructor(e){this.client=e}async uploadResultsArchive(e){let{uploadUrl:t,id:r}=await this.client.generateTestResultsUploadUrl(),o=await $o(t,"application/zip",e);if(!o.ok)throw new Error(`Failed to upload test results: ${await o.text()}`);let{runGroupId:i}=await this.client.startProcessingResultsUpload(r);return i}};import{PostHog as jI}from"posthog-node";var qo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var AS=n=>{let e=n.reason===void 0?new DOMException("This operation was aborted.","AbortError"):n.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};async function D(n,e){let{milliseconds:t,fallback:r,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a;return new Promise((l,c)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:d}=e;d.aborted&&c(AS(d)),a=()=>{c(AS(d))},d.addEventListener("abort",a)}if(t===Number.POSITIVE_INFINITY){n.then(l,c);return}let p=new qo;s=i.setTimeout.call(void 0,()=>{if(r){try{l(r())}catch(d){c(d)}return}"cancel"in n&&typeof n.cancel=="function"&&n.cancel(),o instanceof Error?c(o):(p.message=o??`Promise timed out after ${t} milliseconds`,c(p))},t),(async()=>{try{l(await n)}catch(d){c(d)}})()}).catch(l=>{throw l}).finally(()=>{s!==void 0&&i.clearTimeout.call(void 0,s),a!==void 0&&e.signal&&e.signal.removeEventListener("abort",a)})}async function IS(n,e){let t,r=0,o=3,i,s;for(;r<o;)try{let a=await D(n.getAllFlagsAndPayloads(e),{milliseconds:5e3});i=a.featureFlags||{},s=a.featureFlagPayloads||{};break}catch(a){t=a,r++,await new Promise(l=>setTimeout(l,100*r))}if(i&&s)return{flags:i,payloads:s};throw t}var Ko=class n extends $i{constructor(t,r,o,i){super(o,i);this.client=t;this.orgId=r}static async init(t,r){let o=r??new jI("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:i,payloads:s}=await IS(o,t);return new n(o,t,i,s)}async refresh(){let{flags:t,payloads:r}=await IS(this.client,this.orgId);this.flags=t,this.payloads=r}};import{Server as Tk}from"socket.io";import{cloneDeep as HI}from"lodash-es";var $I={showOverlay:!1},Kd=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:t,cleanup:r,clientIp:o,sessionId:i,browserbaseSessionId:s}){return this.sessions.set(i,{controller:e,context:t,cleanup:r,clientIp:o,browserbaseSessionId:s,browserBehavior:HI($I)}),i}removeSession(e,t){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:i}=o;try{i.setClosed(),await i.browser.cleanup()}catch(s){t.error({err:s},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(s){t.error({err:s},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}},Z=new Kd;function PS(n,e,t){let r=Date.now(),o=Date.now(),i,s,a,l,c=!1,p=async(h,g)=>{if(!h.closed&&!h.isInPageLoad)try{let f=a;a=void 0;let S=h.url(),x=g.toEditorDisplayCopy();JSON.stringify(x)===JSON.stringify(i)&&S===l&&r>o||(n.emit("browserState",{logsPerPage:f?.logsPerPage,harPages:f?.harPages,harEntries:f?.harEntries,viewport:h.getViewport(),url:S,iframeSrcUrls:s??[],context:x,isInPageLoad:h.isInPageLoad}),r=Date.now()),l=S,i=x}catch(f){if(!n.connected)return;let S=f instanceof Error?f.message:`${f}`;if(S.includes("Frame was detached")||S.includes("Not attached to an active page")||S.includes("browser has been closed")||S.includes("UserInfrastructureError"))return;t.error({err:f,sessionId:e},"Error grabbing browser state")}},d=setInterval(()=>{let h=Z.getSession(e),g=h?.controller?.browser;if(!g||g.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(d);return}p(g,h.context)},1e3),u=(h,g)=>!!(JSON.stringify(h)!==JSON.stringify(s)||g.logsPerPage.some(f=>f.length>0)||g.harPages&&Object.keys(g.harPages).length>0||g.harEntries&&Object.keys(g.harEntries).length>0),m=setInterval(async()=>{let g=Z.getSession(e)?.controller?.browser;if(!g||g.closed){clearInterval(m);return}else if(c)return;c=!0;try{let f=await g.getAllFrameUrls(),S=g.retrieveAndClearDebugData();u(f,S)&&(s=f,a=S,o=Date.now())}catch(f){t.warn({err:f},"Failed to fetch extended details")}finally{c=!1}},2500);return{timers:[d,m]}}var sr={};var WI=n=>()=>{let{sessionId:e}=n.metadata;sr[e]?.abort?.abort()},LS={event:"cancelApiTest",createHandler:WI};import{CookieJar as lP}from"tough-cookie";import{randomUUID as ZI}from"crypto";import{faker as GI}from"@faker-js/faker";import VI from"assert";import qI from"axios";import KI from"moment";import*as YI from"otpauth";import JI from"pg";async function OS(n){let e;try{e=new URL(n.url).hostname}catch{}let t=[];return n.headers.getSetCookie()?.forEach(r=>{let o=ga(r,e);t.push(...o)}),t}var XI=Object.getPrototypeOf(async function(){}).constructor;async function kS(n,e,t){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o}=e.bindings,i=e.tools,s={},a=(f,S)=>{o[f]=S,s[f]=S},l={},c=(f,S)=>{o[f]=S,l[f]=S},p;r.includes("Octokit")&&(p=(await import("@octokit/rest")).Octokit);let d;r.includes("createAppAuth")&&(d=(await import("@octokit/auth-app")).createAppAuth);let u=async()=>await Promise.resolve(new XI("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai",r)(qI,KI,i.fakerInstance??GI,VI,JI,p,d,YI,OS,o,a,c,S=>i.sms.send(S),S=>i.sms.fetchLatest(S),i.email,i.sms,i.ai)),m=!0,h,g;try{h=await D(u(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal})}catch(f){t.error(`[${n}] Error executing code: ${f}`),m=!1,f instanceof qo?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:h,variableUpdates:s,persistentVariableUpdates:l,success:m,error:g}}async function NS({code:n,fragment:e,context:t,localTools:r,logger:o,signal:i,timeoutMs:s=Kn}){let a=ZI(),l=await kS(a,{code:n,options:{fragment:e,timeoutMs:s},bindings:t.toObjectCopy(),tools:r,signal:i},o);return y.debug(`[${a}] Got execution result: ${JSON.stringify(l)}`),l}import{createHmac as QI,randomUUID as eP}from"crypto";import tP from"fetch-retry";var nP=tP(global.fetch,{retries:3,retryOn:function(n,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(n){return Math.pow(2,n)*500}}),_S=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,MS=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function FS({orgId:n,code:e,fragment:t,context:r,timeoutMs:o=Kn,retries:i=2,signal:s,logger:a}){if(!_S)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,p=0;if(!MS)throw new Error("Missing lambda auth secret.");let d=QI("sha256",MS).update(n).digest("hex");for(;p<=i;){p++,s?.throwIfAborted();let m={id:eP(),orgId:n,momenticLambdaAuthHash:d,code:e,fragment:t,state:r.toObjectCopy(),timeoutMs:o};try{if(l=await D(nP(_S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:s}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(h){c=h}}if(c)throw a.error({err:c},"Failed to evaluate code remotely"),c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let u;try{u=uh.parse(await l.json())}catch(m){throw new Error(`Code evaluation server returned invalid response: ${m}`)}if(u.error)throw new Error(`Code evaluation error: ${u.error}`);return u}async function Dn(n){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await FS(n);else if(n.localTools)e=await NS({...n,localTools:n.localTools});else throw new Error("No code evaluation environment available");if(e.error)throw new Error(`Code evaluation error: ${e.error}`);if(e.variableUpdates)for(let[t,r]of Object.entries(e.variableUpdates))n.context.setVariable(t,r);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await n.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,r]of Object.entries(e.persistentVariableUpdates))n.context.setVariable(t,r)}return e.result}async function Ht(n){let{orgId:e,s:t,context:r,logger:o,signal:i,flagStore:s,retries:a=2,timeoutMs:l=Kn,allowUndefined:c=!1}=n,p=/{{(.*?)}}/g,d=t.matchAll(p),u=t;for(let m of d){if(m.length<2)continue;let h=m[1].trim(),g;try{g=await Dn({orgId:e,code:h,fragment:!0,context:r,timeoutMs:l,logger:o,retries:a,localTools:n.localTools,signal:i,flagStore:s})}catch(S){throw o.error({err:S,value:t},"Error evaluating template string"),S}if(g===void 0&&!c)throw new R("UserConfigurationError",`Template fragment '${h}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let f=typeof g=="string"?g:`${g}`;f=f.replaceAll(/\$/g,"$$$$"),u=u.replace(m[0],f)}return u}async function Yo(n){return DS(n)}async function DS({obj:n,bannedKeys:e,allowList:t,context:r,prefixPath:o="",replacements:i={},...s}){for(let a in n){if(e.includes(a))continue;let l=!1;if(t)if(t.includes(a))l=!0;else continue;let c=n[a],p=o?`${o}.${a}`:a;if(typeof c=="string"&&c.includes("{{")){let d=await Ht({s:c,context:r,...s});if(c===d)continue;i[p]=c,n[a]=d}else typeof c=="object"&&c!==null&&!Array.isArray(c)&&await DS({obj:c,bannedKeys:e,context:r,prefixPath:p,replacements:i,allowList:l?void 0:t,...s})}return i}import rP from"fetch-retry";var $Y=process.env.MAILINATOR_API_KEY,WY=rP(global.fetch,{retryOn:function(n,e,t){return n>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(n){return 500}});import iP from"fetch-cookie";import{cloneDeep as sP}from"lodash-es";var el=(n,e)=>{try{let{hostname:t,pathname:r}=new URL(n),{hostname:o,pathname:i}=new URL(e);return t!==o||r!==i}catch{return!1}},Jo=n=>{try{return new URL(n),!0}catch{return!1}},US=n=>!n.toLowerCase().startsWith("http"),Xo=(n,e)=>{try{return new URL(n,e),!0}catch{return!1}};function ar(n,e){try{return!!new URL(n).origin.trim()}catch(t){return e?.error({url:n,err:t},"Invalid URL in check"),!1}}var oP=3e4;async function tl({command:n,logger:e,baseUrl:t,fetchImplementation:r=fetch}){let o=n.timeout??oP/1e3,i=Object.fromEntries(Object.entries(n.headers||{}).filter(([m,h])=>m&&h)),s=new URLSearchParams;Object.entries(n.params||{}).filter(([m,h])=>m&&h).forEach(([m,h])=>{s.append(m,h)});let a=s.toString(),l;if(Jo(n.url)&&(l=n.url),t&&Xo(n.url,t)&&(l=new URL(n.url,t).toString()),!l)throw new R("ActionFailureError",`Invalid URL: ${n.url}`);e.debug({url:l,searchParams:a,headers:i,body:n.body,method:n.method},"Making HTTP request");let p=await D((async()=>{let m=a?`${l}?${a}`:l;try{return await r(m,{headers:i,method:n.method,body:n.body})}catch(h){throw e.error({err:h},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${h}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!p.ok){let m;try{m=await p.text()}catch(h){m=`Failed to read response body: ${h}`}throw new R("ActionFailureError",`Fetch request failed with status ${p.status}: ${m}`)}let d={};p.headers.forEach((m,h)=>{d[h]=m});let u={status:p.status,headers:d};return p.headers.get("content-type")?.includes("json")?u.json=await p.json():p.headers.get("content-type")?.includes("text")&&(u.text=await p.text()),u}async function BS(n){let{fixtures:e,inputs:t}=n,{context:r}=e,{orgId:o,step:i}=t,s=sP(i);await Yo({obj:s,orgId:o,bannedKeys:["code"],...e});let a=await aP(n);return s.envKey&&a.data&&r.setVariable(s.envKey,a.data),a}async function aP(n){let{fixtures:e,inputs:t}=n,{step:r,orgId:o,baseUrl:i}=t,{cookieJar:s}=e,a=new Date;switch(r.type){case"JAVASCRIPT":{let c=await Dn({code:r.code,orgId:o,fragment:!!r.fragment,timeoutMs:r.timeout?r.timeout*1e3:void 0,...e});try{JSON.stringify(c)}catch(p){return{...r,startedAt:a,finishedAt:new Date,status:"FAILED",message:`JavaScript return value is not serializable: ${p instanceof Error?p.message:`${p}`}`}}return{...r,startedAt:a,finishedAt:new Date,message:"JavaScript code executed successfully",status:"SUCCESS",data:c}}case"REQUEST":{let c=iP(fetch,s),p=await tl({command:r,logger:e.logger,baseUrl:i,fetchImplementation:c});return{...r,startedAt:a,finishedAt:new Date,status:"SUCCESS",message:"Request executed successfully",data:p}}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}async function zS(n){let{inputs:e,fixtures:t,callbacks:r}=n,{signal:o}=t,{steps:i,orgId:s,baseUrl:a}=e,{test:l,step:c}=r,p={startedAt:new Date,status:"RUNNING",results:[]},d=p.results,u=new lP,m={cookieJar:u,...t};for(let h of i){let g=new Date;c.onStarted?.(h.id);let f;try{o?.throwIfAborted(),f=await BS({inputs:{step:h,baseUrl:a,orgId:s},fixtures:m})}catch(S){o?.aborted?f={...h,startedAt:g,finishedAt:new Date,status:"CANCELLED",message:"Step cancelled by user."}:f={...h,startedAt:g,finishedAt:new Date,status:"FAILED",message:`Step failed: ${S instanceof Error?S.message:`${S}`}`}}if(d.push(f),c.onFinished?.({result:f,cookies:Sa(u,new URL(a).hostname)}),l.updateAttemptProgress?.({results:d}),f.status!=="SUCCESS"){p.status=f.status==="CANCELLED"?"CANCELLED":"FAILED";break}}return p.status==="RUNNING"&&(p.status="PASSED"),p.finishedAt=new Date,l.onFinished?.(),p}async function jS(n){let{socket:e,storage:t}=n,r=n.socket.id,{testId:o}=e.handshake.query;if(typeof o!="string")throw new Error(`Received invalid test ID that does not parse as a string: ${o}`);let i=await t.getOrgId({type:"api-test",testId:o}),{baseUrl:s,envName:a,environmentVariables:l}=await Yd({testId:o,orgId:i,logger:n.logger,storage:t,authorization:n.authorization}),c={type:"api-test",orgId:await n.storage.getOrgId({type:"api-test",testId:o}),testId:o,sessionId:r,latestContext:new It({baseUrl:s||"",currentUrl:s||"",variablesFromEnvironment:l,envName:a})};return sr[r]=c,c}async function Yd({testId:n,orgId:e,logger:t,storage:r,authorization:o}){let i=await r.fetchApiTestMetadata(n,e,t);if(!i)throw new Error(`Failed to fetch API test metadata for test ID: ${n}`);let s;o?.type==="API_KEY"&&(s=new ir({httpClient:new Mt({...o,logger:t}),fakerSeed:void 0}));let a=i.envs?.find(d=>d.default),l;a&&(l=await r.fetchEnvironment(e,a.name,t));let c=i.baseUrl||l?.variables?.[Ie];if(!c)throw new Error("Base URL is empty in both API test options and the configured environment");let p={...l?.variables};return{baseUrl:c,envName:l?.name,environmentVariables:p,localCodeEvalTools:s}}var cP=n=>async(e,t)=>{let{steps:r}=e,{authorization:o,metadata:i,socket:s,storage:a,logger:l,flagStoreFactory:c}=n,{orgId:p,testId:d,sessionId:u}=i,m=l.child({testId:d,orgId:p,sessionId:u}),h=sr[u];if(!h)throw new Error(`No api testing session with id ${u} could be found. Please reconnect and try again.`);let g=new AbortController;h.abort=g;let f=h.latestContext,{localCodeEvalTools:S,baseUrl:x}=await Yd({testId:d,orgId:p,logger:m,storage:a,authorization:o}),v={context:f,logger:m,localTools:S,signal:g.signal,flagStore:await c(p)},C=await zS({inputs:{steps:r,orgId:p,baseUrl:x},fixtures:v,callbacks:{test:{onFinished:()=>{s.emit("apiTestFinished")}},step:{onStarted:I=>{s.emit("apiStepStarted",I)},onFinished:I=>{s.emit("apiStepFinished",I)}}}});t({result:C})},HS={event:"executeApiTest",createHandler:cP};var dP=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async()=>{e.info({sessionId:t},"Cancel event received");let r=Z.getSession(t);if(!r)throw new Error("No active session found");try{r.controller.setClosed()}catch{}}},$S={event:"cancel",createHandler:dP};var pP=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async(r,o)=>{let i=Z.getSession(t);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let a=await s.getBrowserState({skipWait:!0});o({a11yTree:a.serialize()})}catch(a){e.error({err:a},"Error fetching a11y tree from the browser"),o({err:a.message})}}},WS={event:"fetchA11yTree",createHandler:pP};var uP=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async(r,o)=>{let i=Z.getSession(t);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let a=await s.html();o({html:a})}catch(a){e.error({err:a},"Error fetching DOM from the browser"),a.name==="TimeoutError"?o({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):o({err:a.message})}}},GS={event:"fetchDom",createHandler:uP};var mP=({metadata:n,logger:e})=>{let{sessionId:t,type:r}=n;return o=>{e.info({sessionId:t,reason:o},`Disconnect event received (${o})`),r==="e2e"?Z.removeSession(t,e):r==="api-test"&&delete sr[t]}},VS={event:"disconnect",createHandler:mP};function nn(n){let{result:e,nestedResults:t}=n;if(!n.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=hP(t);gP(e,r,o);let i=[...n.asyncTasks];n.asyncTasks.push((async()=>{try{await fP(i,e,r,o)}catch(s){n.logger.error({result:n.result,err:s},"Error hoisting scalar result metadata")}})())}function hP(n){let e=n[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertion){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let r=n[n.length-1],o;for(;;){switch(r.type){case"PRESET_ACTION":{o=r;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!r.results.length){o=r;break}r=r.results[r.results.length-1];break;default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function gP(n,e,t){e&&(n.beforeUrl=e.beforeUrl),t&&(n.afterUrl=t.afterUrl,n.data=t.data,t.status!=="SUCCESS"&&(n.message=t.message))}async function fP(n,e,t,r){await Promise.allSettled(n),t&&(e.beforeSnapshot=t.beforeSnapshot),r&&(e.afterSnapshot=r.afterSnapshot)}import ys from"os";import SP from"v8";var qS,En,yP=ys.platform(),bP=ys.cpus().map(n=>({model:n.model,speed:n.speed}));function KS(n){let e=()=>{try{let t=!1,r=wP(),o=vP();r.freeMemory<1e6&&(t=!0);let i=SP.getHeapStatistics(),s=i.used_heap_size,a=i.heap_size_limit;s/a>.9&&(t=!0),t?n.warn({memory:r,cpu:o,heapStats:i},"Critical resource usage metrics detected"):n.debug({memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,1e4),cpuMetadata:bP,platform:yP}}function wP(){let n=ys.totalmem(),e=ys.freemem(),t=n-e;return{totalMemory:n,freeMemory:e,usedMemory:t}}function vP(){let n=ys.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of n)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!En)return En=t,null;let r={user:t.user-En.user,nice:t.nice-En.nice,sys:t.sys-En.sys,idle:t.idle-En.idle,irq:t.irq-En.irq,total:t.total-En.total};return qS={measurementTime:e,intervalMs:e-En.measurementTime,user:r.user/r.total*100,nice:r.nice/r.total*100,sys:r.sys/r.total*100,idle:r.idle/r.total*100,irq:r.irq/r.total*100,total:100-r.idle/r.total*100},En=t,qS}import{hostname as RP}from"os";async function JS(n){let{command:e,tracer:t,timeoutMs:r,targetingWrapper:o,disableCache:i,fixtures:s}=n,{logger:a,abortSignal:l}=s;if(e.target&&!Vn(e.target))throw new Error("Element assertion with x/y is not supported yet");let c=e.assertion.type==="ELEMENT_EXISTENCE"&&e.assertion.negated,p=Date.now(),d=0,u,m=500;for(;d<2||Date.now()-p<r;){d++,d>1&&await te(m,l),l?.throwIfAborted();try{let{newTarget:h,elementInteractedDisplayString:g,result:f}=await o({ctx:s.ctx,tracer:t,command:e,target:e.target,cache:e.cache?.target,action:async S=>xP(S.locator,n),options:{disableCache:i,useSelector:!!e.useSelector,iframeUrl:e.iframeUrl,disableGlobalLocatorRedirect:!0,source:c?"NEGATED_CHECK":void 0}});if(u={success:f.success,data:f.data,err:f.err,newTarget:h,elementInteractedDisplayString:g},!f.success){u=f,m=Math.min(m*2,1e4);continue}return u}catch(h){if(l?.throwIfAborted(),c)return{success:!0,thoughts:`The element described does not exist on the page: ${h.message}`};if(a.warn({err:h},"Element assertion ended in error, retrying..."),!(h instanceof R)||h.reason!="ActionFailureError")throw h;u={success:!1,err:h}}}if(!u)throw new Error(`Failed to evaluate manual element assertion in ${r}ms.`);return u}async function xP(n,{command:e,fixtures:t}){let r=e.assertion;await t.browser.highlight(n);let o=!0,i,s;switch(r.type){case"ELEMENT_CONTENT":{let a=await n.textContent()??"";if(s={elementTextContent:Me(a,500,!0)},!YS(a,r.value,r.operation,!!r.negated)){let l=r.negated?Zn[r.operation]:Qn[r.operation];o=!1,i=new R("AssertionFailureError",`The content ${l} '${r.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{s={elementOuterHtml:Me(await n.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let a;try{a=await n.getAttribute(r.attr,{timeout:3e3})??""}catch(l){i=new R("AssertionFailureError",`The element does not have an attribute named ${r.attr}: ${l}`),o=!1;break}if(!YS(a,r.value,r.operation,!!r.negated)){let l=r.negated?Zn[r.operation]:Qn[r.operation];o=!1,r.operation==="EXISTS"?i=r.negated?new R("AssertionFailureError",`The attribute ${r.attr} ${l}: ${a}`):new R("AssertionFailureError",`The attribute ${r.attr} ${l}`):i=new R("AssertionFailureError",`The attribute ${r.attr} ${l} '${r.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(r.condition){case"VISIBLE":{o=await n.isVisible({timeout:wn*1e3});break}case"EDITABLE":{o=await n.isEditable({timeout:wn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await n.isEnabled({timeout:wn*1e3});break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.condition)}if(o=r.negated?!o:o,!o){let a=r.negated?ld[r.condition]:cd[r.condition];i=new R("AssertionFailureError",`The element ${a}`)}break}}return{success:o,data:s,err:i}}function YS(n,e,t,r){let o;switch(t){case"CONTAINS":{o=n.includes(e);break}case"EQUALS":{o=n.trim()===e.trim();break}case"STARTS_WITH":{o=n.trim().startsWith(e);break}case"EXISTS":{o=n.trim().length>0;break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return r?!o:o}import{Jimp as TP}from"jimp";async function bs(n,e){let t=await n.screenshot(e),r=await TP.fromBuffer(t);return{buffer:t,width:Math.ceil(r.bitmap.width??0),height:Math.ceil(r.bitmap.height??0)}}import{Jimp as XS}from"jimp";import Jd from"jpeg-js";import EP from"pixelmatch";async function ZS({ctx:n,tracer:e,command:t,disableCache:r,browser:o,targetingWrapper:i,logger:s,screenshotStorage:a}){if(t.target&&!Vn(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:s});let l={clearHighlights:!0,hideCaret:!0},c;t.target?.elementDescriptor?c=(await i({ctx:n,tracer:e,command:t,target:t.target,cache:t.cache?.target??t.target?.a11yData,action:async j=>bs(o,{locator:j.locator,...l}),options:{disableCache:!!r,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl,disableGlobalLocatorRedirect:!0}})).result:c=await bs(o,l);let p=await a.prepareGoldenScreenshotForComparison(s,t,c);if((c.height!==p.height||c.width!==p.width)&&s.debug({currHeight:c.height,currWidth:c.width,savedHeight:p.height,savedWidth:p.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-p.height)>10||Math.abs(c.width-p.width)>10){let z=`${c.width}x${c.height}`,j=`${p.width}x${p.height}`;return{fail:!0,thoughts:`Current screenshot (${z}) does not match saved screenshot dimensions (${j}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:p.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await XS.fromBuffer(c.buffer),u={width:c.width,height:c.height},m=await XS.fromBuffer(p.buffer),h={width:p.width,height:p.height},g,f=u.width*u.height,S=h.width*h.height,x=Math.abs(u.height-h.height),v=Math.abs(u.width-h.width);if(f>S){let z=d.cover({w:h.width,h:h.height});c.buffer=await z.getBuffer("image/jpeg"),g="current",c.width=h.width,c.height=h.height}else if(S>f){let z=m.cover({w:u.width,h:u.height});p.buffer=await z.getBuffer("image/jpeg"),g="saved"}let b={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},E=t.threshold??.1,I=EP(Jd.decode(p.buffer).data,Jd.decode(c.buffer).data,b.data,c.width,c.height,{threshold:E,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,_=I>E*100,L=`Visual diff of ${I.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${E*100}%.`;if(g&&(L+=` The ${g} screenshot was cropped since it was taller by ${x} pixels and wider by ${v} pixels.`),_)throw new R("ActionFailureError",L);return{fail:_,thoughts:L,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:Jd.encode(b,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var CP=5e3;async function nl({timeout:n=wn,...e}){let t=Date.now(),r=n*1e3,o=r+1e4,i,s=0,a=500;for(;s-t<r;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let l=Date.now();i=await QS(e),s=Date.now();let c=s-l;if(c>1e3&&e.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await te(a,e.signal),a=Math.min(Math.floor(a*1.5),CP);else return i}return i=await QS(e),i}async function QS({assertion:n,browser:e,flagStore:t}){switch(n.type){case"CONTENT":{let o,i=!1,s;try{let a;if(t.isBooleanFlagEnabled("auto_expand_iframes")){let l=await e.evaluateFunctionInAllFrames(ey,{value:n.value,negated:!!n.negated,returnHtml:!1});i=l.some(c=>c.evaluation),a=l.find(c=>c.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:a}=await e.evaluateFunctionInPage(ey,{value:n.value,negated:!!n.negated,returnHtml:!0}));if(!i){let l=n.negated?Zn.CONTAINS:Qn.CONTAINS;s=new R("AssertionFailureError",`The page ${l} '${n.value}'.`),o=a}}catch(a){s=new R("AssertionFailureError",`Failed to evaluate page content assertion: ${a instanceof Error?a.message:`${a}`}`)}return{success:i,err:s,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.type)}}function ey({value:n,negated:e,returnHtml:t}){let r=document.documentElement.outerHTML,o=r.includes(n)===!e;return r.length>1e4&&(r=r.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?r:void 0}}var Xd=async n=>{let{step:e,resolvedInputs:t}=n.moduleParams,{logger:r,context:o,storage:i,codeEvalTools:s,controller:a}=n.fixtures,l=a.browser,{orgId:c,runId:p}=n.inputs,d=a.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),r.debug({inputs:t,moduleId:e.moduleId},"Set module inputs"));let u,m=!1,h,g;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",S=await Ht({orgId:c,s:f,context:o,logger:r,localTools:s,signal:d,flagStore:a.flagStore});g={orgId:c,cacheKeys:[S,...Object.entries(t).map(([v,b])=>`${v}:${b}`)]},r.debug({original:f,keyParams:g},"Module cache key params");let x=Date.now();for(;Date.now()-x<Fh;){d?.throwIfAborted();let v=await i.getCacheResult(g);if(v){r.debug({cacheResult:v},"Got result from module execution cache"),u=rl(e,t,"SUCCESS"),u.message="Used cached module result.",u.data=JSON.parse(v),m=!0;break}else r.debug({cacheKey:f,keyParams:g},"No cache result found, continuing with lock acquisition");let b=await i.acquireCacheLock({keyParams:g,clientMetadata:`hostName:${RP()};runId:${p}`},d);if(b.acquired){h=b.keyPrefix,r.info({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Acquired cache lock and proceeding with module execution");break}else r.debug({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Failed to acquire cache lock, retrying...");await te(2500+Math.random()*1e4,d)}}try{if(!u)u=await AP(n);else if(e.autoAuth){let f=fa.safeParse(u.data);if(!f.success)throw new R("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);r.debug("Automatically loading auth state after cached module result"),await l.loadAuthState(f.data);let S=!1,x=e.advanced?.cacheInvalidation;if(x&&x.type==="PAGE_CHECK"){let v={type:"CONTENT",value:x.substring},b=await nl({timeout:wn,assertion:v,browser:l,flagStore:a.flagStore,logger:r,signal:d});b.success?r.debug({invalResult:b},"Cached result still valid after page check, continuing..."):(r.info({invalResult:b},"Invalidating cached result due to page check failure"),S=!0)}if(g&&S)return await i.deleteCacheResult(g),Xd(n)}}finally{try{h!==void 0&&!m&&u?.status==="SUCCESS"&&await IP({step:e,result:u,browser:a.browser,cacheKeyPrefix:h,logger:r,storage:i})}finally{h!==void 0&&await i.releaseCacheLock(h)}}return u},AP=async n=>{let{step:e,tracer:t}=n.moduleParams,r=rl(e,n.moduleParams.resolvedInputs,"SUCCESS"),o=await t.startSubSteps(),{status:i,results:s}=await lr(n.work,()=>n.executeStepList({...n,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}}));return r.results=s,r.status=i,r.finishedAt=new Date,nn({asyncTasks:n.work.asyncTasks,nestedResults:s,result:r,logger:n.fixtures.logger}),r};function rl(n,e,t){let r={};return Object.entries(e).forEach(([i,s])=>{r[i]=JSON.stringify(s)}),{type:"MODULE",id:n.id,moduleId:n.moduleId,moduleName:n.name,startedAt:new Date,cacheConfig:n.cacheConfig,inputs:r,results:[],finishedAt:new Date,status:t}}async function ty({orgId:n,step:e,context:t,logger:r,flagStore:o,codeEvalTools:i,signal:s}){let a={};try{for(let l of e.parameters??[]){let c=e.inputs?.[l]??e.defaultParameters?.[l];if(!c){r.warn(`No value or default found for parameter '${l}' that is required by module '${e.name}'`);continue}a[l]=await Dn({orgId:n,code:c,fragment:!0,context:t,logger:r,localTools:i,signal:s,flagStore:o})}return a}catch(l){throw s?.throwIfAborted(),new R("UserConfigurationError",`Failed to evaluate module inputs: ${l}`)}}async function IP({step:n,result:e,browser:t,cacheKeyPrefix:r,logger:o,storage:i}){let s=n.cacheConfig?.cacheExpiryMs;(!s||s===gg)&&(s=n.defaultCacheTtl??fg);let a;n.autoAuth?a=JSON.stringify(await t.saveAuthState()):e.data!==void 0?a=JSON.stringify(e.data):a='""',o.debug({cacheKeyPrefix:r,ttlMs:s,truncatedCacheResultJson:Dg(a)},"Setting module cache result"),await i.setCacheResult({result:a,keyPrefix:r,ttlMs:s})}async function cr(n,e,t){let r=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,s="FAILED",a;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(a="Step aborted by user.",s="CANCELLED"):o instanceof R?a=`${o}`:a=`An unexpected error occurred: ${o.message}`,n.type==="RESOLVED_MODULE"){let l=rl(n,{},"FAILED");return l.message=a,l.startedAt=r,l.finishedAt=i,l}return{...Pa(n),startedAt:r,finishedAt:i,status:s,data:null,message:a,results:[]}}}async function lr(n,e){let t=!1;try{return n&&!n.state.failureRecoveryDisabled&&(n.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{n&&t&&(n.state.failureRecoveryDisabled=void 0)}}import{randomUUID as ny}from"crypto";import{cloneDeep as LP}from"lodash-es";function ol(n,e){n.state.healingDetails?n.state.healingDetails.push(e):n.state.healingDetails=[e]}var il=async n=>{let{step:e,tracer:t}=n.presetParams,{logger:r,controller:o,context:i,billingReporter:s}=n.fixtures,{collectDebugData:a}=n.options,{testMetadata:l,suiteMetadata:c}=n.inputs,p=e.command.type,d=r.child({commandType:p,stepId:e.id,commandId:e.command.id}),u=zi(e.command);n.work.asyncTasks.push(s.reportCreditsUsed(d,p,u,{testId:l?.id,testName:l?.name,suiteId:c?.id,suiteName:c?.name}));let m=o.browser.url(),h=new Date,g,f=ny(),S=ny();if(a)try{g=await o.browser.screenshot({retries:1,clearHighlights:!0});let C=await o.browser.getRawCondensedHtml();t.attachBeforeHtmlSnapshot({logger:d,snapshotId:f,html:C}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(d,f,C))}catch(C){d.debug({err:C},"Failed to take screenshot before step, likely because the page is still loading. This is non-fatal and does not affect the test.")}let x,v,b,E=ua();try{let C=await o.executePresetCommand(E,t,e.command,i,l?.advanced.disableAICaching??!1);C.beforeScreenshotOverride&&(g=C.beforeScreenshotOverride),b=C.afterScreenshotOverride;let{proposedStep:I}=OP({work:n.work,step:e,newTargets:C.newTargets,logger:d}),_=new Date,L=o.browser.url();v={beforeUrl:m,afterUrl:L,startedAt:h,finishedAt:_,viewport:o.browser.getViewport(),status:C.fail?"FAILED":"SUCCESS",elementInteracted:C.elementInteracted},x={...e,message:C.thoughts??kP(C.newTargets)??"Successfully executed preset action.",beforeUrl:m,afterUrl:L,finishedAt:_,startedAt:h,status:C.fail?"FAILED":"SUCCESS",data:C.data,results:[v],details:E.details,proposedStep:I},"assertion"in e.command&&(x.message=C.thoughts||"Assertion passed.")}catch(C){d.error({message:C.message,stack:C.stack},`Failed executing preset step ${Mr(e.command)}`);let I=o.browser.url(),_=new Date,L=C instanceof Error?C.message:`${C}`;C instanceof R&&C.getLastScreenshotBuffer()&&(b=C.getLastScreenshotBuffer()),v={beforeUrl:m,afterUrl:I,startedAt:h,finishedAt:_,viewport:o.browser.getViewport(),status:C instanceof DOMException&&C.name==="AbortError"?"CANCELLED":"FAILED",message:L},x={...e,startedAt:h,finishedAt:_,beforeUrl:m,afterUrl:I,status:C instanceof DOMException&&C.name==="AbortError"?"CANCELLED":"FAILED",message:L,failureReason:C instanceof R?C.reason:void 0,results:[v],details:E.details}}if(a)try{b||(b=await o.browser.screenshot({retries:1}));let C=await o.browser.getRawCondensedHtml();t.attachAfterHtmlSnapshot({logger:d,snapshotId:S,html:C}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(d,S,C))}catch(C){d.debug({err:C},"Failed store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return v.beforeSnapshot=f,x.beforeSnapshot=f,v.afterSnapshot=S,x.afterSnapshot=S,g&&(t.attachBeforeScreenshot({logger:d,snapshotId:f,screenshot:g}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(d,f,g))),b&&(t.attachAfterScreenshot({logger:d,snapshotId:S,screenshot:b}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(d,S,b))),x};function OP({work:n,step:e,newTargets:t,logger:r}){if(!t?.length)return{proposedStep:void 0};let o=e.command;_g(o,t,r);let i=t[0]?.description;if(i&&"target"in o&&o.target&&o.target.type==="description"){let s={...o,target:{...o.target,elementDescriptor:i}},a={...LP(e),command:s};return ol(n,{type:"DESCRIPTION_UPDATE",thoughts:`Updated element description after the original element could not be found on the page. New element location reasoning: ${t[0]?.thoughts}`}),{proposedStep:a}}return{proposedStep:void 0}}function kP(n){if(n?.length){if(n.length===1&&n[0]?.thoughts)return n[0].thoughts;if(n.length===2&&n.every(e=>e.thoughts))return`Located first element: ${n[0]?.thoughts}
|
|
50
|
-
Located second element: ${n[1]?.thoughts}`}}var Zd=["ability","able","aboard","about","above","accept","accident","according","account","accurate","acres","across","act","action","active","activity","actual","actually","add","addition","additional","adjective","adult","adventure","advice","affect","afraid","after","afternoon","again","against","age","ago","agree","ahead","aid","air","airplane","alike","alive","all","allow","almost","alone","along","aloud","alphabet","already","also","although","am","among","amount","ancient","angle","angry","animal","announced","another","answer","ants","any","anybody","anyone","anything","anyway","anywhere","apart","apartment","appearance","apple","applied","appropriate","are","area","arm","army","around","arrange","arrangement","arrive","arrow","art","article","as","aside","ask","asleep","at","ate","atmosphere","atom","atomic","attached","attack","attempt","attention","audience","author","automobile","available","average","avoid","aware","away","baby","back","bad","badly","bag","balance","ball","balloon","band","bank","bar","bare","bark","barn","base","baseball","basic","basis","basket","bat","battle","be","bean","bear","beat","beautiful","beauty","became","because","become","becoming","bee","been","before","began","beginning","begun","behavior","behind","being","believed","bell","belong","below","belt","bend","beneath","bent","beside","best","bet","better","between","beyond","bicycle","bigger","biggest","bill","birds","birth","birthday","bit","bite","black","blank","blanket","blew","blind","block","blood","blow","blue","board","boat","body","bone","book","border","born","both","bottle","bottom","bound","bow","bowl","box","boy","brain","branch","brass","brave","bread","break","breakfast","breath","breathe","breathing","breeze","brick","bridge","brief","bright","bring","broad","broke","broken","brother","brought","brown","brush","buffalo","build","building","built","buried","burn","burst","bus","bush","business","busy","but","butter","buy","by","cabin","cage","cake","call","calm","came","camera","camp","can","canal","cannot","cap","capital","captain","captured","car","carbon","card","care","careful","carefully","carried","carry","case","cast","castle","cat","catch","cattle","caught","cause","cave","cell","cent","center","central","century","certain","certainly","chain","chair","chamber","chance","change","changing","chapter","character","characteristic","charge","chart","check","cheese","chemical","chest","chicken","chief","child","children","choice","choose","chose","chosen","church","circle","circus","citizen","city","class","classroom","claws","clay","clean","clear","clearly","climate","climb","clock","close","closely","closer","cloth","clothes","clothing","cloud","club","coach","coal","coast","coat","coffee","cold","collect","college","colony","color","column","combination","combine","come","comfortable","coming","command","common","community","company","compare","compass","complete","completely","complex","composed","composition","compound","concerned","condition","congress","connected","consider","consist","consonant","constantly","construction","contain","continent","continued","contrast","control","conversation","cook","cookies","cool","copper","copy","corn","corner","correct","correctly","cost","cotton","could","count","country","couple","courage","course","court","cover","cow","cowboy","crack","cream","create","creature","crew","crop","cross","crowd","cry","cup","curious","current","curve","customs","cut","cutting","daily","damage","dance","danger","dangerous","dark","darkness","date","daughter","dawn","day","dead","deal","dear","death","decide","declared","deep","deeply","deer","definition","degree","depend","depth","describe","desert","design","desk","detail","determine","develop","development","diagram","diameter","did","die","differ","difference","different","difficult","difficulty","dig","dinner","direct","direction","directly","dirt","dirty","disappear","discover","discovery","discuss","discussion","disease","dish","distance","distant","divide","division","do","doctor","does","dog","doing","doll","dollar","done","donkey","door","dot","double","doubt","down","dozen","draw","drawn","dream","dress","drew","dried","drink","drive","driven","driver","driving","drop","dropped","drove","dry","duck","due","dug","dull","during","dust","duty","each","eager","ear","earlier","early","earn","earth","easier","easily","east","easy","eat","eaten","edge","education","effect","effort","egg","eight","either","electric","electricity","element","elephant","eleven","else","empty","end","enemy","energy","engine","engineer","enjoy","enough","enter","entire","entirely","environment","equal","equally","equator","equipment","escape","especially","essential","establish","even","evening","event","eventually","ever","every","everybody","everyone","everything","everywhere","evidence","exact","exactly","examine","example","excellent","except","exchange","excited","excitement","exciting","exclaimed","exercise","exist","expect","experience","experiment","explain","explanation","explore","express","expression","extra","eye","face","facing","fact","factor","factory","failed","fair","fairly","fall","fallen","familiar","family","famous","far","farm","farmer","farther","fast","fastened","faster","fat","father","favorite","fear","feathers","feature","fed","feed","feel","feet","fell","fellow","felt","fence","few","fewer","field","fierce","fifteen","fifth","fifty","fight","fighting","figure","fill","film","final","finally","find","fine","finest","finger","finish","fire","fireplace","firm","first","fish","five","fix","flag","flame","flat","flew","flies","flight","floating","floor","flow","flower","fly","fog","folks","follow","food","foot","football","for","force","foreign","forest","forget","forgot","forgotten","form","former","fort","forth","forty","forward","fought","found","four","fourth","fox","frame","free","freedom","frequently","fresh","friend","friendly","frighten","frog","from","front","frozen","fruit","fuel","full","fully","fun","function","funny","fur","furniture","further","future","gain","game","garage","garden","gas","gasoline","gate","gather","gave","general","generally","gentle","gently","get","getting","giant","gift","girl","give","given","giving","glad","glass","globe","go","goes","gold","golden","gone","good","goose","got","government","grabbed","grade","gradually","grain","grandfather","grandmother","graph","grass","gravity","gray","great","greater","greatest","greatly","green","grew","ground","group","grow","grown","growth","guard","guess","guide","gulf","gun","habit","had","hair","half","halfway","hall","hand","handle","handsome","hang","happen","happened","happily","happy","harbor","hard","harder","hardly","has","hat","have","having","hay","he","headed","heading","health","heard","hearing","heart","heat","heavy","height","held","hello","help","helpful","her","herd","here","herself","hidden","hide","high","higher","highest","highway","hill","him","himself","his","history","hit","hold","hole","hollow","home","honor","hope","horn","horse","hospital","hot","hour","house","how","however","huge","human","hundred","hung","hungry","hunt","hunter","hurried","hurry","hurt","husband","ice","idea","identity","if","ill","image","imagine","immediately","importance","important","impossible","improve","in","inch","include","including","income","increase","indeed","independent","indicate","individual","industrial","industry","influence","information","inside","instance","instant","instead","instrument","interest","interior","into","introduced","invented","involved","iron","is","island","it","its","itself","jack","jar","jet","job","join","joined","journey","joy","judge","jump","jungle","just","keep","kept","key","kids","kill","kind","kitchen","knew","knife","know","knowledge","known","label","labor","lack","lady","laid","lake","lamp","land","language","large","larger","largest","last","late","later","laugh","law","lay","layers","lead","leader","leaf","learn","least","leather","leave","leaving","led","left","leg","length","lesson","let","letter","level","library","lie","life","lift","light","like","likely","limited","line","lion","lips","liquid","list","listen","little","live","living","load","local","locate","location","log","lonely","long","longer","look","loose","lose","loss","lost","lot","loud","love","lovely","low","lower","luck","lucky","lunch","lungs","lying","machine","machinery","mad","made","magic","magnet","mail","main","mainly","major","make","making","man","managed","manner","manufacturing","many","map","mark","market","married","mass","massage","master","material","mathematics","matter","may","maybe","me","meal","mean","means","meant","measure","meat","medicine","meet","melted","member","memory","men","mental","merely","met","metal","method","mice","middle","might","mighty","mile","military","milk","mill","mind","mine","minerals","minute","mirror","missing","mission","mistake","mix","mixture","model","modern","molecular","moment","money","monkey","month","mood","moon","more","morning","most","mostly","mother","motion","motor","mountain","mouse","mouth","move","movement","movie","moving","mud","muscle","music","musical","must","my","myself","mysterious","nails","name","nation","national","native","natural","naturally","nature","near","nearby","nearer","nearest","nearly","necessary","neck","needed","needle","needs","negative","neighbor","neighborhood","nervous","nest","never","new","news","newspaper","next","nice","night","nine","no","nobody","nodded","noise","none","noon","nor","north","nose","not","note","noted","nothing","notice","noun","now","number","numeral","nuts","object","observe","obtain","occasionally","occur","ocean","of","off","offer","office","officer","official","oil","old","older","oldest","on","once","one","only","onto","open","operation","opinion","opportunity","opposite","or","orange","orbit","order","ordinary","organization","organized","origin","original","other","ought","our","ourselves","out","outer","outline","outside","over","own","owner","oxygen","pack","package","page","paid","pain","paint","pair","palace","pale","pan","paper","paragraph","parallel","parent","park","part","particles","particular","particularly","partly","parts","party","pass","passage","past","path","pattern","pay","peace","pen","pencil","people","per","percent","perfect","perfectly","perhaps","period","person","personal","pet","phrase","physical","piano","pick","picture","pictured","pie","piece","pig","pile","pilot","pine","pink","pipe","pitch","place","plain","plan","plane","planet","planned","planning","plant","plastic","plate","plates","play","pleasant","please","pleasure","plenty","plural","plus","pocket","poem","poet","poetry","point","pole","police","policeman","political","pond","pony","pool","poor","popular","population","porch","port","position","positive","possible","possibly","post","pot","potatoes","pound","pour","powder","power","powerful","practical","practice","prepare","present","president","press","pressure","pretty","prevent","previous","price","pride","primitive","principal","principle","printed","private","prize","probably","problem","process","produce","product","production","program","progress","promised","proper","properly","property","protection","proud","prove","provide","public","pull","pupil","pure","purple","purpose","push","put","putting","quarter","queen","question","quick","quickly","quiet","quietly","quite","rabbit","race","radio","railroad","rain","raise","ran","ranch","range","rapidly","rate","rather","raw","rays","reach","read","reader","ready","real","realize","rear","reason","recall","receive","recent","recently","recognize","record","red","refer","refused","region","regular","related","relationship","religious","remain","remarkable","remember","remove","repeat","replace","replied","report","represent","require","research","respect","rest","result","return","review","rhyme","rhythm","rice","rich","ride","riding","right","ring","rise","rising","river","road","roar","rock","rocket","rocky","rod","roll","roof","room","root","rope","rose","rough","round","route","row","rubbed","rubber","rule","ruler","run","running","rush","sad","saddle","safe","safety","said","sail","sale","salmon","salt","same","sand","sang","sat","satellites","satisfied","save","saved","saw","say","scale","scared","scene","school","science","scientific","scientist","score","screen","sea","search","season","seat","second","secret","section","see","seed","seeing","seems","seen","seldom","select","selection","sell","send","sense","sent","sentence","separate","series","serious","serve","service","sets","setting","settle","settlers","seven","several","shade","shadow","shake","shaking","shall","shallow","shape","share","sharp","she","sheep","sheet","shelf","shells","shelter","shine","shinning","ship","shirt","shoe","shoot","shop","shore","short","shorter","shot","should","shoulder","shout","show","shown","shut","sick","sides","sight","sign","signal","silence","silent","silk","silly","silver","similar","simple","simplest","simply","since","sing","single","sink","sister","sit","sitting","situation","six","size","skill","skin","sky","slabs","slave","sleep","slept","slide","slight","slightly","slip","slipped","slope","slow","slowly","small","smaller","smallest","smell","smile","smoke","smooth","snake","snow","so","soap","social","society","soft","softly","soil","solar","sold","soldier","solid","solution","solve","some","somebody","somehow","someone","something","sometime","somewhere","son","song","soon","sort","sound","source","south","southern","space","speak","special","species","specific","speech","speed","spell","spend","spent","spider","spin","spirit","spite","split","spoken","sport","spread","spring","square","stage","stairs","stand","standard","star","stared","start","state","statement","station","stay","steady","steam","steel","steep","stems","step","stepped","stick","stiff","still","stock","stomach","stone","stood","stop","stopped","store","storm","story","stove","straight","strange","stranger","straw","stream","street","strength","stretch","strike","string","strip","strong","stronger","struck","structure","struggle","stuck","student","studied","studying","subject","substance","success","successful","such","sudden","suddenly","sugar","suggest","suit","sum","summer","sun","sunlight","supper","supply","support","suppose","sure","surface","surprise","surrounded","swam","sweet","swept","swim","swimming","swing","swung","syllable","symbol","system","table","tail","take","taken","tales","talk","tall","tank","tape","task","taste","taught","tax","tea","teach","teacher","team","tears","teeth","telephone","television","tell","temperature","ten","tent","term","terrible","test","than","thank","that","thee","them","themselves","then","theory","there","therefore","these","they","thick","thin","thing","think","third","thirty","this","those","thou","though","thought","thousand","thread","three","threw","throat","through","throughout","throw","thrown","thumb","thus","thy","tide","tie","tight","tightly","till","time","tin","tiny","tip","tired","title","to","tobacco","today","together","told","tomorrow","tone","tongue","tonight","too","took","tool","top","topic","torn","total","touch","toward","tower","town","toy","trace","track","trade","traffic","trail","train","transportation","trap","travel","treated","tree","triangle","tribe","trick","tried","trip","troops","tropical","trouble","truck","trunk","truth","try","tube","tune","turn","twelve","twenty","twice","two","type","typical","uncle","under","underline","understanding","unhappy","union","unit","universe","unknown","unless","until","unusual","up","upon","upper","upward","us","use","useful","using","usual","usually","valley","valuable","value","vapor","variety","various","vast","vegetable","verb","vertical","very","vessels","victory","view","village","visit","visitor","voice","volume","vote","vowel","voyage","wagon","wait","walk","wall","want","war","warm","warn","was","wash","waste","watch","water","wave","way","we","weak","wealth","wear","weather","week","weigh","weight","welcome","well","went","were","west","western","wet","whale","what","whatever","wheat","wheel","when","whenever","where","wherever","whether","which","while","whispered","whistle","white","who","whole","whom","whose","why","wide","widely","wife","wild","will","willing","win","wind","window","wing","winter","wire","wise","wish","with","within","without","wolf","women","won","wonder","wonderful","wood","wooden","wool","word","wore","work","worker","world","worried","worry","worse","worth","would","wrapped","write","writer","writing","written","wrong","wrote","yard","year","yellow","yes","yesterday","yet","you","young","younger","your","yourself","youth","zero","zebra","zipper","zoo","zulu"];function ry(n){return new Array(n).fill(0).map(()=>Zd[Math.floor(Math.random()*Zd.length)]).join("-")}async function oy({codePath:n,screenshotBuff:e,storage:t,logger:r}){if(e)try{let o=await t.uploadScreenshot(e);return r.debug({screenshotUrl:o,codePath:n},"Saved screenshot for debugging"),o}catch(o){r.error({err:o,codePath:n},"Failed to save screenshot for debugging")}}async function Cn({frameConfig:n,action:e,browser:t}){let r=t.getActiveFrameConfig();n?t.setActiveFrameConfig(n):r?.type==="auto"&&t.setActiveFrameConfig(void 0);try{return await e()}finally{t.setActiveFrameConfig(r)}}var sl="MOMENTIC_RUN_ID",iy="FINAL_SCREENSHOT_URL";import{cloneDeep as jP}from"lodash-es";async function sy(n){let{step:e,tracer:t}=n.conditionalParams,{logger:r,controller:o}=n.fixtures,i=new Date,s=Pa(e),a=e.elseSteps,l=!0,c=[],p,d=ua();for(let f=0;f<e.blocks.length;f++){r.info(`Evaluating condition ${f} in conditional step`);let S=e.blocks[f];try{let x=await il({...n,presetParams:{tracer:t,step:S.assertion}});c.push(x),r.info(`Condition ${f} resolved to true, executing the corresponding ${S.steps.length} steps`),l=!1,a=S.steps,p=x}catch(x){r.info({err:x},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(a)l&&r.info("No conditions resolved to true, executing the else block steps");else return r.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...s,status:"SUCCESS",startedAt:i,data:c[c.length-1]?.data,message:c[c.length-1]?.message,results:[],finishedAt:new Date,details:d.details};r.info(`Executing ${a.length} steps in the selected conditional block`);let u=await n.conditionalParams.tracer.startSubSteps(),m=await n.executeStepList({...n,listParams:{steps:a,containerName:"conditional block",tracer:u}}),g={...s,assertion:p,...m,startedAt:i,finishedAt:new Date};return nn({asyncTasks:n.work.asyncTasks,nestedResults:[...c,...m.results],result:g,logger:r}),g}import{randomUUID as ay}from"crypto";var ly=async n=>{let{controller:e}=n.fixtures;await e.browser.waitForDOMStability();let t=await e.browser.screenshot({}),r=await NP(n);r.finishedAt=new Date,nn({asyncTasks:n.work.asyncTasks,result:r,nestedResults:r.results,logger:n.fixtures.logger});let o=await e.browser.screenshot({}),i=ay();r.beforeSnapshot=i,n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(n.fixtures.logger,i,t));let s=ay();return r.afterSnapshot=s,n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(n.fixtures.logger,s,o)),r},NP=async n=>{let{step:e,tracer:t}=n.aiStepParams,{controller:r,context:o,logger:i}=n.fixtures,s={...e,startedAt:new Date,beforeTestContext:o.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in e&&e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS"))throw new R("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let l=await t.startSubSteps(),{status:c}=await n.executeStepList({...n,listParams:{steps:e.steps,containerName:"AI action",results:s.results,tracer:l}});return s.finishedAt=new Date,s.status=c,s}catch(l){i.warn({err:l},"Failed executing saved deprecated AI action steps");let c=r.executeAbortController.signal.aborted;s.message=l instanceof Error?l.message:`${l}`,s.status=c?"CANCELLED":"FAILED"}return s};import{randomUUID as Qd}from"crypto";var cy=15,_P=7,dy=async n=>{let{controller:e}=n.fixtures;await e.browser.waitForDOMStability();let t=await e.browser.screenshot({}),r=await MP(n);r.finishedAt=new Date,nn({asyncTasks:n.work.asyncTasks,result:r,nestedResults:r.results,logger:n.fixtures.logger});let o=await e.browser.screenshot({}),i=Qd();r.beforeSnapshot=i,n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(n.fixtures.logger,i,t));let s=Qd();return r.afterSnapshot=s,n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(n.fixtures.logger,s,o)),r},MP=async n=>{let{step:e,tracer:t}=n.aiStepParams,{testMetadata:r,orgId:o}=n.inputs,{controller:i,context:s,logger:a,codeEvalTools:l}=n.fixtures,{step:c}=n.callbacks,p=`${e.id}-${Date.now()}`,d=a.child({stepId:e.id,langfuseSessionId:p}),u={...e,startedAt:new Date,beforeTestContext:s.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},m=await Ht({orgId:o,s:e.text,context:s,logger:d,localTools:l,flagStore:i.flagStore});await i.browser.waitForDOMStability({logger:d});let g=`data:image/jpeg;base64,${(await i.browser.screenshot({clearHighlights:!0,retries:2})).toString("base64")}`,f=[],S=0,x=0,v,b;for(;;){if(S>cy)return u.message=`Exceeded the maximum number of commands allowed per AI step (${cy})`,u.status="FAILED",u;if(i.executeAbortController.signal.aborted)return u.message="Test execution was cancelled",u.status="CANCELLED",u;c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let E=await i.evaluateAiAction({goal:m,startingScreenshot:S===0?void 0:g,history:f,logger:d,langfuseSessionId:p,lastError:b}),{evaluation:C,reasoning:I,summary:_}=E;d.info(E,"Got AI evaluation");let L=u.results[S-1]?.id;switch(C.type){case"DONE":return u.message=`Our AI evaluator confirmed all tasks are complete: ${I}`,u.status="SUCCESS",L&&c.onDynamicAIActionEvaluatingEvent?.({stepId:L,status:"SUCCESS",message:`${_}
|
|
51
|
-
|
|
52
|
-
${C.feedback}`,x++,x>=_P)return u.message=`Our AI agent requires additional information to achieve this goal:
|
|
48
|
+
Second test path: ${o}`)}t.tests[d.id]={type:fe.TEST,name:d.name,id:d.id,description:d.description??void 0,labels:d.labels,...p};return}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case fe.MODULE:try{let d=Rt.parse(a);t.modules[d.moduleId]={type:fe.MODULE,name:d.name,id:d.moduleId,description:d.description??void 0,...p};let m=p.fileName.replace(".module.yaml","");!bS&&Pe(d.name)!==m&&n.warn(`The module with ID ${d.moduleId} has a name (${d.name}) that does not match its file name (${m}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`);return}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}default:n.warn(`Unsupported file type ${l}, skipping...`);return}}var Ho="momentic.config.yaml",wS="momentic.workspace.yaml",dI=ue.object({projects:ue.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),pI=ue.union([ue.string(),ue.object({fromFile:ue.string(),json:ue.boolean().optional()})]),uI=ue.object({name:Bd,baseUrl:ue.string(),envFile:ue.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:ue.record(ue.string(),pI).optional(),inheritFromShell:ue.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:xo.optional().transform(r=>r&&(r.localChromeExtensionPaths&&(r.localChromeExtensionPaths=r.localChromeExtensionPaths.map(e=>e.startsWith("~")?ir.join(cI.homedir(),e.slice(1)):e)),r))}),mI=ue.object({postSave:ue.string().optional()}),hI=ue.object({name:Bd,include:ue.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:ue.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:ue.string().optional(),reporterDir:ue.string().optional(),outputDir:ue.string().optional(),retries:ue.number().optional().describe("number of retries per test"),parallel:ue.number().optional().describe("degree of parallelism"),environments:ue.array(uI).optional(),ai:ed.extend({ragV2:ue.boolean().optional()}).optional(),browser:xo.extend({autoExpandIframes:ue.boolean().optional(),useNewHeadlessChromium:ue.boolean().optional(),disableSecondaryCacheResolution:ue.boolean().optional(),filterZeroOpacityElements:ue.boolean().optional(),globalLocatorRedirect:ue.boolean().optional(),visualActions:ue.boolean().optional()}).optional(),advanced:kh.optional(),hooks:mI.optional()});function TS(r,e){let t;try{t=aI(r,"utf-8")}catch(o){y.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=xS.parse(t),typeof n!="object"||n===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof n} instead`)}catch(o){y.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function Hd(r){let e=TS(r,"project configuration");if(e!==void 0)try{return hI.parse(e)}catch(t){y.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function gI(r){let e=TS(r,"workspace configuration");if(e!==void 0)try{return dI.parse(e)}catch(t){y.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function fI(){let r=[],e=jd(),t=ir.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=ir.basename(e);if(qi.includes(i))return y.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of sI(e))if(a.endsWith(Ho)){let s=ir.join(e,a),l=Hd(s);l&&r.push({configFilePath:s,config:l,rootDir:vS(s)})}if(r.length)return r;if(e=ir.dirname(e),e===t)break}return r}function mn(r={}){let{configFilePath:e,nameFilter:t}=r,n=$d(e);if(t&&(n=n.filter(o=>o.config.name===t)),n.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
|
|
49
|
+
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return y.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}function SI(r){let e=gI(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${Ho}`)),n=jo(t,{absolute:!1,cwd:jd(),dotRelative:!1,maxDepth:zd,nodir:!0}),o=[];for(let i of n){let a=ir.join(jd(),i),s=Hd(a);s&&o.push({configFilePath:a,config:s,rootDir:vS(a)})}return o}function $d(r){if(r){r=ir.resolve(r);let t=Hd(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:ir.dirname(r)}]}if(iI(wS)){let t=SI(wS);if(t)return t}return fI()}function $o(r,e){let t=xS.stringify(r);lI(e,t)}import Wo from"fs";import Wd from"path";import{z as Gd}from"zod";var yI=Gd.object({width:Gd.number(),height:Gd.number()}),Go=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let n=Wd.join(e.rootDir,e.config.goldenFileDir??"golden/visual-diff");this.defaultGoldenScreenshotDir=n,this.regenerateGoldenFiles=t}async prepareGoldenScreenshotForComparison(e,t,n){if(t.screenshot?.data?.startsWith("https://")){let a=await fetch(t.screenshot.data);return{buffer:Buffer.from(await a.arrayBuffer()),width:t.screenshot.width,height:t.screenshot.height}}let o=t.screenshot?.data;o||(o=Wd.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return Wo.mkdirSync(Wd.dirname(o),{recursive:!0}),Wo.writeFileSync(o,n.buffer),Wo.writeFileSync(i,JSON.stringify({width:n.width,height:n.height})),{buffer:Buffer.from(n.buffer),width:n.width,height:n.height};if(Wo.existsSync(o)){let a=Wo.readFileSync(o),s=yI.parse(JSON.parse(Wo.readFileSync(i,"utf-8")));return{buffer:a,width:s.width,height:s.height}}else throw new A("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};var Vo=class r{flags;constructor(e){this.flags={auto_expand_iframes:e.browser?.autoExpandIframes??!1,use_new_chrome_headless_chromium:e.browser?.useNewHeadlessChromium??!1,rag_v2:e.ai?.ragV2??!1,faker_constant_seed:e.advanced?.fakerConstantSeed??!1,disable_secondary_cache_resolution:e.browser?.disableSecondaryCacheResolution??!1,filter_zero_opacity_elements:e.browser?.filterZeroOpacityElements??!1,global_locator_redirect:e.browser?.globalLocatorRedirect??!1,visual_actions:e.browser?.visualActions??!1,mini_model_initial_assertion:!1,mini_model_initial_locator:!1,show_test_plans:!1,icon_knowledge_base:!1}}static initIfConfigHasOverrides(e,t){let n;if(t.ai&&"ragV2"in t.ai&&(n=new r(t)),t.browser&&("autoExpandIframes"in t.browser||"useNewHeadlessChromium"in t.browser||"disableSecondaryCacheResolution"in t.browser||"filterZeroOpacityElements"in t.browser||"globalLocatorRedirect"in t.browser||"visualActions"in t.browser)&&(n=new r(t)),t.advanced&&"fakerConstantSeed"in t.advanced&&(n=new r(t)),n)return e.debug({flags:n.flags},"using config-based feature flags because overrides have been set"),n;e.debug("using Posthog feature flags because no overrides have been set")}async getAllFlagsAndPayloads(e){return{featureFlags:this.flags,featureFlagPayloads:{}}}};import CO from"http";var _="v1",ba="1.5.1";var bI=9e4,wI=15e3,hn=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function vI(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Vd=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return ba&&(e["X-MOMENTIC-CLI-VERSION"]=ba),e}async sendRequest(e,t,n=3,o=bI){let i=n,a,s={path:e,baseUrl:this.baseUrl,method:t.method};for(;n>0;)try{return n--,await this.sendSingleRequestHelper(e,t,o)}catch(l){if(a=l,l instanceof hn&&l.status>=400&&l.status<500||n===0)throw l;let c=1500,p=i-n,d=Math.min(c*Math.pow(2,p-1),wI);await new Promise(m=>setTimeout(m,d))}throw this.logger.warn({...s,err:a},"Got fatal error response from Momentic server"),a}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s);let l=this.getHeaders();try{let c=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!c.ok){let d=await vI(c);throw new hn(c.status,d,`Request to ${e} failed with status ${c.status}: ${d}`)}let p;if(c.status===204)p={};else{let d=await c.text();try{p=JSON.parse(d)}catch{p=d}}return this.logger&&!t.noLog&&p&&this.logger.debug({result:p,status:c.status,...o},"Got response from Momentic server"),p}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},_t=class extends Vd{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var at=class extends _t{constructor(e){super(e)}getAppUrl(){return this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${_}/auth/check`,{method:"GET",noLog:!0},10,5e3),{orgId:t,userId:n}=Xh.parse(e);return{orgId:t,userId:n}}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${_}/runs/status`,{method:"POST",body:e,noLog:!0});return Vh.parse(t)}async createRunGroup(e){let t=await this.sendRequest(`/${_}/run-groups`,{method:"POST",body:e,noLog:!0},10);return Hh.parse(t)}async updateRunGroup(e,t){await this.sendRequest(`/${_}/run-groups/${e}`,{method:"PATCH",body:t,noLog:!0},5)}async createRun(e){let t=await this.sendRequest(`/${_}/runs`,{method:"POST",body:e,noLog:!0},10);return Gh.parse(t)}async updateRun(e,t){await this.sendRequest(`/${_}/runs/${e}`,{method:"PATCH",body:t,noLog:!0},5)}async createRunAttempt(e){let t=await this.sendRequest(`/${_}/runs/${e}/attempts`,{method:"POST",noLog:!0},10);return Kh.parse(t)}async updateRunAttempt(e,t,n){await this.sendRequest(`/${_}/runs/${e}/attempts/${t}`,{method:"PATCH",body:n,noLog:!0},5)}async getTest(e){let t=await this.sendRequest(`/${_}/tests/${e}`,{method:"GET"});return Dh.parse(t)}async getAllTestIds(){let e=await this.sendRequest(`/${_}/tests`,{method:"GET"});return Uh.parse(e)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${_}/tests/export`,{method:"POST",body:e});return Bh.parse(t)}async updateTestWithYAML(e){await this.sendRequest(`/${_}/tests/update`,{method:"POST",body:e})}async updateStepCaches(e){await this.sendRequest(`/${_}/cache`,{method:"PATCH",body:e})}async getStepCacheForTest(e){let t=await this.sendRequest(`/${_}/cache`,{method:"POST",body:e},10);return zh.parse(t)}async queueTests(e){let t=await this.sendRequest(`/${_}/tests/queue`,{method:"POST",body:e});return Fh.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${_}/screenshots`,{method:"POST",body:e,noLog:!0},3,5e3);return Jh.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${_}/environments`,{method:"GET"});return Zh.parse(e)}async getEnvironment(e){let t=await this.sendRequest(`/${_}/environments/${e}`,{method:"GET"});return Xa.parse(t)}async getAllFeatureFlags(){let e=await this.sendRequest(`/${_}/auth/flags`,{method:"GET",noLog:!0},10);return Qh.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${_}/result-cache/lock`,{method:"POST",body:e,signal:t});return lg.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${_}/result-cache/lock`,{method:"DELETE",body:{key:e}})}async deleteCacheResult(e){await this.sendRequest(`/${_}/result-cache/entry`,{method:"DELETE",body:e})}async setCacheResult(e){await this.sendRequest(`/${_}/result-cache/entry`,{method:"PATCH",body:e})}async getCacheResult(e){try{return await this.sendRequest(`/${_}/result-cache/entry`,{method:"POST",body:e})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${_}/suites/queue`,{method:"POST",body:e});return eg.parse(t)}async bulkGetSuiteStatus(e){let t={suiteRunIds:e},n=await this.sendRequest(`/${_}/suites/status`,{method:"POST",body:t,noLog:!0});return tg.parse(n)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${_}/run-groups/status`,{method:"POST",body:t,noLog:!0});return Um.array().parse(n)}async updateCacheLastUsedDate(e,t){try{await this.sendRequest(`/${_}/cache/lastUsedAt`,{method:"PATCH",body:e,noLog:!0})}catch(n){t.error({err:n},"Failed to update cache last used date")}}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${_}/test-fragments/`,{method:"POST",body:e})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}async uploadSnapshotScreenshot(e,t,n){try{await this.sendRequest(`/${_}/snapshots/${t}/screenshot`,{method:"POST",body:n,noLog:!0})}catch(o){e.error({err:o},"Failed to upload screenshot")}}async generateConsoleLogsForRunAttemptUploadUrl(e,t,n){let o=await this.sendRequest(`/${_}/runs/${t}/attempts/${n}/console-logs`,{method:"POST",noLog:!0});return Po.parse(o)}async generateNetworkLogsForRunAttemptUploadUrl(e,t,n){let o=await this.sendRequest(`/${_}/runs/${t}/attempts/${n}/network-logs`,{method:"POST",noLog:!0});return Po.parse(o)}async generateHtmlSnapshotUploadUrl(e,t){let n=await this.sendRequest(`/${_}/snapshots/${t}/html`,{method:"POST",noLog:!0});return Po.parse(n)}async generateA11yTreeSnapshotUploadUrl(e,t){let n=await this.sendRequest(`/${_}/snapshots/${t}/a11y`,{method:"POST",noLog:!0});return Po.parse(n)}async reportBillableEvents(e,t){try{await this.sendRequest(`/${_}/billing/events`,{method:"POST",body:t,noLog:!0},10,5e3)}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${_}/test-fragments/${e}`,{method:"GET",noLog:!0});return ng.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${_}/test-fragments/${e}`,{method:"PATCH",body:t})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${_}/results/tests/${e}`,{method:"POST",body:t});return rg.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${_}/results/uploads`,{method:"POST",noLog:!0});return og.parse(e)}async startProcessingResultsUpload(e){let t=await this.sendRequest(`/${_}/results/uploads/${e}/process`,{method:"POST",noLog:!0});return ig.parse(t)}async fetchIconKnowledgeBase(e,t){try{let n=await this.sendRequest(`/${_}/knowledge-base/icons`,{method:"GET",noLog:!0});return hg.parse(n)}catch(n){return t.error({err:n},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t,n){try{await this.sendRequest(`/${_}/icon-knowledge-base/icons`,{method:"POST",body:t,noLog:!0},3,5e3)}catch(o){n.error({err:o},"Failed to save new icons to icon knowledge base")}}async getAllFlagsAndPayloads(){let e=await this.sendRequest(`/${_}/feature-flags`,{method:"GET",noLog:!0},3,5e3);return ag.parse(e)}};import{randomUUID as ES}from"crypto";var Qs=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvent(e,t,n){try{return await this.apiClient.reportBillableEvents(e,[{event:t,timestamp:new Date().toISOString(),transactionId:n?.eventId??ES(),properties:Vc({},n)}])}catch(o){e.error({err:o},"Failed to report billable event")}}async reportCreditsUsed(e,t,n,o){if(n)try{return await this.apiClient.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:o?.eventId??ES(),properties:Vc({creditsUsed:n,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};function qo(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var el=class{constructor(e){this.client=e}async storeConsoleLogsForRunAttempt(e,t,n,o){try{let i=JSON.stringify(o),{uploadUrl:a}=await this.client.generateConsoleLogsForRunAttemptUploadUrl(e,t,n),s=await qo(a,"application/json",i);if(!s.ok)throw new Error(`Failed to upload network logs: ${s.statusText}`)}catch(i){e.error({err:i},"Failed to upload console logs")}}async storeNetworkLogsForRunAttempt(e,t,n,o){let i=JSON.stringify(o);try{let{uploadUrl:a}=await this.client.generateNetworkLogsForRunAttemptUploadUrl(e,t,n),s=await qo(a,"application/json",i);if(!s.ok)throw new Error(`Failed to upload network logs: ${s.statusText}`)}catch(a){e.error({err:a},"Failed to upload network logs")}}async storeHtmlSnapshot(e,t,n){try{let{uploadUrl:o}=await this.client.generateHtmlSnapshotUploadUrl(e,t),i=await qo(o,"text/html",n);if(!i.ok)throw new Error(`Failed to upload network logs: ${i.statusText}`)}catch(o){e.error({err:o},"Failed to upload html snapshot")}}async storeScreenshot(e,t,n){try{await this.client.uploadSnapshotScreenshot(e,t,{screenshot:n.toString("base64")})}catch(o){e.error({err:o},"Failed to upload screenshot")}}async storeA11yTreeSnapshot(e,t,n){return Promise.resolve()}async getConsoleLogsForRunAttempt(e,t,n){}async getNetworkLogsForRunAttempt(e,t,n){}async getHtmlSnapshot(e,t){}async getA11yTreeSnapshot(e,t){}async getScreenshot(e,t){}};var Ko=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}async saveStepCacheEntries(e,t,n){try{await this.client.updateStepCaches({entries:e,testId:t})}catch(o){n.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let t=await this.client.getStepCacheForTest({testId:e.testId,organizationId:e.organizationId,steps:e.steps,schemaVersion:e.schemaVersion}),{hits:n}=Lo({steps:e.steps,stepCacheEntries:t,logger:e.logger});this.client.updateCacheLastUsedDate(n,e.logger)}fetchIconKnowledgeBase(e,t){return this.client.fetchIconKnowledgeBase(e,t)}saveNewIcons(e,t,n){return this.client.saveNewIcons(e,t,n)}};import{Faker as xI,en as TI}from"@faker-js/faker";var Yo="v1",ar=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new xI({locale:TI}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Yo}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof hn?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Yo}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof hn?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Yo}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof hn?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Yo}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof hn?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Yo}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof hn?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Yo}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof hn?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as EI}from"zod";var Jo=class extends _t{constructor(e){super(e)}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return Zm.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${_}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ba,...e},signal:t.abortSignal});return Xm.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${_}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return EI.string().parse(t)}async getElementLocation(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return Mh.parse(o)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return td.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return Nh.parse(o)}async getVisualAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return td.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${_}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Oh.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${_}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let n=await this.sendRequest(`/${_}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Tc.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${_}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return _h.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${_}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return xc.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${_}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Mc.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${_}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return Jm.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${_}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return $u.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${_}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Wu.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${_}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Cu.parse(n)}};var Kr=class extends _t{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${_}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Au.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var tl=class{constructor(e){this.client=e}async uploadResultsArchive(e){let{uploadUrl:t,id:n}=await this.client.generateTestResultsUploadUrl(),o=await qo(t,"application/zip",e);if(!o.ok)throw new Error(`Failed to upload test results: ${await o.text()}`);let{runGroupId:i}=await this.client.startProcessingResultsUpload(n);return i}};import{PostHog as CI}from"posthog-node";var Xo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var CS=r=>{let e=r.reason===void 0?new DOMException("This operation was aborted.","AbortError"):r.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};async function D(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,s;return new Promise((l,c)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:d}=e;d.aborted&&c(CS(d)),s=()=>{c(CS(d))},d.addEventListener("abort",s)}if(t===Number.POSITIVE_INFINITY){r.then(l,c);return}let p=new Xo;a=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(d){c(d)}return}"cancel"in r&&typeof r.cancel=="function"&&r.cancel(),o instanceof Error?c(o):(p.message=o??`Promise timed out after ${t} milliseconds`,c(p))},t),(async()=>{try{l(await r)}catch(d){c(d)}})()}).catch(l=>{throw l}).finally(()=>{a!==void 0&&i.clearTimeout.call(void 0,a),s!==void 0&&e.signal&&e.signal.removeEventListener("abort",s)})}async function AS(r,e){let t,n=0,o=3,i,a;for(;n<o;)try{let s=await D(r.getAllFlagsAndPayloads(e),{milliseconds:5e3});i=s.featureFlags||{},a=s.featureFlagPayloads||{};break}catch(s){t=s,n++,await new Promise(l=>setTimeout(l,100*n))}if(i&&a)return{flags:i,payloads:a};throw t}var Zo=class r extends Gi{constructor(t,n,o,i){super(o,i);this.client=t;this.orgId=n}static async init(t,n){let o=n??new CI("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:i,payloads:a}=await AS(o,t);return new r(o,t,i,a)}async refresh(){let{flags:t,payloads:n}=await AS(this.client,this.orgId);this.flags=t,this.payloads=n}};import{Server as tO}from"socket.io";import{cloneDeep as AI}from"lodash-es";var RI={showOverlay:!1},qd=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:t,cleanup:n,clientIp:o,sessionId:i,browserbaseSessionId:a}){return this.sessions.set(i,{controller:e,context:t,cleanup:n,clientIp:o,browserbaseSessionId:a,browserBehavior:AI(RI)}),i}removeSession(e,t){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:i}=o;try{i.setClosed(),await i.browser.cleanup()}catch(a){t.error({err:a},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(a){t.error({err:a},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}},Z=new qd;function RS(r,e,t){let n=Date.now(),o=Date.now(),i,a,s,l,c=!1,p=async(h,g)=>{if(!h.closed&&!h.isInPageLoad)try{let f=s;s=void 0;let S=h.url(),x=g.toEditorDisplayCopy();JSON.stringify(x)===JSON.stringify(i)&&S===l&&n>o||(r.emit("browserState",{logsPerPage:f?.logsPerPage,harPages:f?.harPages,harEntries:f?.harEntries,viewport:h.getViewport(),url:S,iframeSrcUrls:a??[],context:x,isInPageLoad:h.isInPageLoad}),n=Date.now()),l=S,i=x}catch(f){if(!r.connected)return;let S=f instanceof Error?f.message:`${f}`;if(S.includes("Frame was detached")||S.includes("Not attached to an active page")||S.includes("browser has been closed")||S.includes("UserInfrastructureError"))return;t.error({err:f,sessionId:e},"Error grabbing browser state")}},d=setInterval(()=>{let h=Z.getSession(e),g=h?.controller?.browser;if(!g||g.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(d);return}p(g,h.context)},1e3),m=(h,g)=>!!(JSON.stringify(h)!==JSON.stringify(a)||g.logsPerPage.some(f=>f.length>0)||g.harPages&&Object.keys(g.harPages).length>0||g.harEntries&&Object.keys(g.harEntries).length>0),u=setInterval(async()=>{let g=Z.getSession(e)?.controller?.browser;if(!g||g.closed){clearInterval(u);return}else if(c)return;c=!0;try{let f=await g.getAllFrameUrls(),S=g.retrieveAndClearDebugData();m(f,S)&&(a=f,s=S,o=Date.now())}catch(f){t.warn({err:f},"Failed to fetch extended details")}finally{c=!1}},2500);return{timers:[d,u]}}var sr={};var II=r=>()=>{let{sessionId:e}=r.metadata;sr[e]?.abort?.abort()},IS={event:"cancelApiTest",createHandler:II};import{CookieJar as VI}from"tough-cookie";import{randomUUID as FI}from"crypto";import{faker as PI}from"@faker-js/faker";import LI from"assert";import kI from"axios";import OI from"moment";import*as NI from"otpauth";import MI from"pg";async function PS(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=fs(n,e);t.push(...o)}),t}var _I=Object.getPrototypeOf(async function(){}).constructor;async function LS(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o}=e.bindings,i=e.tools,a={},s=(f,S)=>{o[f]=S,a[f]=S},l={},c=(f,S)=>{o[f]=S,l[f]=S},p;n.includes("Octokit")&&(p=(await import("@octokit/rest")).Octokit);let d;n.includes("createAppAuth")&&(d=(await import("@octokit/auth-app")).createAppAuth);let m=async()=>await Promise.resolve(new _I("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai",n)(kI,OI,i.fakerInstance??PI,LI,MI,p,d,NI,PS,o,s,c,S=>i.sms.send(S),S=>i.sms.fetchLatest(S),i.email,i.sms,i.ai)),u=!0,h,g;try{h=await D(m(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal})}catch(f){t.error({err:f,env:o,evalCode:n},`[${r}] Error executing code: ${f}`),u=!1,f instanceof Xo?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:h,variableUpdates:a,persistentVariableUpdates:l,success:u,error:g}}async function kS({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=Yn}){let s=FI(),l=await LS(s,{code:r,options:{fragment:e,timeoutMs:a},bindings:t.toObjectCopy(),tools:n,signal:i},o);return y.debug(`[${s}] Got execution result: ${JSON.stringify(l)}`),l}import{createHmac as DI,randomUUID as UI}from"crypto";import BI from"fetch-retry";var zI=BI(global.fetch,{retries:3,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),OS=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,NS=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function MS({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=Yn,retries:i=2,signal:a,logger:s}){if(!OS)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,p=0;if(!NS)throw new Error("Missing lambda auth secret.");let d=DI("sha256",NS).update(r).digest("hex");for(;p<=i;){p++,a?.throwIfAborted();let u={id:UI(),orgId:r,momenticLambdaAuthHash:d,code:e,fragment:t,state:n.toObjectCopy(),timeoutMs:o};try{if(l=await D(zI(OS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(h){c=h}}if(c)throw s.error({err:c},"Failed to evaluate code remotely"),c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let m;try{m=ah.parse(await l.json())}catch(u){throw new Error(`Code evaluation server returned invalid response: ${u}`)}if(m.error)throw new Error(`Code evaluation error: ${m.error}`);return m}async function Fn(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await MS(r);else if(r.localTools)e=await kS({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
50
|
+
${e.error}
|
|
51
|
+
Code received:
|
|
52
|
+
${r.code}`;throw r.logger.error({err:e.error,code:r.code,env:r.context.toObjectCopy()},t),new Error(t)}if(e.variableUpdates)for(let[t,n]of Object.entries(e.variableUpdates))r.context.setVariable(t,n);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await r.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,n]of Object.entries(e.persistentVariableUpdates))r.context.setVariable(t,n)}return e.result}async function jt(r){let{orgId:e,s:t,context:n,logger:o,signal:i,flagStore:a,retries:s=2,timeoutMs:l=Yn,allowUndefined:c=!1}=r,p=/{{(.*?)}}/g,d=t.matchAll(p),m=t;for(let u of d){if(u.length<2)continue;let h=u[1].trim(),g;try{g=await Fn({orgId:e,code:h,fragment:!0,context:n,timeoutMs:l,logger:o,retries:s,localTools:r.localTools,signal:i,flagStore:a})}catch(S){throw o.error({err:S,value:t},"Error evaluating template string"),S}if(g===void 0&&!c)throw new A("UserConfigurationError",`Template fragment '${h}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let f=typeof g=="string"?g:`${g}`;f=f.replaceAll(/\$/g,"$$$$"),m=m.replace(u[0],f)}return m}async function Qo(r){return _S(r)}async function _S({obj:r,bannedKeys:e,allowList:t,context:n,prefixPath:o="",replacements:i={},...a}){for(let s in r){if(e.includes(s))continue;let l=!1;if(t)if(t.includes(s))l=!0;else continue;let c=r[s],p=o?`${o}.${s}`:s;if(typeof c=="string"&&c.includes("{{")){let d=await jt({s:c,context:n,...a});if(c===d)continue;i[p]=c,r[s]=d}else typeof c=="object"&&c!==null&&!Array.isArray(c)&&await _S({obj:c,bannedKeys:e,context:n,prefixPath:p,replacements:i,allowList:l?void 0:t,...a})}return i}import jI from"fetch-retry";var C5=process.env.MAILINATOR_API_KEY,A5=jI(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import $I from"fetch-cookie";import{cloneDeep as WI}from"lodash-es";var nl=(r,e)=>{try{let{hostname:t,pathname:n}=new URL(r),{hostname:o,pathname:i}=new URL(e);return t!==o||n!==i}catch{return!1}},ei=r=>{try{return new URL(r),!0}catch{return!1}},FS=r=>!r.toLowerCase().startsWith("http"),ti=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function lr(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}var HI=3e4;async function rl({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??HI/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([u,h])=>u&&h)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([u,h])=>u&&h).forEach(([u,h])=>{a.append(u,h)});let s=a.toString(),l;if(ei(r.url)&&(l=r.url),t&&ti(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new A("ActionFailureError",`Invalid URL: ${r.url}`);e.debug({url:l,searchParams:s,headers:i,body:r.body,method:r.method},"Making HTTP request");let p=await D((async()=>{let u=s?`${l}?${s}`:l;try{return await n(u,{headers:i,method:r.method,body:r.body})}catch(h){throw e.error({err:h},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${h}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new A("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!p.ok){let u;try{u=await p.text()}catch(h){u=`Failed to read response body: ${h}`}throw new A("ActionFailureError",`Fetch request failed with status ${p.status}: ${u}`)}let d={};p.headers.forEach((u,h)=>{d[h]=u});let m={status:p.status,headers:d};return p.headers.get("content-type")?.includes("json")?m.json=await p.json():p.headers.get("content-type")?.includes("text")&&(m.text=await p.text()),m}async function DS(r){let{fixtures:e,inputs:t}=r,{context:n}=e,{orgId:o,step:i}=t,a=WI(i);await Qo({obj:a,orgId:o,bannedKeys:["code"],...e});let s=await GI(r);return a.envKey&&s.data&&n.setVariable(a.envKey,s.data),s}async function GI(r){let{fixtures:e,inputs:t}=r,{step:n,orgId:o,baseUrl:i}=t,{cookieJar:a}=e,s=new Date;switch(n.type){case"JAVASCRIPT":{let c=await Fn({code:n.code,orgId:o,fragment:!!n.fragment,timeoutMs:n.timeout?n.timeout*1e3:void 0,...e});try{JSON.stringify(c)}catch(p){return{...n,startedAt:s,finishedAt:new Date,status:"FAILED",message:`JavaScript return value is not serializable: ${p instanceof Error?p.message:`${p}`}`}}return{...n,startedAt:s,finishedAt:new Date,message:"JavaScript code executed successfully",status:"SUCCESS",data:c}}case"REQUEST":{let c=$I(fetch,a),p=await rl({command:n,logger:e.logger,baseUrl:i,fetchImplementation:c});return{...n,startedAt:s,finishedAt:new Date,status:"SUCCESS",message:"Request executed successfully",data:p}}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}async function US(r){let{inputs:e,fixtures:t,callbacks:n}=r,{signal:o}=t,{steps:i,orgId:a,baseUrl:s}=e,{test:l,step:c}=n,p={startedAt:new Date,status:"RUNNING",results:[]},d=p.results,m=new VI,u={cookieJar:m,...t};for(let h of i){let g=new Date;c.onStarted?.(h.id);let f;try{o?.throwIfAborted(),f=await DS({inputs:{step:h,baseUrl:s,orgId:a},fixtures:u})}catch(S){o?.aborted?f={...h,startedAt:g,finishedAt:new Date,status:"CANCELLED",message:"Step cancelled by user."}:f={...h,startedAt:g,finishedAt:new Date,status:"FAILED",message:`Step failed: ${S instanceof Error?S.message:`${S}`}`}}if(d.push(f),c.onFinished?.({result:f,cookies:ys(m,new URL(s).hostname)}),l.updateAttemptProgress?.({results:d}),f.status!=="SUCCESS"){p.status=f.status==="CANCELLED"?"CANCELLED":"FAILED";break}}return p.status==="RUNNING"&&(p.status="PASSED"),p.finishedAt=new Date,l.onFinished?.(),p}async function BS(r){let{socket:e,storage:t}=r,n=r.socket.id,{testId:o}=e.handshake.query;if(typeof o!="string")throw new Error(`Received invalid test ID that does not parse as a string: ${o}`);let i=await t.getOrgId({type:"api-test",testId:o}),{baseUrl:a,envName:s,environmentVariables:l}=await Kd({testId:o,orgId:i,logger:r.logger,storage:t,authorization:r.authorization}),c={type:"api-test",orgId:await r.storage.getOrgId({type:"api-test",testId:o}),testId:o,sessionId:n,latestContext:new It({baseUrl:a||"",currentUrl:a||"",variablesFromEnvironment:l,envName:s})};return sr[n]=c,c}async function Kd({testId:r,orgId:e,logger:t,storage:n,authorization:o}){let i=await n.fetchApiTestMetadata(r,e,t);if(!i)throw new Error(`Failed to fetch API test metadata for test ID: ${r}`);let a;o?.type==="API_KEY"&&(a=new ar({httpClient:new _t({...o,logger:t}),fakerSeed:void 0}));let s=i.envs?.find(d=>d.default),l;s&&(l=await n.fetchEnvironment(e,s.name,t));let c=i.baseUrl||l?.variables?.[Ie];if(!c)throw new Error("Base URL is empty in both API test options and the configured environment");let p={...l?.variables};return{baseUrl:c,envName:l?.name,environmentVariables:p,localCodeEvalTools:a}}var qI=r=>async(e,t)=>{let{steps:n}=e,{authorization:o,metadata:i,socket:a,storage:s,logger:l,flagStoreFactory:c}=r,{orgId:p,testId:d,sessionId:m}=i,u=l.child({testId:d,orgId:p,sessionId:m}),h=sr[m];if(!h)throw new Error(`No api testing session with id ${m} could be found. Please reconnect and try again.`);let g=new AbortController;h.abort=g;let f=h.latestContext,{localCodeEvalTools:S,baseUrl:x}=await Kd({testId:d,orgId:p,logger:u,storage:s,authorization:o}),v={context:f,logger:u,localTools:S,signal:g.signal,flagStore:await c(p)},C=await US({inputs:{steps:n,orgId:p,baseUrl:x},fixtures:v,callbacks:{test:{onFinished:()=>{a.emit("apiTestFinished")}},step:{onStarted:I=>{a.emit("apiStepStarted",I)},onFinished:I=>{a.emit("apiStepFinished",I)}}}});t({result:C})},zS={event:"executeApiTest",createHandler:qI};var KI=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async()=>{e.info({sessionId:t},"Cancel event received");let n=Z.getSession(t);if(!n)throw new Error("No active session found");try{n.controller.setClosed()}catch{}}},jS={event:"cancel",createHandler:KI};var YI=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async(n,o)=>{let i=Z.getSession(t);if(!i)throw new Error("No active session found");i.controller.setOpen();let a=i.controller.browser;try{let s=await a.getBrowserState({skipWait:!0});o({a11yTree:s.serialize()})}catch(s){e.error({err:s},"Error fetching a11y tree from the browser"),o({err:s.message})}}},HS={event:"fetchA11yTree",createHandler:YI};var JI=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async(n,o)=>{let i=Z.getSession(t);if(!i)throw new Error("No active session found");i.controller.setOpen();let a=i.controller.browser;try{let s=await a.html();o({html:s})}catch(s){e.error({err:s},"Error fetching DOM from the browser"),s.name==="TimeoutError"?o({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):o({err:s.message})}}},$S={event:"fetchDom",createHandler:JI};var XI=({metadata:r,logger:e})=>{let{sessionId:t,type:n}=r;return o=>{e.info({sessionId:t,reason:o},`Disconnect event received (${o})`),n==="e2e"?Z.removeSession(t,e):n==="api-test"&&delete sr[t]}},WS={event:"disconnect",createHandler:XI};function nn(r){let{result:e,nestedResults:t}=r;if(!r.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=ZI(t);QI(e,n,o);let i=[...r.asyncTasks];r.asyncTasks.push((async()=>{try{await eP(i,e,n,o)}catch(a){r.logger.error({result:r.result,err:a},"Error hoisting scalar result metadata")}})())}function ZI(r){let e=r[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertion){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let n=r[r.length-1],o;for(;;){switch(n.type){case"PRESET_ACTION":{o=n;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!n.results.length){o=n;break}n=n.results[n.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function QI(r,e,t){e&&(r.beforeUrl=e.beforeUrl),t&&(r.afterUrl=t.afterUrl,r.data=t.data,t.status!=="SUCCESS"&&(r.message=t.message))}async function eP(r,e,t,n){await Promise.allSettled(r),t&&(e.beforeSnapshot=t.beforeSnapshot),n&&(e.afterSnapshot=n.afterSnapshot)}import wa from"os";import tP from"v8";var GS,En,nP=wa.platform(),rP=wa.cpus().map(r=>({model:r.model,speed:r.speed}));function VS(r){let e=()=>{try{let t=!1,n=oP(),o=iP();n.freeMemory<1e6&&(t=!0);let i=tP.getHeapStatistics(),a=i.used_heap_size,s=i.heap_size_limit;a/s>.9&&(t=!0),t?r.warn({memory:n,cpu:o,heapStats:i},"Critical resource usage metrics detected"):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,1e4),cpuMetadata:rP,platform:nP}}function oP(){let r=wa.totalmem(),e=wa.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function iP(){let r=wa.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of r)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!En)return En=t,null;let n={user:t.user-En.user,nice:t.nice-En.nice,sys:t.sys-En.sys,idle:t.idle-En.idle,irq:t.irq-En.irq,total:t.total-En.total};return GS={measurementTime:e,intervalMs:e-En.measurementTime,user:n.user/n.total*100,nice:n.nice/n.total*100,sys:n.sys/n.total*100,idle:n.idle/n.total*100,irq:n.irq/n.total*100,total:100-n.idle/n.total*100},En=t,GS}import{hostname as dP}from"os";async function KS(r){let{command:e,tracer:t,timeoutMs:n,targetingWrapper:o,disableCache:i,fixtures:a}=r,{logger:s,abortSignal:l}=a;if(e.target&&!qn(e.target))throw new Error("Element assertion with x/y is not supported yet");let c=e.assertion.type==="ELEMENT_EXISTENCE"&&e.assertion.negated,p=Date.now(),d=0,m,u=500;for(;d<2||Date.now()-p<n;){d++,d>1&&await Q(u,l),l?.throwIfAborted();try{let{newTarget:h,elementInteractedDisplayString:g,result:f}=await o({ctx:a.ctx,tracer:t,command:e,target:e.target,cache:e.cache?.target,action:async S=>aP(S.locator,r),options:{disableCache:i,useSelector:!!e.useSelector,iframeUrl:e.iframeUrl,disableGlobalLocatorRedirect:!0,source:c?"NEGATED_CHECK":void 0}});if(m={success:f.success,data:f.data,err:f.err,newTarget:h,elementInteractedDisplayString:g},!f.success){m=f,u=Math.min(u*2,1e4);continue}return m}catch(h){if(l?.throwIfAborted(),c)return{success:!0,thoughts:`The element described does not exist on the page: ${h.message}`};if(s.warn({err:h},"Element assertion ended in error, retrying..."),!(h instanceof A)||h.reason!="ActionFailureError")throw h;m={success:!1,err:h}}}if(!m)throw new Error(`Failed to evaluate manual element assertion in ${n}ms.`);return m}async function aP(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let s=await r.textContent()??"";if(a={elementTextContent:_e(s,500,!0)},!qS(s,n.value,n.operation,!!n.negated)){let l=n.negated?Qn[n.operation]:er[n.operation];o=!1,i=new A("AssertionFailureError",`The content ${l} '${n.value}': ${s}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:_e(await r.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let s;try{s=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(l){i=new A("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${l}`),o=!1;break}if(!qS(s,n.value,n.operation,!!n.negated)){let l=n.negated?Qn[n.operation]:er[n.operation];o=!1,n.operation==="EXISTS"?i=n.negated?new A("AssertionFailureError",`The attribute ${n.attr} ${l}: ${s}`):new A("AssertionFailureError",`The attribute ${n.attr} ${l}`):i=new A("AssertionFailureError",`The attribute ${n.attr} ${l} '${n.value}': ${s}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.isVisible({timeout:wn*1e3});break}case"EDITABLE":{o=await r.isEditable({timeout:wn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:wn*1e3});break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let s=n.negated?ad[n.condition]:sd[n.condition];i=new A("AssertionFailureError",`The element ${s}`)}break}}return{success:o,data:a,err:i}}function qS(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}import{Jimp as sP}from"jimp";async function va(r,e){let t=await r.screenshot(e),n=await sP.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as YS}from"jimp";import Yd from"jpeg-js";import lP from"pixelmatch";async function JS({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!qn(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let l={clearHighlights:!0,hideCaret:!0},c;t.target?.elementDescriptor?c=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target??t.target?.a11yData,action:async j=>va(o,{locator:j.locator,...l}),options:{disableCache:!!n,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl,disableGlobalLocatorRedirect:!0}})).result:c=await va(o,l);let p=await s.prepareGoldenScreenshotForComparison(a,t,c);if((c.height!==p.height||c.width!==p.width)&&a.debug({currHeight:c.height,currWidth:c.width,savedHeight:p.height,savedWidth:p.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-p.height)>10||Math.abs(c.width-p.width)>10){let z=`${c.width}x${c.height}`,j=`${p.width}x${p.height}`;return{fail:!0,thoughts:`Current screenshot (${z}) does not match saved screenshot dimensions (${j}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:p.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await YS.fromBuffer(c.buffer),m={width:c.width,height:c.height},u=await YS.fromBuffer(p.buffer),h={width:p.width,height:p.height},g,f=m.width*m.height,S=h.width*h.height,x=Math.abs(m.height-h.height),v=Math.abs(m.width-h.width);if(f>S){let z=d.cover({w:h.width,h:h.height});c.buffer=await z.getBuffer("image/jpeg"),g="current",c.width=h.width,c.height=h.height}else if(S>f){let z=u.cover({w:m.width,h:m.height});p.buffer=await z.getBuffer("image/jpeg"),g="saved"}let b={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},E=t.threshold??.1,I=lP(Yd.decode(p.buffer).data,Yd.decode(c.buffer).data,b.data,c.width,c.height,{threshold:E,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,M=I>E*100,L=`Visual diff of ${I.toFixed(2)}% detected, which is ${M?"over":"under"} the threshold of ${E*100}%.`;if(g&&(L+=` The ${g} screenshot was cropped since it was taller by ${x} pixels and wider by ${v} pixels.`),M)throw new A("ActionFailureError",L);return{fail:M,thoughts:L,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:Yd.encode(b,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var cP=5e3;async function ol({timeout:r=wn,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,s=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let l=Date.now();i=await XS(e),a=Date.now();let c=a-l;if(c>1e3&&e.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await Q(s,e.signal),s=Math.min(Math.floor(s*1.5),cP);else return i}return i=await XS(e),i}async function XS({assertion:r,browser:e,flagStore:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let s;if(t.isBooleanFlagEnabled("auto_expand_iframes")){let l=await e.evaluateFunctionInAllFrames(ZS,{value:r.value,negated:!!r.negated,returnHtml:!1});i=l.some(c=>c.evaluation),s=l.find(c=>c.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(ZS,{value:r.value,negated:!!r.negated,returnHtml:!0}));if(!i){let l=r.negated?Qn.CONTAINS:er.CONTAINS;a=new A("AssertionFailureError",`The page ${l} '${r.value}'.`),o=s}}catch(s){a=new A("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function ZS({value:r,negated:e,returnHtml:t}){let n=document.documentElement.outerHTML,o=n.includes(r)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?n:void 0}}var Jd=async r=>{let{step:e,resolvedInputs:t}=r.moduleParams,{logger:n,context:o,storage:i,codeEvalTools:a,controller:s}=r.fixtures,l=s.browser,{orgId:c,runId:p}=r.inputs,d=s.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),n.debug({inputs:t,moduleId:e.moduleId},"Set module inputs"));let m,u=!1,h,g;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",S=await jt({orgId:c,s:f,context:o,logger:n,localTools:a,signal:d,flagStore:s.flagStore});g={orgId:c,cacheKeys:[S,...Object.entries(t).map(([v,b])=>`${v}:${b}`)]},n.debug({original:f,keyParams:g},"Module cache key params");let x=Date.now();for(;Date.now()-x<Lh;){d?.throwIfAborted();let v=await i.getCacheResult(g);if(v){n.debug({cacheResult:v},"Got result from module execution cache"),m=il(e,t,"SUCCESS"),m.message="Used cached module result.",m.data=JSON.parse(v),u=!0;break}else n.debug({cacheKey:f,keyParams:g},"No cache result found, continuing with lock acquisition");let b=await i.acquireCacheLock({keyParams:g,clientMetadata:`hostName:${dP()};runId:${p}`},d);if(b.acquired){h=b.keyPrefix,n.info({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Acquired cache lock and proceeding with module execution");break}else n.debug({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Failed to acquire cache lock, retrying...");await Q(2500+Math.random()*1e4,d)}}try{if(!m)m=await pP(r);else if(e.autoAuth){let f=Ss.safeParse(m.data);if(!f.success)throw new A("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);n.debug("Automatically loading auth state after cached module result"),await l.loadAuthState(f.data);let S=!1,x=e.advanced?.cacheInvalidation;if(x&&x.type==="PAGE_CHECK"){let v={type:"CONTENT",value:x.substring},b=await ol({timeout:wn,assertion:v,browser:l,flagStore:s.flagStore,logger:n,signal:d});b.success?n.debug({invalResult:b},"Cached result still valid after page check, continuing..."):(n.info({invalResult:b},"Invalidating cached result due to page check failure"),S=!0)}if(g&&S)return await i.deleteCacheResult(g),Jd(r)}}finally{try{h!==void 0&&!u&&m?.status==="SUCCESS"&&await uP({step:e,result:m,browser:s.browser,cacheKeyPrefix:h,logger:n,storage:i})}finally{h!==void 0&&await i.releaseCacheLock(h)}}return m},pP=async r=>{let{step:e,tracer:t}=r.moduleParams,n=il(e,r.moduleParams.resolvedInputs,"SUCCESS"),o=await t.startSubSteps(),{status:i,results:a}=await cr(r.work,()=>r.executeStepList({...r,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}}));return n.results=a,n.status=i,n.finishedAt=new Date,nn({asyncTasks:r.work.asyncTasks,nestedResults:a,result:n,logger:r.fixtures.logger}),n};function il(r,e,t){let n={};return Object.entries(e).forEach(([i,a])=>{n[i]=JSON.stringify(a)}),{type:"MODULE",id:r.id,moduleId:r.moduleId,moduleName:r.name,startedAt:new Date,cacheConfig:r.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:t}}async function QS({orgId:r,step:e,context:t,logger:n,flagStore:o,codeEvalTools:i,signal:a}){let s={};try{for(let l of e.parameters??[]){let c=e.inputs?.[l]??e.defaultParameters?.[l];if(!c){n.warn(`No value or default found for parameter '${l}' that is required by module '${e.name}'`);continue}s[l]=await Fn({orgId:r,code:c,fragment:!0,context:t,logger:n,localTools:i,signal:a,flagStore:o})}return s}catch(l){throw a?.throwIfAborted(),new A("UserConfigurationError",`Failed to evaluate module inputs: ${l}`)}}async function uP({step:r,result:e,browser:t,cacheKeyPrefix:n,logger:o,storage:i}){let a=r.cacheConfig?.cacheExpiryMs;(!a||a===cg)&&(a=r.defaultCacheTtl??dg);let s;r.autoAuth?s=JSON.stringify(await t.saveAuthState()):e.data!==void 0?s=JSON.stringify(e.data):s='""',o.debug({cacheKeyPrefix:n,ttlMs:a,truncatedCacheResultJson:_g(s)},"Setting module cache result"),await i.setCacheResult({result:s,keyPrefix:n,ttlMs:a})}async function dr(r,e,t){let n=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",s;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(s="Step aborted by user.",a="CANCELLED"):o instanceof A?s=`${o}`:s=`An unexpected error occurred: ${o.message}`,r.type==="RESOLVED_MODULE"){let l=il(r,{},"FAILED");return l.message=s,l.startedAt=n,l.finishedAt=i,l}return{...ks(r),startedAt:n,finishedAt:i,status:a,data:null,message:s,results:[]}}}async function cr(r,e){let t=!1;try{return r&&!r.state.failureRecoveryDisabled&&(r.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{r&&t&&(r.state.failureRecoveryDisabled=void 0)}}import{randomUUID as ey}from"crypto";import{cloneDeep as hP}from"lodash-es";function al(r,e){r.state.healingDetails?r.state.healingDetails.push(e):r.state.healingDetails=[e]}var sl=async r=>{let{step:e,tracer:t}=r.presetParams,{logger:n,controller:o,context:i,billingReporter:a}=r.fixtures,{collectDebugData:s}=r.options,{testMetadata:l,suiteMetadata:c}=r.inputs,p=e.command.type,d=n.child({commandType:p,stepId:e.id,commandId:e.command.id}),m=Hi(e.command);r.work.asyncTasks.push(a.reportCreditsUsed(d,p,m,{testId:l?.id,testName:l?.name,suiteId:c?.id,suiteName:c?.name}));let u=o.browser.url(),h=new Date,g,f=ey(),S=ey();if(s)try{g=await o.browser.screenshot({retries:1,clearHighlights:!0});let C=await o.browser.getRawCondensedHtml();t.attachBeforeHtmlSnapshot({logger:d,snapshotId:f,html:C}),r.work.asyncTasks.push(r.fixtures.debugDataStorage.storeHtmlSnapshot(d,f,C))}catch(C){d.debug({err:C},"Failed to take screenshot before step, likely because the page is still loading. This is non-fatal and does not affect the test.")}let x,v,b,E=ms();try{let C=await o.executePresetCommand(E,t,e.command,i,l?.advanced.disableAICaching??!1);C.beforeScreenshotOverride&&(g=C.beforeScreenshotOverride),b=C.afterScreenshotOverride;let{proposedStep:I}=gP({work:r.work,step:e,newTargets:C.newTargets,logger:d}),M=new Date,L=o.browser.url();v={beforeUrl:u,afterUrl:L,startedAt:h,finishedAt:M,viewport:o.browser.getViewport(),status:C.fail?"FAILED":"SUCCESS",elementInteracted:C.elementInteracted},x={...e,message:C.thoughts??fP(C.newTargets)??"Successfully executed preset action.",beforeUrl:u,afterUrl:L,finishedAt:M,startedAt:h,status:C.fail?"FAILED":"SUCCESS",data:C.data,results:[v],details:E.details,proposedStep:I},"assertion"in e.command&&(x.message=C.thoughts||"Assertion passed.")}catch(C){d.error({message:C.message,stack:C.stack},`Failed executing preset step ${Ur(e.command)}`);let I=o.browser.url(),M=new Date,L=C instanceof Error?C.message:`${C}`;C instanceof A&&C.getLastScreenshotBuffer()&&(b=C.getLastScreenshotBuffer()),v={beforeUrl:u,afterUrl:I,startedAt:h,finishedAt:M,viewport:o.browser.getViewport(),status:C instanceof DOMException&&C.name==="AbortError"?"CANCELLED":"FAILED",message:L},x={...e,startedAt:h,finishedAt:M,beforeUrl:u,afterUrl:I,status:C instanceof DOMException&&C.name==="AbortError"?"CANCELLED":"FAILED",message:L,failureReason:C instanceof A?C.reason:void 0,results:[v],details:E.details}}if(s)try{b||(b=await o.browser.screenshot({retries:1}));let C=await o.browser.getRawCondensedHtml();t.attachAfterHtmlSnapshot({logger:d,snapshotId:S,html:C}),r.work.asyncTasks.push(r.fixtures.debugDataStorage.storeHtmlSnapshot(d,S,C))}catch(C){d.debug({err:C},"Failed store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return v.beforeSnapshot=f,x.beforeSnapshot=f,v.afterSnapshot=S,x.afterSnapshot=S,g&&(t.attachBeforeScreenshot({logger:d,snapshotId:f,screenshot:g}),r.work.asyncTasks.push(r.fixtures.debugDataStorage.storeScreenshot(d,f,g))),b&&(t.attachAfterScreenshot({logger:d,snapshotId:S,screenshot:b}),r.work.asyncTasks.push(r.fixtures.debugDataStorage.storeScreenshot(d,S,b))),x};function gP({work:r,step:e,newTargets:t,logger:n}){if(!t?.length)return{proposedStep:void 0};let o=e.command;Ig(o,t,n);let i=t[0]?.description;if(i&&"target"in o&&o.target&&o.target.type==="description"){let a={...o,target:{...o.target,elementDescriptor:i}},s={...hP(e),command:a};return al(r,{type:"DESCRIPTION_UPDATE",thoughts:`Updated element description after the original element could not be found on the page. New element location reasoning: ${t[0]?.thoughts}`}),{proposedStep:s}}return{proposedStep:void 0}}function fP(r){if(r?.length){if(r.length===1&&r[0]?.thoughts)return r[0].thoughts;if(r.length===2&&r.every(e=>e.thoughts))return`Located first element: ${r[0]?.thoughts}
|
|
53
|
+
Located second element: ${r[1]?.thoughts}`}}var Xd=["ability","able","aboard","about","above","accept","accident","according","account","accurate","acres","across","act","action","active","activity","actual","actually","add","addition","additional","adjective","adult","adventure","advice","affect","afraid","after","afternoon","again","against","age","ago","agree","ahead","aid","air","airplane","alike","alive","all","allow","almost","alone","along","aloud","alphabet","already","also","although","am","among","amount","ancient","angle","angry","animal","announced","another","answer","ants","any","anybody","anyone","anything","anyway","anywhere","apart","apartment","appearance","apple","applied","appropriate","are","area","arm","army","around","arrange","arrangement","arrive","arrow","art","article","as","aside","ask","asleep","at","ate","atmosphere","atom","atomic","attached","attack","attempt","attention","audience","author","automobile","available","average","avoid","aware","away","baby","back","bad","badly","bag","balance","ball","balloon","band","bank","bar","bare","bark","barn","base","baseball","basic","basis","basket","bat","battle","be","bean","bear","beat","beautiful","beauty","became","because","become","becoming","bee","been","before","began","beginning","begun","behavior","behind","being","believed","bell","belong","below","belt","bend","beneath","bent","beside","best","bet","better","between","beyond","bicycle","bigger","biggest","bill","birds","birth","birthday","bit","bite","black","blank","blanket","blew","blind","block","blood","blow","blue","board","boat","body","bone","book","border","born","both","bottle","bottom","bound","bow","bowl","box","boy","brain","branch","brass","brave","bread","break","breakfast","breath","breathe","breathing","breeze","brick","bridge","brief","bright","bring","broad","broke","broken","brother","brought","brown","brush","buffalo","build","building","built","buried","burn","burst","bus","bush","business","busy","but","butter","buy","by","cabin","cage","cake","call","calm","came","camera","camp","can","canal","cannot","cap","capital","captain","captured","car","carbon","card","care","careful","carefully","carried","carry","case","cast","castle","cat","catch","cattle","caught","cause","cave","cell","cent","center","central","century","certain","certainly","chain","chair","chamber","chance","change","changing","chapter","character","characteristic","charge","chart","check","cheese","chemical","chest","chicken","chief","child","children","choice","choose","chose","chosen","church","circle","circus","citizen","city","class","classroom","claws","clay","clean","clear","clearly","climate","climb","clock","close","closely","closer","cloth","clothes","clothing","cloud","club","coach","coal","coast","coat","coffee","cold","collect","college","colony","color","column","combination","combine","come","comfortable","coming","command","common","community","company","compare","compass","complete","completely","complex","composed","composition","compound","concerned","condition","congress","connected","consider","consist","consonant","constantly","construction","contain","continent","continued","contrast","control","conversation","cook","cookies","cool","copper","copy","corn","corner","correct","correctly","cost","cotton","could","count","country","couple","courage","course","court","cover","cow","cowboy","crack","cream","create","creature","crew","crop","cross","crowd","cry","cup","curious","current","curve","customs","cut","cutting","daily","damage","dance","danger","dangerous","dark","darkness","date","daughter","dawn","day","dead","deal","dear","death","decide","declared","deep","deeply","deer","definition","degree","depend","depth","describe","desert","design","desk","detail","determine","develop","development","diagram","diameter","did","die","differ","difference","different","difficult","difficulty","dig","dinner","direct","direction","directly","dirt","dirty","disappear","discover","discovery","discuss","discussion","disease","dish","distance","distant","divide","division","do","doctor","does","dog","doing","doll","dollar","done","donkey","door","dot","double","doubt","down","dozen","draw","drawn","dream","dress","drew","dried","drink","drive","driven","driver","driving","drop","dropped","drove","dry","duck","due","dug","dull","during","dust","duty","each","eager","ear","earlier","early","earn","earth","easier","easily","east","easy","eat","eaten","edge","education","effect","effort","egg","eight","either","electric","electricity","element","elephant","eleven","else","empty","end","enemy","energy","engine","engineer","enjoy","enough","enter","entire","entirely","environment","equal","equally","equator","equipment","escape","especially","essential","establish","even","evening","event","eventually","ever","every","everybody","everyone","everything","everywhere","evidence","exact","exactly","examine","example","excellent","except","exchange","excited","excitement","exciting","exclaimed","exercise","exist","expect","experience","experiment","explain","explanation","explore","express","expression","extra","eye","face","facing","fact","factor","factory","failed","fair","fairly","fall","fallen","familiar","family","famous","far","farm","farmer","farther","fast","fastened","faster","fat","father","favorite","fear","feathers","feature","fed","feed","feel","feet","fell","fellow","felt","fence","few","fewer","field","fierce","fifteen","fifth","fifty","fight","fighting","figure","fill","film","final","finally","find","fine","finest","finger","finish","fire","fireplace","firm","first","fish","five","fix","flag","flame","flat","flew","flies","flight","floating","floor","flow","flower","fly","fog","folks","follow","food","foot","football","for","force","foreign","forest","forget","forgot","forgotten","form","former","fort","forth","forty","forward","fought","found","four","fourth","fox","frame","free","freedom","frequently","fresh","friend","friendly","frighten","frog","from","front","frozen","fruit","fuel","full","fully","fun","function","funny","fur","furniture","further","future","gain","game","garage","garden","gas","gasoline","gate","gather","gave","general","generally","gentle","gently","get","getting","giant","gift","girl","give","given","giving","glad","glass","globe","go","goes","gold","golden","gone","good","goose","got","government","grabbed","grade","gradually","grain","grandfather","grandmother","graph","grass","gravity","gray","great","greater","greatest","greatly","green","grew","ground","group","grow","grown","growth","guard","guess","guide","gulf","gun","habit","had","hair","half","halfway","hall","hand","handle","handsome","hang","happen","happened","happily","happy","harbor","hard","harder","hardly","has","hat","have","having","hay","he","headed","heading","health","heard","hearing","heart","heat","heavy","height","held","hello","help","helpful","her","herd","here","herself","hidden","hide","high","higher","highest","highway","hill","him","himself","his","history","hit","hold","hole","hollow","home","honor","hope","horn","horse","hospital","hot","hour","house","how","however","huge","human","hundred","hung","hungry","hunt","hunter","hurried","hurry","hurt","husband","ice","idea","identity","if","ill","image","imagine","immediately","importance","important","impossible","improve","in","inch","include","including","income","increase","indeed","independent","indicate","individual","industrial","industry","influence","information","inside","instance","instant","instead","instrument","interest","interior","into","introduced","invented","involved","iron","is","island","it","its","itself","jack","jar","jet","job","join","joined","journey","joy","judge","jump","jungle","just","keep","kept","key","kids","kill","kind","kitchen","knew","knife","know","knowledge","known","label","labor","lack","lady","laid","lake","lamp","land","language","large","larger","largest","last","late","later","laugh","law","lay","layers","lead","leader","leaf","learn","least","leather","leave","leaving","led","left","leg","length","lesson","let","letter","level","library","lie","life","lift","light","like","likely","limited","line","lion","lips","liquid","list","listen","little","live","living","load","local","locate","location","log","lonely","long","longer","look","loose","lose","loss","lost","lot","loud","love","lovely","low","lower","luck","lucky","lunch","lungs","lying","machine","machinery","mad","made","magic","magnet","mail","main","mainly","major","make","making","man","managed","manner","manufacturing","many","map","mark","market","married","mass","massage","master","material","mathematics","matter","may","maybe","me","meal","mean","means","meant","measure","meat","medicine","meet","melted","member","memory","men","mental","merely","met","metal","method","mice","middle","might","mighty","mile","military","milk","mill","mind","mine","minerals","minute","mirror","missing","mission","mistake","mix","mixture","model","modern","molecular","moment","money","monkey","month","mood","moon","more","morning","most","mostly","mother","motion","motor","mountain","mouse","mouth","move","movement","movie","moving","mud","muscle","music","musical","must","my","myself","mysterious","nails","name","nation","national","native","natural","naturally","nature","near","nearby","nearer","nearest","nearly","necessary","neck","needed","needle","needs","negative","neighbor","neighborhood","nervous","nest","never","new","news","newspaper","next","nice","night","nine","no","nobody","nodded","noise","none","noon","nor","north","nose","not","note","noted","nothing","notice","noun","now","number","numeral","nuts","object","observe","obtain","occasionally","occur","ocean","of","off","offer","office","officer","official","oil","old","older","oldest","on","once","one","only","onto","open","operation","opinion","opportunity","opposite","or","orange","orbit","order","ordinary","organization","organized","origin","original","other","ought","our","ourselves","out","outer","outline","outside","over","own","owner","oxygen","pack","package","page","paid","pain","paint","pair","palace","pale","pan","paper","paragraph","parallel","parent","park","part","particles","particular","particularly","partly","parts","party","pass","passage","past","path","pattern","pay","peace","pen","pencil","people","per","percent","perfect","perfectly","perhaps","period","person","personal","pet","phrase","physical","piano","pick","picture","pictured","pie","piece","pig","pile","pilot","pine","pink","pipe","pitch","place","plain","plan","plane","planet","planned","planning","plant","plastic","plate","plates","play","pleasant","please","pleasure","plenty","plural","plus","pocket","poem","poet","poetry","point","pole","police","policeman","political","pond","pony","pool","poor","popular","population","porch","port","position","positive","possible","possibly","post","pot","potatoes","pound","pour","powder","power","powerful","practical","practice","prepare","present","president","press","pressure","pretty","prevent","previous","price","pride","primitive","principal","principle","printed","private","prize","probably","problem","process","produce","product","production","program","progress","promised","proper","properly","property","protection","proud","prove","provide","public","pull","pupil","pure","purple","purpose","push","put","putting","quarter","queen","question","quick","quickly","quiet","quietly","quite","rabbit","race","radio","railroad","rain","raise","ran","ranch","range","rapidly","rate","rather","raw","rays","reach","read","reader","ready","real","realize","rear","reason","recall","receive","recent","recently","recognize","record","red","refer","refused","region","regular","related","relationship","religious","remain","remarkable","remember","remove","repeat","replace","replied","report","represent","require","research","respect","rest","result","return","review","rhyme","rhythm","rice","rich","ride","riding","right","ring","rise","rising","river","road","roar","rock","rocket","rocky","rod","roll","roof","room","root","rope","rose","rough","round","route","row","rubbed","rubber","rule","ruler","run","running","rush","sad","saddle","safe","safety","said","sail","sale","salmon","salt","same","sand","sang","sat","satellites","satisfied","save","saved","saw","say","scale","scared","scene","school","science","scientific","scientist","score","screen","sea","search","season","seat","second","secret","section","see","seed","seeing","seems","seen","seldom","select","selection","sell","send","sense","sent","sentence","separate","series","serious","serve","service","sets","setting","settle","settlers","seven","several","shade","shadow","shake","shaking","shall","shallow","shape","share","sharp","she","sheep","sheet","shelf","shells","shelter","shine","shinning","ship","shirt","shoe","shoot","shop","shore","short","shorter","shot","should","shoulder","shout","show","shown","shut","sick","sides","sight","sign","signal","silence","silent","silk","silly","silver","similar","simple","simplest","simply","since","sing","single","sink","sister","sit","sitting","situation","six","size","skill","skin","sky","slabs","slave","sleep","slept","slide","slight","slightly","slip","slipped","slope","slow","slowly","small","smaller","smallest","smell","smile","smoke","smooth","snake","snow","so","soap","social","society","soft","softly","soil","solar","sold","soldier","solid","solution","solve","some","somebody","somehow","someone","something","sometime","somewhere","son","song","soon","sort","sound","source","south","southern","space","speak","special","species","specific","speech","speed","spell","spend","spent","spider","spin","spirit","spite","split","spoken","sport","spread","spring","square","stage","stairs","stand","standard","star","stared","start","state","statement","station","stay","steady","steam","steel","steep","stems","step","stepped","stick","stiff","still","stock","stomach","stone","stood","stop","stopped","store","storm","story","stove","straight","strange","stranger","straw","stream","street","strength","stretch","strike","string","strip","strong","stronger","struck","structure","struggle","stuck","student","studied","studying","subject","substance","success","successful","such","sudden","suddenly","sugar","suggest","suit","sum","summer","sun","sunlight","supper","supply","support","suppose","sure","surface","surprise","surrounded","swam","sweet","swept","swim","swimming","swing","swung","syllable","symbol","system","table","tail","take","taken","tales","talk","tall","tank","tape","task","taste","taught","tax","tea","teach","teacher","team","tears","teeth","telephone","television","tell","temperature","ten","tent","term","terrible","test","than","thank","that","thee","them","themselves","then","theory","there","therefore","these","they","thick","thin","thing","think","third","thirty","this","those","thou","though","thought","thousand","thread","three","threw","throat","through","throughout","throw","thrown","thumb","thus","thy","tide","tie","tight","tightly","till","time","tin","tiny","tip","tired","title","to","tobacco","today","together","told","tomorrow","tone","tongue","tonight","too","took","tool","top","topic","torn","total","touch","toward","tower","town","toy","trace","track","trade","traffic","trail","train","transportation","trap","travel","treated","tree","triangle","tribe","trick","tried","trip","troops","tropical","trouble","truck","trunk","truth","try","tube","tune","turn","twelve","twenty","twice","two","type","typical","uncle","under","underline","understanding","unhappy","union","unit","universe","unknown","unless","until","unusual","up","upon","upper","upward","us","use","useful","using","usual","usually","valley","valuable","value","vapor","variety","various","vast","vegetable","verb","vertical","very","vessels","victory","view","village","visit","visitor","voice","volume","vote","vowel","voyage","wagon","wait","walk","wall","want","war","warm","warn","was","wash","waste","watch","water","wave","way","we","weak","wealth","wear","weather","week","weigh","weight","welcome","well","went","were","west","western","wet","whale","what","whatever","wheat","wheel","when","whenever","where","wherever","whether","which","while","whispered","whistle","white","who","whole","whom","whose","why","wide","widely","wife","wild","will","willing","win","wind","window","wing","winter","wire","wise","wish","with","within","without","wolf","women","won","wonder","wonderful","wood","wooden","wool","word","wore","work","worker","world","worried","worry","worse","worth","would","wrapped","write","writer","writing","written","wrong","wrote","yard","year","yellow","yes","yesterday","yet","you","young","younger","your","yourself","youth","zero","zebra","zipper","zoo","zulu"];function ty(r){return new Array(r).fill(0).map(()=>Xd[Math.floor(Math.random()*Xd.length)]).join("-")}async function ny({codePath:r,screenshotBuff:e,storage:t,logger:n}){if(e)try{let o=await t.uploadScreenshot(e);return n.debug({screenshotUrl:o,codePath:r},"Saved screenshot for debugging"),o}catch(o){n.error({err:o,codePath:r},"Failed to save screenshot for debugging")}}async function Cn({frameConfig:r,action:e,browser:t}){let n=t.getActiveFrameConfig();r?t.setActiveFrameConfig(r):n?.type==="auto"&&t.setActiveFrameConfig(void 0);try{return await e()}finally{t.setActiveFrameConfig(n)}}var ll="MOMENTIC_RUN_ID",ry="FINAL_SCREENSHOT_URL";import{cloneDeep as CP}from"lodash-es";async function oy(r){let{step:e,tracer:t}=r.conditionalParams,{logger:n,controller:o}=r.fixtures,i=new Date,a=ks(e),s=e.elseSteps,l=!0,c=[],p,d=ms();for(let f=0;f<e.blocks.length;f++){n.info(`Evaluating condition ${f} in conditional step`);let S=e.blocks[f];try{let x=await sl({...r,presetParams:{tracer:t,step:S.assertion}});c.push(x),n.info(`Condition ${f} resolved to true, executing the corresponding ${S.steps.length} steps`),l=!1,s=S.steps,p=x}catch(x){n.info({err:x},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(s)l&&n.info("No conditions resolved to true, executing the else block steps");else return n.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...a,status:"SUCCESS",startedAt:i,data:c[c.length-1]?.data,message:c[c.length-1]?.message,results:[],finishedAt:new Date,details:d.details};n.info(`Executing ${s.length} steps in the selected conditional block`);let m=await r.conditionalParams.tracer.startSubSteps(),u=await r.executeStepList({...r,listParams:{steps:s,containerName:"conditional block",tracer:m}}),g={...a,assertion:p,...u,startedAt:i,finishedAt:new Date};return nn({asyncTasks:r.work.asyncTasks,nestedResults:[...c,...u.results],result:g,logger:n}),g}import{randomUUID as iy}from"crypto";var ay=async r=>{let{controller:e}=r.fixtures;await e.browser.waitForDOMStability();let t=await e.browser.screenshot({}),n=await SP(r);n.finishedAt=new Date,nn({asyncTasks:r.work.asyncTasks,result:n,nestedResults:n.results,logger:r.fixtures.logger});let o=await e.browser.screenshot({}),i=iy();n.beforeSnapshot=i,r.work.asyncTasks.push(r.fixtures.debugDataStorage.storeScreenshot(r.fixtures.logger,i,t));let a=iy();return n.afterSnapshot=a,r.work.asyncTasks.push(r.fixtures.debugDataStorage.storeScreenshot(r.fixtures.logger,a,o)),n},SP=async r=>{let{step:e,tracer:t}=r.aiStepParams,{controller:n,context:o,logger:i}=r.fixtures,a={...e,startedAt:new Date,beforeTestContext:o.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in e&&e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS"))throw new A("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let l=await t.startSubSteps(),{status:c}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"AI action",results:a.results,tracer:l}});return a.finishedAt=new Date,a.status=c,a}catch(l){i.warn({err:l},"Failed executing saved deprecated AI action steps");let c=n.executeAbortController.signal.aborted;a.message=l instanceof Error?l.message:`${l}`,a.status=c?"CANCELLED":"FAILED"}return a};import{randomUUID as Zd}from"crypto";var sy=15,yP=7,ly=async r=>{let{controller:e}=r.fixtures;await e.browser.waitForDOMStability();let t=await e.browser.screenshot({}),n=await bP(r);n.finishedAt=new Date,nn({asyncTasks:r.work.asyncTasks,result:n,nestedResults:n.results,logger:r.fixtures.logger});let o=await e.browser.screenshot({}),i=Zd();n.beforeSnapshot=i,r.work.asyncTasks.push(r.fixtures.debugDataStorage.storeScreenshot(r.fixtures.logger,i,t));let a=Zd();return n.afterSnapshot=a,r.work.asyncTasks.push(r.fixtures.debugDataStorage.storeScreenshot(r.fixtures.logger,a,o)),n},bP=async r=>{let{step:e,tracer:t}=r.aiStepParams,{testMetadata:n,orgId:o}=r.inputs,{controller:i,context:a,logger:s,codeEvalTools:l}=r.fixtures,{step:c}=r.callbacks,p=`${e.id}-${Date.now()}`,d=s.child({stepId:e.id,langfuseSessionId:p}),m={...e,startedAt:new Date,beforeTestContext:a.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},u=await jt({orgId:o,s:e.text,context:a,logger:d,localTools:l,flagStore:i.flagStore});await i.browser.waitForDOMStability({logger:d});let g=`data:image/jpeg;base64,${(await i.browser.screenshot({clearHighlights:!0,retries:2})).toString("base64")}`,f=[],S=0,x=0,v,b;for(;;){if(S>sy)return m.message=`Exceeded the maximum number of commands allowed per AI step (${sy})`,m.status="FAILED",m;if(i.executeAbortController.signal.aborted)return m.message="Test execution was cancelled",m.status="CANCELLED",m;c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let E=await i.evaluateAiAction({goal:u,startingScreenshot:S===0?void 0:g,history:f,logger:d,langfuseSessionId:p,lastError:b}),{evaluation:C,reasoning:I,summary:M}=E;d.info(E,"Got AI evaluation");let L=m.results[S-1]?.id;switch(C.type){case"DONE":return m.message=`Our AI evaluator confirmed all tasks are complete: ${I}`,m.status="SUCCESS",L&&c.onDynamicAIActionEvaluatingEvent?.({stepId:L,status:"SUCCESS",message:`${M}
|
|
54
|
+
${I}`}),m;case"RIGHT_TRACK":{v=void 0,S===0?c.onDynamicAIActionEvaluatingEvent?.({stepId:e.id,status:"RUNNING",message:I}):L&&c.onDynamicAIActionEvaluatingEvent?.({stepId:L,status:"SUCCESS",message:I});break}case"WRONG_TRACK":{if(v=`${I}
|
|
55
|
+
${C.feedback}`,x++,x>=yP)return m.message=`Our AI agent requires additional information to achieve this goal:
|
|
53
56
|
${I}
|
|
54
|
-
${C.feedback}`,u.status="FAILED",c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:u.message}),u;L&&c.onDynamicAIActionEvaluatingEvent?.({stepId:L,status:"FAILED",message:C.feedback});break}case"IMPOSSIBLE":return u.message=`Our AI evaluator determined this task cannot be achieved: ${I}`,u.status="FAILED",c.onDynamicAIActionEvaluatingEvent?.({stepId:L??e.id,status:"FAILED",message:u.message}),u}let z=setTimeout(()=>{c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);d.info({commandIndex:S,lastActionHint:v},`Generating new sub-command ${S} within AI action`);let j,O;try{({command:j,reasoning:O}=await i.promptToCommand({goal:m,history:f,startingScreenshot:g,disableCache:r?.advanced.disableAICaching??!1,logger:d,actionHint:v,langfuseSessionId:p})),d.info({command:j,reasoning:O},"Got proposed command")}finally{clearTimeout(z)}if(j.type==="FAILURE")return clearTimeout(z),u.status="FAILED",u.message=`Our AI agent determined that no supported actions can fulfill the goals: ${O}`,u;let U={id:Qd(),type:"PRESET_ACTION",command:j},P={substepIndex:S+1,message:O||"Generated new command."};c.onDynamicCommandGenerated?.({...P,step:U,parentStepId:e.id}),d.info({commandId:j.id},`Executing sub-command ${S} within AI step: ${Mr(j)}`);let G=await t.startSubSteps(),X=(await n.executeStepList({...n,options:{...n.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[U],tracer:G}})).results[0];c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await i.browser.waitForDOMStability({logger:d});let re=await i.browser.screenshot({clearHighlights:!0,retries:1});u.results.push(X),f.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${re.toString("base64")}`,urlAfterCommand:i.browser.url(),serializedCommand:Mr(j),elementInteracted:X.results[0]?.elementInteracted,thoughts:O});let Tt={substepIndex:S,output:{...X,message:X.message??"Successfully executed preset action."},step:U,parentStepId:e.id};if(c.onDynamicCommandExecuted?.(Tt),await t.finish({output:ta.parse(X),step:X,message:X.message}),X.status==="FAILED")if(u.status="FAILED",u.message=X.message,x<3)x++,b=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${X.message}`;else return u;else if(X.status==="CANCELLED")return u.status="CANCELLED",u.message=X.message,u;S++}};async function uy(n){let{results:e}=n.failureRecoveryParams,t=e[e.length-1],r=DP(t);if(r)return n.fixtures.logger.info({failedResult:t,isNotEligible:r},"Skipping failure recovery because of ineligible failure"),null;try{return await FP(n)}catch(o){return n.fixtures.logger.error({err:o},"Error during failure recovery attempt"),null}}async function py({screenshot:n,controller:e,currentPageState:t,newStep:r,patch:o,logger:i}){if(r.aiSuggested=!0,r.type==="PRESET_ACTION"&&"cache"in r.command&&r.command.cache&&"target"in r.command.cache&&"target"in r.command&&r.command.target?.type==="description")try{let s=r.command.cache.target.id,a=await e.getReverseMappedDescription({browserState:t,targetId:s,disableCache:!1,screenshot:n});r.command.target.elementDescriptor=a}catch(s){i.error({err:s},"Error while reverse mapping target in failure recovery")}r.type==="PRESET_ACTION"&&(r.command.thoughts=o.thoughts)}async function FP(n){let{fixtures:e,work:t,failureRecoveryParams:r}=n,{controller:o,logger:i}=e,{results:s,failedStep:a,nextSteps:l,tracer:c}=r;if(!s.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(t.asyncTasks??[]);let p=o.browser.url(),d=`data:image/jpeg;base64,${(await o.browser.screenshot({})).toString("base64")}`,u=(await o.browser.getBrowserState({skipWait:!0})).serialize(),{results:m}=await Ea(i,e.debugDataStorage,s,{numScreenshots:3,addIndices:!0}),h=l.map(v=>ln(v)),g=await o.runFailureRecovery({currentUrl:p,currentScreenshot:d,failedResults:m,currentPageState:u,nextStepsSerialized:h});if(g.scenario==="INELIGIBLE"||!g.patch)return null;let f=[];if(g.patch.op==="add"){let v=g.patch.value;if(!v)throw new Error("No value in add patch in failure recovery");await py({screenshot:d,controller:o,currentPageState:u,newStep:v,patch:g.patch,logger:i}),f=[v,a]}else if(g.patch.op==="replace"){let v=g.patch.value;if(!v)throw new Error("No value in replace patch in failure recovery");await py({screenshot:d,controller:o,currentPageState:u,newStep:v,patch:g.patch,logger:i}),f=[v]}else if(g.patch.op==="remove"&&a.type==="PRESET_ACTION"&&["AI_ASSERTION","PAGE_CHECK","ELEMENT_CHECK"].includes(a.command.type))throw new Error("Cannot modify assertion step in failure recovery");let S=await c.startSubSteps(),x;if(f.length){x=await lr(n.work,()=>n.executeStepList({...n,fixtures:{...n.fixtures},listParams:{steps:f,containerName:"AI-recovered step list",tracer:S}}));for(let v of x.results)v.aiSuggested&&v.type==="PRESET_ACTION"&&(v.message=`AI suggested step: ${v.command.thoughts}`)}else x={status:"SUCCESS",results:[],proposedSteps:[]};return ol(t,{type:"FAILURE_RECOVERY",thoughts:g.reasoning}),t.state.failureRecoveryDisabled=!0,x}function DP(n){if(!n)return"No failed result";if(n.type!=="PRESET_ACTION")return"Not a preset action";let e=n.message;return e?e.includes("AbortError:")?"AbortError":Mm.some(t=>e.includes(t))?"User fault and likely irrecoverable":"":"No error message available"}async function my(n){let{step:e,tracer:t}=n.frameParams,{logger:r,controller:o}=n.fixtures,i=new Date,s=o.browser.getActiveFrameConfig();o.browser.setActiveFrameConfig(e.identifier);let a;try{let p=await t.startSubSteps();a=await n.executeStepList({...n,listParams:{steps:e.steps,containerName:"frame step list",tracer:p}})}finally{o.browser.setActiveFrameConfig(s)}let c={...e,...a,startedAt:i,finishedAt:new Date};return nn({asyncTasks:n.work.asyncTasks,nestedResults:a.results,result:c,logger:r}),c}import{randomUUID as al}from"crypto";import UP from"fast-json-patch";import{cloneDeep as BP}from"lodash-es";async function hy(n){let e=n.failedResults,t=[],{sectionParams:r,fixtures:o,work:i,startingUrl:s,startingContextSnapshot:a,tracer:l}=n,{step:c}=r,{controller:p,logger:d,debugDataStorage:u}=o,m=c?.autohealingConfig,h=m?.restartBehavior??{type:"GO_TO_SECTION_START"},g=m?.attempts??1;for(let f=0;f<g;f++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let S=BP(c.steps);await Promise.allSettled(i.asyncTasks??[]);let{results:x}=await Ea(d,u,e.results,{numScreenshots:4}),v=await p.runSectionAutohealing({results:x,errorMessage:e.terminalResult?.message,goal:c.description});S=UP.applyPatch(S,v.patches).newDocument;let b=It.fromSnapshot({snapshot:a,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await zP({logger:d,controller:p,tracer:l,context:b,restartConfig:h,startingUrl:s});let E=await lr(n.work,()=>n.executeStepList({...n,fixtures:{...n.fixtures,context:b},listParams:{steps:S,containerName:"auto-healed step list",tracer:l}}));if(t.push(E.results),E.status==="SUCCESS")return{successfulHealing:{proposedStep:{...c,steps:S},listResult:E,context:b},healingAttempts:t};e=E}return{healingAttempts:t}}async function zP({logger:n,controller:e,tracer:t,restartConfig:r,context:o,startingUrl:i}){switch(r.type){case"NAVIGATE_URL":{let s={id:al(),type:"PRESET_ACTION",command:{id:al(),type:"NAVIGATE",url:r.url}},a=await t.startStep({logger:n,step:s});await e.executePresetCommand(null,a,s.command,o,!1);break}case"GO_TO_SECTION_START":{let s={id:al(),type:"PRESET_ACTION",command:{id:al(),type:"NAVIGATE",url:i}},a=await t.startStep({logger:n,step:s});await e.executePresetCommand(null,a,s.command,o,!1);break}}}function gy(n,e){switch(n||(n="ON_FAILURE"),n){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&ju(e.command.type))}}async function fy(n){let{step:e,tracer:t}=n.sectionParams,{logger:r,controller:o,context:i}=n.fixtures,s=new Date,a=o.browser.url(),l=i.toObjectCopy(),c=await t.startSubSteps(),p=async()=>n.executeStepList({...n,listParams:{steps:e.steps,containerName:"section step list",tracer:c}}),d=e.autohealingConfig?await lr(n.work,p):await p(),u,m;if(d.status==="FAILED"&&e.autohealingConfig&&!n.work.state.autoHealingDisabled&&gy(e.autohealingConfig.trigger,d.terminalResult)){let g=await t.startSubSteps(),f=await hy({...n,startingContextSnapshot:l,startingUrl:a,failedResults:d,tracer:g});f.successfulHealing&&(u=f.successfulHealing.proposedStep,d=f.successfulHealing.listResult,n.fixtures.context=f.successfulHealing.context),m=f.healingAttempts}let h={...e,...d,startedAt:s,finishedAt:new Date,proposedStep:u,healingAttempts:m};return nn({asyncTasks:n.work.asyncTasks,nestedResults:d.results,result:h,logger:r}),h}async function Rn(n){let{results:e=[],containerName:t,steps:r,tracer:o}=n.listParams,{logger:i,context:s,controller:a,codeEvalTools:l,billingReporter:c,analytics:p}=n.fixtures,d=o.getParentStepIdChain(),{orgId:u,fromStep:m,toStep:h}=n.inputs,g=n.work,f=[],S="SUCCESS",x,v=0;for(v;v<r.length;v++){let b=r[v],E,C=ln(b);if(b.skipped)continue;if(g.fastForwardingToStep&&m){let ce=JSON.stringify(d);if(b.id===m.fromStepId&&ce===JSON.stringify(m.parentStepIdChain))g.fastForwardingToStep=!1;else if(!Ig(b,d,m.fromStepId,m.parentStepIdChain))continue}let I=new Date,_=p.child({step_id:b.id});_.track({type:"execution:step_start",step_type:b.type==="RESOLVED_MODULE"?"MODULE":b.type,command_type:"command"in b?b.command.type:void 0}),i.info({step:b},`Executing step ${v+1}/${r.length} in ${t}: ${C}`);let L=await o.startStep({logger:i,step:b}),z=jP(b),j=s.toRedactedDisplayCopy(),O=a.browser.url(),U=a.executeAbortController.signal,P=Bi(b.type);g.asyncTasks.push(c.reportCreditsUsed(i,b.type,P,{testId:n.inputs.testMetadata?.id,testName:n.inputs.testMetadata?.name,suiteId:n.inputs.suiteMetadata?.id,suiteName:n.inputs.suiteMetadata?.name}));let G,N;switch(b.type){case"PRESET_ACTION":{G="Preset action",N=await cr(b,async()=>await il({...n,presetParams:{tracer:L,step:b}}),U),"proposedStep"in N&&N.proposedStep&&(E=N.proposedStep,N.proposedStep=void 0);break}case"AI_ACTION":{G="AI action",N=await cr(b,()=>ly({...n,aiStepParams:{step:b,tracer:L},executeStepList:Rn}),U);break}case"AI_ACTION_DYNAMIC":{G="AI action",N=await cr(b,()=>dy({...n,aiStepParams:{step:b,tracer:L},executeStepList:Rn}),U);break}case"RESOLVED_MODULE":{G=`Module (${b.name})`,N=await cr(b,async()=>{let ce=await ty({orgId:u,step:b,context:s,logger:i,flagStore:a.flagStore,codeEvalTools:l,signal:U});return Xd({...n,executeStepList:Rn,moduleParams:{step:b,resolvedInputs:ce,tracer:L}})},U);break}case"CONDITIONAL":{G="Conditional step",N=await cr(b,()=>sy({...n,conditionalParams:{step:b,tracer:L},executeStepList:Rn}),U);break}case"IFRAME":{G="Frame step",N=await cr(b,()=>my({...n,frameParams:{step:b,tracer:L},executeStepList:Rn}),U);break}case"SECTION":{G="Section";let ce=await cr(b,()=>fy({...n,sectionParams:{step:b,tracer:L},executeStepList:Rn}),U);"proposedStep"in ce&&ce.proposedStep&&(E=ce.proposedStep,ce.proposedStep=void 0),N=ce;break}default:return(Se=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(b)}N.beforeUrl=N.beforeUrl??O,N.beforeTestContext=j,b.envKey&&s.setVariable(b.envKey,N.data);let X=a.browser.url();s.setCurrentUrl(X),N.afterUrl=N.afterUrl??X,N.afterTestContext=s.toRedactedDisplayCopy(),e.push(N),await HP({startedAt:I,stepTypeName:G,result:N,callbacks:n.callbacks,analytics:_,globalWorkRef:n.work,tracer:L});let re;if(N.status==="FAILED"&&!g.state.failureRecoveryDisabled&&m?.fromStepId===void 0&&h?.toStepId===void 0){let ce=await uy({...n,executeStepList:Rn,failureRecoveryParams:{failedStep:z,nextSteps:r.slice(v+1),results:e,tracer:L}});ce&&ce.status==="SUCCESS"&&(re=ce.proposedSteps,e.push(...ce.results))}if(re?f.push(...re):E?f.push(E):f.push(b),g.fastForwardingToStep&&m&&m.fromStepId===b.id&&JSON.stringify(d)===JSON.stringify(m.parentStepIdChain)&&(g.fastForwardingToStep=!1),N.status!=="SUCCESS"&&!re||a.closed){S=N.status,x=N;break}else if(h&&b.id===h.toStepId&&JSON.stringify(d)===JSON.stringify(h.parentStepIdChain)){a.setClosed();break}}return{status:S,results:e,terminalResult:x,proposedSteps:f}}async function HP({startedAt:n,stepTypeName:e,result:t,analytics:r,tracer:o}){let i=e.toLowerCase(),s=e.charAt(0).toUpperCase()+e.slice(1),a=new Date,l="";switch(t.status){case"SUCCESS":l=t.message??`${s} executed successfully.`,r.track({type:"execution:step_success",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:a.getTime()-n.getTime()});break;case"FAILED":l=t.message??`${s} failed.`,r.track({type:"execution:step_fail",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:a.getTime()-n.getTime(),fail_reason:t.message??`${s} failed.`});break;case"CANCELLED":l=t.message??`${s} cancelled.`,r.track({type:"execution:step_cancel",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:a.getTime()-n.getTime()});break;default:throw new Error(`Unexpected ${i} status: ${t.status}`)}await o.finish({step:t,message:l,output:ta.parse(t)})}import{randomUUID as Sy}from"crypto";async function yy({browser:n,signal:e}){let t=new Date;try{return await n.navigate({url:n.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(r){let o={id:Sy(),type:"PRESET_ACTION",status:e.aborted||r.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:r.message,startedAt:t,finishedAt:new Date,results:[],command:{id:Sy(),type:"NAVIGATE",url:n.baseUrl}};return{status:e.aborted||r.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:o}}}var ll=async n=>{let{orgId:e,runId:t,runAttemptId:r,testMetadata:o,steps:i,beforeSteps:s,afterSteps:a}=n.inputs;n.fixtures.logger=n.fixtures.logger.child({orgId:e,runId:t,runAttemptId:r,testId:o?.id}),n.fixtures.analytics=n.fixtures.analytics.child({run_id:t,test_id:o?.id,test_name:o?.name});let{logger:l,controller:c}=n.fixtures,{onTestComplete:p,onTestSuccess:d}=n.callbacks.test,u=KS(l);if(n.options.reinitializeBrowser){let h=await yy({browser:c.browser,signal:c.executeAbortController.signal});if(h.status!=="PASSED")return await p?.(),clearInterval(u?.interval),h}let m;try{return l.info({platform:u?.platform,cpuMetadata:u?.cpuMetadata},`Starting run for Momentic test '${o?.name??"Unnamed test"}'`),m=await $P(n),m}finally{if(l.info({status:m?.status},"Momentic test final result"),clearInterval(u?.interval),await p?.(),m?.status==="PASSED")try{await d?.({steps:i,beforeSteps:s,afterSteps:a})}catch(h){l.warn({err:h},"Error running test success handler, continuing...")}}},$P=async n=>{let{tracer:e}=n.testParams,{runId:t,runAttemptId:r,testMetadata:o,fromStep:i,toStep:s,steps:a,beforeSteps:l,afterSteps:c,orgId:p}=n.inputs,{logger:d,controller:u,context:m,storage:h}=n.fixtures,{collectDebugData:g,disableHealing:f}=n.options;m.setCurrentUrl(u.browser.url());let S="test",x=a,v=[],b=f||i!==void 0||s!==void 0||void 0,E={results:v,state:{failureRecoveryDisabled:b,autoHealingDisabled:b},asyncTasks:[]},C=!1;i?.fromStepId&&i.fromStepId===s?.toStepId?(S="filtered step",E.fastForwardingToStep=!0):i?.fromStepId?(S="partial steps list from step",E.fastForwardingToStep=!0):s?S="partial steps list until step":(S="entire test",C=!0);let I;if(C&&l&&l.length>0){let{status:P,results:G}=await by(l,"beforeSteps",n);if(P!=="PASSED")return g&&wy({tracer:e,debugDataStorage:n.fixtures.debugDataStorage,work:E,controller:u,storage:h,context:m,runId:t,runAttemptId:r,logger:d,status:P}),E.asyncTasks.push(Promise.resolve(n.callbacks.test.onSaveFinalRunResults?.({beforeResults:G,results:[]}))),{status:P,beforeResults:G,results:[]}}d.debug({stepsToExecute:x,fromStep:i,toStep:s},`Starting step execution for ${S}`);let _=await e.startStepList(),{status:L,terminalResult:z,proposedSteps:j}=await Rn({...n,work:E,listParams:{steps:x,containerName:S,results:v,tracer:_}}),O;if(C&&c&&c.length>0){d.debug("Starting step execution for after step list");try{let{results:P}=await by(c,"afterSteps",n);O=P}catch(P){d.error({err:P},"Failed to execute after steps list, continuing...")}}if(g&&wy({tracer:e,debugDataStorage:n.fixtures.debugDataStorage,work:E,controller:u,storage:h,context:m,runId:t,runAttemptId:r,logger:d,status:L}),await Promise.allSettled(E.asyncTasks),E.asyncTasks.push(Promise.resolve(n.callbacks.test.onSaveFinalRunResults?.({results:v,beforeResults:I,afterResults:O}))),L==="FAILED")return{status:"FAILED",results:v,beforeResults:I,afterResults:O,failedStepResult:z};if(L==="CANCELLED")return{status:"CANCELLED",results:v,beforeResults:I,afterResults:O};let U;if(j&&E.state.healingDetails&&o){let P=ry(3);await n.callbacks.test.onProposedTestSteps?.({name:P,testId:o.id,orgId:n.inputs.orgId,runId:n.inputs.runId,steps:j,details:E.state.healingDetails,purpose:"AUTO_HEALING"}),U={orgId:n.inputs.orgId,name:P}}return{proposedTest:U,status:"PASSED",results:v,beforeResults:I,afterResults:O}};async function by(n,e,t){let r=t.fixtures.logger,o=await t.testParams.tracer.startStepList();r.debug({stepsToExecute:n},`Starting step execution for ${e}`);let i={results:[],asyncTasks:[],state:{autoHealingDisabled:!0,failureRecoveryDisabled:!0}},s={...t.callbacks,test:{...t.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0,onProposedTestSteps:void 0}},{status:a,results:l}=await Rn({...t,work:i,callbacks:s,listParams:{steps:n,containerName:e,tracer:o}});await Promise.allSettled(i.asyncTasks);let c;return a==="SUCCESS"?c="PASSED":a==="CANCELLED"?c="CANCELLED":c="FAILED",{status:c,results:l}}function wy({tracer:n,debugDataStorage:e,work:t,controller:r,storage:o,logger:i,context:s,runId:a,runAttemptId:l,status:c}){let p=r.browser.retrieveAndClearDebugData(),d=Mg(p.logsPerPage),u=Jc(p.harPages||{},p.harEntries||{});n.attachConsoleLogs({logger:i,logs:d}),n.attachNetworkLogs({logger:i,logs:u}),t.asyncTasks.push((async()=>{try{let m=await r.browser.screenshot({}),h=await oy({codePath:"test-complete-final",storage:o,screenshotBuff:m,logger:i}),g=await D(r.browser.html(),{milliseconds:2e3});s.setVariable(iy,h),c!=="PASSED"&&c!=="SUCCESS"&&(i.debug({finalPageHtml:g},"Final page state HTML"),i.debug({finalScreenshotUrl:h},"Uploaded final screenshot URL"))}catch{}})(),l?e.storeConsoleLogsForRunAttempt(i,a,l,d):Promise.resolve(null),l?e.storeNetworkLogsForRunAttempt(i,a,l,u):Promise.resolve(null))}async function cl({advanced:n,customHeaders:e,envVariables:t,envName:r,baseUrl:o,logger:i,localTools:s,orgId:a,flagStore:l}){let c=aa.parse(n);e&&(c.extraHeaders={...c.extraHeaders,...e});let p=new It({baseUrl:o,envName:r,variablesFromEnvironment:t,currentUrl:o});await Yo({obj:c,context:p,bannedKeys:[],allowList:zm,localTools:s,logger:i,orgId:a,flagStore:l});try{return aa.parse(c)}catch(d){throw new R("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${d.message}`)}}import{cloneDeep as ak}from"lodash-es";var ep={vimiumJs:'var K=Object.defineProperty;var P=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var F=(t,e,n)=>e in t?K(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e)=>{for(var n in e||(e={}))z.call(e,n)&&F(t,n,e[n]);if(P)for(var n of P(e))B.call(e,n)&&F(t,n,e[n]);return t};var g=(t,e,n)=>(F(t,typeof e!="symbol"?e+"":e,n),n);var _=(t,e,n)=>new Promise((o,r)=>{var i=s=>{try{d(n.next(s))}catch(l){r(l)}},a=s=>{try{d(n.throw(s))}catch(l){r(l)}},d=s=>s.done?o(s.value):Promise.resolve(s.value).then(i,a);d((n=n.apply(t,e)).next())});var E=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=E);var k={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[k.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var N={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=E(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=E(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(k.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),a=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>a,a};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let a of Array.from(t.children)){i=window.getComputedStyle(a,null);let d=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(d)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(a,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=k.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,a,d,s=o.coords.split(",").map(p=>parseInt(p,10)),l=o.shape.toLowerCase();if(["rect","rectangle"].includes(l))s.length==4&&([r,a,i,d]=s);else if(["circle","circ"].includes(l)){if(s.length==3){let[p,w,v]=s,u=v/Math.sqrt(2);r=p-u,i=p+u,a=w-u,d=w+u}}else l==="default"?s.length==2&&([r,a,i,d]=[0,0,t.width,t.height]):s.length>=4&&([r,a,i,d]=s);let c=k.translate(k.create(r,a,i,d),t.left,t.top);c=this.cropRectToVisible(c),c&&!isNaN(c.top)&&!isNaN(c.left)&&!isNaN(c.width)&&!isNaN(c.height)&&n.push({element:o,rect:c})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch(e){}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:a}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&a===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return N.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||(n!=null?n.parentNode:void 0),n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var O={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){var r,i;let e={};this.addAttributes(t,this.commonAttributes,e);let n=((i=(r=t.tagName).toLowerCase)==null?void 0:i.call(r))||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,D({tag:n,attributes:e},o&&{content:o}))},getContent(t){var n,o;let e=((o=(n=t.tagName).toLowerCase)==null?void 0:o.call(n))||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){var o,r;if((((r=(o=t.tagName).toLowerCase)==null?void 0:r.call(o))||"")=="label"&&t.hasAttribute("for")){let i=t.getAttribute("for"),a=document.getElementById(i);a&&(e.target=this.describe(a))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var x=null,C=()=>G()||document.scrollingElement||document.body,W=function(t){return t?t<0?-1:1:0},U={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},X=function(t,e,n){if(N.isString(n)){let o=n;return o==="viewSize"&&t===C()?e==="x"?window.innerWidth:window.innerHeight:t[U[e][o]]}else return n},V=function(t,e,n){let o=U[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},q=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},T=function(t,e,n,o){let r=o*X(t,e,n)||-1;return r=W(r),V(t,e,r)&&V(t,e,-r)},$=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),T(t,e,n,o)&&q(t,e)},j=function(t=null){let e;if(!t){let n=C();if(T(n,"y",1,1)||T(n,"y",-1,1))return n;t=document.body||C()}if(T(t,"y",1,1)||T(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=j(e.element);if(o)return o}return null}},L={init(){x=null},isScrollableElement(t){return x||(x=C()&&j()||C()),t!==x&&$(t)}},G=function(){let t=J[window.location.host];if(t)return document.querySelector(t)},J={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=L;var A=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",E(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",E(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:A});var R=class{constructor(e){g(this,"element");g(this,"image");g(this,"rect");g(this,"linkText");g(this,"showLinkText");g(this,"reason");g(this,"secondClassCitizen");g(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},M={getLocalHintsForElement(t){var p,w,v;let e=((w=(p=t.tagName).toLowerCase)==null?void 0:w.call(p))||"",n=!1,o=!1,r=!1,i=[],a=[],d=null;if(e==="img"){let u=t.getAttribute("usemap");if(u){let h=t.getClientRects();u=u.replace(/^#/,"").replace(\'"\',\'\\\\"\');let m=document.querySelector(`map[name="${u}"]`);if(m&&h.length>0){n=!0;let y=m.getElementsByTagName("area"),S=f.getClientRectsForAreas(h[0],y);S=S.map(I=>Object.assign(I,{image:t})),a.push(...S)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let h=[];for(let m of["","data-","x-"])for(let y of["-",":","_"])h.push(`${m}ng${y}click`);return function(m){for(let y of h)if(m.hasAttribute(y))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let u=t.getAttribute("role"),h=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(u!=null&&h.includes(u.toLowerCase()))n=!0;else{let m=t.getAttribute("contentEditable");m!=null&&["","contenteditable","true","plaintext-only"].includes(m.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let u=t.getAttribute("jsaction").split(";");for(let h of u){let m=h.trim().split(":");if(m.length>=1&&m.length<=2){let[y,S,I]=m.length===1?["click",...m[0].trim().split("."),"_"]:[m[0],...m[1].trim().split("."),"_"];n||(n=y==="click"&&S!=="none"&&I!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||(n=!t.disabled&&!t.readOnly);break;case"input":n||(n=!(((v=t.getAttribute("type"))==null?void 0:v.toLowerCase())=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t)));break;case"button":case"select":n||(n=!t.disabled);break;case"object":case"embed":n=!0;break;case"label":n||(n=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0);break;case"body":n||(n=t===document.body&&!A()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?d="Frame.":void 0),n||(n=t===document.body&&A()&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"img":n||(n=["zoom-in","zoom-out"].includes(t.style.cursor));break;case"div":case"ol":case"ul":n||(n=t.clientHeight<t.scrollHeight&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"details":n=!0,d="Open.";break}let l=t.getAttribute("class");!n&&(l!=null&&l.toLowerCase().includes("button"))&&(n=!0,r=!0);let c=t.getAttribute("tabindex"),b=c?parseInt(c):-1;if(!n&&!(b<0)&&!isNaN(b)&&(n=!0,o=!0),n)if(a.length>0){let u=a.map(h=>new R({element:h.element,image:t,rect:h.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:d}));i.push(...u)}else{let u=f.getVisibleClientRect(t,!0);if(u!==null){let h=new R({element:t,rect:u,secondClassCitizen:o,possibleFalsePositive:r,reason:d});i.push(h)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?M.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,l)=>{l==null&&(l=[]);for(let c of Array.from(s.querySelectorAll("*")))l.push(c),c.shadowRoot&&e(c.shadowRoot,l);return l},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let l=this.getLocalHintsForElement(s);o.push(...l)}o=o.reverse();let r=[1,2,3];o=o.filter((s,l)=>{if(!s.possibleFalsePositive)return!0;let b=Math.max(0,l-6);for(;b<l;){let p=o[b].element;for(let w of r)if(p=p==null?void 0:p.parentElement,p===s.element)return!1;b+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let l=s.rect,c=M.getElementFromPoint(l.left+l.width*.5,l.top+l.height*.5);if(c&&(s.element.contains(c)||c.contains(s.element))||s.element.localName=="area"&&c==s.image)return!0;let p=[l.top+.1,l.bottom-.1],w=[l.left+.1,l.right-.1];for(let v of p)for(let u of w){let h=M.getElementFromPoint(u,v);if(h&&(s.element.contains(h)||h.contains(s.element)))return!0}});i.reverse();let{top:a,left:d}=f.getViewportTopLeft();for(let s of i)s.rect.top+=a,s.rect.left+=d;return i}};var H=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}capture(){return _(this,null,function*(){this.reset(),this.createMarkers(),this.displayMarkers()})}createMarkers(){this.hints=M.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{var i,a;let o=f.createElement("div"),r=(a=(i=e.element.attributes["data-momentic-id"])==null?void 0:i.value)!=null?a:void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",Z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(O.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},Z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=H;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`var __defProp = Object.defineProperty;
|
|
57
|
+
${C.feedback}`,m.status="FAILED",c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:m.message}),m;L&&c.onDynamicAIActionEvaluatingEvent?.({stepId:L,status:"FAILED",message:C.feedback});break}case"IMPOSSIBLE":return m.message=`Our AI evaluator determined this task cannot be achieved: ${I}`,m.status="FAILED",c.onDynamicAIActionEvaluatingEvent?.({stepId:L??e.id,status:"FAILED",message:m.message}),m}let z=setTimeout(()=>{c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);d.info({commandIndex:S,lastActionHint:v},`Generating new sub-command ${S} within AI action`);let j,k;try{({command:j,reasoning:k}=await i.promptToCommand({goal:u,history:f,startingScreenshot:g,disableCache:n?.advanced.disableAICaching??!1,logger:d,actionHint:v,langfuseSessionId:p})),d.info({command:j,reasoning:k},"Got proposed command")}finally{clearTimeout(z)}if(j.type==="FAILURE")return clearTimeout(z),m.status="FAILED",m.message=`Our AI agent determined that no supported actions can fulfill the goals: ${k}`,m;let U={id:Zd(),type:"PRESET_ACTION",command:j},P={substepIndex:S+1,message:k||"Generated new command."};c.onDynamicCommandGenerated?.({...P,step:U,parentStepId:e.id}),d.info({commandId:j.id},`Executing sub-command ${S} within AI step: ${Ur(j)}`);let V=await t.startSubSteps(),X=(await r.executeStepList({...r,options:{...r.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[U],tracer:V}})).results[0];c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await i.browser.waitForDOMStability({logger:d});let oe=await i.browser.screenshot({clearHighlights:!0,retries:1});m.results.push(X),f.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${oe.toString("base64")}`,urlAfterCommand:i.browser.url(),serializedCommand:Ur(j),elementInteracted:X.results[0]?.elementInteracted,thoughts:k});let Tt={substepIndex:S,output:{...X,message:X.message??"Successfully executed preset action."},step:U,parentStepId:e.id};if(c.onDynamicCommandExecuted?.(Tt),await t.finish({output:ns.parse(X),step:X,message:X.message}),X.status==="FAILED")if(m.status="FAILED",m.message=X.message,x<3)x++,b=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${X.message}`;else return m;else if(X.status==="CANCELLED")return m.status="CANCELLED",m.message=X.message,m;S++}};async function dy(r){let{results:e}=r.failureRecoveryParams,t=e[e.length-1],n=vP(t);if(n)return r.fixtures.logger.info({failedResult:t,isNotEligible:n},"Skipping failure recovery because of ineligible failure"),null;try{return await wP(r)}catch(o){return r.fixtures.logger.error({err:o},"Error during failure recovery attempt"),null}}async function cy({screenshot:r,controller:e,currentPageState:t,newStep:n,patch:o,logger:i}){if(n.aiSuggested=!0,n.type==="PRESET_ACTION"&&"cache"in n.command&&n.command.cache&&"target"in n.command.cache&&"target"in n.command&&n.command.target?.type==="description")try{let a=n.command.cache.target.id,s=await e.getReverseMappedDescription({browserState:t,targetId:a,disableCache:!1,screenshot:r});n.command.target.elementDescriptor=s}catch(a){i.error({err:a},"Error while reverse mapping target in failure recovery")}n.type==="PRESET_ACTION"&&(n.command.thoughts=o.thoughts)}async function wP(r){let{fixtures:e,work:t,failureRecoveryParams:n}=r,{controller:o,logger:i}=e,{results:a,failedStep:s,nextSteps:l,tracer:c}=n;if(!a.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(t.asyncTasks??[]);let p=o.browser.url(),d=`data:image/jpeg;base64,${(await o.browser.screenshot({})).toString("base64")}`,m=(await o.browser.getBrowserState({skipWait:!0})).serialize(),{results:u}=await Cs(i,e.debugDataStorage,a,{numScreenshots:3,addIndices:!0}),h=l.map(v=>ln(v)),g=await o.runFailureRecovery({currentUrl:p,currentScreenshot:d,failedResults:u,currentPageState:m,nextStepsSerialized:h});if(g.scenario==="INELIGIBLE"||!g.patch)return null;let f=[];if(g.patch.op==="add"){let v=g.patch.value;if(!v)throw new Error("No value in add patch in failure recovery");await cy({screenshot:d,controller:o,currentPageState:m,newStep:v,patch:g.patch,logger:i}),f=[v,s]}else if(g.patch.op==="replace"){let v=g.patch.value;if(!v)throw new Error("No value in replace patch in failure recovery");await cy({screenshot:d,controller:o,currentPageState:m,newStep:v,patch:g.patch,logger:i}),f=[v]}else if(g.patch.op==="remove"&&s.type==="PRESET_ACTION"&&["AI_ASSERTION","PAGE_CHECK","ELEMENT_CHECK"].includes(s.command.type))throw new Error("Cannot modify assertion step in failure recovery");let S=await c.startSubSteps(),x;if(f.length){x=await cr(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures},listParams:{steps:f,containerName:"AI-recovered step list",tracer:S}}));for(let v of x.results)v.aiSuggested&&v.type==="PRESET_ACTION"&&(v.message=`AI suggested step: ${v.command.thoughts}`)}else x={status:"SUCCESS",results:[],proposedSteps:[]};return al(t,{type:"FAILURE_RECOVERY",thoughts:g.reasoning}),t.state.failureRecoveryDisabled=!0,x}function vP(r){if(!r)return"No failed result";if(r.type!=="PRESET_ACTION")return"Not a preset action";let e=r.message;return e?e.includes("AbortError:")?"AbortError":Pm.some(t=>e.includes(t))?"User fault and likely irrecoverable":"":"No error message available"}async function py(r){let{step:e,tracer:t}=r.frameParams,{logger:n,controller:o}=r.fixtures,i=new Date,a=o.browser.getActiveFrameConfig();o.browser.setActiveFrameConfig(e.identifier);let s;try{let p=await t.startSubSteps();s=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"frame step list",tracer:p}})}finally{o.browser.setActiveFrameConfig(a)}let c={...e,...s,startedAt:i,finishedAt:new Date};return nn({asyncTasks:r.work.asyncTasks,nestedResults:s.results,result:c,logger:n}),c}import{randomUUID as cl}from"crypto";import xP from"fast-json-patch";import{cloneDeep as TP}from"lodash-es";async function uy(r){let e=r.failedResults,t=[],{sectionParams:n,fixtures:o,work:i,startingUrl:a,startingContextSnapshot:s,tracer:l}=r,{step:c}=n,{controller:p,logger:d,debugDataStorage:m}=o,u=c?.autohealingConfig,h=u?.restartBehavior??{type:"GO_TO_SECTION_START"},g=u?.attempts??1;for(let f=0;f<g;f++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let S=TP(c.steps);await Promise.allSettled(i.asyncTasks??[]);let{results:x}=await Cs(d,m,e.results,{numScreenshots:4}),v=await p.runSectionAutohealing({results:x,errorMessage:e.terminalResult?.message,goal:c.description});S=xP.applyPatch(S,v.patches).newDocument;let b=It.fromSnapshot({snapshot:s,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await EP({logger:d,controller:p,tracer:l,context:b,restartConfig:h,startingUrl:a});let E=await cr(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures,context:b},listParams:{steps:S,containerName:"auto-healed step list",tracer:l}}));if(t.push(E.results),E.status==="SUCCESS")return{successfulHealing:{proposedStep:{...c,steps:S},listResult:E,context:b},healingAttempts:t};e=E}return{healingAttempts:t}}async function EP({logger:r,controller:e,tracer:t,restartConfig:n,context:o,startingUrl:i}){switch(n.type){case"NAVIGATE_URL":{let a={id:cl(),type:"PRESET_ACTION",command:{id:cl(),type:"NAVIGATE",url:n.url}},s=await t.startStep({logger:r,step:a});await e.executePresetCommand(null,s,a.command,o,!1);break}case"GO_TO_SECTION_START":{let a={id:cl(),type:"PRESET_ACTION",command:{id:cl(),type:"NAVIGATE",url:i}},s=await t.startStep({logger:r,step:a});await e.executePresetCommand(null,s,a.command,o,!1);break}}}function my(r,e){switch(r||(r="ON_FAILURE"),r){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&_u(e.command.type))}}async function hy(r){let{step:e,tracer:t}=r.sectionParams,{logger:n,controller:o,context:i}=r.fixtures,a=new Date,s=o.browser.url(),l=i.toObjectCopy(),c=await t.startSubSteps(),p=async()=>r.executeStepList({...r,listParams:{steps:e.steps,containerName:"section step list",tracer:c}}),d=e.autohealingConfig?await cr(r.work,p):await p(),m,u;if(d.status==="FAILED"&&e.autohealingConfig&&!r.work.state.autoHealingDisabled&&my(e.autohealingConfig.trigger,d.terminalResult)){let g=await t.startSubSteps(),f=await uy({...r,startingContextSnapshot:l,startingUrl:s,failedResults:d,tracer:g});f.successfulHealing&&(m=f.successfulHealing.proposedStep,d=f.successfulHealing.listResult,r.fixtures.context=f.successfulHealing.context),u=f.healingAttempts}let h={...e,...d,startedAt:a,finishedAt:new Date,proposedStep:m,healingAttempts:u};return nn({asyncTasks:r.work.asyncTasks,nestedResults:d.results,result:h,logger:n}),h}async function An(r){let{results:e=[],containerName:t,steps:n,tracer:o}=r.listParams,{logger:i,context:a,controller:s,codeEvalTools:l,billingReporter:c,analytics:p}=r.fixtures,d=o.getParentStepIdChain(),{orgId:m,fromStep:u,toStep:h}=r.inputs,g=r.work,f=[],S="SUCCESS",x,v=0;for(v;v<n.length;v++){let b=n[v],E,C=ln(b);if(b.skipped)continue;if(g.fastForwardingToStep&&u){let se=JSON.stringify(d);if(b.id===u.fromStepId&&se===JSON.stringify(u.parentStepIdChain))g.fastForwardingToStep=!1;else if(!xg(b,d,u.fromStepId,u.parentStepIdChain))continue}let I=new Date,M=p.child({step_id:b.id});M.track({type:"execution:step_start",step_type:b.type==="RESOLVED_MODULE"?"MODULE":b.type,command_type:"command"in b?b.command.type:void 0}),i.info({step:b},`Executing step ${v+1}/${n.length} in ${t}: ${C}`);let L=await o.startStep({logger:i,step:b}),z=CP(b),j=a.toRedactedDisplayCopy(),k=s.browser.url(),U=s.executeAbortController.signal,P=ji(b.type);g.asyncTasks.push(c.reportCreditsUsed(i,b.type,P,{testId:r.inputs.testMetadata?.id,testName:r.inputs.testMetadata?.name,suiteId:r.inputs.suiteMetadata?.id,suiteName:r.inputs.suiteMetadata?.name}));let V,N;switch(b.type){case"PRESET_ACTION":{V="Preset action",N=await dr(b,async()=>await sl({...r,presetParams:{tracer:L,step:b}}),U),"proposedStep"in N&&N.proposedStep&&(E=N.proposedStep,N.proposedStep=void 0);break}case"AI_ACTION":{V="AI action",N=await dr(b,()=>ay({...r,aiStepParams:{step:b,tracer:L},executeStepList:An}),U);break}case"AI_ACTION_DYNAMIC":{V="AI action",N=await dr(b,()=>ly({...r,aiStepParams:{step:b,tracer:L},executeStepList:An}),U);break}case"RESOLVED_MODULE":{V=`Module (${b.name})`,N=await dr(b,async()=>{let se=await QS({orgId:m,step:b,context:a,logger:i,flagStore:s.flagStore,codeEvalTools:l,signal:U});return Jd({...r,executeStepList:An,moduleParams:{step:b,resolvedInputs:se,tracer:L}})},U);break}case"CONDITIONAL":{V="Conditional step",N=await dr(b,()=>oy({...r,conditionalParams:{step:b,tracer:L},executeStepList:An}),U);break}case"IFRAME":{V="Frame step",N=await dr(b,()=>py({...r,frameParams:{step:b,tracer:L},executeStepList:An}),U);break}case"SECTION":{V="Section";let se=await dr(b,()=>hy({...r,sectionParams:{step:b,tracer:L},executeStepList:An}),U);"proposedStep"in se&&se.proposedStep&&(E=se.proposedStep,se.proposedStep=void 0),N=se;break}default:return(Se=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(b)}N.beforeUrl=N.beforeUrl??k,N.beforeTestContext=j,b.envKey&&a.setVariable(b.envKey,N.data);let X=s.browser.url();a.setCurrentUrl(X),N.afterUrl=N.afterUrl??X,N.afterTestContext=a.toRedactedDisplayCopy(),e.push(N),await AP({startedAt:I,stepTypeName:V,result:N,callbacks:r.callbacks,analytics:M,globalWorkRef:r.work,tracer:L});let oe;if(N.status==="FAILED"&&!g.state.failureRecoveryDisabled&&u?.fromStepId===void 0&&h?.toStepId===void 0){let se=await dy({...r,executeStepList:An,failureRecoveryParams:{failedStep:z,nextSteps:n.slice(v+1),results:e,tracer:L}});se&&se.status==="SUCCESS"&&(oe=se.proposedSteps,e.push(...se.results))}if(oe?f.push(...oe):E?f.push(E):f.push(b),g.fastForwardingToStep&&u&&u.fromStepId===b.id&&JSON.stringify(d)===JSON.stringify(u.parentStepIdChain)&&(g.fastForwardingToStep=!1),N.status!=="SUCCESS"&&!oe||s.closed){S=N.status,x=N;break}else if(h&&b.id===h.toStepId&&JSON.stringify(d)===JSON.stringify(h.parentStepIdChain)){s.setClosed();break}}return{status:S,results:e,terminalResult:x,proposedSteps:f}}async function AP({startedAt:r,stepTypeName:e,result:t,analytics:n,tracer:o}){let i=e.toLowerCase(),a=e.charAt(0).toUpperCase()+e.slice(1),s=new Date,l="";switch(t.status){case"SUCCESS":l=t.message??`${a} executed successfully.`,n.track({type:"execution:step_success",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:s.getTime()-r.getTime()});break;case"FAILED":l=t.message??`${a} failed.`,n.track({type:"execution:step_fail",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:s.getTime()-r.getTime(),fail_reason:t.message??`${a} failed.`});break;case"CANCELLED":l=t.message??`${a} cancelled.`,n.track({type:"execution:step_cancel",step_type:t.type,command_type:"command"in t?t.command.type:void 0,duration_ms:s.getTime()-r.getTime()});break;default:throw new Error(`Unexpected ${i} status: ${t.status}`)}await o.finish({step:t,message:l,output:ns.parse(t)})}import{randomUUID as gy}from"crypto";async function fy({browser:r,signal:e}){let t=new Date;try{return await r.navigate({url:r.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(n){let o={id:gy(),type:"PRESET_ACTION",status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:n.message,startedAt:t,finishedAt:new Date,results:[],command:{id:gy(),type:"NAVIGATE",url:r.baseUrl}};return{status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:o}}}var dl=async r=>{let{orgId:e,runId:t,runAttemptId:n,testMetadata:o,steps:i,beforeSteps:a,afterSteps:s}=r.inputs;r.fixtures.logger=r.fixtures.logger.child({orgId:e,runId:t,runAttemptId:n,testId:o?.id}),r.fixtures.analytics=r.fixtures.analytics.child({run_id:t,test_id:o?.id,test_name:o?.name});let{logger:l,controller:c}=r.fixtures,{onTestComplete:p,onTestSuccess:d}=r.callbacks.test,m=VS(l);if(r.options.reinitializeBrowser){let h=await fy({browser:c.browser,signal:c.executeAbortController.signal});if(h.status!=="PASSED")return await p?.(),clearInterval(m?.interval),h}let u;try{return l.info({platform:m?.platform,cpuMetadata:m?.cpuMetadata},`Starting run for Momentic test '${o?.name??"Unnamed test"}'`),u=await RP(r),u}finally{if(l.info({status:u?.status},"Momentic test final result"),clearInterval(m?.interval),await p?.(),u?.status==="PASSED")try{await d?.({steps:i,beforeSteps:a,afterSteps:s})}catch(h){l.warn({err:h},"Error running test success handler, continuing...")}}},RP=async r=>{let{tracer:e}=r.testParams,{runId:t,runAttemptId:n,testMetadata:o,fromStep:i,toStep:a,steps:s,beforeSteps:l,afterSteps:c,orgId:p}=r.inputs,{logger:d,controller:m,context:u,storage:h}=r.fixtures,{collectDebugData:g,disableHealing:f}=r.options;u.setCurrentUrl(m.browser.url());let S="test",x=s,v=[],b=f||i!==void 0||a!==void 0||void 0,E={results:v,state:{failureRecoveryDisabled:b,autoHealingDisabled:b},asyncTasks:[]},C=!1;i?.fromStepId&&i.fromStepId===a?.toStepId?(S="filtered step",E.fastForwardingToStep=!0):i?.fromStepId?(S="partial steps list from step",E.fastForwardingToStep=!0):a?S="partial steps list until step":(S="entire test",C=!0);let I;if(C&&l&&l.length>0){let{status:P,results:V}=await Sy(l,"beforeSteps",r);if(P!=="PASSED")return g&&yy({tracer:e,debugDataStorage:r.fixtures.debugDataStorage,work:E,controller:m,storage:h,context:u,runId:t,runAttemptId:n,logger:d,status:P}),E.asyncTasks.push(Promise.resolve(r.callbacks.test.onSaveFinalRunResults?.({beforeResults:V,results:[]}))),{status:P,beforeResults:V,results:[]}}d.debug({stepsToExecute:x,fromStep:i,toStep:a},`Starting step execution for ${S}`);let M=await e.startStepList(),{status:L,terminalResult:z,proposedSteps:j}=await An({...r,work:E,listParams:{steps:x,containerName:S,results:v,tracer:M}}),k;if(C&&c&&c.length>0){d.debug("Starting step execution for after step list");try{let{results:P}=await Sy(c,"afterSteps",r);k=P}catch(P){d.error({err:P},"Failed to execute after steps list, continuing...")}}if(g&&yy({tracer:e,debugDataStorage:r.fixtures.debugDataStorage,work:E,controller:m,storage:h,context:u,runId:t,runAttemptId:n,logger:d,status:L}),await Promise.allSettled(E.asyncTasks),E.asyncTasks.push(Promise.resolve(r.callbacks.test.onSaveFinalRunResults?.({results:v,beforeResults:I,afterResults:k}))),L==="FAILED")return{status:"FAILED",results:v,beforeResults:I,afterResults:k,failedStepResult:z};if(L==="CANCELLED")return{status:"CANCELLED",results:v,beforeResults:I,afterResults:k};let U;if(j&&E.state.healingDetails&&o){let P=ty(3);await r.callbacks.test.onProposedTestSteps?.({name:P,testId:o.id,orgId:r.inputs.orgId,runId:r.inputs.runId,steps:j,details:E.state.healingDetails,purpose:"AUTO_HEALING"}),U={orgId:r.inputs.orgId,name:P}}return{proposedTest:U,status:"PASSED",results:v,beforeResults:I,afterResults:k}};async function Sy(r,e,t){let n=t.fixtures.logger,o=await t.testParams.tracer.startStepList();n.debug({stepsToExecute:r},`Starting step execution for ${e}`);let i={results:[],asyncTasks:[],state:{autoHealingDisabled:!0,failureRecoveryDisabled:!0}},a={...t.callbacks,test:{...t.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0,onProposedTestSteps:void 0}},{status:s,results:l}=await An({...t,work:i,callbacks:a,listParams:{steps:r,containerName:e,tracer:o}});await Promise.allSettled(i.asyncTasks);let c;return s==="SUCCESS"?c="PASSED":s==="CANCELLED"?c="CANCELLED":c="FAILED",{status:c,results:l}}function yy({tracer:r,debugDataStorage:e,work:t,controller:n,storage:o,logger:i,context:a,runId:s,runAttemptId:l,status:c}){let p=n.browser.retrieveAndClearDebugData(),d=Pg(p.logsPerPage),m=Kc(p.harPages||{},p.harEntries||{});r.attachConsoleLogs({logger:i,logs:d}),r.attachNetworkLogs({logger:i,logs:m}),t.asyncTasks.push((async()=>{try{let u=await n.browser.screenshot({}),h=await ny({codePath:"test-complete-final",storage:o,screenshotBuff:u,logger:i}),g=await D(n.browser.html(),{milliseconds:2e3});a.setVariable(ry,h),c!=="PASSED"&&c!=="SUCCESS"&&(i.debug({finalPageHtml:g},"Final page state HTML"),i.debug({finalScreenshotUrl:h},"Uploaded final screenshot URL"))}catch{}})(),l?e.storeConsoleLogsForRunAttempt(i,s,l,d):Promise.resolve(null),l?e.storeNetworkLogsForRunAttempt(i,s,l,m):Promise.resolve(null))}async function pl({advanced:r,customHeaders:e,envVariables:t,envName:n,baseUrl:o,logger:i,localTools:a,orgId:s,flagStore:l}){let c=ls.parse(r);e&&(c.extraHeaders={...c.extraHeaders,...e});let p=new It({baseUrl:o,envName:n,variablesFromEnvironment:t,currentUrl:o});await Qo({obj:c,context:p,bannedKeys:[],allowList:Mm,localTools:a,logger:i,orgId:s,flagStore:l});try{return ls.parse(c)}catch(d){throw new A("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${d.message}`)}}import{cloneDeep as Bk}from"lodash-es";var Qd={vimiumJs:'var K=Object.defineProperty;var P=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var F=(t,e,n)=>e in t?K(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e)=>{for(var n in e||(e={}))z.call(e,n)&&F(t,n,e[n]);if(P)for(var n of P(e))B.call(e,n)&&F(t,n,e[n]);return t};var g=(t,e,n)=>(F(t,typeof e!="symbol"?e+"":e,n),n);var _=(t,e,n)=>new Promise((o,r)=>{var i=s=>{try{d(n.next(s))}catch(l){r(l)}},a=s=>{try{d(n.throw(s))}catch(l){r(l)}},d=s=>s.done?o(s.value):Promise.resolve(s.value).then(i,a);d((n=n.apply(t,e)).next())});var E=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=E);var k={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[k.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var N={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=E(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=E(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(k.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),a=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>a,a};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let a of Array.from(t.children)){i=window.getComputedStyle(a,null);let d=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(d)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(a,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=k.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,a,d,s=o.coords.split(",").map(p=>parseInt(p,10)),l=o.shape.toLowerCase();if(["rect","rectangle"].includes(l))s.length==4&&([r,a,i,d]=s);else if(["circle","circ"].includes(l)){if(s.length==3){let[p,w,v]=s,u=v/Math.sqrt(2);r=p-u,i=p+u,a=w-u,d=w+u}}else l==="default"?s.length==2&&([r,a,i,d]=[0,0,t.width,t.height]):s.length>=4&&([r,a,i,d]=s);let c=k.translate(k.create(r,a,i,d),t.left,t.top);c=this.cropRectToVisible(c),c&&!isNaN(c.top)&&!isNaN(c.left)&&!isNaN(c.width)&&!isNaN(c.height)&&n.push({element:o,rect:c})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch(e){}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:a}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&a===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return N.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||(n!=null?n.parentNode:void 0),n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var O={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){var r,i;let e={};this.addAttributes(t,this.commonAttributes,e);let n=((i=(r=t.tagName).toLowerCase)==null?void 0:i.call(r))||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,D({tag:n,attributes:e},o&&{content:o}))},getContent(t){var n,o;let e=((o=(n=t.tagName).toLowerCase)==null?void 0:o.call(n))||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){var o,r;if((((r=(o=t.tagName).toLowerCase)==null?void 0:r.call(o))||"")=="label"&&t.hasAttribute("for")){let i=t.getAttribute("for"),a=document.getElementById(i);a&&(e.target=this.describe(a))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var x=null,C=()=>G()||document.scrollingElement||document.body,W=function(t){return t?t<0?-1:1:0},U={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},X=function(t,e,n){if(N.isString(n)){let o=n;return o==="viewSize"&&t===C()?e==="x"?window.innerWidth:window.innerHeight:t[U[e][o]]}else return n},V=function(t,e,n){let o=U[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},q=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},T=function(t,e,n,o){let r=o*X(t,e,n)||-1;return r=W(r),V(t,e,r)&&V(t,e,-r)},$=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),T(t,e,n,o)&&q(t,e)},j=function(t=null){let e;if(!t){let n=C();if(T(n,"y",1,1)||T(n,"y",-1,1))return n;t=document.body||C()}if(T(t,"y",1,1)||T(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=j(e.element);if(o)return o}return null}},L={init(){x=null},isScrollableElement(t){return x||(x=C()&&j()||C()),t!==x&&$(t)}},G=function(){let t=J[window.location.host];if(t)return document.querySelector(t)},J={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=L;var A=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",E(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",E(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:A});var R=class{constructor(e){g(this,"element");g(this,"image");g(this,"rect");g(this,"linkText");g(this,"showLinkText");g(this,"reason");g(this,"secondClassCitizen");g(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},M={getLocalHintsForElement(t){var p,w,v;let e=((w=(p=t.tagName).toLowerCase)==null?void 0:w.call(p))||"",n=!1,o=!1,r=!1,i=[],a=[],d=null;if(e==="img"){let u=t.getAttribute("usemap");if(u){let h=t.getClientRects();u=u.replace(/^#/,"").replace(\'"\',\'\\\\"\');let m=document.querySelector(`map[name="${u}"]`);if(m&&h.length>0){n=!0;let y=m.getElementsByTagName("area"),S=f.getClientRectsForAreas(h[0],y);S=S.map(I=>Object.assign(I,{image:t})),a.push(...S)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let h=[];for(let m of["","data-","x-"])for(let y of["-",":","_"])h.push(`${m}ng${y}click`);return function(m){for(let y of h)if(m.hasAttribute(y))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let u=t.getAttribute("role"),h=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(u!=null&&h.includes(u.toLowerCase()))n=!0;else{let m=t.getAttribute("contentEditable");m!=null&&["","contenteditable","true","plaintext-only"].includes(m.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let u=t.getAttribute("jsaction").split(";");for(let h of u){let m=h.trim().split(":");if(m.length>=1&&m.length<=2){let[y,S,I]=m.length===1?["click",...m[0].trim().split("."),"_"]:[m[0],...m[1].trim().split("."),"_"];n||(n=y==="click"&&S!=="none"&&I!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||(n=!t.disabled&&!t.readOnly);break;case"input":n||(n=!(((v=t.getAttribute("type"))==null?void 0:v.toLowerCase())=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t)));break;case"button":case"select":n||(n=!t.disabled);break;case"object":case"embed":n=!0;break;case"label":n||(n=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0);break;case"body":n||(n=t===document.body&&!A()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?d="Frame.":void 0),n||(n=t===document.body&&A()&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"img":n||(n=["zoom-in","zoom-out"].includes(t.style.cursor));break;case"div":case"ol":case"ul":n||(n=t.clientHeight<t.scrollHeight&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"details":n=!0,d="Open.";break}let l=t.getAttribute("class");!n&&(l!=null&&l.toLowerCase().includes("button"))&&(n=!0,r=!0);let c=t.getAttribute("tabindex"),b=c?parseInt(c):-1;if(!n&&!(b<0)&&!isNaN(b)&&(n=!0,o=!0),n)if(a.length>0){let u=a.map(h=>new R({element:h.element,image:t,rect:h.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:d}));i.push(...u)}else{let u=f.getVisibleClientRect(t,!0);if(u!==null){let h=new R({element:t,rect:u,secondClassCitizen:o,possibleFalsePositive:r,reason:d});i.push(h)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?M.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,l)=>{l==null&&(l=[]);for(let c of Array.from(s.querySelectorAll("*")))l.push(c),c.shadowRoot&&e(c.shadowRoot,l);return l},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let l=this.getLocalHintsForElement(s);o.push(...l)}o=o.reverse();let r=[1,2,3];o=o.filter((s,l)=>{if(!s.possibleFalsePositive)return!0;let b=Math.max(0,l-6);for(;b<l;){let p=o[b].element;for(let w of r)if(p=p==null?void 0:p.parentElement,p===s.element)return!1;b+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let l=s.rect,c=M.getElementFromPoint(l.left+l.width*.5,l.top+l.height*.5);if(c&&(s.element.contains(c)||c.contains(s.element))||s.element.localName=="area"&&c==s.image)return!0;let p=[l.top+.1,l.bottom-.1],w=[l.left+.1,l.right-.1];for(let v of p)for(let u of w){let h=M.getElementFromPoint(u,v);if(h&&(s.element.contains(h)||h.contains(s.element)))return!0}});i.reverse();let{top:a,left:d}=f.getViewportTopLeft();for(let s of i)s.rect.top+=a,s.rect.left+=d;return i}};var H=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}capture(){return _(this,null,function*(){this.reset(),this.createMarkers(),this.displayMarkers()})}createMarkers(){this.hints=M.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{var i,a;let o=f.createElement("div"),r=(a=(i=e.element.attributes["data-momentic-id"])==null?void 0:i.value)!=null?a:void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",Z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(O.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},Z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=H;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`var __defProp = Object.defineProperty;
|
|
55
58
|
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
56
59
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
57
60
|
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
@@ -3583,63 +3586,57 @@ function registerAllMomenticListeners() {
|
|
|
3583
3586
|
|
|
3584
3587
|
// src/html/index.ts
|
|
3585
3588
|
registerAllMomenticListeners();
|
|
3586
|
-
`,cssGeneratorLibJs:'// Taken from https://cdn.jsdelivr.net/npm/css-selector-generator@3.6.8/build/index.min.js\n!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.CssSelectorGenerator=e():t.CssSelectorGenerator=e()}(self,(()=>(()=>{"use strict";var t={d:(e,n)=>{for(var o in n)t.o(n,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:n[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};function n(t){return"object"==typeof t&&null!==t&&t.nodeType===Node.ELEMENT_NODE}t.r(e),t.d(e,{default:()=>K,getCssSelector:()=>J});const o={NONE:"",DESCENDANT:" ",CHILD:" > "},r={id:"id",class:"class",tag:"tag",attribute:"attribute",nthchild:"nthchild",nthoftype:"nthoftype"},i="CssSelectorGenerator";function c(t="unknown problem",...e){console.warn(`${i}: ${t}`,...e)}const u={selectors:[r.id,r.class,r.tag,r.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY};function s(t){return t instanceof RegExp}function a(t){return["string","function"].includes(typeof t)||s(t)}function l(t){return Array.isArray(t)?t.filter(a):[]}function f(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return function(t){return t instanceof Node}(t)&&e.includes(t.nodeType)}function d(t,e){if(f(t))return t.contains(e)||c("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element\'s real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will nto work as intended."),t;const n=e.getRootNode({composed:!1});return f(n)?(n!==document&&c("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),n):e.ownerDocument.querySelector(":root")}function m(t){return"number"==typeof t?t:Number.POSITIVE_INFINITY}function p(t=[]){const[e=[],...n]=t;return 0===n.length?e:n.reduce(((t,e)=>t.filter((t=>e.includes(t)))),e)}function h(t){return[].concat(...t)}function g(t){const e=t.map((t=>{if(s(t))return e=>t.test(e);if("function"==typeof t)return e=>{const n=t(e);return"boolean"!=typeof n?(c("pattern matcher function invalid","Provided pattern matching function does not return boolean. It\'s result will be ignored.",t),!1):n};if("string"==typeof t){const e=new RegExp("^"+t.replace(/[|\\\\{}()[\\]^$+?.]/g,"\\\\$&").replace(/\\*/g,".+")+"$");return t=>e.test(t)}return c("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1}));return t=>e.some((e=>e(t)))}function y(t,e,n){const o=Array.from(d(n,t[0]).querySelectorAll(e));return o.length===t.length&&t.every((t=>o.includes(t)))}function b(t,e){e=null!=e?e:function(t){return t.ownerDocument.querySelector(":root")}(t);const o=[];let r=t;for(;n(r)&&r!==e;)o.push(r),r=r.parentElement;return o}function N(t,e){return p(t.map((t=>b(t,e))))}const S=", ",E=new RegExp(["^$","\\\\s"].join("|")),w=new RegExp(["^$"].join("|")),I=[r.nthoftype,r.tag,r.id,r.class,r.attribute,r.nthchild],v=g(["class","id","ng-*"]);function T({name:t}){return`[${t}]`}function C({name:t,value:e}){return`[${t}=\'${e}\']`}function O({nodeName:t,nodeValue:e}){return{name:V(t),value:V(e)}}function x(t){const e=Array.from(t.attributes).filter((e=>function({nodeName:t},e){const n=e.tagName.toLowerCase();return!(["input","option"].includes(n)&&"value"===t||v(t))}(e,t))).map(O);return[...e.map(T),...e.map(C)]}function j(t){return(t.getAttribute("class")||"").trim().split(/\\s+/).filter((t=>!w.test(t))).map((t=>`.${V(t)}`))}function A(t){const e=t.getAttribute("id")||"",n=`#${V(e)}`,o=t.getRootNode({composed:!1});return!E.test(e)&&y([t],n,o)?[n]:[]}function $(t){const e=t.parentNode;if(e){const o=Array.from(e.childNodes).filter(n).indexOf(t);if(o>-1)return[`:nth-child(${o+1})`]}return[]}function D(t){return[V(t.tagName.toLowerCase())]}function R(t){const e=[...new Set(h(t.map(D)))];return 0===e.length||e.length>1?[]:[e[0]]}function P(t){const e=R([t])[0],n=t.parentElement;if(n){const o=Array.from(n.children).filter((t=>t.tagName.toLowerCase()===e)),r=o.indexOf(t);if(r>-1)return[`${e}:nth-of-type(${r+1})`]}return[]}function _(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){return Array.from(function*(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){let n=0,o=L(1);for(;o.length<=t.length&&n<e;){n+=1;const e=o.map((e=>t[e]));yield e,o=k(o,t.length-1)}}(t,{maxResults:e}))}function k(t=[],e=0){const n=t.length;if(0===n)return[];const o=[...t];o[n-1]+=1;for(let t=n-1;t>=0;t--)if(o[t]>e){if(0===t)return L(n+1);o[t-1]++,o[t]=o[t-1]+1}return o[n-1]>e?L(n+1):o}function L(t=1){return Array.from(Array(t).keys())}const M=":".charCodeAt(0).toString(16).toUpperCase(),F=/[ !"#$%&\'()\\[\\]{|}<>*+,./;=?@^`~\\\\]/;function V(t=""){var e,n;return null!==(n=null===(e=null===CSS||void 0===CSS?void 0:CSS.escape)||void 0===e?void 0:e.call(CSS,t))&&void 0!==n?n:function(t=""){return t.split("").map((t=>":"===t?`\\\\${M} `:F.test(t)?`\\\\${t}`:escape(t).replace(/%/g,"\\\\"))).join("")}(t)}const Y={tag:R,id:function(t){return 0===t.length||t.length>1?[]:A(t[0])},class:function(t){return p(t.map(j))},attribute:function(t){return p(t.map(x))},nthchild:function(t){return p(t.map($))},nthoftype:function(t){return p(t.map(P))}},q={tag:D,id:A,class:j,attribute:x,nthchild:$,nthoftype:P};function B(t){return t.includes(r.tag)||t.includes(r.nthoftype)?[...t]:[...t,r.tag]}function G(t={}){const e=[...I];return t[r.tag]&&t[r.nthoftype]&&e.splice(e.indexOf(r.tag),1),e.map((e=>{return(o=t)[n=e]?o[n].join(""):"";var n,o})).join("")}function H(t,e,n="",r){const i=function(t,e){return""===e?t:function(t,e){return[...t.map((t=>e+o.DESCENDANT+t)),...t.map((t=>e+o.CHILD+t))]}(t,e)}(function(t,e,n){const o=function(t,e){const{blacklist:n,whitelist:o,combineWithinSelector:r,maxCombinations:i}=e,c=g(n),u=g(o);return function(t){const{selectors:e,includeTag:n}=t,o=[].concat(e);return n&&!o.includes("tag")&&o.push("tag"),o}(e).reduce(((e,n)=>{const o=function(t,e){var n;return(null!==(n=Y[e])&&void 0!==n?n:()=>[])(t)}(t,n),s=function(t=[],e,n){return t.filter((t=>n(t)||!e(t)))}(o,c,u),a=function(t=[],e){return t.sort(((t,n)=>{const o=e(t),r=e(n);return o&&!r?-1:!o&&r?1:0}))}(s,u);return e[n]=r?_(a,{maxResults:i}):a.map((t=>[t])),e}),{})}(t,n),r=function(t,e){return function(t){const{selectors:e,combineBetweenSelectors:n,includeTag:o,maxCandidates:r}=t,i=n?_(e,{maxResults:r}):e.map((t=>[t]));return o?i.map(B):i}(e).map((e=>function(t,e){const n={};return t.forEach((t=>{const o=e[t];o.length>0&&(n[t]=o)})),function(t={}){let e=[];return Object.entries(t).forEach((([t,n])=>{e=n.flatMap((n=>0===e.length?[{[t]:n}]:e.map((e=>Object.assign(Object.assign({},e),{[t]:n})))))})),e}(n).map(G)}(e,t))).filter((t=>t.length>0))}(o,n),i=h(r);return[...new Set(i)]}(t,r.root,r),n);for(const e of i)if(y(t,e,r.root))return e;return null}function W(t){return{value:t,include:!1}}function U({selectors:t,operator:e}){let n=[...I];t[r.tag]&&t[r.nthoftype]&&(n=n.filter((t=>t!==r.tag)));let o="";return n.forEach((e=>{(t[e]||[]).forEach((({value:t,include:e})=>{e&&(o+=t)}))})),e+o}function z(t){return[":root",...b(t).reverse().map((t=>{const e=function(t,e,n=o.NONE){const r={};return e.forEach((e=>{Reflect.set(r,e,function(t,e){return q[e](t)}(t,e).map(W))})),{element:t,operator:n,selectors:r}}(t,[r.nthchild],o.CHILD);return e.selectors.nthchild.forEach((t=>{t.include=!0})),e})).map(U)].join("")}function J(t,e={}){const o=function(t){(t instanceof NodeList||t instanceof HTMLCollection)&&(t=Array.from(t));const e=(Array.isArray(t)?t:[t]).filter(n);return[...new Set(e)]}(t),i=function(t,e={}){const n=Object.assign(Object.assign({},u),e);return{selectors:(o=n.selectors,Array.isArray(o)?o.filter((t=>{return e=r,n=t,Object.values(e).includes(n);var e,n})):[]),whitelist:l(n.whitelist),blacklist:l(n.blacklist),root:d(n.root,t),combineWithinSelector:!!n.combineWithinSelector,combineBetweenSelectors:!!n.combineBetweenSelectors,includeTag:!!n.includeTag,maxCombinations:m(n.maxCombinations),maxCandidates:m(n.maxCandidates)};var o}(o[0],e);let c="",s=i.root;function a(){return function(t,e,n="",o){if(0===t.length)return null;const r=[t.length>1?t:[],...N(t,e).map((t=>[t]))];for(const t of r){const e=H(t,0,n,o);if(e)return{foundElements:t,selector:e}}return null}(o,s,c,i)}let f=a();for(;f;){const{foundElements:t,selector:e}=f;if(y(o,e,i.root))return e;s=t[0],c=e,f=a()}return o.length>1?o.map((t=>J(t,i))).join(S):function(t){return t.map(z).join(S)}(o)}const K=J;return e})()));'};import{execSync as TO}from"child_process";import{randomUUID as jb}from"crypto";import{existsSync as Tl,mkdirSync as EO,readFileSync as CO,writeFileSync as RO}from"fs";import{Jimp as AO}from"jimp";import IO from"js-beautify";import{cloneDeep as PO}from"lodash-es";var vy={"application/prs.cww":["cww"],"application/prs.xsf+xml":["xsf"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["*xfdf"],"application/vnd.age":["age"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["*fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["*mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.pwg-xhtml-print+xml":["xhtm"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml","uo"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["*prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["*sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["*aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif","btf"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.cld":["cld"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.pytha.pyox":["pyo","pyox"],"model/vnd.sap.vds":["vds"],"model/vnd.usda":["usda"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.familysearch.gedcom":["ged"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]};Object.freeze(vy);var xy=vy;var Ty={"application/andrew-inset":["ez"],"application/appinstaller":["appinstaller"],"application/applixware":["aw"],"application/appx":["appx"],"application/appxbundle":["appxbundle"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/automationml-aml+xml":["aml"],"application/automationml-amlx+zip":["amlx"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cpl+xml":["cpl"],"application/cu-seeme":["cu"],"application/cwl":["cwl"],"application/dash+xml":["mpd"],"application/dash-patch+xml":["mpp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdf":["fdf"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["*js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/media-policy-dataset+xml":["mpf"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["*mp4","*mpg4","mp4s","m4p"],"application/msix":["msix"],"application/msixbundle":["msixbundle"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-keys":["asc"],"application/pgp-signature":["sig","*asc"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/sql":["sql"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/watcherinfo+xml":["wif"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xfdf":["xfdf"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/aac":["adts","aac"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avci":["avci"],"image/avcs":["avcs"],"image/avif":["avif"],"image/bmp":["bmp","dib"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/dpx":["dpx"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm","jpgm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/jt":["jt"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/prc":["prc"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/u3d":["u3d"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/javascript":["js","mjs"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["md","markdown"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/wgsl":["wgsl"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","*jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};Object.freeze(Ty);var Ey=Ty;var rn=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},Zo,ws,Vr,tp=class{constructor(...e){Zo.set(this,new Map),ws.set(this,new Map),Vr.set(this,new Map);for(let t of e)this.define(t)}define(e,t=!1){for(let[r,o]of Object.entries(e)){r=r.toLowerCase(),o=o.map(a=>a.toLowerCase()),rn(this,Vr,"f").has(r)||rn(this,Vr,"f").set(r,new Set);let i=rn(this,Vr,"f").get(r),s=!0;for(let a of o){let l=a.startsWith("*");if(a=l?a.slice(1):a,i?.add(a),s&&rn(this,ws,"f").set(r,a),s=!1,l)continue;let c=rn(this,Zo,"f").get(a);if(c&&c!=r&&!t)throw new Error(`"${r} -> ${a}" conflicts with "${c} -> ${a}". Pass \`force=true\` to override this definition.`);rn(this,Zo,"f").set(a,r)}}return this}getType(e){if(typeof e!="string")return null;let t=e.replace(/^.*[/\\]/,"").toLowerCase(),r=t.replace(/^.*\./,"").toLowerCase(),o=t.length<e.length;return!(r.length<t.length-1)&&o?null:rn(this,Zo,"f").get(r)??null}getExtension(e){return typeof e!="string"?null:(e=e?.split?.(";")[0],(e&&rn(this,ws,"f").get(e.trim().toLowerCase()))??null)}getAllExtensions(e){return typeof e!="string"?null:rn(this,Vr,"f").get(e.toLowerCase())??null}_freeze(){this.define=()=>{throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances")},Object.freeze(this);for(let e of rn(this,Vr,"f").values())Object.freeze(e);return this}_getTestState(){return{types:rn(this,Zo,"f"),extensions:rn(this,ws,"f")}}};Zo=new WeakMap,ws=new WeakMap,Vr=new WeakMap;var np=tp;var Cy=new np(Ey,xy)._freeze();import{homedir as $b,hostname as LO,platform as OO}from"os";import{basename as kO,extname as NO,join as Ts,resolve as _O}from"path";import{chromium as Wb,devices as MO}from"playwright";import{addExtra as FO}from"playwright-extra";import DO from"puppeteer-extra-plugin-recaptcha";import{v4 as UO}from"uuid";import{rmSync as db}from"fs";import{basename as GL,join as VL}from"path";import{errors as qL}from"playwright-core";var Un={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-aria-hidden","data-hidden","data-automation-id","data-content-editable-leaf","data-wf-icon","data-tns","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"]};var GP=new Set(["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z"]),VP=new Set(["a","e","i","o","u","y"]);function Ry(n){if(n.length>75)return!1;if(n[0]?.match(/[0-9a-zA-Z]/)===null)return!0;if(n.length>10){let u=Math.floor(n.length/8);if((n.match(/[-_:A-Z/ ]/g)??[]).length<u)return!0}if((n.match(/[^0-9a-zA-Z-_.]/g)??[]).length/n.length>.2)return!0;let t=(n.match(/[0-9]/g)??[]).length;if(t/n.length>.3)return!0;let r=(n.toLowerCase().match(/[aeiou]/gi)??[]).length;if((n.toLowerCase().match(/[bcdfghjklmnpqrstvwxyz]/gi)??[]).length/r>5)return!0;let i=0,s=0;for(let u of n.toLowerCase())GP.has(u)?(s++,s>i&&(i=s)):s=0;if(i>4)return!0;let a=0,l=0;for(let u of n.toLowerCase())u>="a"&&u<="z"&&!VP.has(u)?(l++,l>a&&(a=l)):l=0;if(a>4)return!0;let c=(n.match(/[A-Z]/g)??[]).length,p=(n.match(/[a-z]/g)??[]).length,d=Math.ceil(n.length*.3);return!!(p&&t&&Math.abs(p-t)<d||p&&c&&Math.abs(p-c)<d)}function Ay(n,e,t){if(n.length<t)return n;let r=n.indexOf(e);if(r===-1)return n;let o=Math.max(0,r-t/3),i=Math.min(r+t/3,n.length),s=n.indexOf(`
|
|
3587
|
-
`,o);
|
|
3588
|
-
`;)l++,
|
|
3589
|
-
`&&(i=a),n.slice(o,i)}import{randomUUID as nL}from"crypto";import{cloneDeep as ap}from"lodash-es";import{randomUUID as ZP}from"crypto";var Iy=new Set(["about:blank","chrome-error://chromewebdata/"]);var wt="data-momentic-id";var rp=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],op=1e4,vs=500;function dr(n,e){let t=n.findIndex(r=>r===e);if(!(t===-1||!n[t+1]))return n[t+1]}import{createHash as qP}from"crypto";var KP="v1";function dl(n,e){if(n.tagName.toLowerCase()==="svg"&&!JP(n))try{let t=Py(n,e),r=YP(JSON.stringify(t));return{version:KP,json:t,hash:r}}catch{return}}function YP(n){return qP("md5").update(n).digest("hex")}function Py(n,e){let t=n.tagName.toLowerCase(),r=XP(n);if(t==="image"&&r["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:t,props:r,children:[]};for(let i of n.childrenBackendIds){let s=e.backendIdToNode[i];if(s&&s.nodeType===1){let a=Py(s,e);a&&o.children.push(a)}}return o}function JP(n){let e=n.computedStyles.display,t=n.computedStyles.visibility,r=n.computedStyles.opacity;return e==="none"||t==="hidden"||r==="0"}function XP(n){let e={},t=n.attributes;for(let r of Object.keys(t))Un.visualAttributesForSvgSerialization.includes(r)&&(e[r]=t[r]);return t.id&&n.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var qr={r:147,g:196,b:125,a:.55},ky={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:qr,paddingColor:qr,borderColor:qr,marginColor:qr,eventTargetColor:qr,shapeColor:qr,shapeMarginColor:qr,showInfo:!0,showAccessibilityInfo:!0},pl=["display","opacity","visibility","height","position"];function Ny({snapshot:n,devicePixelRatio:e,logger:t}){let r=n.strings,o=n.documents,i={},s={},a={roots:[],backendIdToNode:i,frameIndexToIframeNode:s};return o.forEach((l,c)=>{let p=QP({allDocuments:o,stringConstants:r,frameIndex:c,devicePixelRatio:e,backendIdToNode:i,frameIndexToIframeNode:s,logger:t});a.roots.push(p)}),a}function QP({allDocuments:n,stringConstants:e,devicePixelRatio:t,frameIndex:r,frameIndexToIframeNode:o,backendIdToNode:i,logger:s}){let a=n[r],l=a.layout,c={};l.nodeIndex.forEach((C,I)=>{c[C]=I});let p=l.styles,d=l.bounds??[],u=a.nodes,m=u.contentDocumentIndex??{index:[],value:[]},h=u.backendNodeId??[],g=u.attributes??[],f=u.parentIndex??[],S=u.nodeName??[],x=u.nodeType??[],v=u.pseudoType??{index:[],value:[]},b=u.inputChecked??{index:[]},E=e[a.frameId];for(let C=0;C<h.length;C++){let I=h[C],_=x[C],L=g[C]??[],z=f[C]!==void 0&&f[C]>=0?f[C]:void 0,j=z!==void 0?h[z]:void 0,O=j!==void 0?i[j]:void 0,U=v.index.indexOf(C),P=U!==-1?e[v.value[U]]:void 0,G=c[C],N;G?N=d[G]??[]:N=[];let X=S[C]!==void 0?e[S[C]]?.toLowerCase():void 0;if(!X){s.warn({backendNodeId:I,frameId:E,frameIndex:r,nodeBounds:N},"DOM node has no tag name");continue}let re={backendNodeId:I,psuedoType:P,nodeType:_,frameIndex:r,parentFrameId:E,ownedFrameId:void 0,bounds:{x:N[0]??null,y:N[1]??null,width:N[2]??null,height:N[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:j??null,tagName:X,parent:O??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};O&&O.childrenBackendIds.push(I);let Tt=m.index.indexOf(C);if(Tt!==-1){let Se=m.value[Tt];o[Se]=re;let De=n[Se]?.frameId;re.ownedFrameId=De!==void 0?e[De]:void 0}for(let Se of Object.keys(re.bounds)){let De=Se;re.bounds[De]!==null&&(re.bounds[De]/=t)}let ce=G!==void 0?p[G]??[]:[];for(let Se=0;Se<ce.length&&!(Se>=pl.length);Se++){let De=ce[Se];if(De===void 0||isNaN(De))continue;let Ft=e[De];if(Ft===void 0)continue;let gt=pl[Se];re.computedStyles[gt]=Ft}for(let Se=0;Se<L.length;Se+=2){let De=L[Se],Ft=L[Se+1];if(!De||!Ft)continue;let gt=e[De],Dt=e[Ft];!gt||!Dt||(re.attributes[gt]=Dt)}b.index.includes(C)&&(re.attributes.checked="true"),i[re.backendNodeId]=re}return i[h[0]]}function sp(n,e){if(n.mPathSelector)return n.mPathSelector;let t=n.parent,r;if(!t)r=n.tagName;else if(n.tagName==="body")r="body";else{let i=t.childrenBackendIds.filter(l=>e.backendIdToNode[l]?.nodeType===1&&!e.backendIdToNode[l]?.psuedoType).indexOf(n.backendNodeId),s=` > ${n.tagName}:nth-child(${i+1})`;r=`${sp(t,e)}${s}`}return n.mPathSelector=r,r}function Ly({originalNode:n,candidate:e,logKey:t,logger:r}){if(!e.bounds)return r.debug({candidate:e},"Filtering out click candidate since it has no bounding box"),!1;let o=n.bounds,i=o.x??0,s=o.width??0,a=o.height??0,l=i+s,c=o.y??0,p=c+(o.height??0),d=e.bounds,u=d.width??0,m=d.height??0,h=d.x??0,g=h+(d.width??0),f=d.y??0,S=f+(d.height??0);return h<l&&g>i&&f<p&&S>c?Math.abs(s-u)<200||Math.abs(a-m)<200?!0:(_r({logger:r,logKey:t,maxCount:5,intervalMs:3e3},{candidate:e,originalNode:n},"Filtering out click candidate since it has a significantly different area"),!1):(_r({logger:r,logKey:t,maxCount:5,intervalMs:3e3},{candidate:e},"Filtering out click candidate since it does not intersect with the original node"),!1)}function ul(n,e,t){let r=Object.values(e.backendIdToNode),o,i=ZP();for(let c of r)if(c.attributes?.[wt]===n){o=c;break}if(!o)return[];let s=[],a=e.backendIdToNode[o.parentBackendNodeId??-1];for(;a&&(a?.momenticIgnored||!Ly({originalNode:o,candidate:a,logKey:i,logger:t}));)a=e.backendIdToNode[a.parentBackendNodeId??-1];a&&s.push(a);let l=[o];for(;l.length;){let c=l.shift();for(let p of c.childrenBackendIds??[]){let d=e.backendIdToNode[p];d&&!d.momenticIgnored&&Ly({originalNode:o,candidate:d,logKey:i,logger:t})?s.push(d):d&&l.push(d)}}return s}function Oy(n,e){return n.parentBackendNodeId!==null?e.backendIdToNode[n.parentBackendNodeId]:n.frameIndex===0?void 0:e.frameIndexToIframeNode[n.frameIndex]}var eL=["html","#document","#document-fragment"];function _y({node:n,domGraph:e}){let t=[],r=n,o=Oy(n,e);if(!o)return[n.tagName];let i=()=>{if(r=o,o=Oy(o,e),!o&&r.frameIndex!==0)throw new Error("No parent node but not in main frame")},s=0;for(;o&&s<1e6;){if(s++,eL.includes(r.tagName)){i();continue}if(r.tagName==="body")t.push("body");else{let l=!1,c=1;for(let p=0;p<o.childrenBackendIds.length;p++){let d=o.childrenBackendIds[p],u=e.backendIdToNode[d];if(d===r.backendNodeId){t.push(`${r.tagName}:nth-child(${c})`),l=!0;break}else u?.nodeType===1&&!u.psuedoType&&c++}if(!l)throw new Error(`Could not find child (${r.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function My(n,e){let t=n.locator("html"),r=[];for(let o=0;o<e.length;o++){let i=e[o];if(r.push(i),i.startsWith("iframe")){let s=r.join(" > ");r=[],o<e.length-1?t=t.frameLocator(s):t=t.locator(s)}}if(r.length&&(t=t.locator(r.join(" > "))),"owner"in t)throw new Error("Final locator from mpath is a frame locator");return t}async function Fy(n,e){await n.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let t=await n.send({method:"DOM.requestNode",params:{objectId:e},timeout:2e3}),o=(await n.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:2e3})).attributes,i=dr(o,wt);if(!i)throw new Error(`Could not find attribute ${wt} for object ${e}`);return i}function Dy(n){let e=[];for(let t=0;t<n.domGraph.roots.length;t++){let r=n.domGraph.roots[t],o=tL({root:r,domGraph:n.domGraph,existingHashes:n.existingHashes,flagStore:n.flagStore,logger:n.logger});e=e.concat(o)}return e}function tL(n){let{root:e,domGraph:t,existingHashes:r}=n,o=[],i=[e];for(;i.length;){let s=i.pop();if(s.nodeType===1&&s.tagName.toLowerCase()==="svg"){let a=dl(s,t);a&&!r[a.hash]&&o.push(a)}for(let a of s.childrenBackendIds){let l=t.backendIdToNode[a];l&&i.push(l)}}return o}var rL=["focusable","keyshortcuts","controls","live","relevant","orientation"],oL=["selected","readonly","modal","required","invalid"],iL=["id","name","role","content"],Uy=["absolute","fixed","sticky"],sL=["path"],aL=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator"],lL=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog","ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],cL=["menulistpopup","statictext","inlinetextbox"],dL=80,By=100,ml=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],pL=["cite"],uL={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},mL={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},zy={indentLevel:0},lp=class n{id;role;name;nameSources;tagName;content;properties;internalProperties;dataMomenticId;pathFromRoot;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&!Ry(t)?t:""),this.role=this.role||(e.domNode.attributes.role??""),SL(this.properties,e.domNode)}bL(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(){if(this.domNode&&this.domNode.tagName==="div"&&!this.domNode.bounds.x&&!this.domNode.bounds.y&&!this.domNode.bounds.width&&!this.domNode.bounds.height||this.domNode&&sL.includes(this.domNode.tagName))return!1;if(aL.includes(this.role.toLowerCase()))return!0;if(this.domNode?.computedStyles.display==="contents")return!1;if(this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||Un.alwaysInterestingTruthyPropertyNames.some(t=>!!this.properties[t]))return!0;let e=this.properties.class;return typeof e=="string"&&e.split(" ").some(t=>Wy(t))?!0:this.children.every(t=>t.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(t=>t.role==="StaticText")?!0:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(t=>t.startsWith("data"))}serialize(e=zy){let t=Object.assign({},zy,e),{indentLevel:r,noChildren:o,noProperties:i,noId:s,noContent:a,condensedMode:l}=t,c=ap(this.properties),p=" ".repeat(r),d=this.role||"",u=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(E=>!E.superseded&&E.type==="contents")&&this.children.length>0&&(m="");let g=this.nameSources?.find(E=>!E.superseded);if(g&&!g.nativeSource&&g.type==="relatedElement"){let E=g.attributeValue?.relatedNodes??[];E.length===1&&E[0].text&&E[0].text===m&&(m="")}let f=ml.includes(this.role)||pL.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${p}${m}
|
|
3590
|
-
`;let S=`${p}<${
|
|
3591
|
-
`;else{let E="";for(let I of this.children)E+=I.serialize({...e,indentLevel:
|
|
3592
|
-
`)?S+=`>${C}</${
|
|
3589
|
+
`,cssGeneratorLibJs:'// Taken from https://cdn.jsdelivr.net/npm/css-selector-generator@3.6.8/build/index.min.js\n!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.CssSelectorGenerator=e():t.CssSelectorGenerator=e()}(self,(()=>(()=>{"use strict";var t={d:(e,n)=>{for(var o in n)t.o(n,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:n[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};function n(t){return"object"==typeof t&&null!==t&&t.nodeType===Node.ELEMENT_NODE}t.r(e),t.d(e,{default:()=>K,getCssSelector:()=>J});const o={NONE:"",DESCENDANT:" ",CHILD:" > "},r={id:"id",class:"class",tag:"tag",attribute:"attribute",nthchild:"nthchild",nthoftype:"nthoftype"},i="CssSelectorGenerator";function c(t="unknown problem",...e){console.warn(`${i}: ${t}`,...e)}const u={selectors:[r.id,r.class,r.tag,r.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY};function s(t){return t instanceof RegExp}function a(t){return["string","function"].includes(typeof t)||s(t)}function l(t){return Array.isArray(t)?t.filter(a):[]}function f(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return function(t){return t instanceof Node}(t)&&e.includes(t.nodeType)}function d(t,e){if(f(t))return t.contains(e)||c("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element\'s real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will nto work as intended."),t;const n=e.getRootNode({composed:!1});return f(n)?(n!==document&&c("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),n):e.ownerDocument.querySelector(":root")}function m(t){return"number"==typeof t?t:Number.POSITIVE_INFINITY}function p(t=[]){const[e=[],...n]=t;return 0===n.length?e:n.reduce(((t,e)=>t.filter((t=>e.includes(t)))),e)}function h(t){return[].concat(...t)}function g(t){const e=t.map((t=>{if(s(t))return e=>t.test(e);if("function"==typeof t)return e=>{const n=t(e);return"boolean"!=typeof n?(c("pattern matcher function invalid","Provided pattern matching function does not return boolean. It\'s result will be ignored.",t),!1):n};if("string"==typeof t){const e=new RegExp("^"+t.replace(/[|\\\\{}()[\\]^$+?.]/g,"\\\\$&").replace(/\\*/g,".+")+"$");return t=>e.test(t)}return c("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1}));return t=>e.some((e=>e(t)))}function y(t,e,n){const o=Array.from(d(n,t[0]).querySelectorAll(e));return o.length===t.length&&t.every((t=>o.includes(t)))}function b(t,e){e=null!=e?e:function(t){return t.ownerDocument.querySelector(":root")}(t);const o=[];let r=t;for(;n(r)&&r!==e;)o.push(r),r=r.parentElement;return o}function N(t,e){return p(t.map((t=>b(t,e))))}const S=", ",E=new RegExp(["^$","\\\\s"].join("|")),w=new RegExp(["^$"].join("|")),I=[r.nthoftype,r.tag,r.id,r.class,r.attribute,r.nthchild],v=g(["class","id","ng-*"]);function T({name:t}){return`[${t}]`}function C({name:t,value:e}){return`[${t}=\'${e}\']`}function O({nodeName:t,nodeValue:e}){return{name:V(t),value:V(e)}}function x(t){const e=Array.from(t.attributes).filter((e=>function({nodeName:t},e){const n=e.tagName.toLowerCase();return!(["input","option"].includes(n)&&"value"===t||v(t))}(e,t))).map(O);return[...e.map(T),...e.map(C)]}function j(t){return(t.getAttribute("class")||"").trim().split(/\\s+/).filter((t=>!w.test(t))).map((t=>`.${V(t)}`))}function A(t){const e=t.getAttribute("id")||"",n=`#${V(e)}`,o=t.getRootNode({composed:!1});return!E.test(e)&&y([t],n,o)?[n]:[]}function $(t){const e=t.parentNode;if(e){const o=Array.from(e.childNodes).filter(n).indexOf(t);if(o>-1)return[`:nth-child(${o+1})`]}return[]}function D(t){return[V(t.tagName.toLowerCase())]}function R(t){const e=[...new Set(h(t.map(D)))];return 0===e.length||e.length>1?[]:[e[0]]}function P(t){const e=R([t])[0],n=t.parentElement;if(n){const o=Array.from(n.children).filter((t=>t.tagName.toLowerCase()===e)),r=o.indexOf(t);if(r>-1)return[`${e}:nth-of-type(${r+1})`]}return[]}function _(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){return Array.from(function*(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){let n=0,o=L(1);for(;o.length<=t.length&&n<e;){n+=1;const e=o.map((e=>t[e]));yield e,o=k(o,t.length-1)}}(t,{maxResults:e}))}function k(t=[],e=0){const n=t.length;if(0===n)return[];const o=[...t];o[n-1]+=1;for(let t=n-1;t>=0;t--)if(o[t]>e){if(0===t)return L(n+1);o[t-1]++,o[t]=o[t-1]+1}return o[n-1]>e?L(n+1):o}function L(t=1){return Array.from(Array(t).keys())}const M=":".charCodeAt(0).toString(16).toUpperCase(),F=/[ !"#$%&\'()\\[\\]{|}<>*+,./;=?@^`~\\\\]/;function V(t=""){var e,n;return null!==(n=null===(e=null===CSS||void 0===CSS?void 0:CSS.escape)||void 0===e?void 0:e.call(CSS,t))&&void 0!==n?n:function(t=""){return t.split("").map((t=>":"===t?`\\\\${M} `:F.test(t)?`\\\\${t}`:escape(t).replace(/%/g,"\\\\"))).join("")}(t)}const Y={tag:R,id:function(t){return 0===t.length||t.length>1?[]:A(t[0])},class:function(t){return p(t.map(j))},attribute:function(t){return p(t.map(x))},nthchild:function(t){return p(t.map($))},nthoftype:function(t){return p(t.map(P))}},q={tag:D,id:A,class:j,attribute:x,nthchild:$,nthoftype:P};function B(t){return t.includes(r.tag)||t.includes(r.nthoftype)?[...t]:[...t,r.tag]}function G(t={}){const e=[...I];return t[r.tag]&&t[r.nthoftype]&&e.splice(e.indexOf(r.tag),1),e.map((e=>{return(o=t)[n=e]?o[n].join(""):"";var n,o})).join("")}function H(t,e,n="",r){const i=function(t,e){return""===e?t:function(t,e){return[...t.map((t=>e+o.DESCENDANT+t)),...t.map((t=>e+o.CHILD+t))]}(t,e)}(function(t,e,n){const o=function(t,e){const{blacklist:n,whitelist:o,combineWithinSelector:r,maxCombinations:i}=e,c=g(n),u=g(o);return function(t){const{selectors:e,includeTag:n}=t,o=[].concat(e);return n&&!o.includes("tag")&&o.push("tag"),o}(e).reduce(((e,n)=>{const o=function(t,e){var n;return(null!==(n=Y[e])&&void 0!==n?n:()=>[])(t)}(t,n),s=function(t=[],e,n){return t.filter((t=>n(t)||!e(t)))}(o,c,u),a=function(t=[],e){return t.sort(((t,n)=>{const o=e(t),r=e(n);return o&&!r?-1:!o&&r?1:0}))}(s,u);return e[n]=r?_(a,{maxResults:i}):a.map((t=>[t])),e}),{})}(t,n),r=function(t,e){return function(t){const{selectors:e,combineBetweenSelectors:n,includeTag:o,maxCandidates:r}=t,i=n?_(e,{maxResults:r}):e.map((t=>[t]));return o?i.map(B):i}(e).map((e=>function(t,e){const n={};return t.forEach((t=>{const o=e[t];o.length>0&&(n[t]=o)})),function(t={}){let e=[];return Object.entries(t).forEach((([t,n])=>{e=n.flatMap((n=>0===e.length?[{[t]:n}]:e.map((e=>Object.assign(Object.assign({},e),{[t]:n})))))})),e}(n).map(G)}(e,t))).filter((t=>t.length>0))}(o,n),i=h(r);return[...new Set(i)]}(t,r.root,r),n);for(const e of i)if(y(t,e,r.root))return e;return null}function W(t){return{value:t,include:!1}}function U({selectors:t,operator:e}){let n=[...I];t[r.tag]&&t[r.nthoftype]&&(n=n.filter((t=>t!==r.tag)));let o="";return n.forEach((e=>{(t[e]||[]).forEach((({value:t,include:e})=>{e&&(o+=t)}))})),e+o}function z(t){return[":root",...b(t).reverse().map((t=>{const e=function(t,e,n=o.NONE){const r={};return e.forEach((e=>{Reflect.set(r,e,function(t,e){return q[e](t)}(t,e).map(W))})),{element:t,operator:n,selectors:r}}(t,[r.nthchild],o.CHILD);return e.selectors.nthchild.forEach((t=>{t.include=!0})),e})).map(U)].join("")}function J(t,e={}){const o=function(t){(t instanceof NodeList||t instanceof HTMLCollection)&&(t=Array.from(t));const e=(Array.isArray(t)?t:[t]).filter(n);return[...new Set(e)]}(t),i=function(t,e={}){const n=Object.assign(Object.assign({},u),e);return{selectors:(o=n.selectors,Array.isArray(o)?o.filter((t=>{return e=r,n=t,Object.values(e).includes(n);var e,n})):[]),whitelist:l(n.whitelist),blacklist:l(n.blacklist),root:d(n.root,t),combineWithinSelector:!!n.combineWithinSelector,combineBetweenSelectors:!!n.combineBetweenSelectors,includeTag:!!n.includeTag,maxCombinations:m(n.maxCombinations),maxCandidates:m(n.maxCandidates)};var o}(o[0],e);let c="",s=i.root;function a(){return function(t,e,n="",o){if(0===t.length)return null;const r=[t.length>1?t:[],...N(t,e).map((t=>[t]))];for(const t of r){const e=H(t,0,n,o);if(e)return{foundElements:t,selector:e}}return null}(o,s,c,i)}let f=a();for(;f;){const{foundElements:t,selector:e}=f;if(y(o,e,i.root))return e;s=t[0],c=e,f=a()}return o.length>1?o.map((t=>J(t,i))).join(S):function(t){return t.map(z).join(S)}(o)}const K=J;return e})()));'};import{execSync as nk}from"child_process";import{randomUUID as xb}from"crypto";import{existsSync as Tl,mkdirSync as rk,readFileSync as ok,writeFileSync as ik}from"fs";import{Jimp as ak}from"jimp";import sk from"js-beautify";import{cloneDeep as Tb}from"lodash-es";var by={"application/prs.cww":["cww"],"application/prs.xsf+xml":["xsf"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["*xfdf"],"application/vnd.age":["age"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["*fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["*mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.pwg-xhtml-print+xml":["xhtm"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml","uo"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["*prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["*sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["*aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif","btf"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.cld":["cld"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.pytha.pyox":["pyo","pyox"],"model/vnd.sap.vds":["vds"],"model/vnd.usda":["usda"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.familysearch.gedcom":["ged"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]};Object.freeze(by);var wy=by;var vy={"application/andrew-inset":["ez"],"application/appinstaller":["appinstaller"],"application/applixware":["aw"],"application/appx":["appx"],"application/appxbundle":["appxbundle"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/automationml-aml+xml":["aml"],"application/automationml-amlx+zip":["amlx"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cpl+xml":["cpl"],"application/cu-seeme":["cu"],"application/cwl":["cwl"],"application/dash+xml":["mpd"],"application/dash-patch+xml":["mpp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdf":["fdf"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["*js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/media-policy-dataset+xml":["mpf"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["*mp4","*mpg4","mp4s","m4p"],"application/msix":["msix"],"application/msixbundle":["msixbundle"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-keys":["asc"],"application/pgp-signature":["sig","*asc"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/sql":["sql"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/watcherinfo+xml":["wif"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xfdf":["xfdf"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/aac":["adts","aac"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avci":["avci"],"image/avcs":["avcs"],"image/avif":["avif"],"image/bmp":["bmp","dib"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/dpx":["dpx"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm","jpgm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/jt":["jt"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/prc":["prc"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/u3d":["u3d"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/javascript":["js","mjs"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["md","markdown"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/wgsl":["wgsl"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","*jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};Object.freeze(vy);var xy=vy;var rn=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},ni,xa,Yr,ep=class{constructor(...e){ni.set(this,new Map),xa.set(this,new Map),Yr.set(this,new Map);for(let t of e)this.define(t)}define(e,t=!1){for(let[n,o]of Object.entries(e)){n=n.toLowerCase(),o=o.map(s=>s.toLowerCase()),rn(this,Yr,"f").has(n)||rn(this,Yr,"f").set(n,new Set);let i=rn(this,Yr,"f").get(n),a=!0;for(let s of o){let l=s.startsWith("*");if(s=l?s.slice(1):s,i?.add(s),a&&rn(this,xa,"f").set(n,s),a=!1,l)continue;let c=rn(this,ni,"f").get(s);if(c&&c!=n&&!t)throw new Error(`"${n} -> ${s}" conflicts with "${c} -> ${s}". Pass \`force=true\` to override this definition.`);rn(this,ni,"f").set(s,n)}}return this}getType(e){if(typeof e!="string")return null;let t=e.replace(/^.*[/\\]/,"").toLowerCase(),n=t.replace(/^.*\./,"").toLowerCase(),o=t.length<e.length;return!(n.length<t.length-1)&&o?null:rn(this,ni,"f").get(n)??null}getExtension(e){return typeof e!="string"?null:(e=e?.split?.(";")[0],(e&&rn(this,xa,"f").get(e.trim().toLowerCase()))??null)}getAllExtensions(e){return typeof e!="string"?null:rn(this,Yr,"f").get(e.toLowerCase())??null}_freeze(){this.define=()=>{throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances")},Object.freeze(this);for(let e of rn(this,Yr,"f").values())Object.freeze(e);return this}_getTestState(){return{types:rn(this,ni,"f"),extensions:rn(this,xa,"f")}}};ni=new WeakMap,xa=new WeakMap,Yr=new WeakMap;var tp=ep;var Ty=new tp(xy,wy)._freeze();import{homedir as Cb,hostname as lk,platform as ck}from"os";import{basename as dk,extname as pk,join as Ea,resolve as uk}from"path";import{chromium as Ab,devices as mk}from"playwright";import{addExtra as hk}from"playwright-extra";import gk from"puppeteer-extra-plugin-recaptcha";import{v4 as fk}from"uuid";import{rmSync as lb}from"fs";import{basename as PL,join as LL}from"path";import{errors as kL}from"playwright-core";var Dn={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-aria-hidden","data-hidden","data-automation-id","data-content-editable-leaf","data-wf-icon","data-tns","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"]};var PP=new Set(["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z"]),LP=new Set(["a","e","i","o","u","y"]);function Ey(r){if(r.length>75)return!1;if(r[0]?.match(/[0-9a-zA-Z]/)===null)return!0;if(r.length>10){let m=Math.floor(r.length/8);if((r.match(/[-_:A-Z/ ]/g)??[]).length<m)return!0}if((r.match(/[^0-9a-zA-Z-_.]/g)??[]).length/r.length>.2)return!0;let t=(r.match(/[0-9]/g)??[]).length;if(t/r.length>.3)return!0;let n=(r.toLowerCase().match(/[aeiou]/gi)??[]).length;if((r.toLowerCase().match(/[bcdfghjklmnpqrstvwxyz]/gi)??[]).length/n>5)return!0;let i=0,a=0;for(let m of r.toLowerCase())PP.has(m)?(a++,a>i&&(i=a)):a=0;if(i>4)return!0;let s=0,l=0;for(let m of r.toLowerCase())m>="a"&&m<="z"&&!LP.has(m)?(l++,l>s&&(s=l)):l=0;if(s>4)return!0;let c=(r.match(/[A-Z]/g)??[]).length,p=(r.match(/[a-z]/g)??[]).length,d=Math.ceil(r.length*.3);return!!(p&&t&&Math.abs(p-t)<d||p&&c&&Math.abs(p-c)<d)}function Cy(r,e,t){if(r.length<t)return r;let n=r.indexOf(e);if(n===-1)return r;let o=Math.max(0,n-t/3),i=Math.min(n+t/3,r.length),a=r.indexOf(`
|
|
3590
|
+
`,o);a>0&&a<n&&(o=a);let s=i,l=0;for(;l<1e3&&s>n&&r[s]!==`
|
|
3591
|
+
`;)l++,s--;return s>n&&r[s]===`
|
|
3592
|
+
`&&(i=s),r.slice(o,i)}import{randomUUID as zP}from"crypto";import{cloneDeep as ap}from"lodash-es";import{randomUUID as FP}from"crypto";var Ay=new Set(["about:blank","chrome-error://chromewebdata/"]);var wt="data-momentic-id";var np=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],rp=1e4,Ta=500;function pr(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as kP}from"crypto";var OP="v1";function ul(r,e){if(r.tagName.toLowerCase()==="svg"&&!MP(r))try{let t=Ry(r,e),n=NP(JSON.stringify(t));return{version:OP,json:t,hash:n}}catch{return}}function NP(r){return kP("md5").update(r).digest("hex")}function Ry(r,e){let t=r.tagName.toLowerCase(),n=_P(r);if(t==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:t,props:n,children:[]};for(let i of r.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let s=Ry(a,e);s&&o.children.push(s)}}return o}function MP(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function _P(r){let e={},t=r.attributes;for(let n of Object.keys(t))Dn.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var Jr={r:147,g:196,b:125,a:.55},Ly={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:Jr,paddingColor:Jr,borderColor:Jr,marginColor:Jr,eventTargetColor:Jr,shapeColor:Jr,shapeMarginColor:Jr,showInfo:!0,showAccessibilityInfo:!0},ml=["display","opacity","visibility","height","position"];function ky({snapshot:r,devicePixelRatio:e,logger:t}){let n=r.strings,o=r.documents,i={},a={},s={roots:[],backendIdToNode:i,frameIndexToIframeNode:a};return o.forEach((l,c)=>{let p=DP({allDocuments:o,stringConstants:n,frameIndex:c,devicePixelRatio:e,backendIdToNode:i,frameIndexToIframeNode:a,logger:t});s.roots.push(p)}),s}function DP({allDocuments:r,stringConstants:e,devicePixelRatio:t,frameIndex:n,frameIndexToIframeNode:o,backendIdToNode:i,logger:a}){let s=r[n],l=s.layout,c={};l.nodeIndex.forEach((C,I)=>{c[C]=I});let p=l.styles,d=l.bounds??[],m=s.nodes,u=m.contentDocumentIndex??{index:[],value:[]},h=m.backendNodeId??[],g=m.attributes??[],f=m.parentIndex??[],S=m.nodeName??[],x=m.nodeType??[],v=m.pseudoType??{index:[],value:[]},b=m.inputChecked??{index:[]},E=e[s.frameId];for(let C=0;C<h.length;C++){let I=h[C],M=x[C],L=g[C]??[],z=f[C]!==void 0&&f[C]>=0?f[C]:void 0,j=z!==void 0?h[z]:void 0,k=j!==void 0?i[j]:void 0,U=v.index.indexOf(C),P=U!==-1?e[v.value[U]]:void 0,V=c[C],N;V?N=d[V]??[]:N=[];let X=S[C]!==void 0?e[S[C]]?.toLowerCase():void 0;if(!X){a.warn({backendNodeId:I,frameId:E,frameIndex:n,nodeBounds:N},"DOM node has no tag name");continue}let oe={backendNodeId:I,psuedoType:P,nodeType:M,frameIndex:n,parentFrameId:E,ownedFrameId:void 0,bounds:{x:N[0]??null,y:N[1]??null,width:N[2]??null,height:N[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:j??null,tagName:X,parent:k??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};k&&k.childrenBackendIds.push(I);let Tt=u.index.indexOf(C);if(Tt!==-1){let Se=u.value[Tt];o[Se]=oe;let De=r[Se]?.frameId;oe.ownedFrameId=De!==void 0?e[De]:void 0}for(let Se of Object.keys(oe.bounds)){let De=Se;oe.bounds[De]!==null&&(oe.bounds[De]/=t)}let se=V!==void 0?p[V]??[]:[];for(let Se=0;Se<se.length&&!(Se>=ml.length);Se++){let De=se[Se];if(De===void 0||isNaN(De))continue;let Ft=e[De];if(Ft===void 0)continue;let gt=ml[Se];oe.computedStyles[gt]=Ft}for(let Se=0;Se<L.length;Se+=2){let De=L[Se],Ft=L[Se+1];if(!De||!Ft)continue;let gt=e[De],Wt=e[Ft];!gt||!Wt||(oe.attributes[gt]=Wt)}b.index.includes(C)&&(oe.attributes.checked="true"),i[oe.backendNodeId]=oe}return i[h[0]]}function ip(r,e){if(r.mPathSelector)return r.mPathSelector;let t=r.parent,n;if(!t)n=r.tagName;else if(r.tagName==="body")n="body";else{let i=t.childrenBackendIds.filter(l=>e.backendIdToNode[l]?.nodeType===1&&!e.backendIdToNode[l]?.psuedoType).indexOf(r.backendNodeId),a=` > ${r.tagName}:nth-child(${i+1})`;n=`${ip(t,e)}${a}`}return r.mPathSelector=n,n}function Iy({originalNode:r,candidate:e,logKey:t,logger:n}){if(!e.bounds)return n.debug({candidate:e},"Filtering out click candidate since it has no bounding box"),!1;let o=r.bounds,i=o.x??0,a=o.width??0,s=o.height??0,l=i+a,c=o.y??0,p=c+(o.height??0),d=e.bounds,m=d.width??0,u=d.height??0,h=d.x??0,g=h+(d.width??0),f=d.y??0,S=f+(d.height??0);return h<l&&g>i&&f<p&&S>c?Math.abs(a-m)<200||Math.abs(s-u)<200?!0:(Dr({logger:n,logKey:t,maxCount:5,intervalMs:3e3},{candidate:e,originalNode:r},"Filtering out click candidate since it has a significantly different area"),!1):(Dr({logger:n,logKey:t,maxCount:5,intervalMs:3e3},{candidate:e},"Filtering out click candidate since it does not intersect with the original node"),!1)}function hl(r,e,t){let n=Object.values(e.backendIdToNode),o,i=FP();for(let c of n)if(c.attributes?.[wt]===r){o=c;break}if(!o)return[];let a=[],s=e.backendIdToNode[o.parentBackendNodeId??-1];for(;s&&(s?.momenticIgnored||!Iy({originalNode:o,candidate:s,logKey:i,logger:t}));)s=e.backendIdToNode[s.parentBackendNodeId??-1];s&&a.push(s);let l=[o];for(;l.length;){let c=l.shift();for(let p of c.childrenBackendIds??[]){let d=e.backendIdToNode[p];d&&!d.momenticIgnored&&Iy({originalNode:o,candidate:d,logKey:i,logger:t})?a.push(d):d&&l.push(d)}}return a}function Py(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var UP=["html","#document","#document-fragment"];function Oy({node:r,domGraph:e}){let t=[],n=r,o=Py(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=Py(o,e),!o&&n.frameIndex!==0)throw new Error("No parent node but not in main frame")},a=0;for(;o&&a<1e6;){if(a++,UP.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let l=!1,c=1;for(let p=0;p<o.childrenBackendIds.length;p++){let d=o.childrenBackendIds[p],m=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${c})`),l=!0;break}else m?.nodeType===1&&!m.psuedoType&&c++}if(!l)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function Ny(r,e){let t=r.locator("html"),n=[];for(let o=0;o<e.length;o++){let i=e[o];if(n.push(i),i.startsWith("iframe")){let a=n.join(" > ");n=[],o<e.length-1?t=t.frameLocator(a):t=t.locator(a)}}if(n.length&&(t=t.locator(n.join(" > "))),"owner"in t)throw new Error("Final locator from mpath is a frame locator");return t}async function My(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:2e3}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:2e3})).attributes,i=pr(o,wt);if(!i)throw new Error(`Could not find attribute ${wt} for object ${e}`);return i}function _y(r){let e=[];for(let t=0;t<r.domGraph.roots.length;t++){let n=r.domGraph.roots[t],o=BP({root:n,domGraph:r.domGraph,existingHashes:r.existingHashes,flagStore:r.flagStore,logger:r.logger});e=e.concat(o)}return e}function BP(r){let{root:e,domGraph:t,existingHashes:n}=r,o=[],i=[e];for(;i.length;){let a=i.pop();if(a.nodeType===1&&a.tagName.toLowerCase()==="svg"){let s=ul(a,t);s&&!n[s.hash]&&o.push(s)}for(let s of a.childrenBackendIds){let l=t.backendIdToNode[s];l&&i.push(l)}}return o}var jP=["focusable","keyshortcuts","controls","live","relevant","orientation"],HP=["selected","readonly","modal","required","invalid"],$P=["id","name","role","content"],Fy=["absolute","fixed","sticky"],WP=["path"],GP=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator"],VP=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog","ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],qP=["menulistpopup","statictext","inlinetextbox"],KP=80,Dy=100,gl=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],YP=["cite"],JP={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},XP={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},Uy={indentLevel:0},sp=class r{id;role;name;nameSources;tagName;content;properties;internalProperties;dataMomenticId;pathFromRoot;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&!Ey(t)?t:""),this.role=this.role||(e.domNode.attributes.role??""),tL(this.properties,e.domNode)}rL(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(){if(this.domNode&&this.domNode.tagName==="div"&&!this.domNode.bounds.x&&!this.domNode.bounds.y&&!this.domNode.bounds.width&&!this.domNode.bounds.height||this.domNode&&WP.includes(this.domNode.tagName))return!1;if(GP.includes(this.role.toLowerCase()))return!0;if(this.domNode?.computedStyles.display==="contents")return!1;if(this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||Dn.alwaysInterestingTruthyPropertyNames.some(t=>!!this.properties[t]))return!0;let e=this.properties.class;return typeof e=="string"&&e.split(" ").some(t=>Hy(t))?!0:this.children.every(t=>t.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(t=>t.role==="StaticText")?!0:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(t=>t.startsWith("data"))}serialize(e=Uy){let t=Object.assign({},Uy,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:l}=t,c=ap(this.properties),p=" ".repeat(n),d=this.role||"",m=this.tagName??"unknown",u=this.name;d==="heading"&&u==="heading"&&(u=""),this.nameSources?.find(E=>!E.superseded&&E.type==="contents")&&this.children.length>0&&(u="");let g=this.nameSources?.find(E=>!E.superseded);if(g&&!g.nativeSource&&g.type==="relatedElement"){let E=g.attributeValue?.relatedNodes??[];E.length===1&&E[0].text&&E[0].text===u&&(u="")}let f=gl.includes(this.role)||YP.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${p}${u}
|
|
3593
|
+
`;let S=`${p}<${m}`;!a&&!f&&(S+=` id="${this.id}"`);let x=s??!1;(c.multiline||c.contenteditable)&&this.children.length>0&&(x=!0),d&&d!=="generic"&&d!==m&&!(JP[d]??[]).includes(m)&&(S+=` role=${JSON.stringify(d)}`),u&&(S+=` name=${JSON.stringify(u)}`),this.content&&!x&&(S+=` content=${JSON.stringify(this.content)}`);let v=Date.now();if(Object.keys(c).length>0&&!i){if(Date.now()-v>1e3)throw new Error(`Serialization for the HTML element with tag ${m} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(c).forEach(([E,C])=>{if(!jP.includes(E)){{if(HP.includes(E)&&(!C||C==="false"))return;if(E==="value"&&x&&(c.type==="text"||this.role==="textbox"))return;if(E==="level"&&`${C}`=="1")return;if(E==="url"&&c.src&&m==="img")return;if(E==="url"&&c.href&&m==="a")return;if(E==="editable"&&C==="plaintext")return;if(E==="type"&&C===m)return;if(l&&!XP[E])return}typeof C=="string"?S+=` ${E}="${_e(C,Dy,!0)}"`:typeof C=="boolean"?C?S+=` ${E}`:S+=` ${E}={false}`:typeof C<"u"&&(S+=` ${E}={${_e(JSON.stringify(C),Dy,!0)}}`)}})}if(m==="::before"||m==="::after"){let E="";for(let C of this.children)E+=C.serialize({...e,indentLevel:n,neighbors:0});return E}let b=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||b)S+=` />
|
|
3594
|
+
`;else{let E="";for(let I of this.children)E+=I.serialize({...e,indentLevel:n+2,neighbors:0});let C=E.trim();C.length<=KP&&!C.includes(`
|
|
3595
|
+
`)?S+=`>${C}</${m}>
|
|
3593
3596
|
`:S+=`>
|
|
3594
|
-
${E}${p}</${
|
|
3595
|
-
`}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let E=this.parent.children.findIndex(
|
|
3597
|
+
${E}${p}</${m}>
|
|
3598
|
+
`}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let E=this.parent.children.findIndex(M=>M.id===this.id),C=E>0?this.parent.children[E-1]?.serialize({...e,neighbors:0}):"",I=E<this.parent.children.length-1?this.parent.children[E+1]?.serialize({...e,neighbors:0}):"";return`${C||""}
|
|
3596
3599
|
${S}
|
|
3597
|
-
${I||""}`}return S}shallowClone(){let e=new n({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:ap(this.internalProperties),parentFrame:this.parentFrame});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=ap(this.properties),e}},cp=class n{constructor(e,t,r,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=r;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function r(i,s=!1){let a=e.has(`${i.id}`)||i.id===t?.id,l=i.shallowClone(),c=i.children,p=!1,d=[];for(let u of c){let m=r(u,a||p);m&&(d.push(m),m.parent=l,p=!0)}if(l.children=d,a||p)return l;if(ml.includes(i.role)&&s)return l}let o=r(t);return new n(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function hL(n){return n.name?.value?`"${n.name.value}"`:n.role?.value&&n.role.value!=="none"&&n.role.value!=="generic"?`"${n.role.value}"`:`"${n.nodeId}"`}function gL(n,e,t,r){return n.bounds.x===null||n.bounds.y===null||n.bounds.height===null||n.bounds.width===null||n.bounds.width===0||n.bounds.height===0?!0:n.bounds.x+n.bounds.width<e.leftBound||n.bounds.x>e.rightBound?(_r({logger:t,logKey:r,maxCount:5,intervalMs:3e3},{domNode:n,logKey:r},"Filtering out node since it is not in the viewport horizontally"),!1):n.bounds.y+n.bounds.height<e.upperBound||n.bounds.y>e.lowerBound?(_r({logger:t,logKey:r,maxCount:5,intervalMs:3e3},{domNode:n,logKey:r},"Filtering out node since it is not in the viewport vertically"),!1):n.computedStyles.display==="none"?(t.debug({domNode:n},"Filtering out node since it has display none"),!1):!0}async function jy({node:n,parent:e,frameId:t,frameContext:r,axGraph:o,domGraph:i,inputNodeMap:s,filterZeroOpacity:a,filterByViewport:l,viewportDetails:c,useMPaths:p,cdpClient:d,logger:u,callId:m}){if(!e&&n.parentId)throw new Error(`Got no parent for accessibility node ${n.nodeId}: ${JSON.stringify(n)}`);let h=(O,U={})=>{},g=n.backendDOMNodeId,f=cL.includes((n.role?.value).toLowerCase());if(!f&&g===void 0)return h("Filtering out node since it doesn't exist in the DOM"),[];let S=g?i.backendIdToNode[g]:void 0;if(!f&&!S)try{let O=await D(d.send({method:"DOM.describeNode",params:{backendNodeId:g}}),{milliseconds:750,fallback:()=>{u.debug("Timeout getting node from CDP while processing a11y tree")}});if(O&&O.node.nodeName.toLowerCase()==="slot"&&O.node.distributedNodes?.length)u.debug({redirectedDomNode:S,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:n,cdpResult:O},"Redirecting node to assigned slot");else return h("Filtering out node since it doesn't exist in the DOM",{cdpResult:O}),[]}catch(O){return h("Filtering out node since it doesn't exist in the DOM",{err:O}),[]}if(S&&e&&l&&c&&n.backendDOMNodeId&&!gL(S,c,u,m))return S.momenticIgnored=!0,[];if(S&&S.computedStyles.display==="none")return u.debug({domNode:S},"Filtering out node since it has display none"),S.momenticIgnored=!0,[];if(S&&S.attributes.tabindex==="-1"&&S.tagName.toLowerCase()==="input"&&(S.bounds.width??0)<10&&(S.bounds.height??0)<10)return _r({logger:u,logKey:m,maxCount:5,intervalMs:3e3},{attributes:S.attributes},"Filtering out node since it is likely an invisible input that is non-interactive"),S.momenticIgnored=!0,[];let x=n.name?.value?typeof n.name.value=="string"?n.name.value:`${n.name.value}`:"",v=n.value?.value?typeof n.value.value=="string"?n.value.value:`${n.value.value}`:"",b=new lp({domNode:S,id:parseInt(n.nodeId),role:n.role?.value||"",name:x,nameSources:n.name?.sources,content:v,properties:n.properties,children:[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+hL(n),backendNodeID:n.backendDOMNodeId,ignoredByCDP:n.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},parentFrame:r.type==="root"?void 0:r}),E=r,C=s[t],I=t;if(S?.tagName.toLowerCase()==="iframe"&&S.ownedFrameId){let O=r.childFrames.find(G=>G.frameId===S.ownedFrameId),U=o[O?.frameId??""]?.root,P=s[O?.frameId??""];if(O&&U&&P){n.childIds&&n.childIds.length>0&&u.debug("Replacing existing node's children with children from the iframe");let G=U;n.childIds=G.childIds,E=O,C=P,I=O.frameId}}let _=S?.childrenBackendIds?.length??0,L=n.childIds?.length??0;if(_>L&&(!a||S?.computedStyles.opacity!=="0")){let O=n.childIds?.map(P=>C.get(parseInt(P))).filter(Boolean).map(P=>P?.backendDOMNodeId).filter(P=>P!==void 0)??[],U=0;for(let P of S?.childrenBackendIds??[]){if(O.includes(P)){U=(n.childIds?.findIndex(Tt=>C.get(parseInt(Tt))?.backendDOMNodeId===P)??0)+1;continue}let G=i.backendIdToNode[P];if(!G||G?.tagName.toLowerCase()!=="svg")continue;let N=Math.floor(-1*Math.random()*1e7),X={nodeId:N.toString(),parentId:n.nodeId,ignored:!1,backendDOMNodeId:P,frameId:I,role:{type:"string",value:"graphics-symbol"}};C.set(N,X),n.childIds||(n.childIds=[]),n.childIds.splice(U,0,N.toString()),U++}}for(let O of n.childIds??[]){if(!O)continue;let U=C.get(parseInt(O));if(!U)continue;let P=await jy({node:U,parent:b,domGraph:i,axGraph:o,frameId:I,frameContext:E,inputNodeMap:s,cdpClient:d,logger:u,callId:m,filterByViewport:l,filterZeroOpacity:a,viewportDetails:c,useMPaths:p});P.length&&(b.children=b.children.concat(P))}if(b.role==="StaticText"&&(b.children=[]),b.children.length===1&&b.children[0].role==="StaticText"){let O=b.name,U=b.children[0]?.name;(O===U||!U)&&(b.children=[])}let z=[];for(let O=b.children.length-1;O>=0;O--){let U=b.children[O];if(U.role!=="StaticText"){z.push(U);continue}if(O===0||b.children[O-1].role!=="StaticText"){z.push(U);continue}b.children[O-1].name+=U.name}if(b.children=z.reverse(),b.role==="generic"&&b.children.length===1){let O=b.children[0];if(b.name&&!ml.includes(O.role)&&b.name===O.name)return S&&(S.momenticIgnored=!0),b.children}if(!b.isInteresting()&&n.parentId)return S&&(S.momenticIgnored=!0),b.children;for(let O of b.children)O.parent=b;return yL(b),S&&p&&sp(S,i),[b]}function Hy({node:n,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:r,callId:o,domGraph:i,useMPaths:s,selectorToNodeMap:a,iconKnowledgeBase:l,startId:c=1}){n.id=c,c+=1,e[n.id]=n,n.dataMomenticId?t[n.dataMomenticId]=n:ml.includes(n.role);let p=n.backendNodeId,d=p!==void 0?i.backendIdToNode[p]:void 0;if(s&&p&&d&&d.mPathSelector&&(a[d.mPathSelector]=n),l&&d&&d.tagName?.toLowerCase()==="svg"){let u=dl(d,i),m=u?l[u.hash]:void 0,h=m?m.description:void 0;m&&(n.properties["data-momentic-description"]=h)}for(let u of n.children)c=Hy({node:u,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:r,callId:o,startId:c,useMPaths:s,domGraph:i,selectorToNodeMap:a,iconKnowledgeBase:l});return c}async function $y({rawA11yGraph:n,domGraph:e,startingFrameId:t,logger:r,cdpClient:o,filterByViewport:i,filterZeroOpacity:s,viewportDetails:a,useMPaths:l,frameContext:c,iconKnowledgeBase:p}){let d=t??"root",u=n[d]?.root;if(!u)throw new Error("A11y tree has no root");let m=nL(),h=b=>{let E=b.allNodes.filter(I=>!I.ignoredReasons?.find(L=>lL.includes(L.name))),C=new Map;return E.forEach(I=>{C.set(parseInt(I.nodeId),I)}),C},g={};Object.entries(n).forEach(([b,E])=>{g[b]=h(E)});let f=await jy({node:u,domGraph:e,parent:null,inputNodeMap:g,axGraph:n,frameId:d,frameContext:c,cdpClient:o,logger:r,callId:m,filterZeroOpacity:s,filterByViewport:i,viewportDetails:a,useMPaths:l});if(f.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(f)}`);if(f.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let S={},x={},v={};return Hy({node:f[0],a11yIdNodeMap:S,dataMomenticIdMap:x,selectorToNodeMap:v,domGraph:e,logger:r,callId:m,useMPaths:l,iconKnowledgeBase:p}),new cp(f[0],S,x,v)}function fL(n,e,t){if(n==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(i=>i.length<50&&!Un.bannedClassSubstrings.some(s=>i.includes(s))).slice(0,3).join(" ");let r=e.split(" "),o=[];for(let i of r)if(Wy(i)){o.push(i);continue}return o.length?o.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let r=parseInt(e);if(!isNaN(r))return r}catch{}return n==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function SL(n,e){if(!e)return;Object.entries(e.attributes).forEach(([i,s])=>{if(Un.relevantElementAttributes.includes(i)&&!iL.includes(i)&&!n[i]&&!i.startsWith("aria")){let a=fL(i,s,e);a!==null&&(n[i]=a)}});let t,r=[];if(e.computedStyles.position&&Uy.includes(e.computedStyles.position))t=e.computedStyles.position;else if(e.attributes.style){for(let i of Uy)if(e.attributes.style.includes(`position: ${i}`)){t=i;break}}t&&r.push(`position: ${t}`);let o;(e.computedStyles.opacity&&e.computedStyles.opacity==="0"||e.attributes.style&&e.attributes.style.includes("opacity: 0"))&&(o="opacity: 0"),o&&r.push(o),r.length>0&&(n.style=r.join("; "))}function yL(n){let e=n.properties.class;if(typeof e=="string"&&e.includes("cm-content")){n.children.forEach((i,s)=>{i.properties["cm-line-number"]=`${s+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){n.children.forEach((i,s)=>{i.properties["block-number"]=`${s+1}`}),n.children.length>0&&(n.children[n.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(n.tagName==="table"){let i=[],s=n.children.find(l=>l.tagName==="thead");if(s){let l=s.children.find(c=>c.tagName==="tr");if(l){let c=l.children.filter(p=>p.tagName==="th");c.forEach((p,d)=>{p.properties["col-index"]||(p.properties["col-index"]=d+1),i?.push(Me(p.name,100,!1))}),i?.length!==c.length&&(i=void 0)}}let a=0;for(let l of n.children)if(l.tagName==="tbody")for(let c=0;c<l.children.length;c++){let p=l.children[c];if(p.tagName!=="tr")continue;if(c===0&&!i?.length){let m=p.children.filter(h=>h.tagName==="th");if(m.length){if(i=m.map(h=>Me(h.name,100,!1)),i.length===m.length)continue;i=void 0}}a+=1,p.properties["row-index"]||(p.properties["row-index"]=a);let d=p.children.filter(m=>m.tagName==="td"||m.tagName==="th"),u=d.length===i?.length;d.forEach((m,h)=>{m.tagName!=="th"&&(m.properties["col-index"]||(m.properties["col-index"]=h+1),u&&(m.properties.col||(m.properties.col=i[h])))})}}}function bL(n){let e=n.properties.class,t=typeof e=="string"&&e.includes("cm-content");n.internalProperties.inCodeMirrorEditor=n.internalProperties?.inCodeMirrorEditor||t}function Wy(n){if(Un.bannedClassSubstrings.some(e=>n.includes(e)))return!1;if(Un.alwaysInterestingClassNames.includes(n))return!0;for(let e of Un.alwaysInterestingClassPrefixes)if(n.startsWith(e))return!0;return!1}var hl=class n{constructor(e,t,r,o,i){this.session=e;this.logger=t;this.contextGetter=r;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;static async init({logger:e,contextGetter:t,pageGetter:r,defaultTimeoutMs:o}){let i=t(),s=r(),a,l;for(let p=0;p<2;p++)try{a=await D(i.newCDPSession(s),{milliseconds:o*p,fallback:()=>{throw new R("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${s.url()})`)}});break}catch(d){await te(500),l=d}if(!a)throw l;let c=new n(a,e,t,r,o);try{await D(c.registerHandlers(a),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(p){throw c.cdpFullyDead=!0,new R("UserInfrastructureError",`Failed to initialize CDP client: ${p}`)}return c}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(t){this.logger.debug({err:t},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP inspector session crashed, Momentic will likely not function correctly")}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:t,timeout:r=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await this.cdpInitializingPromise;if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new R("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await D(this.session.send(e,t),{milliseconds:r,message:o??`Chrome command ${e} timed out after ${r}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(i){throw["Internal error","Target crashed"].some(s=>i.message.includes(s))&&!this.cdpInitializingPromise&&(this.logger.warn({err:i},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),i}}async createRawCDPSession(e=this.defaultTimeoutMs){let t=e,r=this.pageGetter(),o=await D(this.contextGetter().newCDPSession(r),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${r.url()})`),new R("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${r.url()})`)}});return this.logger.debug(`Created new CDP session for ${r.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let t=this.session;this.session=await this.createRawCDPSession(e),await this.registerHandlers(this.session),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await D(t.detach(),{milliseconds:1e3})}catch(r){this.logger.warn({err:r},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(t){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${t}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,t){return this.session.on(e,t),this.session}off(e,t){return this.session.off(e,t),this.session}addListener(e,t){return this.session.addListener(e,t),this.session}removeListener(e,t){return this.session.removeListener(e,t),this.session}};import{mkdirSync as wL,rmSync as Gy,statSync as vL}from"fs";import*as up from"node:fs";import xL from"nodejs-file-downloader";import{tmpdir as TL}from"os";import pr,{basename as EL,dirname as CL}from"path";var mp="file://",pp=pr.join(TL(),"momentic","downloads"),dp=1e4,RL=50*1024*1024;async function Vy(n){let{uri:e}=n;return e.startsWith(mp)?IL(n):e.startsWith("http")?LL(n):PL(n)}function AL(n,e){let t=pr.join(pp,n,e.slice(mp.length)),r=pr.join(pp,n),o=t.startsWith(r);if(!up.existsSync(t)||!o)throw new R("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function IL({uri:n,orgId:e}){let t=AL(e,n);return{filePath:t,cleanup:()=>{Gy(CL(t),{recursive:!0,force:!0})}}}async function PL({uri:n}){let e=pr.resolve(n);if(!up.existsSync(e))throw new R("UserConfigurationError",`The referenced file (${n}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function LL({uri:n,logger:e,orgId:t}){let r=new URL(n);r.search&&(r.search="");let o=EL(r.href),i=gp(o),s=pr.extname(i);if(Th.includes(s))throw new Error(`Downloading files with extension ${s} is not allowed.`);let a=hp(t),l=new xL({url:n,fileName:i,directory:a,maxAttempts:2,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:dp}),{downloadStatus:c,filePath:p}=await D(l.download(),{milliseconds:dp,message:`Download timed out after ${dp}ms`});if(c!=="COMPLETE")throw new Error(`Download ended in non-success status: ${c}`);if(!p)throw new Error("File path of successfully downloaded file was empty");let u=vL(p).size;if(u>RL)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:u,filePath:p,fileName:i},"Downloaded file to disk");let m;return{filePath:p,cleanup:()=>{clearTimeout(m),m=setTimeout(()=>Gy(a,{recursive:!0,force:!0}),10*60*1e3)}}}function qy(n,e){return`${mp}${n}/${e}`}function hp(n){let e=Math.random().toString(36).substring(4),t=pr.join(pp,n,e);return wL(t,{recursive:!0}),t}function gp(n){let e=pr.extname(n),t=pr.basename(n,e);return n=(t.length>100?t.slice(t.length-100):t)+e,n=n.trim().replaceAll(" ","_"),n}async function gn(n,e){try{return await n.evaluate(r=>window.serializeElementOnlyWithText?.(r,{truncateToLength:500}),void 0,{timeout:1e3})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}var gl=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let r=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let s=this.userActions.get(o)?.filter(a=>r-a<=this.windowMs)??[];s.length>0?this.userActions.set(o,s):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let r=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(r),!1)}};async function Ky(n,e){let t=n.evaluate(async()=>{let i=window,s={};try{let a=await indexedDB.databases();for(let l of a){if(!l.name)continue;let c=await i.exportIdbToObject?.(l.name,l.version);c&&(s[l.name]=c)}return[s,void 0]}catch(a){return[void 0,a.message]}}),[r,o]=await D(t,{milliseconds:3e3});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),r}async function Yy(n,e,t){if(e){t.debug("Importing indexedDB data");try{let r=n.evaluate(async o=>{let i=window;for(let[s,a]of Object.entries(o))await i.importObjectToIdb?.(s,a)},e);await D(r,{milliseconds:3e3})}catch(r){t.warn({err:r},"Failed to import indexedDB data")}}}async function Jy(n,e){try{let t=n.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(r=>{r.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await D(t,{milliseconds:3e3})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function Xy(n,e,t,r,o){try{await OL(n,e,t,r)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function OL(n,e,t,r){let o=r.text();o.length>vs&&(o=o.slice(0,vs)+"...(TRUNCATED)");let i=[];for(let s of r.args())try{let a=await s.jsonValue(),l=JSON.stringify(a);l.length>vs?i.push(l.slice(0,vs)+"...(TRUNCATED)"):(typeof a!="object"||Object.keys(a).length>0)&&i.push(a)}catch{}fp(n,t,e,{url:n.url(),location:r.location(),type:r.type(),text:r.text(),args:i})}function fp(n,e,t,r){let o=Date.now(),i=e.logsPerPage;if(i.length<=t||i[t]===void 0){i[t]=[];for(let s=0;s<t;s++)i[s]===void 0&&(i[s]=[])}i[t].length>op&&(i[t]=i[t].slice(Math.floor(op/2)),i[t]?.push({url:n.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:t})),i[t].push({...r,tabIndex:t,timestamp:o})}async function Bn({fn:n,codePath:e,logObject:t,signal:r,logger:o}){r?.throwIfAborted();let i=Date.now(),s=await Ki({promiseGenerator:n,signal:r,codePath:e,logger:o}),a=Date.now();return t[e]=a-i,s}import{randomUUID as kL}from"crypto";var NL="[redacted due to size]",_L=1e4;async function nb(n,e,t){let r=new Date().toISOString();e.harPages||(e.harPages={}),e.harPages[n]={id:n,startedDateTime:r,title:void 0,pageTimings:{}}}async function rb(n,e,t,r){try{await ML(n,e,t)}catch(o){o.message.includes("browser has been closed")||r.warn({err:o,pageId:n},"Error handling new network request, skipping...")}}function Kr(n){return n<0?0:n}function Zy(n){return{timings:{blocked:Kr(n.domainLookupStart),dns:Kr(n.domainLookupEnd-n.domainLookupStart),connect:Kr(n.connectEnd-n.connectStart),send:Kr(n.responseStart-n.requestStart),wait:0,receive:Kr(n.responseEnd-n.responseStart),ssl:Kr(n.connectEnd-n.secureConnectionStart)},total:Kr(n.responseEnd)}}async function ML(n,e,t){let r=kL(),o=t.timing(),i=new URL(t.url()),s=[...i.searchParams.entries()].map(([h,g])=>({name:h,value:g})),a={...await tb(t),url:i.toString(),method:t.method(),queryString:s,postData:await DL(t)},l={pageref:n,_resourceType:t.resourceType(),startedDateTime:new Date(o.startTime).toISOString(),request:a,timings:Zy(o).timings};Qy(e,l,r);let c=await t.response();if(c){await c.finished();let h={};try{h=await UL(c)}catch{}let g={...await tb(c),status:c.status(),statusText:c.statusText(),content:h,redirectURL:c.headers().location};l.response=g}let p;try{p=await t.sizes(),l.request.bodySize=p.requestBodySize,l.request.headersSize=p.requestHeadersSize}catch{}l.response&&p&&(l.response.bodySize=p.responseBodySize,l.response.headersSize=p.responseHeadersSize,l.response.content.size=p.responseBodySize);let d=t.timing(),{timings:u,total:m}=Zy(d);l.time=m,l.timings=u,Qy(e,l,r)}function Qy(n,e,t){n.harEntries||(n.harEntries={}),n.harEntries[t]=e}function eb(n){try{return new Date(n).toISOString()}catch{return}}function FL(n){let e={name:"",value:""},t=!0;for(let r of n.split(/; */)){let o=r.indexOf("="),i=o!==-1?r.substring(0,o).trim():r.trim(),s=o!==-1?r.substring(o+1,r.length).trim():"";if(t){t=!1,e.name=An(i),e.value=An(s);continue}i==="Domain"&&(e.domain=An(s)),i==="Expires"&&(e.expires=eb(s)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=eb(Date.now()+ +s*1e3)),i==="Path"&&(e.path=An(s)),i==="Secure"&&(e.secure=!0)}return e}async function tb(n){let e=await n.headersArray(),t=[];for(let r of e.filter(o=>o.name.toLowerCase()==="cookie"))t.push(...r.value.split(";").map(FL));return{headers:e.map(r=>({name:An(r.name),value:An(r.value)})),cookies:t}}async function DL(n){let e=n.postData();if(!e)return;let t=await n.headerValue("content-type"),r={mimeType:t??"application/octet-stream",text:An(e),params:[]};if(t==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[i,s]of o.entries())r.params.push({name:An(i),value:s?An(s):void 0})}return r}async function UL(n){return{mimeType:await n.headerValue("content-type")??void 0,text:An(await n.text()),encoding:await n.headerValue("content-encoding")??void 0}}function An(n){return n.length>_L?NL:n}function ob(){return async n=>{let{fragment:e,code:t,context:r}=n,{env:o}=r||{},i=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new i("env",e?`return ${t}`:t)(o))}}}async function Ve({root:n,fn:e,arg:t,timeout:r,waitForPageLoad:o,codePath:i}){return await o(),await D(n.evaluate(e,t),{milliseconds:r,message:`Timed out executing code path ${i} after ${r}ms`})}function Sp(){return window.lastCursorPos}import{errors as BL}from"playwright-core";async function Yr({func:n,action:e,logger:t,callbacks:r,retryTimeoutMs:o,targetingResult:i}){let s=Date.now(),a;for(;Date.now()-s<o;)try{return await n(i)}catch(l){let c=l;if(Hi(c)){t.warn("Attempting to recover from removed data-momentic-ids by re-adding ids to DOM");let[p]=await Promise.all([n(i),r.getBrowserState({skipWaitForPageLoad:!0,skipWait:!0})]);return p}else if(c instanceof BL.TimeoutError)t.warn({err:c,rootUrl:(await r.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),a=await zL(c,i.locator,r,t);else throw c}throw a instanceof R?a:new R("ActionFailureError",`Failed to interact with targeted element. Error: ${a.message}`,{errOptions:{cause:a}})}async function zL(n,e,t,r){return n.message.includes("attempt #")?jL(n,e,t,r):HL(n)}async function jL(n,e,t,r){let o=n.message.split(/- retrying \w+ action, attempt #\d+/).filter(l=>l.length>0);if(!o.length)return r.warn({err:n},"Failed to parse Playwright error message for translation, returning raw message"),n;let i=o.length>2?o[o.length-2]:o[0];i=i.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
|
|
3598
|
-
`,";").replace(/\s+/g," ");let
|
|
3599
|
-
${l}`,{errOptions:{cause:n}})}if(i.includes("element is not visible")){let l="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let c=await e.boundingBox({timeout:1e3});c?c.height===0?l="The element you attempted to interact with has zero height.":c.width===0&&(l="The element you attempted to interact with has zero width."):l="The element you attempted to interact with has no bounding box."}catch{}return new R("ActionFailureError",`${l} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${s}`,{errOptions:{cause:n}})}return i.includes("element is outside of the viewport")?new R("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${s}`):n}function HL(n){let e=n.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new R("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:n}});return n}async function ib(n){try{return await $L(n)}catch(e){n.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function $L({locator:n,logger:e}){let[t,r]=await n.evaluate(l=>[l.id,l.tagName.toLowerCase()],{timeout:1e3}),o=await gn(n,e),i=await n.boundingBox({timeout:1e3});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5)return;if(r==="input"&&t)try{let l=n.page().locator(`label[for=${JSON.stringify(t)}]`);return await l.waitFor({state:"visible",timeout:1e3}),{locator:l,relativePoint:void 0}}catch{}let s=await n.evaluate(l=>{let c=window;if(!c.CssSelectorGenerator)return{type:"error",error:"[MOMENTIC] Missing CSS selector libraries"};let p=l.parentElement;if(!p)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.CssSelectorGenerator.getCssSelector(p,{}),u=l.getBoundingClientRect(),m=p.getBoundingClientRect();if(m.width===0||m.height===0)return{type:"error",error:"Parent element has no width or height"};let h={x:Math.min(Math.max(1,u.left-m.left),m.width-1),y:Math.min(Math.max(1,u.top-m.top),m.height-1)};return{type:"result",selector:d,relativePoint:h,serializedForm:p.outerHTML.slice(0,500)}},{timeout:1e3});if(s.type==="error")throw new Error(s.error);let a=n.page().locator(s.selector);return await a.waitFor({state:"visible",timeout:1e3}),e.info({parentElementResult:s,originalElementDisplayString:o},`Redirected click to parent element with selector: ${s.selector}`),{locator:a,relativePoint:s.relativePoint}}var ab=["date","datetime-local","month","time","week"],sb={date:/^\d{4}-\d{2}-\d{2}$/,"datetime-local":/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,month:/^\d{4}-\d{2}$/,time:/^\d{2}:\d{2}$/,week:/^\d{4}-W\d{2}$/};async function lb(n){try{await D(WL(n),{milliseconds:3e3})}catch(e){n.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function WL({root:n,text:e,options:t,logger:r,callbacks:o}){let i=(await Ve({root:n,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transformNativeDateTimeInputFillHelper"})).toLowerCase();if(!sb[i])return;sb[i].test(e)&&r.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),t.clearContent=!1,r.debug("Transforming datetime input to use sequential key presses")}async function fl({locator:n,callbacks:e,logger:t,timeoutMs:r=1e3}){try{await yp(e,r);let o=n.evaluate(i=>{let s=window;s.momenticIsEligible=d=>{let m=window.getComputedStyle(d,null).getPropertyValue("display");if(m==="none"||m==="contents")return!1;let h=d.getBoundingClientRect();return!(!h.height||!h.width)},s.removeHighlightTimers=s.removeHighlightTimers||[],s.removeHighlightFunctions=s.removeHighlightFunctions||{};let a=0;for(;!s.momenticIsEligible(i)&&a<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,a++}let l=i.style.getPropertyValue("outline"),c=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let p=`momentic${Math.floor(Math.random()*1e7)}`;s[p]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",l,c),i.getAttribute("style")||i.removeAttribute("style")},s.removeHighlightTimers.push(setTimeout(()=>{s[p](),s.removeHighlightFunctions?.[p]&&delete s.removeHighlightFunctions[p]},5e3)),s.removeHighlightFunctions[p]=s[p]},void 0,{timeout:r});return await D(o,{milliseconds:r}),!0}catch(o){return t.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function yp(n,e=1e3){let t=await n.state.getRoot();await Ve({root:t,fn:()=>{let o=window,i=o.removeHighlightTimers||[];for(;i.length;){let s=i.pop();clearTimeout(s)}Object.values(o.removeHighlightFunctions??{}).forEach(s=>{s()})},timeout:e,arg:void 0,waitForPageLoad:n.waitForPageLoad,codePath:"removeAllHighlights"})}async function wp(n){let e=n.flagStore.isBooleanFlagEnabled("visual_actions");return Yr({action:"clicking element",targetingResult:n.targetingResult,logger:n.logger,retryTimeoutMs:n.retryTimeoutMs,callbacks:n.browserCallbacks,func:async t=>bp({...n,targetingResult:t,useVisualClick:e})})}async function KL(n,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw n;try{return await YL(n,e)}catch(r){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:r,originalError:n},"Error handling click error, rethrowing original error"),n):r}}async function YL(n,e){let{logger:t,redirectionAttempts:r=0,browserCallbacks:o,actionSource:i}=e,s=e.targetingResult.locator,a=o.state.getDomGraph();if(n.message.includes("label")&&n.message.includes("for=")&&n.message.includes("intercepts pointer events")){let l=await s.getAttribute("id",{timeout:1e3});if(!l)throw n;let c=s.page().locator(`[for=${JSON.stringify(l)}]`);return await c.waitFor({state:"visible",timeout:1e3}),t.warn({err:n},"Attempting locator redirection due to input being covered by label"),bp({...e,targetingResult:{locator:c},redirectionAttempts:r+1})}else if(i==="click"&&a&&n.message.includes("intercepts pointer events")){t.warn({err:n},"Attempting locator redirection due to covering error");let l=await eO(s,a,t);if(l)return bp({...e,targetingResult:{locator:l},redirectionAttempts:r+1});throw t.error({err:n},"No updated locator could be found to fix covering error, rethrowing"),n}else throw t.error({err:n},"Click error does not match any known recoverable patterns, rethrowing"),n}async function JL(n){let{browserCallbacks:e,logger:t,targetingResult:r,position:o,options:i}=n,s=await e.state.getRoot(),a=s&&s!==r.locator.page()&&"frameElement"in s?await s.frameElement():null,l;try{l=a?await Br({promiseGenerator:async()=>a.boundingBox(),timeoutMs:3e3,logger:t}):null}catch(m){throw new R("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${m.message}`)}finally{await a?.dispose()}let c=Date.now(),{clickX:p,clickY:d,reason:u}=await QL({frameCoordinates:l,logger:t,targetingResult:r,position:o,options:i});t.debug({frameCoordinates:l,position:o,targetingResultHints:r.hints,options:i,clickLocation:{clickX:p,clickY:d,reason:u},duration:Date.now()-c},"Visual click")}async function XL(n){let{actionSource:e,targetingResult:t,options:r,logger:o}=n,i=n.targetingResult.locator,s=r?.relativePosition??n.position;if(e==="click"&&!s){let l=await ib({locator:i,logger:o});l&&(i=l.locator,s=l.relativePoint??s)}let a=r?.force||t.hints?.force||!1;try{r?.doubleClick?await i.dblclick({button:r.rightClick?"right":"left",timeout:3e3,position:s,delay:r?.delayMs??25,force:a}):await i.click({button:r?.rightClick?"right":"left",timeout:3e3,position:s,delay:r?.delayMs??25,force:a})}catch(l){let c=l;if(nO(c))o.warn({err:c},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:c},"Error clicking on locator, attempting to recover..."),KL(c,{...n,targetingResult:{...i,locator:i}})}}async function bp(n){let{options:e,logger:t,browserCallbacks:r,controllerCallbacks:o,useVisualClick:i,targetingResult:s}=n,a=(await r.state.getOpenPages()).map(d=>d.url),l=r.state.url(),c=null;try{c=await s.locator.getAttribute("target",{timeout:1e3})}catch(d){t.warn({err:d},"Failed to get attributes of element about to be clicked, continuing...")}let p;e?.waitForDownload&&(p=(async()=>{let d=e.downloadTimeoutMs??3e4;try{return await s.locator.page().waitForEvent("download",{timeout:d})}catch(u){return u instanceof qL.TimeoutError?new R("ActionFailureError",`Download did not complete in ${d}ms`):new R("ActionFailureError",`Download failed: ${u.message}`)}})());try{await fl({locator:s.locator,callbacks:r,logger:t,timeoutMs:1e3})}catch(d){t.warn({err:d},"Error highlighting locator in click, continuing...")}if(i?await JL(n):await XL(n),c==="_blank"){t.debug("Waiting for new page promise due to _blank target");let d=Date.now();for(;(await r.state.getOpenPages()).length<=a.length&&Date.now()-d<2e3;)await te(500);await r.waitForPageLoad()}if(e?.waitForUrl&&await r.waitForUrl({beforeUrl:l,beforePages:a,matcher:{type:"GLOB",glob:e.waitForUrl}}),e?.waitForDownload)if(p){if(!o?.createIsolatedFolder)throw new R("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let d=await D(p,{milliseconds:e.downloadTimeoutMs??3e4});if(d instanceof Error)throw d;return{downloadedFile:await tO(d,o.createIsolatedFolder,t)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function ZL(n,e){if(e.hints?.clickableXY){let i=(n?.x??0)+e.hints.clickableXY.x,s=(n?.y??0)+e.hints.clickableXY.y;return[{x:i,y:s},"targeting hint"]}let t=await e.locator.boundingBox({timeout:1e3});if(!t)throw new R("ActionFailureError","Element does not have a bounding box");let r=t.x+t.width/2,o=t.y+t.height/2;return[{x:r,y:o},"halfway point of the bounding box"]}async function QL({frameCoordinates:n,logger:e,options:t,targetingResult:r,position:o}){let i,s,a;if(o){let d=await r.locator.boundingBox({timeout:3e3});i=(n?.x??0)+(d?.x??0)+o.x,s=(n?.y??0)+(d?.y??0)+o.y,a="predefined position"}else{let[d,u]=await ZL(n,r);i=d.x,s=d.y,a=u}let l=r.locator.page(),c=t?.rightClick?"right":"left",p=t?.delayMs??25;return t?.doubleClick?await l.mouse.dblclick(i,s,{button:c,delay:p}):await l.mouse.click(i,s,{button:c,delay:p}),{clickX:i,clickY:s,reason:a}}async function eO(n,e,t){let r=await n.evaluate(a=>a.getAttribute("data-momentic-id"));if(!r)return;let o=ul(r,e,t);if(!o.length){t.error("No candidates found for parent-based locator redirection");return}let i=parseInt(o[0].attributes?.[wt]??"");if(isNaN(i))return;n=n.page().locator(`[data-momentic-id="${i}"]`);let s=await gn(n,t);return t.warn({candidateMomenticId:i,serializedHtml:s},"Trying new locator based on parent-direction after covering error"),n}async function tO(n,e,t){t.info("Download detected, saving file to disk");let r=await n.path(),o=gp(n.suggestedFilename()),i=e();await n.saveAs(VL(i,o)),db(r,{force:!0}),setTimeout(()=>{db(i,{recursive:!0,force:!0})},5*60*1e3);let s=qy(GL(i),o);return t.debug({uri:s,downloadFolder:i},"Saved download to isolated folder"),s}function nO(n){return n.message.includes("locator.click: Timeout")&&n.message.includes("click action done")}import{platform as rO}from"os";var oO={goToNextWord:{win32:"Control+ArrowRight",darwin:"Alt+ArrowRight",linux:"Control+ArrowRight"},goToPreviousWord:{win32:"Control+ArrowLeft",darwin:"Alt+ArrowLeft",linux:"Control+ArrowLeft"},selectNextWord:{win32:"Control+Shift+ArrowRight",darwin:"Alt+Shift+ArrowRight",linux:"Control+Shift+ArrowRight"},selectPreviousWord:{win32:"Control+Shift+ArrowLeft",darwin:"Alt+Shift+ArrowLeft",linux:"Control+Shift+ArrowLeft"},selectToStartOfLine:{win32:"Shift+Home",darwin:"Meta+Shift+LeftArrow",linux:"Shift+Home"},selectToEndOfLine:{win32:"Shift+End",darwin:"Meta+Shift+RightArrow",linux:"Shift+End"},deleteNextWord:{win32:"Control+Delete",darwin:"Alt+Fn+Delete",linux:"Control+Delete"},deletePreviousWord:{win32:"Control+Backspace",darwin:"Alt+Delete",linux:"Control+Backspace"}};function iO(){let n=rO();return n==="win32"?"win32":n==="darwin"?"darwin":"linux"}function pb(n){return JSON.stringify(n.split("+").sort())}function ub(n){let e=iO(),t=pb(n);for(let r of Object.values(oO))if(Object.values(r).some(o=>pb(o)===t))return r[e];return process.platform==="darwin"?n=n.replaceAll("Control","Meta"):n=n.replaceAll("Meta","Control"),n}async function vp({frame:n,page:e,deltaX:t,directionX:r,deltaY:o,directionY:i,signal:s,callbacks:a}){if(!t&&!o)return;let l=r==="left"?-1:1,c=i==="up"?-1:1;if(n)await Ve({root:n,fn:([p,d,u,m])=>window.scrollTo(window.scrollX+(p??window.innerWidth)*u,window.scrollY+(d??window.innerHeight)*m),arg:[t,o,l,c],waitForPageLoad:a.waitForPageLoad,timeout:2e3,codePath:"scrollFrame"});else{let p=e.viewportSize()||Ut,d=await Ve({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:a.waitForPageLoad,timeout:2e3,codePath:"scrollPageGetHeight"}),[u,m,h]=await Ve({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let S=f.getBoundingClientRect();return[f.scrollTop,S.x,S.y]},arg:void 0,waitForPageLoad:a.waitForPageLoad,timeout:2e3,codePath:"scrollPage"});await e.mouse.wheel((t??p.width)*l,(o??p.height)*c);let g=Date.now();for(;Date.now()-g<2e3;){s?.throwIfAborted();let f=await D(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[S,x,v]=await D(e.evaluate(()=>{let b=document.activeElement;if(!b)return[void 0,void 0,void 0];let E=b.getBoundingClientRect();return[b.scrollTop,E.x,E.y]}),{milliseconds:1e3});if(f===d&&S===u&&x===m&&v===h)break;d=f,u=S,m=x,h=v,await te(500)}}}async function Qo(n,e){let t,r;for(let o=0;o<4;o++)try{return t=n.pages(),await Promise.all(t.map(async i=>{let s="";try{s=e?.getTitles?await i.title():""}catch{s="Unknown page"}return{title:s,url:i.url()}}))}catch(i){r=i,await te(500)}throw new Error(`Failed to get tab titles after all retries: ${r?.message}`)}var ei="<empty>";function sO(n){return n.includes("doubleclick.net")||n.includes("googletagmanager.com")||n.includes("googlesyndication.com")||n.includes("s.amazon-adsystem.com")||n.includes("smartadserver.com")||n.includes("omnitagjs.com")||n.includes("x.adroll.com")}function hb(n){let e=n.adFrameStatus?.adFrameType;return e==="child"||e==="root"||sO(n.url)}async function aO(n,e){let t=await n.send({timeout:3e3,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await n.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],s=(await n.send({timeout:3e3,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return s.nodeId=o,s}async function ti({cdpClient:n,page:e,logger:t}){let r={type:"root",childFrames:[],page:e},o=[],[i]=await Promise.all([n.send({timeout:3e3,method:"Page.getFrameTree",params:{}}),n.send({timeout:3e3,method:"DOM.getDocument",params:{}})]),l=(i.frameTree.childFrames??[]).map(async(p,d)=>{if(hb(p.frame))return null;try{return await gb({cdpClient:n,rawFrameTree:p,indices:[d],parent:r,warnings:o})}catch(u){return o.push(`Failed to get child frame: ${u}`),null}}),c=await Promise.all(l);return r.childFrames=c.filter(p=>p!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),r}async function gb({cdpClient:n,rawFrameTree:e,indices:t,parent:r,warnings:o}){let i=e.frame.id,s=await aO(n,i),a=s.attributes??[],l=null,c=[];for(let m of["src","name","id","title","srcdoc","sandbox"]){let h=dr(a,m);h&&(c.push(`${m}=${JSON.stringify(h)}`),m==="src"&&(l=h))}let p={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:i,locationData:{indices:t,attributeSelectors:c},src:l,childFrames:[],parent:r,domNode:s},u=(e.childFrames??[]).map(async(m,h)=>{if(hb(m.frame))return null;try{return await gb({cdpClient:n,rawFrameTree:m,indices:[...t,h],parent:p,warnings:o})}catch(g){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${g}`),null}});return p.childFrames=(await Promise.all(u)).filter(m=>m!==null),p}async function lO(n){try{return await n.owner().count()===1}catch{return!1}}async function cO(n){try{return await n.count()===1}catch{return!1}}async function In(n,e){let t=[],r=n;for(;r.parent.type==="frame";)t.push(r.parent),r=r.parent;t.reverse();let o=e,i=[];for(let c of t){let p=!1;for(let d of[...c.locationData.attributeSelectors,ei]){let u=o.frameLocator(d===ei?"iframe":`iframe[${d}]`);if(await lO(u)){p=!0,o=u,i.push(d);break}}if(!p)throw new R("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${c.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let s;for(let c of[...n.locationData.attributeSelectors,ei]){let p=o.locator(c===ei?"iframe":`iframe[${c}]`);if(await cO(p)){s=p,i.push(c);break}}if(!s)throw new R("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${n.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let a=await s.evaluateHandle(c=>c,{timeout:1e3}),l=await a.asElement().contentFrame();if(!l)throw new R("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${n.url}'`);return await a.dispose(),{frame:l,mPathSelectorTokens:i}}function mb(n,e){let t=[...n],r=[];for(;t.length;){let o=t.shift();e(o)&&r.push(o),t.push(...o.childFrames)}return r}async function fb({page:n,frameTree:e,cache:t}){let r,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let a=o;for(let p=0;p<t.mPathSelectorTokens.length-1;p++){let d=t.mPathSelectorTokens[p];d===ei?a=a.length===1?a[0].childFrames:[]:a=a.filter(u=>u.locationData.attributeSelectors.includes(d)).map(u=>u.childFrames).flat()}let l=[],c=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(c===ei?l=a:l=a.filter(p=>p.locationData.attributeSelectors.includes(c)),l.length===1)return r=l[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await In(r,n)).frame,handle:r,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${l.length} frames with mpath ${t.mPathSelectorTokens.join(" > ")}`)}if(t.frameSrcRegex){let a=new RegExp(t.frameSrcRegex),l=mb(o,c=>!!c.src&&a.test(c.src));if(l.length===1)return r=l[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await In(r,n)).frame,handle:r,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${l.length} frames with src regex ${t.frameSrcRegex}`),t.frameSrcRegex=void 0}if(t.frameUrlRegex){let a=new RegExp(t.frameUrlRegex),l=mb(o,c=>!!c.url&&a.test(c.url));if(l.length===1)return r=l[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await In(r,n)).frame,handle:r,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${l.length} frames with url regex ${t.frameUrlRegex}`),t.frameUrlRegex=void 0}let s=o;for(let a=0;a<t.indices.length-1;a++)s=s[t.indices[a]]?.childFrames??[];if(r=s[t.indices[t.indices.length-1]],r)return i.push(`Found unique frame with indices ${t.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await In(r,n)).frame,handle:r,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${s.length} frames with indices ${t.indices}`),new Yn("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function Sl(n){return n.type==="auto"?JSON.stringify({type:"auto",frameId:n.handle.frameId}):JSON.stringify(n)}function xp(n){for(;n.parent.type==="frame";)n=n.parent;return n.parent}function Sb(n){let e=xp(n),t=n.src??"",r=n.url??"",o=[],i=[],s=[...e.childFrames];for(;s.length;){let a=s.shift();a.src&&o.push(a.src),a.url&&i.push(a.url),s.push(...a.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:r}}function yb(n){return n.type==="auto"?{type:"auto",frameId:n.handle.frameId,url:n.handle.url,src:n.handle.src??"",mPathSelectorTokens:n.mPathSelectorTokens.join(" > ")}:{type:"url",url:n.url}}async function bb({frame:n,logger:e,signal:t}){let r;try{r=await n.frameElement(),await dO({frameElementHandle:r,logger:e,signal:t})}catch(o){e.warn({err:o},"Failed to scroll iframe into view, continuing...")}finally{await r?.dispose()}}async function dO({frameElementHandle:n,logger:e,signal:t}){let r=await n.boundingBox();if(!r){e.warn("Active frame element has null bounding box, skipping scroll");return}await Br({promiseGenerator:async()=>n.evaluate(async(i,{x:s,y:a})=>{window.scrollTo(window.scrollX+s,window.scrollY+a);let l=Date.now(),c,p,d;for(;Date.now()-l<1500;){let u=document.activeElement,m,h,g;if(!u)m=void 0,h=void 0,g=void 0;else{let f=u.getBoundingClientRect();m=u.scrollTop,h=f.x,g=f.y}if(c!==void 0&&p!==void 0&&d!==void 0&&m===c&&h===p&&g===d)break;c=m,p=h,d=g,await new Promise(f=>setTimeout(f,250))}},r),timeoutMs:2e3,codePath:"scrollIframeIntoView",signal:t}),e.info({bb:r},"Successfully scrolled iframe into view")}async function wb({event:n,transformer:e,enricher:t,frame:r,lastScreenshotForRecording:o,logger:i}){let{warnings:s,error:a,properties:l}=n.target;if(a){i.error({error:a,warnings:s},"Error while capturing passive click");return}if(s.length&&i.warn({warnings:s},"Warnings while capturing passive click"),!l)return;let c=r.parentFrame()?r.url():void 0,d=r.page().frames().map(h=>h.url());i.debug({frameUrl:c,...n},"Passive click event captured on element");let u,m;if(c)try{let h=await r.frameElement();u=await D(h?.boundingBox(),{milliseconds:1e3})??void 0;let g=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:c});if(g.urlRegex)m={type:"url",url:`/${g.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(g)}`)}catch(h){i.warn({err:h},"Failed to construct iframe details for recorded action, using hardcoded URL only"),m={type:"url",url:c}}(async()=>{try{await e.recordElementAction({...n,screenshotBase64:o,frameConfig:m,frameBoundingBox:u})}catch(h){i.error({err:h},"Failed to transform passive click action")}})()}import{randomUUID as Pn}from"crypto";import pO from"js-beautify";var uO=["Shift","CapsLock","Dead","Meta","AudioVolumeUp","AudioVolumeDown"];var yl=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:t,generator:r,testId:o,orgId:i,logger:s}){this.signal=e,this.logger=s,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(a,l)=>{this.recordedSteps.set(l,{step:a}),t.onStepRecorded(a,l)},onActionReceived:(a,l)=>{this.recordedSteps.set(l,{step:a}),t.onActionReceived?.(a,l)}},this.generator=r}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:Pn(),type:"PRESET_ACTION",command:On(e)}}),this.nextStepOffset++,t}async recordElementAction(e){let{type:t,target:r,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,s,a=r.properties.attributes.nodeOnlySerializedHtml.trim(),l=a,c;switch(e.frameConfig?e.frameBoundingBox?c={x:e.frameBoundingBox.x+r.properties.boundingBox.x,y:e.frameBoundingBox.y+r.properties.boundingBox.y,width:r.properties.boundingBox.width,height:r.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):c=r.properties.boundingBox,t){case"CLICK":{i="CLICK";let g=On(i);s={id:Pn(),type:"PRESET_ACTION",command:{...g,target:{type:"description",elementDescriptor:l},iframeUrl:o?.url,cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:c}}}};break}case"SELECT":{i="SELECT_OPTION";let g=On(i);s={id:Pn(),type:"PRESET_ACTION",command:{...g,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:l},cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:c}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let g=On(i);s={id:Pn(),type:"PRESET_ACTION",command:{...g,target:{type:"description",elementDescriptor:l},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:c}}}};break}default:throw new Error(`Unknown action type: ${t}`)}let p;e.offset===void 0?(p=this.nextStepOffset,this.nextStepOffset++):p=e.offset,this.callbacks.onActionReceived?.(s,p);let d=e.target.browserState;try{d=pO.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=Ay(d,"data-momentic-interacted",4e4)}catch{}let u;try{u=(await this.generator.getReverseMappedDescription({target:d,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:r.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...We(this.logger)}})).phrase}catch(g){this.logger.error({err:g},"Error generating reverse mapping description"),u=a}let m=this.recordedSteps.get(p)?.step??s,h=m?.command;h&&"target"in h&&h.target?(h.target={type:"description",elementDescriptor:u},this.callbacks.onStepRecorded({...m,command:h},p)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:r}=e;if(uO.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=On("TYPE");i={id:Pn(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=On("PRESS");i={id:Pn(),type:"PRESET_ACTION",command:{...d,value:t}}}let s,a=this.nextStepOffset-1,l=this.recordedSteps.get(a),c=l?.step,p=c?.command;if(r){if(p?.type===i.command.type){let d=p.value,u=i.command.value;i={id:Pn(),type:"PRESET_ACTION",command:{...p,value:i.command.type==="PRESS"?`${d}+${u}`:`${d}${u}`}},s=a}else if(p?.type==="CLICK"&&i.command.type==="TYPE")c.command={...i.command,target:p.target,cache:p.cache},i=l.step,s=a;else if(p?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=p.value;i={id:Pn(),type:"PRESET_ACTION",command:{...p,value:d.slice(0,d.length-1)}},s=a}}s===void 0&&(s=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,s)}recordScroll(e){if(this.signal.aborted)return;let t=()=>{let{deltaY:i}=e;if(!i)return;let s=this.nextStepOffset-1,a=this.recordedSteps.get(s)?.step.command,l;a?.type==="SCROLL_DOWN"&&a.deltaY?(i+=a.deltaY,l=s):a?.type==="SCROLL_UP"&&a.deltaY?(i-=a.deltaY,l=s):(l=this.nextStepOffset,this.nextStepOffset++);let c=i>0?"SCROLL_DOWN":"SCROLL_UP",p=On(c);p.deltaY=Math.abs(i);let d={id:Pn(),type:"PRESET_ACTION",command:p};this.callbacks.onStepRecorded(d,l)},r=()=>{let{deltaX:i}=e;if(!i)return;let s=this.nextStepOffset-1,a=this.recordedSteps.get(s)?.step.command,l;a?.type==="SCROLL_RIGHT"&&a.deltaX?(i+=a.deltaX,l=s):a?.type==="SCROLL_LEFT"&&a.deltaX?(i-=a.deltaX,l=s):(l=this.nextStepOffset,this.nextStepOffset++);let c=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",p=On(c);p.deltaX=Math.abs(i);let d={id:Pn(),type:"PRESET_ACTION",command:p};this.callbacks.onStepRecorded(d,l)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(r(),e.deltaY>=20&&t()):(t(),e.deltaX>=20&&r())}};var wl=Pu(Db(),1);var vl=class{defaultTimeoutMs;filterZeroOpacity;logger;cdpClient;pageGetter;abortSignalGetter;flagStore;enricher;iconKnowledgeBase;activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeTrie=new wl.default("key",{splitOnRegEx:!1,splitOnGetRegEx:!1});lastA11yTreeRoot;lastDomGraph;constructor({defaultTimeoutMs:e,filterZeroOpacity:t,logger:r,cdpClient:o,pageGetter:i,flagStore:s,abortSignalGetter:a,enricher:l,iconKnowledgeBase:c}){this.defaultTimeoutMs=e,this.filterZeroOpacity=t,this.logger=r,this.cdpClient=o,this.pageGetter=i,this.flagStore=s,this.abortSignalGetter=a,this.enricher=l,this.iconKnowledgeBase=c}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeTrie(){return this.lastSelectorToNodeTrie}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeTrie=new wl.default("key",{splitOnRegEx:!1,splitOnGetRegEx:!1}),this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.flagStore.isBooleanFlagEnabled("auto_expand_iframes"))return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),r=xp(e),{frame:o,mPathSelectorTokens:i}=await In(e,t),s={indices:e.locationData.indices,mPathSelectorTokens:i};return this.constructIframeRegexAsync(e,s),{cache:s,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:i,frameTree:r,cache:s}}}async resolveAutoFrameCache(e){let t=this.pageGetter(),r=await ti({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await fb({page:t,frameTree:r,cache:e});return this.logger.debug({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:t=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(Sl(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let r;return this.frameConfig.type==="url"?r=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:t}):r={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:Sl(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await bb({frame:r.frame,logger:e,signal:t}),this.activeFrameCache=r,r}async executeFunctionInAllFrames(e,t){let r=this.pageGetter(),o=await ti({cdpClient:this.cdpClient,page:r,logger:this.logger}),i=[D(r.evaluate(e,t),{milliseconds:2e3})],s=Array.from(o.childFrames);for(;s.length>0;){let l=s.shift();s.push(...l.childFrames),i.push(In(l,r).then(({frame:c})=>D(c.evaluate(e,t),{milliseconds:2e3})).catch(c=>(this.logger.warn({err:c,frameUrl:l.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR")))}return(await Promise.all(i)).filter(l=>l!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),t=await ti({cdpClient:this.cdpClient,page:e,logger:this.logger}),r=Array.from(t.childFrames),o=[];for(;r.length>0;){let i=r.shift();r.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:t,logger:r}){return this.getDOMTree({devicePixelRatio:e??1,signal:t,logger:r??this.logger})}async getA11yTree(e){let t={},r=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),s,a,l=null;if(this.frameConfig?.type==="url"){if(s=await Bn({fn:()=>this.resolveActiveFrameConfig({logger:r,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:r})??void 0,!s)throw new R("ActionFailureError","Got null frame details despite active frame config");a=s.handle,l=a.frameId}else this.flagStore.isBooleanFlagEnabled("auto_expand_iframes")?(a=await Bn({fn:()=>ti({cdpClient:this.cdpClient,page:this.pageGetter(),logger:r}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:r}),l=null):(a={type:"root",page:i,childFrames:[]},l=null);await Bn({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:a.childFrames,frameFilter:s?.frame,logger:r}),codePath:"addIdsToElement",logObject:t,signal:o,logger:r});let c=await Bn({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:r}),codePath:"domFetch",logObject:t,signal:o,logger:r}),p=await Bn({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:l,childFrames:a.childFrames,logger:r,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:r}),{tree:d}=await Bn({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:p,domGraph:c,startingFrameId:l,frameContext:a,logger:r,iconKnowledgeBase:this.iconKnowledgeBase}),codePath:"a11yProcess",logObject:t,signal:o,logger:r});Object.values(t).some(m=>m>1e3)&&r.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=c;let u=new wl.default("key",{splitOnRegEx:!1,splitOnGetRegEx:!1});for(let[m,h]of Object.entries(d.selectorToNodeMap))u.add({key:m,value:h});return this.lastSelectorToNodeTrie=u,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:Nr,filterByViewport:!1}),Math.random()<.1){let r=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:r&&r.length>4e5?"REDACTED_DUE_TO_SIZE":r},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:t,node:r}){if(r.backendNodeId===void 0)throw new Error(`Node with a11y id ${r.id} has no backend node ID: ${r.getNodeOnlySerializedForm()}`);if(this.flagStore.isBooleanFlagEnabled("visual_actions")){let o=this.domGraph?.backendIdToNode[r.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${r.backendNodeId}`);let i=_y({node:o,domGraph:this.domGraph});return My(e,i)}else return this.getLocatorFromBackendId(t,r.backendNodeId)}async getLocatorFromBackendId(e,t){let r=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:t},timeout:2e3});if(!r||!r.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await Fy(this.cdpClient,r.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(r.object)},"Failed to get ID attribute"),i}return e.locator(`[${wt}="${o}"]`)}getNodeUsingMPathSelector(e){let t=this.selectorToNodeTrie.search(e),r=t.find(o=>o.key===e);if(r)return r.value;this.logger.warn({searchResult:t},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:t=this.abortSignalGetter(),logger:r=this.logger}){let o=Date.now(),i,s,a,l=0;for(;Date.now()-o<this.defaultTimeoutMs;)try{i=await ti({cdpClient:this.cdpClient,page:this.pageGetter(),logger:r}),s=await this.getMatchingFrameByUrlWithCdp(i,e),r.debug({frameId:s.handle.frameId,url:s.handle.url,src:s.handle.src,locationData:s.handle.locationData},`Found matching frame using ${s.matchType}`);break}catch(c){if(a=c,c instanceof R&&c.reason==="UserInfrastructureError")throw c;l%3===0&&this.logger.debug({attempt:l,err:c},"Failed to resolve active frame, retrying..."),await te(500,t)}finally{l++}if(s)return{source:"url",frame:s.frame,handle:s.handle,frameIdentifierStringified:Sl(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw a}async getMatchingFrameByUrlWithCdp(e,t){let r=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),s=[];for(;i.length>0;){let a=i.shift(),l=a.domNode;i.push(...a.childFrames);let c=dr(l.attributes??[],"src"),p=l.contentDocument?.documentURL;if(!c&&!p){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[c,p])if(d){if(r.startsWith("/")&&r.endsWith("/")){if(new RegExp(r.slice(1,-1)).test(d)){s.push({handle:a,matchType:"regex",...await In(a,o)});break}}else if(r.trim()===d.trim()){s.push({handle:a,matchType:"url",...await In(a,o)});break}}}if(s.length===1){let a=s[0];return this.flagStore.isBooleanFlagEnabled("auto_expand_iframes")||(a.handle.childFrames=[]),a}else throw s.length>1?new Error(`Found multiple frames with src matching '${r}'. Please use a more specific selector.`):new R("ActionFailureError",`Failed to find frame with src matching: ${r}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:r,startingFrameId:o,frameContext:i,logger:s,iconKnowledgeBase:a}){let l=await $y({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:r,logger:s,cdpClient:this.cdpClient,filterZeroOpacity:this.filterZeroOpacity,filterByViewport:e.filterByViewport,viewportDetails:void 0,iconKnowledgeBase:a,useMPaths:this.flagStore.isBooleanFlagEnabled("visual_actions")});if(!l||!l.root)throw new Error("Accessibility tree appears empty");return{tree:l}}async addMomenticIds({rootPage:e,childFrames:t,frameFilter:r,logger:o}){if(this.flagStore.isBooleanFlagEnabled("visual_actions"))return;let i=await this.addMomenticIdsHelper(r??e,1);if(!this.flagStore.isBooleanFlagEnabled("auto_expand_iframes")||r)return;let s=Array.from(t),a=[];for(;s.length>0;){let l=s.shift();s.push(...l.childFrames);let c=async()=>{try{let{frame:p}=await In(l,e);i=await this.addMomenticIdsHelper(p,i)}catch(p){o.warn({err:p},"Error adding momentic IDs to child frame, continuing...")}};a.push(c())}await Promise.all(a)}async addMomenticIdsHelper(e,t){if(this.flagStore.isBooleanFlagEnabled("visual_actions"))return t;let r=this.logger;return await Ve({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:2e3,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.defaultTimeoutMs})}catch(i){r.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"addMomenticIds"})??t}getPageDomain(e){try{let t=new URL(e);if(!t.hostname)return null;let r=t.hostname.split("."),o=r.length>2?r.slice(-2).join("."):t.hostname;return`${t.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({domNode:e,viewport:t}){let r=e.attributes??[];if(dr(r,"aria-hidden")==="true")return!1;let o=dr(r,"style");if(o?.includes("display: none")||o?.includes("visibility: hidden"))return!1;await this.cdpClient.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[i,s]=await Promise.all([this.cdpClient.send({timeout:3e3,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:3e3,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!i.model||!i.model.height||!i.model.width)return!1;let a=i.model.content;if(!a||a.length!==8)throw new Error(`Invalid quad data, expected 8 points but got ${a}`);let l={x:a[0],y:a[1]},c={x:a[4],y:a[5]};if(!(l.x<t.clientWidth&&l.y<t.clientHeight&&c.x>0&&c.y>0)||i.model.height<10||i.model.width<10)return!1;for(let d of s.computedStyle)if(d.name==="display"&&d.value==="none"||d.name==="visibility"&&d.value==="hidden"||d.name==="opacity"&&d.value==="0")return!1;return!0}async getRawA11yGraph({cdpClient:e,frameId:t,childFrames:r,logger:o=this.logger,signal:i=this.abortSignalGetter()}){let s={},a=[],[l,c]=await Promise.all([Bn({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.defaultTimeoutMs*2}),codePath:"a11y-tree-fetch-root",logObject:s,signal:i,logger:o}),e.send({timeout:3e3,method:"Page.getLayoutMetrics",params:{}})]);if(!l)throw new Error("The accessibility tree is empty for the root page or frame. Are you sure it is working properly?");let p=c.cssVisualViewport,d={};if(d[t??"root"]=l,!this.flagStore.isBooleanFlagEnabled("auto_expand_iframes"))return d;let u=Array.from(r),m=[];for(;u.length>0;){let h=u.shift(),g=h.domNode;try{if(!await this.decideChildFrameUnrollEligibility({domNode:g,viewport:p}))continue}catch(S){if(S.message.includes("Could not compute box model"))continue;a.push(`Got error when determining whether to filter frame ${h.frameId} with url ${h.url}, allowing it to be fetched: ${S}`)}u.push(...h.childFrames);let f=async()=>{try{let S=await Bn({fn:()=>this.getRawA11yTreeForFrame({frameId:h.frameId,timeoutMs:3e3}),codePath:`a11y-tree-fetch-child-${h.frameId}`,logObject:s,signal:i,logger:o});d[h.frameId]=S}catch(S){o.warn({err:S,url:h.url,src:h.src},`Error getting raw a11y tree for child frame ${h.frameId}, continuing...`)}};m.push(f())}return await Promise.all(m),Object.values(s).some(h=>h>500)&&this.logger.warn(s,"CDP a11y tree fetch took a long time"),a.length>0&&this.logger.warn({warnings:a},"Got warnings when fetching the raw a11y graph"),d}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t}){let r=await this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:2e3});if(!r.node.backendDOMNodeId)throw new Error("Root node has no backend DOM node ID");let o=r.node.backendDOMNodeId,i=await this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:o},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`});if(!i.nodes||i.nodes.length<=1)throw new Error("Document is entirely empty");return{root:i.nodes[0],allNodes:i.nodes}}async getDOMTree({devicePixelRatio:e,signal:t,logger:r}){let o,i=0;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:pl},timeout:3e3}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await te(500,t),r.debug({err:s},"Error fetching DOM tree"),i++}if(!o||!o.documents.length)throw new R("InternalWebAgentError","Error fetching DOM tree");return Ny({snapshot:o,devicePixelRatio:e,logger:r})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let r=Sb(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(r);o?.srcRegex&&(t.frameSrcRegex=o.srcRegex),o?.urlRegex&&(t.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:r},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};var Pp=Ts($b(),"momentic","chromium"),BO=Ts($b(),"video"),El=process.env.TWO_CAPTCHA_KEY,Lp=FO(Wb);Lp.use(DO({provider:{id:"2captcha",token:El},visualFeedback:!0}));var fn=class n{static USER_AGENT=MO["Desktop Chrome"].userAgent;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;lastIconKnowledgeBaseUpdateTime=0;mockedServices;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};enricher;storage;flagStore;logger;stateManager;transformer;lastScreenshotForRecording=void 0;baseUrl;originsVisited=new Set;viewport;onTabsChange=void 0;videos=[];constructor({storage:e,flagStore:t,enricher:r,browser:o,context:i,page:s,baseUrl:a,logger:l,mockedServices:c,userBrowserSettings:p,viewport:d,onTabsChange:u,properties:m,clientCallbacks:h,iconKnowledgeBase:g}){if(vg(p),this.mockedServices=c,this.storage=e,this.flagStore=t,this.enricher=r,this.browser=o,this.context=i,this.page=s,this.baseUrl=a,this.logger=l,this.userControlledBrowserSettings=p,this.viewport=d||Ut,this.onTabsChange=u,this.properties=m,this.clientCallbacks=h,m.recordVideo){let f=this.page.video();f&&this.videos.push(f)}this.iconKnowledgeBase=g}async registerAbortSignal(e){this.abortSignal=e}async initialize(){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera"]);let e=this.flagStore.getAllFlags(),t=[this.context.addInitScript({content:ep.cssGeneratorLibJs}),this.context.addInitScript({content:ep.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(e)};`})],r=Promise.all(Object.entries(this.mockedServices).map(([s,a])=>this.context.route(s,l=>a.handle(l)))),o=s=>this.handleNewPageEvent(s);this.context.on("page",o),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",o)});let i=Promise.all(t);await Promise.all([i,r]),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&OO()==="darwin"&&TO("system_profiler SPDisplaysDataType").toString().includes("Retina")?(y.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await hl.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),this.properties.isNewHeadless&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:this.properties.systemDevicePixelRatio,mobile:this.viewport.width>1e3}}),await this.initializeScreencast(),this.stateManager=new vl({defaultTimeoutMs:this.smartWaitingTimeout,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,flagStore:this.flagStore,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,filterZeroOpacity:this.flagStore.isBooleanFlagEnabled("filter_zero_opacity_elements"),iconKnowledgeBase:this.iconKnowledgeBase}),this.contextInitialized=!0}async initializeScreencast(){this.clientCallbacks?.onScreencastFrame&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let t=e.sessionId,r=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=r,this.clientCallbacks?.onScreencastFrame?.(r,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:t}})}catch{}})()})}))}static async init({baseUrl:e,logger:t,storage:r,flagStore:o,enricher:i,mockedServices:s,userBrowserSettings:a,contextArgs:l,browserbaseConnectUrl:c,onTabsChange:p,recordVideo:d,iconKnowledgeBase:u,callbacks:m}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let h={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:a.browserType==="Google Chrome"?"chrome":void 0},g={...l??{},geolocation:{latitude:37.7749,longitude:-122.4194},locale:"en-US",timezoneId:"America/Los_Angeles",httpCredentials:a.basicAuthorization?{username:a.basicAuthorization.username??"",password:a.basicAuthorization.password??""}:void 0,javaScriptEnabled:a.disableJavaScript?!1:void 0,userAgent:a.userAgent??n.USER_AGENT,viewport:l?.viewport??Ut},f=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-features=IsolateOrigins,site-per-process","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"],S=null,x,v,b={systemDevicePixelRatio:l?.deviceScaleFactor,recordVideo:d};h.headless&&(a.browserType==="Google Chrome"||a.browserType==="Chromium"&&o.isBooleanFlagEnabled("use_new_chrome_headless_chromium"))&&(t.debug("Using new chrome headless mode through feature flag override"),f.push("--headless=new"),b.isNewHeadless=!0),process.env.BROWSER_MEMORY_MB&&f.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),a.disableGpu&&f.push("--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-audio-input","--disable-audio-output");let E=!1;if(a.localChromeExtensionPaths?.length){E=!0;for(let I of a.localChromeExtensionPaths){let _=Ts(I,"manifest.json");if(!Tl(_))throw new R("UserConfigurationError",`Chrome extension path ${_} does not exist.`)}}if(E){let I=Ts(Pp,`momentic-session-${Date.now()}`);if(!Tl(I))try{EO(I,{recursive:!0})}catch(L){throw new R("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${Pp} folder: ${L}`)}let _=[...f];if(a.localChromeExtensionPaths){let L=a.localChromeExtensionPaths.map(z=>_O(z)).join(",");h.headless&&!_.includes("--headless=new")&&_.push("--headless=new"),_.push(`--disable-extensions-except=${L}`),b.isNewHeadless=!0}g?.deviceScaleFactor&&_.push(`--force-device-scale-factor=${g.deviceScaleFactor}`,`--device-scale-factor=${g.deviceScaleFactor}`),g.viewport&&_.push(`--window-size=${g.viewport.width},${g.viewport.height}`),x=await Wb.launchPersistentContext(Ts(Pp,`momentic-session-${Date.now()}`),{...h,...g,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:_,baseURL:e}),t.debug({sharedContextOptions:g,sharedBrowserOptions:h,userBrowserSettings:a,chromeArgs:_,flags:o.getAllFlags()},"Browser initialization context args (persistent)"),v=x.pages()[0]}else if(c){S=await Lp.connectOverCDP(c);let I=S.contexts()[0];if(!I)throw new Error("Failed to get browserbase default context");let _=I.pages()[0];if(!_)throw new Error("Failed to get browserbase default page");x=I,v=_}else{S=await Lp.launch({...h,args:f});let I={...g,baseURL:e,recordVideo:d?{dir:BO}:void 0};x=await S.newContext(I),t.debug({contextArgs:I,sharedBrowserOptions:h,chromeArgs:f,userBrowserSettings:a,flags:o.getAllFlags()},"Browser initialization context args (standard)"),v=await x.newPage()}let C=new n({browser:S,context:x,page:v,baseUrl:e,logger:t,storage:r,flagStore:o,mockedServices:s||{},enricher:i,userBrowserSettings:a,viewport:g.viewport||Ut,onTabsChange:p,properties:b,clientCallbacks:m,iconKnowledgeBase:u});return await C.initialize(),C}async handleAvailableTabsChangeHelper(){try{let e=await Qo(this.context,{getTitles:!0}),t=this.page.url();this.onTabsChange?.(e,t)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,t){let r=jb(),o=`${e}-${r}`,i=Date.now(),s=!1,a=async()=>{try{await D(t(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(l){l.name!=="AbortError"&&this.logger.error({err:l,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],s=!0}};this.pageLoadPromises[o]=a().catch(()=>{}),s&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let t=async()=>{if(this.closed)return;this.logger.debug({url:e.url()},"Detected active page was closed, switching to another tab");let r=this.context.pages();for(let o=r.length-1;o>=0;o--){let i=r[o];if(!(!i||i.isClosed()||!ar(i.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${i.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>t())}handleNewPageEvent(e){let t=e.url();if(this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let r=e.video();r&&this.videos.push(r)}try{this.handleNewPageEventHelper(e)}catch(r){this.logger.warn({err:r},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=jb(),r="new-page-load-handler";e.on("close",s=>this.handlePageClosedEvent(s)),e.on("framenavigated",s=>this.handleFrameNavigationEvent(s)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);e.on("console",s=>{Xy(e,o,this.debugData,s,this.logger)}),e.on("request",s=>{rb(t,this.debugData,s,this.logger)});let i=async()=>{await nb(t,this.debugData,e),await this.loadFrameAndRecordUrl({root:e,codePath:r}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(r,async()=>i())}async handleCollectSvgs(e){if(!this.flagStore.isBooleanFlagEnabled("icon_knowledge_base")||this.page.isClosed()||this.page.mainFrame()!==e||!this.iconKnowledgeBase||!this.clientCallbacks?.onSvgsCollected||Date.now()-this.lastIconKnowledgeBaseUpdateTime<5e3)return;this.lastIconKnowledgeBaseUpdateTime=Date.now();let t=await this.stateManager.getDomGraph({devicePixelRatio:this.devicePixelRatio}),r=Dy({domGraph:t,flagStore:this.flagStore,logger:this.logger,existingHashes:this.iconKnowledgeBase});if(r.forEach(a=>{this.iconKnowledgeBase[a.hash]=a}),!r.length)return;let o=We(this.logger),i={pageUrl:e.url(),firstSeenTime:Date.now(),hostname:LO()};for(let a of["runId","testId"])o[a]&&(i[a]=o[a]);let s={metadata:i,newSvgs:r};this.clientCallbacks.onSvgsCollected(s)}handleFrameNavigationEvent(e){let t=e.url(),r=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${t.slice(0,50)}-${r}`;if(!t||t==="about:blank"||!ar(t))return;let i=async()=>{try{await this.loadFrameAndRecordUrl({root:e,codePath:o,signal:this.abortSignal}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&(await this.waitForDOMStability(),setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(a){this.logger.warn({err:a},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(s){s.name!=="AbortError"&&this.logger.warn({err:s},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>i())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let r={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(r[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let i=window;i._MOMENTIC_ICON_KNOWLEDGE_BASE=o},r)}catch(t){this.logger.warn({err:t},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame()},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await D(yp(this.getBrowserCallbacks()),{milliseconds:1e3})}catch(e){this.logger.warn({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,t,r){let o=Date.now(),i=0,s=0;for(;Date.now()-o<8e3;){s++,r?.throwIfAborted();try{if(await Ve({fn:()=>{let l=window;return!!(l.generateCssSelectors&&l.evaluateCssSelectors&&l.generateHtmlCacheAttributes&&l.ldist)},timeout:1e3,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensureMomenticBrowserScriptsLoaded"}))return}catch(a){if(i++,i>=3){t.warn({err:a},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await te(500),s%2===0&&t.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),Ve({root:e,fn:()=>{let t=window;if(!t?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return t.getFullHtmlTree()},arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getFullHtmlTree"})}url(){return this.page.url()}async screenshot(e){let{retries:t=1}=e;try{let r=await this.screenshotHelper({...e,retries:t});if(r.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(r.length===0)throw new Error("Got empty screenshot");return r}catch(r){if(t<=0||r.message.includes("has been closed"))throw r;return this.logger.debug({pageUrl:this.page.url(),err:r},"Failed taking screenshot, retrying..."),await te(250),this.screenshot({...e,retries:t-1})}}async screenshotHelper({locator:e,quality:t,scale:r="css",saveToDiskPath:o,hideCaret:i,timeout:s,respectActiveFrame:a,disableAnimations:l,clearHighlights:c=!1}){let p={fullPage:!1,type:"jpeg",quality:t,scale:r,caret:i?"hide":"initial",path:o,timeout:s??3e3,animations:l?"disabled":void 0};c&&await this.clearHighlights(),a&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement()),e&&(p.scale="css");let d;if(p.scale==="css"||this.properties.isNewHeadless)d=await this.page.screenshot(p);else{let S=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:2e3});d=Buffer.from(S.data,"base64"),p.path&&RO(p.path,d)}if(this.lastScreenshotForRecording=d,!e)return d;let u=await e.boundingBox({timeout:1e3});if(!u)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:m,y:h,width:g,height:f}=u;if(!g||!f)throw new Error("Attempted to screenshot an element with zero width or height");if(m<0||h<0)throw new Error("Attempted to screenshot an element with negative coordinates");m=Math.floor(m),h=Math.floor(h),g=Math.floor(g),f=Math.floor(f);try{d=await(await AO.fromBuffer(d)).crop({x:m,y:h,w:g,h:f}).getBuffer("image/jpeg")}catch(S){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${h}) with size (${g}, ${f}): ${S}`)}return"dispose"in e&&await e?.dispose(),d}getViewport(){return this.viewport}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:r=this.pageLoadTimeout}){US(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();t||(await this.waitForPageLoad(),await this.waitForDOMStability());let i=!1,s;for(let l=0;l<3;l++)try{await this.page.goto(e,{timeout:r,waitUntil:"domcontentloaded"}),i=!0;break}catch(c){if(s=c,this.abortSignal?.throwIfAborted(),this.logger.warn({err:c},`Error occurred during navigation${l===0?", retrying...":" (fatal)"}`),await te(1e3+1e3*l),s.message.includes("ERR_CONNECTION_CLOSED")&&await this.page.reload({timeout:r,waitUntil:"domcontentloaded"}),s.message.includes("Timeout")&&s.message.includes("exceeded")||s.message.includes("net::ERR_CONNECTION_REFUSED"))break}if(!i)throw new R("UserInfrastructureError",s?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step"}),this.logger.debug({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let a=this.url();if(Iy.has(a))throw new R("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);if(t)try{await this.exposeRecordingBindings()}catch(l){l instanceof Error&&l.message.includes("already registered")||this.logger.error({err:l},"Failed to install Momentic libraries for action recording")}}async type(e,t={},r=!1){await this.directTypeHelper(e,t,r)}async getActiveElement(e){try{return await Ve({root:e,fn:()=>{let r=document.activeElement?.textContent??void 0;return r&&r.length>100&&(r=r.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:r}:void 0},arg:void 0,timeout:1e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getActiveElement"})}catch(t){this.logger.warn({err:t},"Failed to get active element");return}}async directTypeHelper(e,t={},r=!1){let o=await this.getActivePageOrFrame();await lb({root:o,text:e,options:t,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(r){let s=Date.now();for(;Date.now()-s<this.smartWaitingTimeout&&(!i||i.tag==="body");)await te(250),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}t.clearContent&&(t.forceClearContent||i?.tag==="input"||i?.tag==="textarea"?(process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25)):this.logger.warn({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:t.delay??Uu}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoView(e){await e.scrollIntoViewIfNeeded({timeout:2e3})}async highlightA11yId(e){try{let{resolution:t}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(t.locator),!0}catch(t){return this.logger.debug({err:t,id:e},"Failed to highlight target"),!1}}async highlight(e){return fl({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let t=new URL(e).origin;if(t==="null")return;this.originsVisited.add(t)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),t=Object.values(this.pageLoadPromises),r=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;t.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:r,outstandingPromises:t},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:r,outstandingPromises:t},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(t),t=Object.values(this.pageLoadPromises),r=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:1e3}),this.originsVisited.delete(o);let t=this.context.pages().indexOf(this.page),r=[...this.context.pages()];for(let o=0;o<r.length;o++){let i=r[o];if(i.isClosed())continue;let s=i.url();try{this.originsVisited.delete(new URL(s).origin)}catch{}await Jy(i,this.logger),o!==t&&e.closeNonActiveTabs&&(this.logger.debug(`Closing tab ${o} with URL ${s}`),await i.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let t=[];for(let i of e.cookies??[]){let s=await this.setCookie(i);t=t.concat(s)}this.logger.debug(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:1e3});let r=0;for(let i of e.origins??[])for(let s of i.localStorage)try{await this.cdpClient.send({timeout:1e3,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:s.name,value:s.value}}),r++}catch(a){this.logger.warn({err:a,origin:i},"Failed to set local storage entry, continuing...");break}this.logger.debug(`Loaded ${r} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await Yy(this.page,o,this.logger),this.logger.debug(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let t=0,r=null;for(;t<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await Ky(this.page,this.logger),o}catch(o){if(r=o,t++,t<=2){this.logger.warn({err:o,retryCount:t,maxRetries:2},`Error saving auth state, retrying (${t}/2)...`);let i=Math.pow(2,t)*100;await new Promise(s=>setTimeout(s,i))}}throw this.logger.error({err:r},"Failed to save auth state after 2 retries"),new R("ActionFailureError",`Failed to save auth state: ${r?.message}`)}async getOpenPages(e){return Qo(this.context,e)}saveA11yDetailsToCache(e,t){t.id=e.id,t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,t.serializedForm=e.getSerializedFormWithContext(),t.nodeOnlySerializedForm=e.getNodeOnlySerializedForm()}async saveNodeDetailsToCache({node:e,target:t,dataMomenticId:r,locator:o,logger:i=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),!(t.generatedSelectors&&t.generatedSelectors.length>1)){if(r&&(t.dataMomenticId=r),o)try{let s=await this.fetchHtmlAttributes(o,i);Object.assign(t,s)}catch(s){i.warn({err:s},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes(t,o,i)}catch(s){i.debug({err:s},"Failed to save element visual details, continuing...")}}}async saveElementVisualAttributes(e,t,r){if(!t)return;await t.scrollIntoViewIfNeeded({timeout:1e3});let o=await t.boundingBox({timeout:1e3});if(!o||!o.width||!o.height){r.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0;return}e.boundingBox=o;let{x:i=0,y:s=0,width:a=0,height:l=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-a)<1&&Math.abs(e.boundingBox.height-l)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-s)<1||!rp.includes(e?.role??""))return;let c=await this.screenshot({locator:t,retries:0});e.screenshotUrl=await this.storage.uploadScreenshot(c)}async resolveTargetUsingCssSelectors({root:e,target:t,logger:r}){if(!t.generatedSelectors||t.generatedSelectors.length<2||!t.nodeOnlySerializedHtml)throw new ji("Insufficient data to resolve target using CSS selectors");let o;try{o=await Ve({fn:c=>window.evaluateCssSelectors(c),arg:{selectors:t.generatedSelectors,ldistThreshold:.05,serializedNodeWithText:t.nodeOnlySerializedHtml,requireBoundingBox:!0,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0},root:e,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluateCssSelectors"})}catch(c){throw new Error(`Failed to evaluate CSS selectors in browser: ${c}`)}let i=o.result;if(!i)throw new Error(`CSS selector evaluation returned no eligible elements:
|
|
3600
|
-
${
|
|
3601
|
-
`)}`);let s,a,l;if(this.flagStore.isBooleanFlagEnabled("visual_actions")){let c=i.mPath.join(" > ");s=e.locator(c),a=this.stateManager.getNodeUsingMPathSelector(c)}else l=parseInt(i.dataMomenticId),a=this.stateManager.dataMomenticIdToNodeMap[l],s=e.locator(i.workingSelectors[0]);return t.generatedSelectors=void 0,await this.saveNodeDetailsToCache({node:a,target:t,dataMomenticId:l,locator:s,logger:r}),t.generatedSelectors=Array.from(new Set([...i.workingSelectors??[],...t.generatedSelectors??[]].slice(0,12))),{a11yNode:a,displayString:i.serializedElement,locator:s,decisions:[{type:"CSS_SELECTOR",matched:!0,logs:o.logs,reason:`${i.workingSelectors.length} CSS selectors matched the following element: ${i.serializedElement}`,selectors:i.workingSelectors.slice(0,5)}]}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async createTargetFromA11yId({id:e,description:t,targetSource:r,skipSaveToCache:o,logger:i=this.logger}){if(e<0)throw new R("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let s=this.stateManager.a11yIdToNodeMap[e];if(!s)throw new R("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let a=this.stateManager.frameConfig,l,c,p,d;if(this.flagStore.isBooleanFlagEnabled("auto_expand_iframes")&&!a&&s.parentFrame){let f=s.parentFrame,{cache:S,config:x}=await this.stateManager.getAutoFrameDetailsFromHandle(f);c=S,p=x,l=x.frame,d="auto iframe"}else s.parentFrame&&a?(p=a,l=await this.getActivePageOrFrame(),d="hardcoded url already on the state manager"):(l=await this.getActivePageOrFrame(),d="should not be possible");let u=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:l,node:s}),m={id:e,inputDescription:t??void 0,targetSource:r,targetUpdateTime:new Date().toISOString(),frameCache:c},h,g=!1;o||(p&&(i.debug({frameConfigSource:d,frameConfig:yb(p)},"A11y node was resolved to a target within an iframe"),h=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),g=!0),await this.saveNodeDetailsToCache({node:s,target:m,dataMomenticId:s.dataMomenticId,locator:u,logger:i}));try{return{resolution:{locator:u,a11yNode:s,displayString:s.getNodeOnlySerializedForm(),decisions:[]},target:m,frameConfig:p,frameConfigSource:d}}finally{g&&this.stateManager.setActiveFrameConfig(h)}}async resolveTarget(e,t,r={}){let{skipFetchTree:o=!1,targetName:i,logger:s=this.logger,signal:a=this.abortSignal}=r,l=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(l,s,a);let c=Date.now(),p=0,d;for(;Date.now()-c<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),p++;let u=p===1||Date.now()-c>this.smartWaitingTimeout-2e3&&p%2===0;try{d=await this.resolveTargetHelper({root:l,target:t,cssSelectorOnly:!0,skipFetchTree:o,logger:u?s:Nr,signal:a});break}catch(m){if(m instanceof ji)break;a?.throwIfAborted(),u&&s.debug({err:m},`Could not resolve target through CSS selectors only (x${p})`),await te(500,a)}}return d||(d=await this.resolveTargetHelper({root:l,target:t,cssSelectorOnly:!1,skipFetchTree:o,logger:s,signal:a}),t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),s.debug({decisions:d.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:i,elementLocationDecisions:d?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),d}async resolveTargetHelper({root:e,target:t,cssSelectorOnly:r,skipFetchTree:o,logger:i,signal:s,skipSaveToCache:a}){let l=[],c;o||(c=(await this.getBrowserState({logger:i,abortSignal:s,skipWait:!0})).serialize(),i.debug({tree:c},"Got a11y tree before attempting target resolution"));let p=this.stateManager.a11yIdToNodeMap[t.id],d=p?.getNodeOnlySerializedForm();if(!o&&!this.flagStore.isBooleanFlagEnabled("visual_actions")&&p&&t.serializedForm&&d===t.serializedForm){let m=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:e,node:p});return a||await this.saveNodeDetailsToCache({node:p,target:t,dataMomenticId:p.dataMomenticId,locator:m,logger:i}),l.push({type:"A11Y_ID",matched:!0,reason:`An element with the same Chrome-internal accessibility node ID matched the saved content exactly: ${d}.`}),{locator:m,a11yNode:p,displayString:d,decisions:l,pageState:void 0}}let u;if(t.generatedSelectors){let m;try{m=await this.resolveTargetUsingCssSelectors({root:e,target:t,logger:i})}catch(h){u=h}if(m)return{...m,pageState:void 0,decisions:[...l,...m.decisions]};r||(l.push({type:"CSS_SELECTOR",matched:!1,reason:u?.message,selectors:PO(t.generatedSelectors)}),t.generatedSelectors=void 0)}if(r)throw u;if(!this.flagStore.isBooleanFlagEnabled("disable_secondary_cache_resolution")){let m=await this.resolveTargetWithSecondaryMethods({root:e,tree:c,target:t,decisions:l,logger:i,signal:s,skipSaveToCache:a});if(m)return m}throw i.debug({target:t,decisions:l},"Failed to find any relevant node"),new Yn(`Could not find any relevant node given target: ${JSON.stringify(t)}`,l)}async resolveHardcodedCssSelector(e){let{ctx:t,selector:r,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:s=this.smartWaitingTimeout}=e,a=await this.getActivePageOrFrame(),l=Date.now(),c=0,p,d=[];for(;Date.now()-l<s;){i?.throwIfAborted(),c++;let u=a.locator(r),m;try{return await u.waitFor({state:"attached",timeout:1e3}),m=await gn(u,o)??"",d.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${r} matched an element on the page.`}),t?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:d,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:u,displayString:m,decisions:d}}catch(h){let g=h.message;p=new R("ActionFailureError",`CSS selector '${r}' failed to resolve after ${c} attempts: ${g.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":g}`),await te(500,i)}}throw p}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let t=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!t)return;let{x:r,y:o,width:i,height:s}=e.target.boundingBox,a=await t.locator.boundingBox({timeout:1e3});if(!a){this.logger.debug({proposedNode:t.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:l,y:c,width:p,height:d}=a;if(Math.abs(p-i)>50||Math.abs(d-s)>50){this.logger.debug({newW:p,oldW:i,newH:d,oldH:s,proposedNode:t.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(r&&o&&(!l||!c)){this.logger.debug({oldX:r,oldY:o,proposedNode:t.displayString},"Rejecting secondary matching result due to new result not having x/y coords");return}else if(Math.abs((l??0)-(r??0))>200||Math.abs((c??0)-(o??0))>200){this.logger.debug({newX:l,newY:c,oldX:r,oldY:o,proposedNode:t.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return t}async resolveTargetWithSecondaryMethodsHelper({root:e,target:t,decisions:r,logger:o,signal:i,skipSaveToCache:s}){if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<10){let c="Refusing to attempt HTML comparison since the saved element is too short.";r.push({type:"HTML_DISTANCE",matched:!1,reason:c})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let c=await Ve({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:2e3,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"findClosestElementByLDist"}),p=Math.floor(.05*t.nodeOnlySerializedHtml.length);if(c&&c.closestDistance&&c.closestDistance>=p){let d=`Closest HTML candidate still has too far distance (${c.closestDistance}) from threshold (${p})`;r.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:c.closestDistance,closestElement:c.closestNodeSerialized})}else{if(c?.error)throw new Error(c.error);if(c?.dataMomenticId||c?.mPathSelector){let d=c.dataMomenticId?parseInt(c.dataMomenticId):void 0,u,m;if(d)u=this.stateManager.dataMomenticIdToNodeMap[d],m=e.locator(`[${wt}="${d}"]`);else if(c.mPathSelector)u=this.stateManager.getNodeUsingMPathSelector(c.mPathSelector),m=e.locator(c.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let h=c.closestNodeSerialized??await gn(m,o)??"unknown element";return o.warn({result:c,originalTarget:t,displayString:h},"Resolved cached target to new node with pure html levenshtein distance"),s||await this.saveNodeDetailsToCache({node:u,target:t,dataMomenticId:d,locator:m,logger:o}),r.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${p} string comparison distance of the saved element.`,logs:c.logs,distance:c.closestDistance,closestElement:h,savedElement:t.nodeOnlySerializedHtml}),{locator:m,a11yNode:u,displayString:h,decisions:r,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(c)}`)}}catch(c){o.debug({err:c},"Failed to find closest HTML node using levenshtein distance"),r.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${c}`})}let a=t.screenshotUrl,l=t.role??"";if(a&&rp.includes(l))try{let c=await this.resolveTargetWithScreenshot({root:e,oldTarget:t,screenshotUrl:a,signal:i,skipSaveToCache:s});return{...c,decisions:[...r,...c.decisions],pageState:void 0}}catch(c){i?.throwIfAborted(),r.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${c}`,elementImageUrl:a}),o.warn({err:c},"Did not find any close element using saved screenshot")}}async resolveTargetWithScreenshot({root:e,screenshotUrl:t,oldTarget:r,signal:o,skipSaveToCache:i}){let s;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let a=await this.screenshot({retries:0}),c=await(await fetch(t)).arrayBuffer(),p=UO(),d=await this.enricher.runTemplateMatching({id:p,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:a.toString("base64")},{signal:o});this.logger.debug({id:p,templateMatch:d},"Template matching got successful result");let{target:u,locator:m}=await this.getTargetFromPositionPercentages({percentX:d.x,percentY:d.y}),h=u.boundingBox?.width,g=u.boundingBox?.height;if(!h||!g)throw s="Rejecting target from screenshot due to no bounding box",new Error(s);let f=u.id,S=this.stateManager.a11yIdToNodeMap[f];return i||await this.saveNodeDetailsToCache({target:r,node:S,locator:m,dataMomenticId:f}),{locator:m,a11yNode:S,displayString:u.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:t}]}}async resolveTargetWithXY(e,t=!1){if(this.logger.debug({target:e,skipFetchTree:t},"Resolve target through x / y positioning called"),!t){let s=(await this.getBrowserState({})).serialize();this.logger.debug({tree:s},"Got a11y tree for x / y resolution")}let r=await this.getActivePageOrFrame(),{target:o}=await this.getTargetFromPixelPosition(e);if((o.generatedSelectors??[]).length>0)return{locator:r.locator(o.generatedSelectors[0]),a11yNode:this.stateManager.a11yIdToNodeMap[o.id],displayString:o.nodeOnlySerializedHtml??o.nodeOnlySerializedForm??"Unknown element",decisions:[]};let i=this.stateManager.a11yIdToNodeMap[o.id];if(i&&i.dataMomenticId)return{locator:r.locator(`[${wt}="${i.dataMomenticId}"]`),a11yNode:i,displayString:i.getNodeOnlySerializedForm(),decisions:[]};throw new Error("Could not resolve target with x / y through either raw HTML or the accessibility tree")}async typeIntoTarget(e,t,r={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:1e3})??"",i=ab.some(s=>s===o.toLowerCase());return await wp({targetingResult:t,options:{force:r.force},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:i?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks(),flagStore:this.flagStore}),await this.page.waitForTimeout(150),this.directTypeHelper(e,r)}async click(e,t,r={}){return wp({targetingResult:e,options:r,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks(),flagStore:this.flagStore})}async waitForUrl({beforeUrl:e,matcher:t,beforePages:r},o){let i=o?.timeout??this.pageLoadTimeout,s=Date.now();r||(r=(await Qo(this.context)).map(p=>p.url));let a=!1,l=[],c=e;for(;Date.now()-s<i;){this.abortSignal?.throwIfAborted(),l=(await Qo(this.context)).map(d=>d.url);for(let d=l.length-1;d>=r.length;d--){let u=l[d];if(u!==e&&ar(u,this.logger)){md(u,t,o)&&await this.switchToPage({type:"INDEX",index:String(d)});break}}if(c=(await this.getActivePageOrFrame()).url(),md(c,t,o)){a=!0;break}await te(500,this.abortSignal)}if(!a)throw new R("ActionFailureError",`The active page URL ${o?.negated?"still does":"does not"} ${dd(t)} in ${i}ms.
|
|
3600
|
+
${I||""}`}return S}shallowClone(){let e=new r({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:ap(this.internalProperties),parentFrame:this.parentFrame});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=ap(this.properties),e}},lp=class r{constructor(e,t,n,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let s=e.has(`${i.id}`)||i.id===t?.id,l=i.shallowClone(),c=i.children,p=!1,d=[];for(let m of c){let u=n(m,s||p);u&&(d.push(u),u.parent=l,p=!0)}if(l.children=d,s||p)return l;if(gl.includes(i.role)&&a)return l}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function ZP(r){return r.name?.value?`"${r.name.value}"`:r.role?.value&&r.role.value!=="none"&&r.role.value!=="generic"?`"${r.role.value}"`:`"${r.nodeId}"`}function QP(r,e,t,n){return r.bounds.x===null||r.bounds.y===null||r.bounds.height===null||r.bounds.width===null||r.bounds.width===0||r.bounds.height===0?!0:r.bounds.x+r.bounds.width<e.leftBound||r.bounds.x>e.rightBound?(Dr({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport horizontally"),!1):r.bounds.y+r.bounds.height<e.upperBound||r.bounds.y>e.lowerBound?(Dr({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport vertically"),!1):r.computedStyles.display==="none"?(t.debug({domNode:r},"Filtering out node since it has display none"),!1):!0}async function By({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,filterZeroOpacity:s,filterByViewport:l,viewportDetails:c,useMPaths:p,cdpClient:d,logger:m,callId:u}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let h=(k,U={})=>{},g=r.backendDOMNodeId,f=qP.includes((r.role?.value).toLowerCase());if(!f&&g===void 0)return h("Filtering out node since it doesn't exist in the DOM"),[];let S=g?i.backendIdToNode[g]:void 0;if(!f&&!S)try{let k=await D(d.send({method:"DOM.describeNode",params:{backendNodeId:g}}),{milliseconds:750,fallback:()=>{m.debug("Timeout getting node from CDP while processing a11y tree")}});if(k&&k.node.nodeName.toLowerCase()==="slot"&&k.node.distributedNodes?.length)m.debug({redirectedDomNode:S,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:k},"Redirecting node to assigned slot");else return h("Filtering out node since it doesn't exist in the DOM",{cdpResult:k}),[]}catch(k){return h("Filtering out node since it doesn't exist in the DOM",{err:k}),[]}if(S&&e&&l&&c&&r.backendDOMNodeId&&!QP(S,c,m,u))return S.momenticIgnored=!0,[];if(S&&S.computedStyles.display==="none")return m.debug({domNode:S},"Filtering out node since it has display none"),S.momenticIgnored=!0,[];if(S&&S.attributes.tabindex==="-1"&&S.tagName.toLowerCase()==="input"&&(S.bounds.width??0)<10&&(S.bounds.height??0)<10)return Dr({logger:m,logKey:u,maxCount:5,intervalMs:3e3},{attributes:S.attributes},"Filtering out node since it is likely an invisible input that is non-interactive"),S.momenticIgnored=!0,[];let x=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",v=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",b=new sp({domNode:S,id:parseInt(r.nodeId),role:r.role?.value||"",name:x,nameSources:r.name?.sources,content:v,properties:r.properties,children:[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+ZP(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},parentFrame:n.type==="root"?void 0:n}),E=n,C=a[t],I=t;if(S?.tagName.toLowerCase()==="iframe"&&S.ownedFrameId){let k=n.childFrames.find(V=>V.frameId===S.ownedFrameId),U=o[k?.frameId??""]?.root,P=a[k?.frameId??""];if(k&&U&&P){r.childIds&&r.childIds.length>0&&m.debug("Replacing existing node's children with children from the iframe");let V=U;r.childIds=V.childIds,E=k,C=P,I=k.frameId}}let M=S?.childrenBackendIds?.length??0,L=r.childIds?.length??0;if(M>L&&(!s||S?.computedStyles.opacity!=="0")){let k=r.childIds?.map(P=>C.get(parseInt(P))).filter(Boolean).map(P=>P?.backendDOMNodeId).filter(P=>P!==void 0)??[],U=0;for(let P of S?.childrenBackendIds??[]){if(k.includes(P)){U=(r.childIds?.findIndex(Tt=>C.get(parseInt(Tt))?.backendDOMNodeId===P)??0)+1;continue}let V=i.backendIdToNode[P];if(!V||V?.tagName.toLowerCase()!=="svg")continue;let N=Math.floor(-1*Math.random()*1e7),X={nodeId:N.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:P,frameId:I,role:{type:"string",value:"graphics-symbol"}};C.set(N,X),r.childIds||(r.childIds=[]),r.childIds.splice(U,0,N.toString()),U++}}for(let k of r.childIds??[]){if(!k)continue;let U=C.get(parseInt(k));if(!U)continue;let P=await By({node:U,parent:b,domGraph:i,axGraph:o,frameId:I,frameContext:E,inputNodeMap:a,cdpClient:d,logger:m,callId:u,filterByViewport:l,filterZeroOpacity:s,viewportDetails:c,useMPaths:p});P.length&&(b.children=b.children.concat(P))}if(b.role==="StaticText"&&(b.children=[]),b.children.length===1&&b.children[0].role==="StaticText"){let k=b.name,U=b.children[0]?.name;(k===U||!U)&&(b.children=[])}let z=[];for(let k=b.children.length-1;k>=0;k--){let U=b.children[k];if(U.role!=="StaticText"){z.push(U);continue}if(k===0||b.children[k-1].role!=="StaticText"){z.push(U);continue}b.children[k-1].name+=U.name}if(b.children=z.reverse(),b.role==="generic"&&b.children.length===1){let k=b.children[0];if(b.name&&!gl.includes(k.role)&&b.name===k.name)return S&&(S.momenticIgnored=!0),b.children}if(!b.isInteresting()&&r.parentId)return S&&(S.momenticIgnored=!0),b.children;for(let k of b.children)k.parent=b;return nL(b),S&&p&&ip(S,i),[b]}function zy({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:s,iconKnowledgeBase:l,startId:c=1}){r.id=c,c+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:gl.includes(r.role);let p=r.backendNodeId,d=p!==void 0?i.backendIdToNode[p]:void 0;if(a&&d&&d.mPathSelector&&(s[d.mPathSelector]=r),l&&d&&d.tagName?.toLowerCase()==="svg"){let m=ul(d,i),u=m?l[m.hash]:void 0,h=u?u.description:void 0;u&&(r.properties["data-momentic-description"]=h)}for(let m of r.children)c=zy({node:m,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:c,useMPaths:a,domGraph:i,selectorToNodeMap:s,iconKnowledgeBase:l});return c}async function jy({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,filterZeroOpacity:a,viewportDetails:s,useMPaths:l,frameContext:c,iconKnowledgeBase:p}){let d=t??"root",m=r[d]?.root;if(!m)throw new Error("A11y tree has no root");let u=zP(),h=b=>{let E=b.allNodes.filter(I=>!I.ignoredReasons?.find(L=>VP.includes(L.name))),C=new Map;return E.forEach(I=>{C.set(parseInt(I.nodeId),I)}),C},g={};Object.entries(r).forEach(([b,E])=>{g[b]=h(E)});let f=await By({node:m,domGraph:e,parent:null,inputNodeMap:g,axGraph:r,frameId:d,frameContext:c,cdpClient:o,logger:n,callId:u,filterZeroOpacity:a,filterByViewport:i,viewportDetails:s,useMPaths:l});if(f.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(f)}`);if(f.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let S={},x={},v={};return zy({node:f[0],a11yIdNodeMap:S,dataMomenticIdMap:x,selectorToNodeMap:v,domGraph:e,logger:n,callId:u,useMPaths:l,iconKnowledgeBase:p}),new lp(f[0],S,x,v)}function eL(r,e,t){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(i=>i.length<50&&!Dn.bannedClassSubstrings.some(a=>i.includes(a))).slice(0,3).join(" ");let n=e.split(" "),o=[];for(let i of n)if(Hy(i)){o.push(i);continue}return o.length?o.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let n=parseInt(e);if(!isNaN(n))return n}catch{}return r==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function tL(r,e){if(!e)return;Object.entries(e.attributes).forEach(([i,a])=>{if(Dn.relevantElementAttributes.includes(i)&&!$P.includes(i)&&!r[i]&&!i.startsWith("aria")){let s=eL(i,a,e);s!==null&&(r[i]=s)}});let t,n=[];if(e.computedStyles.position&&Fy.includes(e.computedStyles.position))t=e.computedStyles.position;else if(e.attributes.style){for(let i of Fy)if(e.attributes.style.includes(`position: ${i}`)){t=i;break}}t&&n.push(`position: ${t}`);let o;(e.computedStyles.opacity&&e.computedStyles.opacity==="0"||e.attributes.style&&e.attributes.style.includes("opacity: 0"))&&(o="opacity: 0"),o&&n.push(o),n.length>0&&(r.style=n.join("; "))}function nL(r){let e=r.properties.class;if(typeof e=="string"&&e.includes("cm-content")){r.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){r.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),r.children.length>0&&(r.children[r.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(r.tagName==="table"){let i=[],a=r.children.find(l=>l.tagName==="thead");if(a){let l=a.children.find(c=>c.tagName==="tr");if(l){let c=l.children.filter(p=>p.tagName==="th");c.forEach((p,d)=>{p.properties["col-index"]||(p.properties["col-index"]=d+1),i?.push(_e(p.name,100,!1))}),i?.length!==c.length&&(i=void 0)}}let s=0;for(let l of r.children)if(l.tagName==="tbody")for(let c=0;c<l.children.length;c++){let p=l.children[c];if(p.tagName!=="tr")continue;if(c===0&&!i?.length){let u=p.children.filter(h=>h.tagName==="th");if(u.length){if(i=u.map(h=>_e(h.name,100,!1)),i.length===u.length)continue;i=void 0}}s+=1,p.properties["row-index"]||(p.properties["row-index"]=s);let d=p.children.filter(u=>u.tagName==="td"||u.tagName==="th"),m=d.length===i?.length;d.forEach((u,h)=>{u.tagName!=="th"&&(u.properties["col-index"]||(u.properties["col-index"]=h+1),m&&(u.properties.col||(u.properties.col=i[h])))})}}}function rL(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function Hy(r){if(Dn.bannedClassSubstrings.some(e=>r.includes(e)))return!1;if(Dn.alwaysInterestingClassNames.includes(r))return!0;for(let e of Dn.alwaysInterestingClassPrefixes)if(r.startsWith(e))return!0;return!1}var fl=class r{constructor(e,t,n,o,i){this.session=e;this.logger=t;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;static async init({logger:e,contextGetter:t,pageGetter:n,defaultTimeoutMs:o}){let i=t(),a=n(),s,l;for(let p=0;p<2;p++)try{s=await D(i.newCDPSession(a),{milliseconds:o*p,fallback:()=>{throw new A("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await Q(500),l=d}if(!s)throw l;let c=new r(s,e,t,n,o);try{await D(c.registerHandlers(s),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(p){throw c.cdpFullyDead=!0,new A("UserInfrastructureError",`Failed to initialize CDP client: ${p}`)}return c}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(t){this.logger.debug({err:t},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP inspector session crashed, Momentic will likely not function correctly")}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await this.cdpInitializingPromise;if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new A("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await D(this.session.send(e,t),{milliseconds:n,message:o??`Chrome command ${e} timed out after ${n}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(i){throw["Internal error","Target crashed"].some(a=>i.message.includes(a))&&!this.cdpInitializingPromise&&(this.logger.warn({err:i},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),i}}async createRawCDPSession(e=this.defaultTimeoutMs){let t=e,n=this.pageGetter(),o=await D(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new A("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${n.url()})`)}});return this.logger.debug(`Created new CDP session for ${n.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let t=this.session;this.session=await this.createRawCDPSession(e),await this.registerHandlers(this.session),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await D(t.detach(),{milliseconds:1e3})}catch(n){this.logger.warn({err:n},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(t){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${t}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,t){return this.session.on(e,t),this.session}off(e,t){return this.session.off(e,t),this.session}addListener(e,t){return this.session.addListener(e,t),this.session}removeListener(e,t){return this.session.removeListener(e,t),this.session}};import{mkdirSync as oL,rmSync as $y,statSync as iL}from"fs";import*as pp from"node:fs";import aL from"nodejs-file-downloader";import{tmpdir as sL}from"os";import ur,{basename as lL,dirname as cL}from"path";var up="file://",dp=ur.join(sL(),"momentic","downloads"),cp=1e4,dL=50*1024*1024;async function Wy(r){let{uri:e}=r;return e.startsWith(up)?uL(r):e.startsWith("http")?hL(r):mL(r)}function pL(r,e){let t=ur.join(dp,r,e.slice(up.length)),n=ur.join(dp,r),o=t.startsWith(n);if(!pp.existsSync(t)||!o)throw new A("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function uL({uri:r,orgId:e}){let t=pL(e,r);return{filePath:t,cleanup:()=>{$y(cL(t),{recursive:!0,force:!0})}}}async function mL({uri:r}){let e=ur.resolve(r);if(!pp.existsSync(e))throw new A("UserConfigurationError",`The referenced file (${r}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function hL({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=lL(n.href),i=hp(o),a=ur.extname(i);if(Sh.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let s=mp(t),l=new aL({url:r,fileName:i,directory:s,maxAttempts:2,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:cp}),{downloadStatus:c,filePath:p}=await D(l.download(),{milliseconds:cp,message:`Download timed out after ${cp}ms`});if(c!=="COMPLETE")throw new Error(`Download ended in non-success status: ${c}`);if(!p)throw new Error("File path of successfully downloaded file was empty");let m=iL(p).size;if(m>dL)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:m,filePath:p,fileName:i},"Downloaded file to disk");let u;return{filePath:p,cleanup:()=>{clearTimeout(u),u=setTimeout(()=>$y(s,{recursive:!0,force:!0}),10*60*1e3)}}}function Gy(r,e){return`${up}${r}/${e}`}function mp(r){let e=Math.random().toString(36).substring(4),t=ur.join(dp,r,e);return oL(t,{recursive:!0}),t}function hp(r){let e=ur.extname(r),t=ur.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function gn(r,e){try{return await r.evaluate(n=>window.serializeElementOnlyWithText?.(n,{truncateToLength:500}),void 0,{timeout:1e3})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}var Sl=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(s=>n-s<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(n),!1)}};async function Vy(r,e){let t=r.evaluate(async()=>{let i=window,a={};try{let s=await indexedDB.databases();for(let l of s){if(!l.name)continue;let c=await i.exportIdbToObject?.(l.name,l.version);c&&(a[l.name]=c)}return[a,void 0]}catch(s){return[void 0,s.message]}}),[n,o]=await D(t,{milliseconds:3e3});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function qy(r,e,t){if(e){t.debug("Importing indexedDB data");try{let n=r.evaluate(async o=>{let i=window;for(let[a,s]of Object.entries(o))await i.importObjectToIdb?.(a,s)},e);await D(n,{milliseconds:3e3})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function Ky(r,e){try{let t=r.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(n=>{n.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await D(t,{milliseconds:3e3})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function Yy(r,e,t,n,o){try{await gL(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function gL(r,e,t,n){let o=n.text();o.length>Ta&&(o=o.slice(0,Ta)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let s=await a.jsonValue(),l=JSON.stringify(s);l.length>Ta?i.push(l.slice(0,Ta)+"...(TRUNCATED)"):(typeof s!="object"||Object.keys(s).length>0)&&i.push(s)}catch{}gp(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function gp(r,e,t,n){let o=Date.now(),i=e.logsPerPage;if(i.length<=t||i[t]===void 0){i[t]=[];for(let a=0;a<t;a++)i[a]===void 0&&(i[a]=[])}i[t].length>rp&&(i[t]=i[t].slice(Math.floor(rp/2)),i[t]?.push({url:r.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:t})),i[t].push({...n,tabIndex:t,timestamp:o})}async function Un({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await Ji({promiseGenerator:r,signal:n,codePath:e,logger:o}),s=Date.now();return t[e]=s-i,a}import{randomUUID as fL}from"crypto";var SL="[redacted due to size]",yL=1e4;async function eb(r,e,t){let n=new Date().toISOString();e.harPages||(e.harPages={}),e.harPages[r]={id:r,startedDateTime:n,title:void 0,pageTimings:{}}}async function tb(r,e,t,n){try{await bL(r,e,t)}catch(o){o.message.includes("browser has been closed")||n.warn({err:o,pageId:r},"Error handling new network request, skipping...")}}function Xr(r){return r<0?0:r}function Jy(r){return{timings:{blocked:Xr(r.domainLookupStart),dns:Xr(r.domainLookupEnd-r.domainLookupStart),connect:Xr(r.connectEnd-r.connectStart),send:Xr(r.responseStart-r.requestStart),wait:0,receive:Xr(r.responseEnd-r.responseStart),ssl:Xr(r.connectEnd-r.secureConnectionStart)},total:Xr(r.responseEnd)}}async function bL(r,e,t){let n=fL(),o=t.timing(),i=new URL(t.url()),a=[...i.searchParams.entries()].map(([h,g])=>({name:h,value:g})),s={...await Qy(t),url:i.toString(),method:t.method(),queryString:a,postData:await vL(t)},l={pageref:r,_resourceType:t.resourceType(),startedDateTime:new Date(o.startTime).toISOString(),request:s,timings:Jy(o).timings};Xy(e,l,n);let c=await t.response();if(c){await c.finished();let h={};try{h=await xL(c)}catch{}let g={...await Qy(c),status:c.status(),statusText:c.statusText(),content:h,redirectURL:c.headers().location};l.response=g}let p;try{p=await t.sizes(),l.request.bodySize=p.requestBodySize,l.request.headersSize=p.requestHeadersSize}catch{}l.response&&p&&(l.response.bodySize=p.responseBodySize,l.response.headersSize=p.responseHeadersSize,l.response.content.size=p.responseBodySize);let d=t.timing(),{timings:m,total:u}=Jy(d);l.time=u,l.timings=m,Xy(e,l,n)}function Xy(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function Zy(r){try{return new Date(r).toISOString()}catch{return}}function wL(r){let e={name:"",value:""},t=!0;for(let n of r.split(/; */)){let o=n.indexOf("="),i=o!==-1?n.substring(0,o).trim():n.trim(),a=o!==-1?n.substring(o+1,n.length).trim():"";if(t){t=!1,e.name=Rn(i),e.value=Rn(a);continue}i==="Domain"&&(e.domain=Rn(a)),i==="Expires"&&(e.expires=Zy(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=Zy(Date.now()+ +a*1e3)),i==="Path"&&(e.path=Rn(a)),i==="Secure"&&(e.secure=!0)}return e}async function Qy(r){let e=await r.headersArray(),t=[];for(let n of e.filter(o=>o.name.toLowerCase()==="cookie"))t.push(...n.value.split(";").map(wL));return{headers:e.map(n=>({name:Rn(n.name),value:Rn(n.value)})),cookies:t}}async function vL(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:Rn(e),params:[]};if(t==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[i,a]of o.entries())n.params.push({name:Rn(i),value:a?Rn(a):void 0})}return n}async function xL(r){return{mimeType:await r.headerValue("content-type")??void 0,text:Rn(await r.text()),encoding:await r.headerValue("content-encoding")??void 0}}function Rn(r){return r.length>yL?SL:r}function nb(){return async r=>{let{fragment:e,code:t,context:n}=r,{env:o}=n||{},i=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new i("env",e?`return ${t}`:t)(o))}}}async function qe({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await D(r.evaluate(e,t),{milliseconds:n,message:`Timed out executing code path ${i} after ${n}ms`})}function fp(){return window.lastCursorPos}import{errors as TL}from"playwright-core";async function Zr({func:r,action:e,logger:t,callbacks:n,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),s;for(;Date.now()-a<o;)try{return await r(i)}catch(l){let c=l;if(Wi(c)){t.warn("Attempting to recover from removed data-momentic-ids by re-adding ids to DOM");let[p]=await Promise.all([r(i),n.getBrowserState({skipWaitForPageLoad:!0,skipWait:!0})]);return p}else if(c instanceof TL.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),s=await EL(c,i.locator,n,t);else throw c}throw s instanceof A?s:new A("ActionFailureError",`Failed to interact with targeted element. Error: ${s.message}`,{errOptions:{cause:s}})}async function EL(r,e,t,n){return r.message.includes("attempt #")?CL(r,e,t,n):AL(r)}async function CL(r,e,t,n){let o=r.message.split(/- retrying \w+ action, attempt #\d+/).filter(l=>l.length>0);if(!o.length)return n.warn({err:r},"Failed to parse Playwright error message for translation, returning raw message"),r;let i=o.length>2?o[o.length-2]:o[0];i=i.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
|
|
3601
|
+
`,";").replace(/\s+/g," ");let a="",s=await gn(e,n);if(s&&(a=`Target element HTML: ${_e(s,100,!0)}`),i.includes("element is not enabled"))return new A("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}});if(i.includes("intercepts pointer events")){let l="",c=i.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(c){let p=(await t.state.getRoot()).locator(`[data-momentic-id="${c}"]`),d=await gn(p,n);d&&(l=`Covering element HTML: ${_e(d,100,!0)}`)}return new A("ActionFailureError",`The element you attempted to interact with was covered by another element such as dropdown, popup, or dialog for the entire timeout duration. Please add a step to hide the covering element or turn on the 'disable stability checks' option. ${a}
|
|
3602
|
+
${l}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let l="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let c=await e.boundingBox({timeout:1e3});c?c.height===0?l="The element you attempted to interact with has zero height.":c.width===0&&(l="The element you attempted to interact with has zero width."):l="The element you attempted to interact with has no bounding box."}catch{}return new A("ActionFailureError",`${l} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}})}return i.includes("element is outside of the viewport")?new A("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${a}`):r}function AL(r){let e=r.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new A("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}async function rb(r){try{return await RL(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function RL({locator:r,logger:e}){let[t,n]=await r.evaluate(l=>[l.id,l.tagName.toLowerCase()],{timeout:1e3}),o=await gn(r,e),i=await r.boundingBox({timeout:1e3});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5)return;if(n==="input"&&t)try{let l=r.page().locator(`label[for=${JSON.stringify(t)}]`);return await l.waitFor({state:"visible",timeout:1e3}),{locator:l,relativePoint:void 0}}catch{}let a=await r.evaluate(l=>{let c=window;if(!c.CssSelectorGenerator)return{type:"error",error:"[MOMENTIC] Missing CSS selector libraries"};let p=l.parentElement;if(!p)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.CssSelectorGenerator.getCssSelector(p,{}),m=l.getBoundingClientRect(),u=p.getBoundingClientRect();if(u.width===0||u.height===0)return{type:"error",error:"Parent element has no width or height"};let h={x:Math.min(Math.max(1,m.left-u.left),u.width-1),y:Math.min(Math.max(1,m.top-u.top),u.height-1)};return{type:"result",selector:d,relativePoint:h,serializedForm:p.outerHTML.slice(0,500)}},{timeout:1e3});if(a.type==="error")throw new Error(a.error);let s=r.page().locator(a.selector);return await s.waitFor({state:"visible",timeout:1e3}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:s,relativePoint:a.relativePoint}}var ib=["date","datetime-local","month","time","week"],ob={date:/^\d{4}-\d{2}-\d{2}$/,"datetime-local":/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,month:/^\d{4}-\d{2}$/,time:/^\d{2}:\d{2}$/,week:/^\d{4}-W\d{2}$/};async function ab(r){try{await D(IL(r),{milliseconds:3e3})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function IL({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await qe({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transformNativeDateTimeInputFillHelper"})).toLowerCase();if(!ob[i])return;ob[i].test(e)&&n.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),t.clearContent=!1,n.debug("Transforming datetime input to use sequential key presses")}async function yl({locator:r,callbacks:e,logger:t,timeoutMs:n=1e3}){try{await Sp(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let u=window.getComputedStyle(d,null).getPropertyValue("display");if(u==="none"||u==="contents")return!1;let h=d.getBoundingClientRect();return!(!h.height||!h.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let s=0;for(;!a.momenticIsEligible(i)&&s<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,s++}let l=i.style.getPropertyValue("outline"),c=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let p=`momentic${Math.floor(Math.random()*1e7)}`;a[p]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",l,c),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[p](),a.removeHighlightFunctions?.[p]&&delete a.removeHighlightFunctions[p]},5e3)),a.removeHighlightFunctions[p]=a[p]},void 0,{timeout:n});return await D(o,{milliseconds:n}),!0}catch(o){return t.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function Sp(r,e=1e3){let t=await r.state.getRoot();await qe({root:t,fn:()=>{let o=window,i=o.removeHighlightTimers||[];for(;i.length;){let a=i.pop();clearTimeout(a)}Object.values(o.removeHighlightFunctions??{}).forEach(a=>{a()})},timeout:e,arg:void 0,waitForPageLoad:r.waitForPageLoad,codePath:"removeAllHighlights"})}async function bp(r){let e=r.flagStore.isBooleanFlagEnabled("visual_actions");return Zr({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>yp({...r,targetingResult:t,useVisualClick:e})})}async function OL(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await NL(r,e)}catch(n){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:n,originalError:r},"Error handling click error, rethrowing original error"),r):n}}async function NL(r,e){let{logger:t,redirectionAttempts:n=0,browserCallbacks:o,actionSource:i}=e,a=e.targetingResult.locator,s=o.state.getDomGraph();if(r.message.includes("label")&&r.message.includes("for=")&&r.message.includes("intercepts pointer events")){let l=await a.getAttribute("id",{timeout:1e3});if(!l)throw r;let c=a.page().locator(`[for=${JSON.stringify(l)}]`);return await c.waitFor({state:"visible",timeout:1e3}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),yp({...e,targetingResult:{locator:c},redirectionAttempts:n+1})}else if(i==="click"&&s&&r.message.includes("intercepts pointer events")){t.warn({err:r},"Attempting locator redirection due to covering error");let l=await UL(a,s,t);if(l)return yp({...e,targetingResult:{locator:l},redirectionAttempts:n+1});throw t.error({err:r},"No updated locator could be found to fix covering error, rethrowing"),r}else throw t.error({err:r},"Click error does not match any known recoverable patterns, rethrowing"),r}async function ML(r){let{browserCallbacks:e,logger:t,targetingResult:n,position:o,options:i}=r,a=await e.state.getRoot(),s=a&&a!==n.locator.page()&&"frameElement"in a?await a.frameElement():null,l;try{l=s?await Hr({promiseGenerator:async()=>s.boundingBox(),timeoutMs:3e3,logger:t}):null}catch(u){throw new A("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${u.message}`)}finally{await s?.dispose()}let c=Date.now(),{clickX:p,clickY:d,reason:m}=await DL({frameCoordinates:l,logger:t,targetingResult:n,position:o,options:i});t.debug({frameCoordinates:l,position:o,targetingResultHints:n.hints,options:i,clickLocation:{clickX:p,clickY:d,reason:m},duration:Date.now()-c},"Visual click")}async function _L(r){let{actionSource:e,targetingResult:t,options:n,logger:o}=r,i=r.targetingResult.locator,a=n?.relativePosition??r.position;if(e==="click"&&!a){let l=await rb({locator:i,logger:o});l&&(i=l.locator,a=l.relativePoint??a)}let s=n?.force||t.hints?.force||!1;try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:s}):await i.click({button:n?.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:s})}catch(l){let c=l;if(zL(c))o.warn({err:c},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:c},"Error clicking on locator, attempting to recover..."),OL(c,{...r,targetingResult:{...i,locator:i}})}}async function yp(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,s=(await n.state.getOpenPages()).map(d=>d.url),l=n.state.url(),c=null;try{c=await a.locator.getAttribute("target",{timeout:1e3})}catch(d){t.warn({err:d},"Failed to get attributes of element about to be clicked, continuing...")}let p;e?.waitForDownload&&(p=(async()=>{let d=e.downloadTimeoutMs??3e4;try{return await a.locator.page().waitForEvent("download",{timeout:d})}catch(m){return m instanceof kL.TimeoutError?new A("ActionFailureError",`Download did not complete in ${d}ms`):new A("ActionFailureError",`Download failed: ${m.message}`)}})());try{await yl({locator:a.locator,callbacks:n,logger:t,timeoutMs:1e3})}catch(d){t.warn({err:d},"Error highlighting locator in click, continuing...")}if(i?await ML(r):await _L(r),c==="_blank"){t.debug("Waiting for new page promise due to _blank target");let d=Date.now();for(;(await n.state.getOpenPages()).length<=s.length&&Date.now()-d<2e3;)await Q(500);await n.waitForPageLoad()}if(e?.waitForUrl&&await n.waitForUrl({beforeUrl:l,beforePages:s,matcher:{type:"GLOB",glob:e.waitForUrl}}),e?.waitForDownload)if(p){if(!o?.createIsolatedFolder)throw new A("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let d=await D(p,{milliseconds:e.downloadTimeoutMs??3e4});if(d instanceof Error)throw d;return{downloadedFile:await BL(d,o.createIsolatedFolder,t)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function FL(r,e){if(e.hints?.clickableXY){let i=(r?.x??0)+e.hints.clickableXY.x,a=(r?.y??0)+e.hints.clickableXY.y;return[{x:i,y:a},"targeting hint"]}let t=await e.locator.boundingBox({timeout:1e3});if(!t)throw new A("ActionFailureError","Element does not have a bounding box");let n=t.x+t.width/2,o=t.y+t.height/2;return[{x:n,y:o},"halfway point of the bounding box"]}async function DL({frameCoordinates:r,logger:e,options:t,targetingResult:n,position:o}){let i,a,s;if(o){let d=await n.locator.boundingBox({timeout:3e3});i=(r?.x??0)+(d?.x??0)+o.x,a=(r?.y??0)+(d?.y??0)+o.y,s="predefined position"}else{let[d,m]=await FL(r,n);i=d.x,a=d.y,s=m}let l=n.locator.page(),c=t?.rightClick?"right":"left",p=t?.delayMs??25;return t?.doubleClick?await l.mouse.dblclick(i,a,{button:c,delay:p}):await l.mouse.click(i,a,{button:c,delay:p}),{clickX:i,clickY:a,reason:s}}async function UL(r,e,t){let n=await r.evaluate(s=>s.getAttribute("data-momentic-id"));if(!n)return;let o=hl(n,e,t);if(!o.length){t.error("No candidates found for parent-based locator redirection");return}let i=parseInt(o[0].attributes?.[wt]??"");if(isNaN(i))return;r=r.page().locator(`[data-momentic-id="${i}"]`);let a=await gn(r,t);return t.warn({candidateMomenticId:i,serializedHtml:a},"Trying new locator based on parent-direction after covering error"),r}async function BL(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=hp(r.suggestedFilename()),i=e();await r.saveAs(LL(i,o)),lb(n,{force:!0}),setTimeout(()=>{lb(i,{recursive:!0,force:!0})},5*60*1e3);let a=Gy(PL(i),o);return t.debug({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function zL(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as jL}from"os";var HL={goToNextWord:{win32:"Control+ArrowRight",darwin:"Alt+ArrowRight",linux:"Control+ArrowRight"},goToPreviousWord:{win32:"Control+ArrowLeft",darwin:"Alt+ArrowLeft",linux:"Control+ArrowLeft"},selectNextWord:{win32:"Control+Shift+ArrowRight",darwin:"Alt+Shift+ArrowRight",linux:"Control+Shift+ArrowRight"},selectPreviousWord:{win32:"Control+Shift+ArrowLeft",darwin:"Alt+Shift+ArrowLeft",linux:"Control+Shift+ArrowLeft"},selectToStartOfLine:{win32:"Shift+Home",darwin:"Meta+Shift+LeftArrow",linux:"Shift+Home"},selectToEndOfLine:{win32:"Shift+End",darwin:"Meta+Shift+RightArrow",linux:"Shift+End"},deleteNextWord:{win32:"Control+Delete",darwin:"Alt+Fn+Delete",linux:"Control+Delete"},deletePreviousWord:{win32:"Control+Backspace",darwin:"Alt+Delete",linux:"Control+Backspace"}};function $L(){let r=jL();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function cb(r){return JSON.stringify(r.split("+").sort())}function db(r){let e=$L(),t=cb(r);for(let n of Object.values(HL))if(Object.values(n).some(o=>cb(o)===t))return n[e];return process.platform==="darwin"?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function wp({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:s}){if(!t&&!o)return;let l=n==="left"?-1:1,c=i==="up"?-1:1;if(r)await qe({root:r,fn:([p,d,m,u])=>window.scrollTo(window.scrollX+(p??window.innerWidth)*m,window.scrollY+(d??window.innerHeight)*u),arg:[t,o,l,c],waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"scrollFrame"});else{let p=e.viewportSize()||Dt,d=await qe({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"scrollPageGetHeight"}),[m,u,h]=await qe({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let S=f.getBoundingClientRect();return[f.scrollTop,S.x,S.y]},arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"scrollPage"});await e.mouse.wheel((t??p.width)*l,(o??p.height)*c);let g=Date.now();for(;Date.now()-g<2e3;){a?.throwIfAborted();let f=await D(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[S,x,v]=await D(e.evaluate(()=>{let b=document.activeElement;if(!b)return[void 0,void 0,void 0];let E=b.getBoundingClientRect();return[b.scrollTop,E.x,E.y]}),{milliseconds:1e3});if(f===d&&S===m&&x===u&&v===h)break;d=f,m=S,u=x,h=v,await Q(500)}}}async function ri(r,e){let t,n;for(let o=0;o<4;o++)try{return t=r.pages(),await Promise.all(t.map(async i=>{let a="";try{a=e?.getTitles?await i.title():""}catch{a="Unknown page"}return{title:a,url:i.url()}}))}catch(i){n=i,await Q(500)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}var oi="<empty>";function WL(r){return r.includes("doubleclick.net")||r.includes("googletagmanager.com")||r.includes("googlesyndication.com")||r.includes("s.amazon-adsystem.com")||r.includes("smartadserver.com")||r.includes("omnitagjs.com")||r.includes("x.adroll.com")}function ub(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||WL(r.url)}async function GL(r,e){let t=await r.send({timeout:3e3,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:3e3,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function ii({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i]=await Promise.all([r.send({timeout:3e3,method:"Page.getFrameTree",params:{}}),r.send({timeout:3e3,method:"DOM.getDocument",params:{}})]),l=(i.frameTree.childFrames??[]).map(async(p,d)=>{if(ub(p.frame))return null;try{return await mb({cdpClient:r,rawFrameTree:p,indices:[d],parent:n,warnings:o})}catch(m){return o.push(`Failed to get child frame: ${m}`),null}}),c=await Promise.all(l);return n.childFrames=c.filter(p=>p!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function mb({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o}){let i=e.frame.id,a=await GL(r,i),s=a.attributes??[],l=null,c=[];for(let u of["src","name","id","title","srcdoc","sandbox"]){let h=pr(s,u);h&&(c.push(`${u}=${JSON.stringify(h)}`),u==="src"&&(l=h))}let p={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:i,locationData:{indices:t,attributeSelectors:c},src:l,childFrames:[],parent:n,domNode:a},m=(e.childFrames??[]).map(async(u,h)=>{if(ub(u.frame))return null;try{return await mb({cdpClient:r,rawFrameTree:u,indices:[...t,h],parent:p,warnings:o})}catch(g){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${g}`),null}});return p.childFrames=(await Promise.all(m)).filter(u=>u!==null),p}async function VL(r){try{return await r.owner().count()===1}catch{return!1}}async function qL(r){try{return await r.count()===1}catch{return!1}}async function In(r,e){let t=[],n=r;for(;n.parent.type==="frame";)t.push(n.parent),n=n.parent;t.reverse();let o=e,i=[];for(let c of t){let p=!1;for(let d of[...c.locationData.attributeSelectors,oi]){let m=o.frameLocator(d===oi?"iframe":`iframe[${d}]`);if(await VL(m)){p=!0,o=m,i.push(d);break}}if(!p)throw new A("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${c.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let c of[...r.locationData.attributeSelectors,oi]){let p=o.locator(c===oi?"iframe":`iframe[${c}]`);if(await qL(p)){a=p,i.push(c);break}}if(!a)throw new A("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${r.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let s=await a.evaluateHandle(c=>c,{timeout:1e3}),l=await s.asElement().contentFrame();if(!l)throw new A("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await s.dispose(),{frame:l,mPathSelectorTokens:i}}function pb(r,e){let t=[...r],n=[];for(;t.length;){let o=t.shift();e(o)&&n.push(o),t.push(...o.childFrames)}return n}async function hb({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let s=o;for(let p=0;p<t.mPathSelectorTokens.length-1;p++){let d=t.mPathSelectorTokens[p];d===oi?s=s.length===1?s[0].childFrames:[]:s=s.filter(m=>m.locationData.attributeSelectors.includes(d)).map(m=>m.childFrames).flat()}let l=[],c=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(c===oi?l=s:l=s.filter(p=>p.locationData.attributeSelectors.includes(c)),l.length===1)return n=l[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await In(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${l.length} frames with mpath ${t.mPathSelectorTokens.join(" > ")}`)}if(t.frameSrcRegex){let s=new RegExp(t.frameSrcRegex),l=pb(o,c=>!!c.src&&s.test(c.src));if(l.length===1)return n=l[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await In(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${l.length} frames with src regex ${t.frameSrcRegex}`),t.frameSrcRegex=void 0}if(t.frameUrlRegex){let s=new RegExp(t.frameUrlRegex),l=pb(o,c=>!!c.url&&s.test(c.url));if(l.length===1)return n=l[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await In(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${l.length} frames with url regex ${t.frameUrlRegex}`),t.frameUrlRegex=void 0}let a=o;for(let s=0;s<t.indices.length-1;s++)a=a[t.indices[s]]?.childFrames??[];if(n=a[t.indices[t.indices.length-1]],n)return i.push(`Found unique frame with indices ${t.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await In(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new Jn("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function bl(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function vp(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function gb(r){let e=vp(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let s=a.shift();s.src&&o.push(s.src),s.url&&i.push(s.url),a.push(...s.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function fb(r){return r.type==="auto"?{type:"auto",frameId:r.handle.frameId,url:r.handle.url,src:r.handle.src??"",mPathSelectorTokens:r.mPathSelectorTokens.join(" > ")}:{type:"url",url:r.url}}async function Sb({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await KL({frameElementHandle:n,logger:e,signal:t})}catch(o){e.warn({err:o},"Failed to scroll iframe into view, continuing...")}finally{await n?.dispose()}}async function KL({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();if(!n){e.warn("Active frame element has null bounding box, skipping scroll");return}await Hr({promiseGenerator:async()=>r.evaluate(async(i,{x:a,y:s})=>{window.scrollTo(window.scrollX+a,window.scrollY+s);let l=Date.now(),c,p,d;for(;Date.now()-l<1500;){let m=document.activeElement,u,h,g;if(!m)u=void 0,h=void 0,g=void 0;else{let f=m.getBoundingClientRect();u=m.scrollTop,h=f.x,g=f.y}if(c!==void 0&&p!==void 0&&d!==void 0&&u===c&&h===p&&g===d)break;c=u,p=h,d=g,await new Promise(f=>setTimeout(f,250))}},n),timeoutMs:2e3,codePath:"scrollIframeIntoView",signal:t}),e.info({bb:n},"Successfully scrolled iframe into view")}async function yb({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:s,properties:l}=r.target;if(s){i.error({error:s,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!l)return;let c=n.parentFrame()?n.url():void 0,d=n.page().frames().map(h=>h.url());i.debug({frameUrl:c,...r},"Passive click event captured on element");let m,u;if(c)try{let h=await n.frameElement();m=await D(h?.boundingBox(),{milliseconds:1e3})??void 0;let g=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:c});if(g.urlRegex)u={type:"url",url:`/${g.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(g)}`)}catch(h){i.warn({err:h},"Failed to construct iframe details for recorded action, using hardcoded URL only"),u={type:"url",url:c}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:u,frameBoundingBox:m})}catch(h){i.error({err:h},"Failed to transform passive click action")}})()}import{randomUUID as Pn}from"crypto";import YL from"js-beautify";var JL=["Shift","CapsLock","Dead","Meta","AudioVolumeUp","AudioVolumeDown"];var wl=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:t,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(s,l)=>{this.recordedSteps.set(l,{step:s}),t.onStepRecorded(s,l)},onActionReceived:(s,l)=>{this.recordedSteps.set(l,{step:s}),t.onActionReceived?.(s,l)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:Pn(),type:"PRESET_ACTION",command:kn(e)}}),this.nextStepOffset++,t}async recordElementAction(e){let{type:t,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,s=n.properties.attributes.nodeOnlySerializedHtml.trim(),l=s,c;switch(e.frameConfig?e.frameBoundingBox?c={x:e.frameBoundingBox.x+n.properties.boundingBox.x,y:e.frameBoundingBox.y+n.properties.boundingBox.y,width:n.properties.boundingBox.width,height:n.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):c=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let g=kn(i);a={id:Pn(),type:"PRESET_ACTION",command:{...g,target:{type:"description",elementDescriptor:l},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:c}}}};break}case"SELECT":{i="SELECT_OPTION";let g=kn(i);a={id:Pn(),type:"PRESET_ACTION",command:{...g,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:l},cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:c}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let g=kn(i);a={id:Pn(),type:"PRESET_ACTION",command:{...g,target:{type:"description",elementDescriptor:l},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:c}}}};break}default:throw new Error(`Unknown action type: ${t}`)}let p;e.offset===void 0?(p=this.nextStepOffset,this.nextStepOffset++):p=e.offset,this.callbacks.onActionReceived?.(a,p);let d=e.target.browserState;try{d=YL.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=Cy(d,"data-momentic-interacted",4e4)}catch{}let m;try{m=(await this.generator.getReverseMappedDescription({target:d,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:n.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...We(this.logger)}})).phrase}catch(g){this.logger.error({err:g},"Error generating reverse mapping description"),m=s}let u=this.recordedSteps.get(p)?.step??a,h=u?.command;h&&"target"in h&&h.target?(h.target={type:"description",elementDescriptor:m},this.callbacks.onStepRecorded({...u,command:h},p)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(JL.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=kn("TYPE");i={id:Pn(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=kn("PRESS");i={id:Pn(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,s=this.nextStepOffset-1,l=this.recordedSteps.get(s),c=l?.step,p=c?.command;if(n){if(p?.type===i.command.type){let d=p.value,m=i.command.value;i={id:Pn(),type:"PRESET_ACTION",command:{...p,value:i.command.type==="PRESS"?`${d}+${m}`:`${d}${m}`}},a=s}else if(p?.type==="CLICK"&&i.command.type==="TYPE")c.command={...i.command,target:p.target,cache:p.cache},i=l.step,a=s;else if(p?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=p.value;i={id:Pn(),type:"PRESET_ACTION",command:{...p,value:d.slice(0,d.length-1)}},a=s}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let t=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,l;s?.type==="SCROLL_DOWN"&&s.deltaY?(i+=s.deltaY,l=a):s?.type==="SCROLL_UP"&&s.deltaY?(i-=s.deltaY,l=a):(l=this.nextStepOffset,this.nextStepOffset++);let c=i>0?"SCROLL_DOWN":"SCROLL_UP",p=kn(c);p.deltaY=Math.abs(i);let d={id:Pn(),type:"PRESET_ACTION",command:p};this.callbacks.onStepRecorded(d,l)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,l;s?.type==="SCROLL_RIGHT"&&s.deltaX?(i+=s.deltaX,l=a):s?.type==="SCROLL_LEFT"&&s.deltaX?(i-=s.deltaX,l=a):(l=this.nextStepOffset,this.nextStepOffset++);let c=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",p=kn(c);p.deltaX=Math.abs(i);let d={id:Pn(),type:"PRESET_ACTION",command:p};this.callbacks.onStepRecorded(d,l)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(n(),e.deltaY>=20&&t()):(t(),e.deltaX>=20&&n())}};var vl=class{defaultTimeoutMs;filterZeroOpacity;logger;cdpClient;pageGetter;abortSignalGetter;flagStore;enricher;iconKnowledgeBase;activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;constructor({defaultTimeoutMs:e,filterZeroOpacity:t,logger:n,cdpClient:o,pageGetter:i,flagStore:a,abortSignalGetter:s,enricher:l,iconKnowledgeBase:c}){this.defaultTimeoutMs=e,this.filterZeroOpacity=t,this.logger=n,this.cdpClient=o,this.pageGetter=i,this.flagStore=a,this.abortSignalGetter=s,this.enricher=l,this.iconKnowledgeBase=c}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.flagStore.isBooleanFlagEnabled("auto_expand_iframes"))return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),n=vp(e),{frame:o,mPathSelectorTokens:i}=await In(e,t),a={indices:e.locationData.indices,mPathSelectorTokens:i};return this.constructIframeRegexAsync(e,a),{cache:a,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:i,frameTree:n,cache:a}}}async resolveAutoFrameCache(e){let t=this.pageGetter(),n=await ii({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await hb({page:t,frameTree:n,cache:e});return this.logger.debug({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:t=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(bl(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let n;return this.frameConfig.type==="url"?n=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:t}):n={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:bl(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await Sb({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await ii({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[D(n.evaluate(e,t),{milliseconds:2e3})],a=Array.from(o.childFrames);for(;a.length>0;){let l=a.shift();a.push(...l.childFrames),i.push(In(l,n).then(({frame:c})=>D(c.evaluate(e,t),{milliseconds:2e3})).catch(c=>(this.logger.warn({err:c,frameUrl:l.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR")))}return(await Promise.all(i)).filter(l=>l!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),t=await ii({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(t.childFrames),o=[];for(;n.length>0;){let i=n.shift();n.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:t,logger:n}){return this.getDOMTree({devicePixelRatio:e??1,signal:t,logger:n??this.logger})}async getA11yTree(e){let t={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),a,s,l=null;if(this.frameConfig?.type==="url"){if(a=await Un({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new A("ActionFailureError","Got null frame details despite active frame config");s=a.handle,l=s.frameId}else this.flagStore.isBooleanFlagEnabled("auto_expand_iframes")?(s=await Un({fn:()=>ii({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),l=null):(s={type:"root",page:i,childFrames:[]},l=null);await Un({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:s.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let c=await Un({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),p=await Un({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:l,childFrames:s.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await Un({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:p,domGraph:c,startingFrameId:l,frameContext:s,logger:n,iconKnowledgeBase:this.iconKnowledgeBase}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(m=>m>750)&&n.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=c,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:Fr,filterByViewport:!1}),Math.random()<.1){let n=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:n&&n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:t,node:n}){if(n.backendNodeId===void 0)throw new Error(`Node with a11y id ${n.id} has no backend node ID: ${n.getNodeOnlySerializedForm()}`);if(this.flagStore.isBooleanFlagEnabled("visual_actions")){let o=this.domGraph?.backendIdToNode[n.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${n.backendNodeId}`);let i=Oy({node:o,domGraph:this.domGraph});return Ny(e,i)}else return this.getLocatorFromBackendId(t,n.backendNodeId)}async getLocatorFromBackendId(e,t){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:t},timeout:2e3});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await My(this.cdpClient,n.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(n.object)},"Failed to get ID attribute"),i}return e.locator(`[${wt}="${o}"]`)}getNodeUsingMPathSelector(e){let t=this.selectorToNodeMap[e];if(t)return t;let n=e.split(" > "),o="";for(let i=n.length-1;i>=0;i--){let a=n.slice(i).join(" > ");if(this.selectorToNodeMap[a]){o=a;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:t=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,s,l=0;for(;Date.now()-o<this.defaultTimeoutMs;)try{i=await ii({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),a=await this.getMatchingFrameByUrlWithCdp(i,e),n.debug({frameId:a.handle.frameId,url:a.handle.url,src:a.handle.src,locationData:a.handle.locationData},`Found matching frame using ${a.matchType}`);break}catch(c){if(s=c,c instanceof A&&c.reason==="UserInfrastructureError")throw c;l%3===0&&this.logger.debug({attempt:l,err:c},"Failed to resolve active frame, retrying..."),await Q(500,t)}finally{l++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:bl(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw s}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let s=i.shift(),l=s.domNode;i.push(...s.childFrames);let c=pr(l.attributes??[],"src"),p=l.contentDocument?.documentURL;if(!c&&!p){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[c,p])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:s,matchType:"regex",...await In(s,o)});break}}else if(n.trim()===d.trim()){a.push({handle:s,matchType:"url",...await In(s,o)});break}}}if(a.length===1){let s=a[0];return this.flagStore.isBooleanFlagEnabled("auto_expand_iframes")||(s.handle.childFrames=[]),s}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new A("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:s}){let l=await jy({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,filterZeroOpacity:this.filterZeroOpacity,filterByViewport:e.filterByViewport,viewportDetails:void 0,iconKnowledgeBase:s,useMPaths:this.flagStore.isBooleanFlagEnabled("visual_actions")});if(!l||!l.root)throw new Error("Accessibility tree appears empty");return{tree:l}}async addMomenticIds({rootPage:e,childFrames:t,frameFilter:n,logger:o}){if(this.flagStore.isBooleanFlagEnabled("visual_actions"))return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.flagStore.isBooleanFlagEnabled("auto_expand_iframes")||n)return;let a=Array.from(t),s=[];for(;a.length>0;){let l=a.shift();a.push(...l.childFrames);let c=async()=>{try{let{frame:p}=await In(l,e);i=await this.addMomenticIdsHelper(p,i)}catch(p){o.warn({err:p},"Error adding momentic IDs to child frame, continuing...")}};s.push(c())}await Promise.all(s)}async addMomenticIdsHelper(e,t){if(this.flagStore.isBooleanFlagEnabled("visual_actions"))return t;let n=this.logger;return await qe({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:2e3,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.defaultTimeoutMs})}catch(i){n.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"addMomenticIds"})??t}getPageDomain(e){try{let t=new URL(e);if(!t.hostname)return null;let n=t.hostname.split("."),o=n.length>2?n.slice(-2).join("."):t.hostname;return`${t.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({domNode:e,viewport:t}){let n=e.attributes??[];if(pr(n,"aria-hidden")==="true")return!1;let o=pr(n,"style");if(o?.includes("display: none")||o?.includes("visibility: hidden"))return!1;await this.cdpClient.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[i,a]=await Promise.all([this.cdpClient.send({timeout:3e3,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:3e3,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!i.model||!i.model.height||!i.model.width||i.model.height<10||i.model.width<10)return!1;for(let s of a.computedStyle)if(s.name==="display"&&s.value==="none"||s.name==="visibility"&&s.value==="hidden"||s.name==="opacity"&&s.value==="0")return!1;return!0}async getRawA11yGraph({cdpClient:e,frameId:t,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let s=[],[l,c]=await Promise.all([Un({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.defaultTimeoutMs*2}),codePath:"a11y-tree-fetch-root",logObject:o,signal:a,logger:i}),e.send({timeout:3e3,method:"Page.getLayoutMetrics",params:{}})]);if(!l)throw new Error("The accessibility tree is empty for the root page or frame. Are you sure it is working properly?");let p=c.cssVisualViewport,d={};if(d[t??"root"]=l,!this.flagStore.isBooleanFlagEnabled("auto_expand_iframes"))return d;let m=Array.from(n),u=[];for(;m.length>0;){let h=m.shift(),g=h.domNode;try{if(!await this.decideChildFrameUnrollEligibility({domNode:g,viewport:p}))continue}catch(S){if(S.message.includes("Could not compute box model"))continue;s.push(`Got error when determining whether to filter frame ${h.frameId} with url ${h.url}, allowing it to be fetched: ${S}`)}m.push(...h.childFrames);let f=async()=>{try{let S=await Un({fn:()=>this.getRawA11yTreeForFrame({frameId:h.frameId,timeoutMs:3e3}),codePath:`a11y-tree-fetch-child-${h.frameId}`,logObject:o,signal:a,logger:i});d[h.frameId]=S}catch(S){i.warn({err:S,url:h.url,src:h.src},`Error getting raw a11y tree for child frame ${h.frameId}, continuing...`)}};u.push(f())}return await Promise.all(u),s.length>0&&this.logger.warn({warnings:s},"Got warnings when fetching the raw a11y graph"),d}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t}){let n=await this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:2e3});if(!n.node.backendDOMNodeId)throw new Error("Root node has no backend DOM node ID");let o=n.node.backendDOMNodeId,i=await this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:o},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`});if(!i.nodes||i.nodes.length<=1)throw new Error("Document is entirely empty");return{root:i.nodes[0],allNodes:i.nodes}}async getDOMTree({devicePixelRatio:e,signal:t,logger:n}){let o,i=0;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:ml},timeout:3e3}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(a){await Q(500,t),n.debug({err:a},"Error fetching DOM tree"),i++}if(!o||!o.documents.length)throw new A("InternalWebAgentError","Error fetching DOM tree");return ky({snapshot:o,devicePixelRatio:e,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=gb(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(n);o?.srcRegex&&(t.frameSrcRegex=o.srcRegex),o?.urlRegex&&(t.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:n},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};var xp=Ea(Cb(),"momentic","chromium"),Sk=Ea(Cb(),"video"),El=process.env.TWO_CAPTCHA_KEY,Tp=hk(Ab);Tp.use(gk({provider:{id:"2captcha",token:El},visualFeedback:!0}));var fn=class r{static USER_AGENT=mk["Desktop Chrome"].userAgent;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;lastIconKnowledgeBaseUpdateTime=0;mockedServices;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};enricher;storage;flagStore;logger;stateManager;transformer;lastScreenshotForRecording=void 0;baseUrl;originsVisited=new Set;viewport;onTabsChange=void 0;videos=[];constructor({storage:e,flagStore:t,enricher:n,browser:o,context:i,page:a,baseUrl:s,logger:l,mockedServices:c,userBrowserSettings:p,viewport:d,onTabsChange:m,properties:u,clientCallbacks:h,iconKnowledgeBase:g}){if(gg(p),this.mockedServices=c,this.storage=e,this.flagStore=t,this.enricher=n,this.browser=o,this.context=i,this.page=a,this.baseUrl=s,this.logger=l,this.userControlledBrowserSettings=p,this.viewport=d||Dt,this.onTabsChange=m,this.properties=u,this.clientCallbacks=h,u.recordVideo){let f=this.page.video();f&&this.videos.push(f)}this.iconKnowledgeBase=g}async registerAbortSignal(e){this.abortSignal=e}async initialize(){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera"]);let e=this.flagStore.getAllFlags(),t=[this.context.addInitScript({content:Qd.cssGeneratorLibJs}),this.context.addInitScript({content:Qd.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(e)};`})],n=Promise.all(Object.entries(this.mockedServices).map(([a,s])=>this.context.route(a,l=>s.handle(l)))),o=a=>this.handleNewPageEvent(a);this.context.on("page",o),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",o)});let i=Promise.all(t);await Promise.all([i,n]),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&ck()==="darwin"&&nk("system_profiler SPDisplaysDataType").toString().includes("Retina")?(y.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await fl.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),this.properties.isNewHeadless&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:this.properties.systemDevicePixelRatio,mobile:this.viewport.width>1e3}}),await this.initializeScreencast(),this.stateManager=new vl({defaultTimeoutMs:this.smartWaitingTimeout,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,flagStore:this.flagStore,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,filterZeroOpacity:this.flagStore.isBooleanFlagEnabled("filter_zero_opacity_elements"),iconKnowledgeBase:this.iconKnowledgeBase}),this.contextInitialized=!0}async initializeScreencast(){this.clientCallbacks?.onScreencastFrame&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let t=e.sessionId,n=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=n,this.clientCallbacks?.onScreencastFrame?.(n,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:t}})}catch{}})()})}))}static async init({baseUrl:e,logger:t,storage:n,flagStore:o,enricher:i,mockedServices:a,userBrowserSettings:s,contextArgs:l,browserbaseConnectUrl:c,onTabsChange:p,recordVideo:d,iconKnowledgeBase:m,callbacks:u}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let h={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:s.browserType==="Google Chrome"?"chrome":void 0},g={...l??{},geolocation:{latitude:37.7749,longitude:-122.4194},locale:l?.locale||Pr,timezoneId:l?.timezoneId||Lr,httpCredentials:s.basicAuthorization?{username:s.basicAuthorization.username??"",password:s.basicAuthorization.password??""}:void 0,javaScriptEnabled:s.disableJavaScript?!1:void 0,userAgent:s.userAgent??r.USER_AGENT,viewport:l?.viewport??Dt},f=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"],S=null,x,v,b={systemDevicePixelRatio:l?.deviceScaleFactor,recordVideo:d};h.headless&&(s.browserType==="Google Chrome"||s.browserType==="Chromium"&&o.isBooleanFlagEnabled("use_new_chrome_headless_chromium"))&&(t.debug("Using new chrome headless mode through feature flag override"),f.push("--headless=new"),b.isNewHeadless=!0),process.env.BROWSER_MEMORY_MB&&f.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),s.disableGpu&&f.push("--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-audio-input","--disable-audio-output");let E=!1;if(s.localChromeExtensionPaths?.length){E=!0;for(let I of s.localChromeExtensionPaths){let M=Ea(I,"manifest.json");if(!Tl(M))throw new A("UserConfigurationError",`Chrome extension path ${M} does not exist.`)}}if(E){let I=Ea(xp,`momentic-session-${Date.now()}`);if(!Tl(I))try{rk(I,{recursive:!0})}catch(L){throw new A("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${xp} folder: ${L}`)}let M=[...f];if(s.localChromeExtensionPaths){let L=s.localChromeExtensionPaths.map(z=>uk(z)).join(",");h.headless&&!M.includes("--headless=new")&&M.push("--headless=new"),M.push(`--disable-extensions-except=${L}`),b.isNewHeadless=!0}g?.deviceScaleFactor&&M.push(`--force-device-scale-factor=${g.deviceScaleFactor}`,`--device-scale-factor=${g.deviceScaleFactor}`),g.viewport&&M.push(`--window-size=${g.viewport.width},${g.viewport.height}`),x=await Ab.launchPersistentContext(Ea(xp,`momentic-session-${Date.now()}`),{...h,...g,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:M,baseURL:e}),t.debug({sharedContextOptions:g,sharedBrowserOptions:h,userBrowserSettings:s,chromeArgs:M,flags:o.getAllFlags()},"Browser initialization context args (persistent)"),v=x.pages()[0]}else if(c){S=await Tp.connectOverCDP(c);let I=S.contexts()[0];if(!I)throw new Error("Failed to get browserbase default context");let M=I.pages()[0];if(!M)throw new Error("Failed to get browserbase default page");x=I,v=M}else{S=await Tp.launch({...h,args:f});let I={...g,baseURL:e,recordVideo:d?{dir:Sk}:void 0};x=await S.newContext(I),t.debug({contextArgs:I,sharedBrowserOptions:h,chromeArgs:f,userBrowserSettings:s,flags:o.getAllFlags()},"Browser initialization context args (standard)"),v=await x.newPage()}let C=new r({browser:S,context:x,page:v,baseUrl:e,logger:t,storage:n,flagStore:o,mockedServices:a||{},enricher:i,userBrowserSettings:s,viewport:g.viewport||Dt,onTabsChange:p,properties:b,clientCallbacks:u,iconKnowledgeBase:m});return await C.initialize(),C}async handleAvailableTabsChangeHelper(){try{let e=await ri(this.context,{getTitles:!0}),t=this.page.url();this.onTabsChange?.(e,t)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,t){let n=xb(),o=`${e}-${n}`,i=Date.now(),a=!1,s=async()=>{try{await D(t(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(l){l.name!=="AbortError"&&this.logger.error({err:l,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],a=!0}};this.pageLoadPromises[o]=s().catch(()=>{}),a&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let t=async()=>{if(this.closed)return;this.logger.debug({url:e.url()},"Detected active page was closed, switching to another tab");let n=this.context.pages();for(let o=n.length-1;o>=0;o--){let i=n[o];if(!(!i||i.isClosed()||!lr(i.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${i.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>t())}handleNewPageEvent(e){let t=e.url();if(this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let n=e.video();n&&this.videos.push(n)}try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=xb(),n="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);e.on("console",a=>{Yy(e,o,this.debugData,a,this.logger)}),e.on("request",a=>{tb(t,this.debugData,a,this.logger)});let i=async()=>{await eb(t,this.debugData,e),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){if(!this.flagStore.isBooleanFlagEnabled("icon_knowledge_base")||this.page.isClosed()||this.page.mainFrame()!==e||!this.iconKnowledgeBase||!this.clientCallbacks?.onSvgsCollected||Date.now()-this.lastIconKnowledgeBaseUpdateTime<5e3)return;this.lastIconKnowledgeBaseUpdateTime=Date.now();let t=await this.stateManager.getDomGraph({devicePixelRatio:this.devicePixelRatio}),n=_y({domGraph:t,flagStore:this.flagStore,logger:this.logger,existingHashes:this.iconKnowledgeBase});if(n.forEach(s=>{this.iconKnowledgeBase[s.hash]=s}),!n.length)return;let o=We(this.logger),i={pageUrl:e.url(),firstSeenTime:Date.now(),hostname:lk()};for(let s of["runId","testId"])o[s]&&(i[s]=o[s]);let a={metadata:i,newSvgs:n};this.clientCallbacks.onSvgsCollected(a)}handleFrameNavigationEvent(e){let t=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${t.slice(0,50)}-${n}`;if(!t||t==="about:blank"||!lr(t))return;let i=async()=>{try{await this.loadFrameAndRecordUrl({root:e,codePath:o,signal:this.abortSignal}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&(await this.waitForDOMStability(),setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(s){this.logger.warn({err:s},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(a){a.name!=="AbortError"&&this.logger.warn({err:a},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>i())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let n={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(n[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let i=window;i._MOMENTIC_ICON_KNOWLEDGE_BASE=o},n)}catch(t){this.logger.warn({err:t},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame()},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await D(Sp(this.getBrowserCallbacks()),{milliseconds:1e3})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,t,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<8e3;){a++,n?.throwIfAborted();try{if(await qe({fn:()=>{let l=window;return!!(l.generateCssSelectors&&l.evaluateCssSelectors&&l.generateHtmlCacheAttributes&&l.ldist)},timeout:1e3,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensureMomenticBrowserScriptsLoaded"}))return}catch(s){if(i++,i>=3){t.warn({err:s},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await Q(500),a%2===0&&t.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),qe({root:e,fn:()=>{let t=window;if(!t?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return t.getFullHtmlTree()},arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getFullHtmlTree"})}url(){return this.page.url()}async screenshot(e){let{retries:t=1}=e;try{let n=await this.screenshotHelper({...e,retries:t});if(n.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(n.length===0)throw new Error("Got empty screenshot");return n}catch(n){if(t<=0||n.message.includes("has been closed"))throw n;return this.logger.debug({pageUrl:this.page.url(),err:n},"Failed taking screenshot, retrying..."),await Q(250),this.screenshot({...e,retries:t-1})}}async screenshotHelper({locator:e,quality:t,scale:n="css",saveToDiskPath:o,hideCaret:i,timeout:a,respectActiveFrame:s,disableAnimations:l,clearHighlights:c=!1}){let p={fullPage:!1,type:"jpeg",quality:t,scale:n,caret:i?"hide":"initial",path:o,timeout:a??3e3,animations:l?"disabled":void 0};c&&await this.clearHighlights(),s&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement()),e&&(p.scale="css");let d;if(p.scale==="css"||this.properties.isNewHeadless)d=await this.page.screenshot(p);else{let S=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:2e3});d=Buffer.from(S.data,"base64"),p.path&&ik(p.path,d)}if(this.lastScreenshotForRecording=d,!e)return d;let m=await e.boundingBox({timeout:1e3});if(!m)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:u,y:h,width:g,height:f}=m;if(!g||!f)throw new Error("Attempted to screenshot an element with zero width or height");if(u<0||h<0)throw new Error("Attempted to screenshot an element with negative coordinates");u=Math.floor(u),h=Math.floor(h),g=Math.floor(g),f=Math.floor(f);try{d=await(await ak.fromBuffer(d)).crop({x:u,y:h,w:g,h:f}).getBuffer("image/jpeg")}catch(S){throw new Error(`Failed taking element screenshot at coordinates (${u}, ${h}) with size (${g}, ${f}): ${S}`)}return"dispose"in e&&await e?.dispose(),d}getViewport(){return this.viewport}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){FS(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();t||(await this.waitForPageLoad(),await this.waitForDOMStability());let i=!1,a;for(let l=0;l<3;l++)try{await this.page.goto(e,{timeout:n,waitUntil:"domcontentloaded"}),i=!0;break}catch(c){if(a=c,this.abortSignal?.throwIfAborted(),this.logger.warn({err:c},`Error occurred during navigation${l===0?", retrying...":" (fatal)"}`),await Q(1e3+1e3*l),a.message.includes("ERR_CONNECTION_CLOSED")&&await this.page.reload({timeout:n,waitUntil:"domcontentloaded"}),a.message.includes("Timeout")&&a.message.includes("exceeded")||a.message.includes("net::ERR_CONNECTION_REFUSED"))break}if(!i)throw new A("UserInfrastructureError",a?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step"}),this.logger.debug({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let s=this.url();if(Ay.has(s))throw new A("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);if(t)try{await this.exposeRecordingBindings()}catch(l){l instanceof Error&&l.message.includes("already registered")||this.logger.error({err:l},"Failed to install Momentic libraries for action recording")}}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async getActiveElement(e){try{return await qe({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;return n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n}:void 0},arg:void 0,timeout:1e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getActiveElement"})}catch(t){this.logger.warn({err:t},"Failed to get active element");return}}async directTypeHelper(e,t={},n=!1){let o=await this.getActivePageOrFrame();await ab({root:o,text:e,options:t,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(n){let a=Date.now();for(;Date.now()-a<this.smartWaitingTimeout&&(!i||i.tag==="body");)await Q(250),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}t.clearContent&&(t.forceClearContent||i?.tag==="input"||i?.tag==="textarea"?(process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25)):this.logger.warn({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:t.delay??Ou}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoView(e){await e.scrollIntoViewIfNeeded({timeout:2e3})}async highlightA11yId(e){try{let{resolution:t}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(t.locator),!0}catch(t){return this.logger.debug({err:t,id:e},"Failed to highlight target"),!1}}async highlight(e){return yl({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let t=new URL(e).origin;if(t==="null")return;this.originsVisited.add(t)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;t.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(t),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:1e3}),this.originsVisited.delete(o);let t=this.context.pages().indexOf(this.page),n=[...this.context.pages()];for(let o=0;o<n.length;o++){let i=n[o];if(i.isClosed())continue;let a=i.url();try{this.originsVisited.delete(new URL(a).origin)}catch{}await Ky(i,this.logger),o!==t&&e.closeNonActiveTabs&&(this.logger.debug(`Closing tab ${o} with URL ${a}`),await i.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let t=[];for(let i of e.cookies??[]){let a=await this.setCookie(i);t=t.concat(a)}this.logger.debug(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:1e3});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:1e3,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(s){this.logger.warn({err:s,origin:i},"Failed to set local storage entry, continuing...");break}this.logger.debug(`Loaded ${n} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await qy(this.page,o,this.logger),this.logger.debug(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let t=0,n=null;for(;t<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await Vy(this.page,this.logger),o}catch(o){if(n=o,t++,t<=2){this.logger.warn({err:o,retryCount:t,maxRetries:2},`Error saving auth state, retrying (${t}/2)...`);let i=Math.pow(2,t)*100;await new Promise(a=>setTimeout(a,i))}}throw this.logger.error({err:n},"Failed to save auth state after 2 retries"),new A("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return ri(this.context,e)}saveA11yDetailsToCache(e,t){t.id=e.id,t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,t.serializedForm=e.getSerializedFormWithContext(),t.nodeOnlySerializedForm=e.getNodeOnlySerializedForm()}async saveNodeDetailsToCache({node:e,target:t,dataMomenticId:n,locator:o,generateNewCssSelectors:i,logger:a=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n&&(t.dataMomenticId=n),o)try{let s=await this.fetchHtmlAttributes(o,a);s&&(t.serializedHtml=s.serializedHtml,t.nodeOnlySerializedHtml=s.nodeOnlySerializedHtml,i&&(t.generatedSelectors=s.generatedSelectors))}catch(s){a.warn({err:s},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes(t,o,a)}catch(s){a.debug({err:s},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes(e,t,n){if(!t)return;await t.scrollIntoViewIfNeeded({timeout:1e3});let o=await t.boundingBox({timeout:1e3});if(!o||!o.width||!o.height){n.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0;return}e.boundingBox=o;let{x:i=0,y:a=0,width:s=0,height:l=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-s)<1&&Math.abs(e.boundingBox.height-l)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-a)<1||!np.includes(e?.role??""))return;let c=await this.screenshot({locator:t,retries:0});e.screenshotUrl=await this.storage.uploadScreenshot(c)}async resolveTargetUsingCssSelectors({root:e,target:t,logger:n}){if(!t.generatedSelectors||t.generatedSelectors.length<2||!t.nodeOnlySerializedHtml)throw new $i("Insufficient data to resolve target using CSS selectors");let o=Tb(t.generatedSelectors),i;try{i=await qe({fn:p=>window.evaluateCssSelectors(p),arg:{selectors:t.generatedSelectors,ldistThreshold:.05,serializedNodeWithText:t.nodeOnlySerializedHtml,requireBoundingBox:!0,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0},root:e,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluateCssSelectors"})}catch(p){throw new Error(`Failed to evaluate CSS selectors in browser: ${p}`)}let a=i.result;if(!a)throw new Error(`CSS selector evaluation returned no eligible elements:
|
|
3603
|
+
${i.logs.join(`
|
|
3604
|
+
`)}`);let s,l,c;if(this.flagStore.isBooleanFlagEnabled("visual_actions")){a.mPath||n.error({foundElement:a},"Found element did not have an mPath despite using visual actions");let d=a.mPath.join(" > ");s=e.locator(d),l=this.stateManager.getNodeUsingMPathSelector(d)}else c=parseInt(a.dataMomenticId),l=this.stateManager.dataMomenticIdToNodeMap[c],s=e.locator(a.workingSelectors[0]);return await this.saveNodeDetailsToCache({node:l,target:t,dataMomenticId:c,locator:s,logger:n,generateNewCssSelectors:a.workingSelectors.length<5}),{a11yNode:l,displayString:a.serializedElement,locator:s,decisions:[{type:"CSS_SELECTOR",matched:!0,logs:i.logs,reason:`${a.workingSelectors.length} CSS selectors matched the following element: ${a.serializedElement}`,selectors:a.workingSelectors.slice(0,5)}]}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger}){if(e<0)throw new A("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let a=this.stateManager.a11yIdToNodeMap[e];if(!a)throw new A("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let s=this.stateManager.frameConfig,l,c,p,d;if(this.flagStore.isBooleanFlagEnabled("auto_expand_iframes")&&!s&&a.parentFrame){let f=a.parentFrame,{cache:S,config:x}=await this.stateManager.getAutoFrameDetailsFromHandle(f);c=S,p=x,l=x.frame,d="auto iframe"}else a.parentFrame&&s?(p=s,l=await this.getActivePageOrFrame(),d="hardcoded url already on the state manager"):(l=await this.getActivePageOrFrame(),d="should not be possible");let m=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:l,node:a}),u={id:e,inputDescription:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),frameCache:c},h,g=!1;o||(p&&(i.debug({frameConfigSource:d,frameConfig:fb(p)},"A11y node was resolved to a target within an iframe"),h=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),g=!0),await this.saveNodeDetailsToCache({node:a,target:u,dataMomenticId:a.dataMomenticId,locator:m,logger:i,generateNewCssSelectors:!0}));try{return{resolution:{locator:m,a11yNode:a,displayString:a.getNodeOnlySerializedForm(),decisions:[]},target:u,frameConfig:p,frameConfigSource:d}}finally{g&&this.stateManager.setActiveFrameConfig(h)}}async resolveTarget(e,t,n={}){let{skipFetchTree:o=!1,targetName:i,logger:a=this.logger,signal:s=this.abortSignal}=n;if(t.frameCache&&this.flagStore.isBooleanFlagEnabled("auto_expand_iframes")){let m,u=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let g=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(g),u=!0;break}catch(g){m=g,await Q(500,s)}if(!u)throw m}let l=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(l,a,s);let c=Date.now(),p=0,d;for(;Date.now()-c<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),p++;let m=p===1||Date.now()-c>this.smartWaitingTimeout-2e3&&p%2===0;try{d=await this.resolveTargetHelper({root:l,target:t,cssSelectorOnly:!0,skipFetchTree:o,logger:m?a:Fr,signal:s});break}catch(u){if(u instanceof $i)break;s?.throwIfAborted(),m&&a.debug({err:u},`Could not resolve target through CSS selectors only (x${p})`),await Q(500,s)}}return d||(d=await this.resolveTargetHelper({root:l,target:t,cssSelectorOnly:!1,skipFetchTree:o,logger:a,signal:s}),t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),a.debug({decisions:d.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:i,elementLocationDecisions:d?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),d}async resolveTargetHelper({root:e,target:t,cssSelectorOnly:n,skipFetchTree:o,logger:i,signal:a,skipSaveToCache:s}){let l=[],c;o||(c=(await this.getBrowserState({logger:i,abortSignal:a,skipWait:!0})).serialize(),i.debug({tree:c.length>4e5?c.slice(0,4e5):c},"Got a11y tree before attempting target resolution"));let p=this.stateManager.a11yIdToNodeMap[t.id],d=p?.getNodeOnlySerializedForm();if(!o&&!this.flagStore.isBooleanFlagEnabled("visual_actions")&&p&&t.serializedForm&&d===t.serializedForm){let u=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:e,node:p});return s||await this.saveNodeDetailsToCache({node:p,target:t,dataMomenticId:p.dataMomenticId,locator:u,logger:i,generateNewCssSelectors:!1}),l.push({type:"A11Y_ID",matched:!0,reason:`An element with the same Chrome-internal accessibility node ID matched the saved content exactly: ${d}.`}),{locator:u,a11yNode:p,displayString:d,decisions:l,pageState:void 0}}let m;if(t.generatedSelectors){let u;try{u=await this.resolveTargetUsingCssSelectors({root:e,target:t,logger:i})}catch(h){m=h}if(u)return{...u,pageState:void 0,decisions:[...l,...u.decisions]};n||(l.push({type:"CSS_SELECTOR",matched:!1,reason:m?.message,selectors:Tb(t.generatedSelectors)}),t.generatedSelectors=void 0)}if(n)throw m;if(!this.flagStore.isBooleanFlagEnabled("disable_secondary_cache_resolution")){let u=await this.resolveTargetWithSecondaryMethods({root:e,tree:c,target:t,decisions:l,logger:i,signal:a,skipSaveToCache:s});if(u)return u}throw i.debug({target:t,decisions:l},"Failed to find any relevant node"),new Jn(`Could not find any relevant node given target: ${JSON.stringify(t)}`,l)}async resolveHardcodedCssSelector(e){let{ctx:t,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,s=await this.getActivePageOrFrame(),l=Date.now(),c=0,p,d=[];for(;Date.now()-l<a;){i?.throwIfAborted(),c++;let m=s.locator(n),u;try{return await m.waitFor({state:"attached",timeout:1e3}),u=await gn(m,o)??"",d.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${n} matched an element on the page.`}),t?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:d,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:m,displayString:u,decisions:d}}catch(h){let g=h.message;p=new A("ActionFailureError",`CSS selector '${n}' failed to resolve after ${c} attempts: ${g.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":g}`),await Q(500,i)}}throw p}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let t=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!t)return;let{x:n,y:o,width:i,height:a}=e.target.boundingBox,s=await t.locator.boundingBox({timeout:1e3});if(!s){this.logger.debug({proposedNode:t.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:l,y:c,width:p,height:d}=s;if(Math.abs(p-i)>50||Math.abs(d-a)>50){this.logger.debug({newW:p,oldW:i,newH:d,oldH:a,proposedNode:t.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(n&&o&&(!l||!c)){this.logger.debug({oldX:n,oldY:o,proposedNode:t.displayString},"Rejecting secondary matching result due to new result not having x/y coords");return}else if(Math.abs((l??0)-(n??0))>200||Math.abs((c??0)-(o??0))>200){this.logger.debug({newX:l,newY:c,oldX:n,oldY:o,proposedNode:t.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return t}async resolveTargetWithSecondaryMethodsHelper({root:e,target:t,decisions:n,logger:o,signal:i,skipSaveToCache:a}){if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<10){let c="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:c})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let c=await qe({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:2e3,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"findClosestElementByLDist"}),p=Math.floor(.05*t.nodeOnlySerializedHtml.length);if(c&&c.closestDistance&&c.closestDistance>=p){let d=`Closest HTML candidate still has too far distance (${c.closestDistance}) from threshold (${p})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:c.closestDistance,closestElement:c.closestNodeSerialized})}else{if(c?.error)throw new Error(c.error);if(c?.dataMomenticId||c?.mPathSelector){let d=c.dataMomenticId?parseInt(c.dataMomenticId):void 0,m,u;if(d)m=this.stateManager.dataMomenticIdToNodeMap[d],u=e.locator(`[${wt}="${d}"]`);else if(c.mPathSelector)m=this.stateManager.getNodeUsingMPathSelector(c.mPathSelector),u=e.locator(c.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let h=c.closestNodeSerialized??await gn(u,o)??"unknown element";return o.warn({result:c,originalTarget:t,displayString:h},"Resolved cached target to new node with pure html levenshtein distance"),a||await this.saveNodeDetailsToCache({node:m,target:t,dataMomenticId:d,locator:u,logger:o,generateNewCssSelectors:!0}),n.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${p} string comparison distance of the saved element.`,logs:c.logs,distance:c.closestDistance,closestElement:h,savedElement:t.nodeOnlySerializedHtml}),{locator:u,a11yNode:m,displayString:h,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(c)}`)}}catch(c){o.debug({err:c},"Failed to find closest HTML node using levenshtein distance"),n.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${c}`})}let s=t.screenshotUrl,l=t.role??"";if(s&&np.includes(l))try{let c=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:s,signal:i,skipSaveToCache:a});return{...c,decisions:[...n,...c.decisions],pageState:void 0}}catch(c){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${c}`,elementImageUrl:s}),o.warn({err:c},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({root:e,screenshotUrl:t,oldTarget:n,signal:o,skipSaveToCache:i}){let a;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let s=await this.screenshot({retries:0}),c=await(await fetch(t)).arrayBuffer(),p=fk(),d=await this.enricher.runTemplateMatching({id:p,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:s.toString("base64")},{signal:o});this.logger.debug({id:p,templateMatch:d},"Template matching got successful result");let{target:m,locator:u}=await this.getTargetFromPositionPercentages({percentX:d.x,percentY:d.y}),h=m.boundingBox?.width,g=m.boundingBox?.height;if(!h||!g)throw a="Rejecting target from screenshot due to no bounding box",new Error(a);let f=m.id,S=this.stateManager.a11yIdToNodeMap[f];return i||await this.saveNodeDetailsToCache({target:n,node:S,locator:u,dataMomenticId:f,generateNewCssSelectors:!0}),{locator:u,a11yNode:S,displayString:m.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:t}]}}async resolveTargetWithXY(e,t=!1){if(this.logger.debug({target:e,skipFetchTree:t},"Resolve target through x / y positioning called"),!t){let a=(await this.getBrowserState({})).serialize()}let n=await this.getActivePageOrFrame(),{target:o}=await this.getTargetFromPixelPosition(e);if((o.generatedSelectors??[]).length>0)return{locator:n.locator(o.generatedSelectors[0]),a11yNode:this.stateManager.a11yIdToNodeMap[o.id],displayString:o.nodeOnlySerializedHtml??o.nodeOnlySerializedForm??"Unknown element",decisions:[]};let i=this.stateManager.a11yIdToNodeMap[o.id];if(i&&i.dataMomenticId)return{locator:n.locator(`[${wt}="${i.dataMomenticId}"]`),a11yNode:i,displayString:i.getNodeOnlySerializedForm(),decisions:[]};throw new Error("Could not resolve target with x / y through either raw HTML or the accessibility tree")}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:1e3})??"",i=ib.some(a=>a===o.toLowerCase());return await bp({targetingResult:t,options:{force:n.force},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:i?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks(),flagStore:this.flagStore}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,t,n={}){return bp({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks(),flagStore:this.flagStore})}async waitForUrl({beforeUrl:e,matcher:t,beforePages:n},o){let i=o?.timeout??this.pageLoadTimeout,a=Date.now();n||(n=(await ri(this.context)).map(p=>p.url));let s=!1,l=[],c=e;for(;Date.now()-a<i;){this.abortSignal?.throwIfAborted(),l=(await ri(this.context)).map(d=>d.url);for(let d=l.length-1;d>=n.length;d--){let m=l[d];if(m!==e&&lr(m,this.logger)){ud(m,t,o)&&await this.switchToPage({type:"INDEX",index:String(d)});break}}if(c=(await this.getActivePageOrFrame()).url(),ud(c,t,o)){s=!0;break}await Q(500,this.abortSignal)}if(!s)throw new A("ActionFailureError",`The active page URL ${o?.negated?"still does":"does not"} ${ld(t)} in ${i}ms.
|
|
3602
3605
|
Current tab: ${c}
|
|
3603
3606
|
All tabs: ${l.join(`
|
|
3604
|
-
`)}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(p){this.logger.warn({err:p},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,t,r={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:1e3});if(!o)throw new R("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,s=o.y+o.height/2,a=r.steps??5;await this.page.mouse.move(i,s,{steps:a}),await te(r.hoverSeconds?Math.min(r.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,t,r,o){o&&await this.hover({locator:o});let i=await(await this.getActivePageOrFrame()).evaluate(Sp);i||(this.logger.debug("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:r}),await te(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await Yr({func:async t=>{await t.locator.scrollIntoViewIfNeeded({timeout:1e3});let r=await t.locator.boundingBox({timeout:1e3});if(!r)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(r.x+r.width/2,r.y+r.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await Yr({func:t=>t.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let t=await this.getActivePageOrFrame();await Ve({fn:()=>{let r=document.activeElement;r&&r.nodeType===1&&r.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurCommand"});return}await this.highlight(e.locator),await Yr({func:t=>t.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,t,r=!1){await this.highlight(e.locator),await Yr({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(t.type==="INDEX"){let i=Number(t.index);if(isNaN(i))throw new R("UserConfigurationError",`Page index ${t.index} is not a number`)}await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?Number(t.index):void 0},{force:r,timeout:3e3})},targetingResult:e})}async press(e,t){let r=t.repeat??1;if(t.convertMeta){let o=ub(e);o!==e&&(this.logger.debug({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<r;o++)await this.page.keyboard.press(e,{delay:t.delayMs??0})}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let r=0,o=2;for(;r<o;){r++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});break}catch(i){this.logger.warn({err:i,attempt:r},`Failed to reload page${r<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"})}async getBrowserState(e){let{logger:t=this.logger,maxAttempts:r=2,skipWaitForPageLoad:o}=e,i=e.abortSignal??this.abortSignal;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:t,signal:i});let s=0,a;for(;s<r;){s++;try{return await D(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:i,logger:t,filterByViewport:e.filterByViewport}),{milliseconds:this.pageLoadTimeout*s,signal:i,message:"Getting browser state took too long"})}catch(l){if(i?.throwIfAborted(),a=l instanceof Error?l.message:`${l}`,s>=r)throw l;t.debug({err:l,url:this.url()},"Error getting a11y tree, retrying...")}}throw new R("ActionFailureError",`Getting page content failed after ${r} attempts. Error: ${a}`)}async getViewportOffsetDetails(e){let[t,r,o,i,s]=await Ve({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:async()=>{},codePath:"getViewportOffsetDetails"});return{upperBound:t,lowerBound:t+i,leftBound:r,rightBound:r+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??s}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:r=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},s=u=>{i.value=Date.now()},a=()=>s("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",a);let l=()=>s("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>l);let c=()=>s("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",c);let p=()=>s("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",p);let d=()=>s("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",d);try{await this.waitForDOMStabilityHelper(i,t,r,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",a),this.cdpClient.removeListener("Page.frameDetached",l),this.cdpClient.removeListener("Page.frameStartedLoading",c),this.cdpClient.removeListener("Page.navigatedWithinDocument",p),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,r,o){let i=!1,s=Date.now(),a,l={quality:25,retries:0,hideCaret:!0,disableAnimations:!0},c=!1,p=0;for(;Date.now()-s<r;){if(o?.throwIfAborted(),await te(500,this.abortSignal),a)try{let u=await this.screenshot(l);if(!u.equals(a)){a=u,c=!1;continue}c=!0}catch(u){p++,p%3===0&&t.warn({err:u,screenshotErrors:p},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{a=await this.screenshot(l)}catch(u){p++,p%3===0&&t.warn({err:u,screenshotErrors:p},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<750)){i=!0;break}}let d={duration:Date.now()-s,a11yStableReceived:i,lastTreeUpdateMillisecondsAgo:Date.now()-e.value,screenshotStable:c};i||t.warn(d,"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,t){let{x:r,y:o}=e,i=this.url(),s=(await Qo(this.context)).map(a=>a.url);this.logger.debug({x:r,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(r,o,{button:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1}),t.waitForUrl&&await this.waitForUrl({beforeUrl:i,beforePages:s,matcher:{type:"GLOB",glob:t.waitForUrl}})}async dragAndDropUsingVisualCoordinates(e,t,r){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await te(r.hoverSeconds?Math.min(r.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,t,r,o){await this.hoverUsingVisualCoordinates(o);let i=await(await this.getActivePageOrFrame()).evaluate(Sp);i||(this.logger.debug("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:r}),await te(250),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),r=await D(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&r===1&&(r=2);let o=t.documents[0],i=o.layout,s=o.nodes,a=s.nodeName||[],l=s.backendNodeId||[],c=i.nodeIndex,p=i.bounds,d=-1;for(let x=0;x<a.length;x++)if(l[x]===e){d=c.indexOf(x);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[u=0,m=0,h=0,g=0]=p[d];u/=r,m/=r,h/=r,g/=r;let f=u+h/2,S=m+g/2;return{centerX:f,centerY:S}}async scrollVertical(e){return vp({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:0,directionX:null,deltaY:e?Math.abs(e):null,directionY:e&&e>0?"down":"up",signal:this.abortSignal,callbacks:this.getBrowserCallbacks()})}async scrollHorizontal(e){return vp({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks()})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout})}async createRawCDPSession(e){let t=await D(this.context.newCDPSession(this.page),{milliseconds:e??this.pageLoadTimeout,fallback:()=>{throw this.logger.error(`Timed out creating new CDP session for ${this.page.url()}`),new R("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${this.page.url()})`)}});return this.logger.debug(`Created new CDP session for ${this.page.url()}`),t}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async changeActivePage(e,t){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let r=await this.context.newPage();await this.changeActivePage(r,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let r=!0,o,i=Date.now();for(;r||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){r=!1;try{await this.switchToPageHelper(e,t);return}catch(s){this.logger.warn({err:s},"Error switching to page, retrying..."),o=s,await te(500)}}throw o}async switchToPageHelper(e,t){let r=this.context.pages().map((i,s)=>({page:i,url:i.url(),index:s})),o;if(e.type==="INDEX"){let i=Number(e.index);if(isNaN(i))throw new R("UserConfigurationError",`Page index ${e.index} is not a number`);if(i<0||i>=r.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(r.map(s=>s.url))}`);o=r[i]}else{let i=r.filter(s=>e.type==="SUBSTRING"?s.url.includes(e.substring):s.url.match(e.pattern));i.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(i.map(s=>s.url))}`),o=i[i.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
|
|
3605
|
-
Available pages:${JSON.stringify(r.map(i=>i.url))}`);if(!ar(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.debug(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,t?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let t;return typeof e=="string"?t=ga(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let r=await this.getActivePageOrFrame();await D(r.evaluate(([o,i])=>{o&&localStorage.setItem(o,i||"")},[e,t]),{milliseconds:2e3})}async solveCaptcha(){await this.getBrowserState({});let e;for(let a of Object.values(this.stateManager.a11yIdToNodeMap))if(a.role==="image"&&a.name.toLowerCase().includes("captcha")){if(!a.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,a.backendNodeId);break}if(!e){let a=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!a.captchas||!a.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),r=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:El,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!r.ok){let a=`Captcha solver API returned error response: ${r.statusText}`;throw this.logger.error({text:await r.text()},a),new Error(a)}let{taskId:o}=await r.json(),i=Date.now(),s="";for(;Date.now()-i<6e4;){await te(2500);let a=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:El,taskId:o})});if(!a.ok){let c=`Captcha solution API returned error response: ${a.statusText}`;throw this.logger.error({text:await a.text()},c),new Error(c)}let l=await a.json();if(l.errorId){let c=`Captcha solution API returned error ID ${l.errorId}`;throw this.logger.error(c),new Error(c)}if(l.status==="ready"){s=l.solution.text;break}}if(!s)throw new Error("Captcha solution timed out");return s}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&wb({event:t,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async startRecordingCrons(e){if(e.aborted)return;let t,r=(await this.getOpenPages()).map(a=>a.url),o=0,i=!1,s=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let a;try{a=(await this.getOpenPages()).map(c=>c.url),o=0}catch(c){this.logger.debug({err:c},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let l=this.url();for(let c=a.length-1;c>=r.length;c--){let p=a[c];ar(p,this.logger)&&p!==l&&this.logger.info({lastActivePages:r,currentUrl:l,newOpenPages:a},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(c)});break}r=a};t=setInterval(async()=>{if(!i){i=!0;try{await s()}catch(a){this.logger.error({err:a},"Error while checking pages during recording")}finally{i=!1}}},500),e.addEventListener("abort",async()=>{clearInterval(t)})}async startRecording(e,t,r){this.logger.debug({isClickToRecord:r},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(o=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!0,i._MOMENTIC_CLICK_RECORD_ACTIVE=o},r),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page),e.addEventListener("abort",async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let o=window;o._MOMENTIC_RECORDING_ACTIVE=!1,o._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}})}async getSelectOptions(e){return await e.evaluate(r=>Array.from(r.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:1e3})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:r}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await Br({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomLoad-${r}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(s){let a=s;if(a.name==="AbortError")throw new Error(`The page with URL ${Me(i,50)} did not load within the configured timeout (${o}ms): ${a}`);if(!a.message.includes("detached"))throw a}try{await Br({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlPageLoad-${r}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(s){this.logger.warn({err:s,codePath:r,url:i},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return IO.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:t,error:r}=await Ve({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getCondensedHtmlTree"});if(r)throw new Error(`Failed to process page HTML: ${r}`);if(!t)throw new R("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}async registerDialogHandler(e){let t=async r=>{try{e==="ACCEPT"?await r.accept():await r.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",t)}async evaluateFunctionInAllFrames(e,t){return this.stateManager.executeFunctionInAllFrames(e,t)}async evaluateFunctionInPage(e,t){let r=await this.getActivePageOrFrame();return D(r.evaluate(e,t),{milliseconds:2e3})}async evaluateCodeInPage({code:e,fragment:t,context:r,timeoutMs:o=Kn}){let i=ob(),s={code:e,fragment:t,context:r},{result:a}=await D(this.page.evaluate(i,s),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new R("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return a}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let r;try{r=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return r}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:r}){if(t<0||t>1||r<0||r>1)throw new R("InternalWebAgentError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:s,leftBound:a}=await this.getViewportOffsetDetails(e),l=Math.round(s),c=Math.round(a),p=Math.ceil(o*t),d=Math.ceil(i*r),u=p+c,m=d+l;return this.getDomNodeFromPixelPosition(u,m)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),r;try{r=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return r?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:ky,backendNodeId:r.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:1e3,method:"Overlay.hideHighlight",params:{backendNodeId:r?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:1e3})}catch{}}async getTargetFromPixelPosition(e,t=!0){let r=await this.getActivePageOrFrame(),o=await this.getDomNodeFromPixelPosition(e.x,e.y);return this.getTargetFromBackendNodeId(r,o.backendNodeId,t)}async getTargetFromPositionPercentages(e,t=!0){let r=await this.getActivePageOrFrame(),o=await this.getDomNodeFromPositionPercentages(r,e);return this.getTargetFromBackendNodeId(r,o.backendNodeId,t)}async getTargetFromBackendNodeId(e,t,r){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[wt],s=parseInt(i??"");if(!i||isNaN(s))throw new Error("No data-momentic-id was found on the DOM node");let a=e.locator(`[${wt}="${i}"]`);if(r){for(let d of Object.values(this.stateManager.a11yIdToNodeMap)){if(d.backendNodeId!==t)continue;let u={id:d.id,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString()};return await this.saveNodeDetailsToCache({node:d,target:u,dataMomenticId:parseInt(i),locator:a}),this.logger.debug({target:u},"Tied backend id to existing a11y node"),{target:u,locator:a}}let p=ul(`${i}`,this.stateManager.domGraph,this.logger);for(let d of p){let u=parseInt(d.attributes?.[wt]??"");if(isNaN(u))continue;let m=e.locator(`[${wt}="${u}"]`),h=this.stateManager.dataMomenticIdToNodeMap[u],g=h?.id;if(!g)continue;let f={id:g,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString()};return await this.saveNodeDetailsToCache({node:h,target:f,dataMomenticId:parseInt(i),locator:m}),this.logger.debug({target:f},"Tied backend id on non-accessible element to nearest a11y node"),{target:f,locator:m}}}let l=await this.fetchHtmlAttributes(a,this.logger),c={id:-1,dataMomenticId:s,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...l};return this.logger.debug({target:c},"Tied backend id to html node"),{target:c,locator:a}}async performTargetRedirection(e,t,r){try{return await e.scrollIntoViewIfNeeded({timeout:3e3}),await D(this.performTargetRedirectionHelper(e,t,r),{milliseconds:3e3})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,r){let o=Date.now(),i=await gn(e,t);if(r===void 0&&(r=await e.boundingBox({timeout:1e3})),!r){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:s,y:a,width:l,height:c}=r,p=this.getViewport();if(s<0||a<0||s+l>p.width||a+c>p.height){t.debug("Skipping locator redirection because the element is outside the viewport");return}let d=await this.getActivePageOrFrame(),{dataMomenticId:u,mPathSelector:m,error:h,serializedElement:g,point:f,force:S,logs:x}=await e.evaluate(b=>{let E=window;if(!E.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return E.performTargetRedirection(b)},void 0,{timeout:1e3}),v=Date.now()-o;if(h){t.warn({error:h,serializedElement:g,duration:v,force:S,logs:x},"Got error from target redirection with bounding box");return}else{if(u)return t.debug({newDataMomenticId:u,serializedElement:g,duration:v,force:S,logs:x},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(`[data-momentic-id="${u}"]`),hints:{clickableXY:f,force:S}};if(m)return t.debug({newMPathSelector:m,serializedElement:g,duration:v,force:S,logs:x},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(m),hints:{clickableXY:f,force:S}};if(f)return t.debug({point:f,serializedElement:g,duration:v,force:S,logs:x},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:S}};if(S)return t.debug({serializedElement:g,duration:v,force:S,logs:x},"Forcing click on original element"),{locator:e,hints:{force:S}}}}async fetchHtmlAttributes(e,t=this.logger){let r=await e.evaluate(o=>{let i=window;return i.generateHtmlCacheAttributes?i.generateHtmlCacheAttributes(o):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},void 0,{timeout:2e3});if("error"in r)throw new Error(r.error);return r.warnings.length?t.warn(r,"Got warnings while generating HTML attributes for target"):t.debug(r,"Generated HTML attributes for target"),r.attributes??{}}async moveMouseFromPositionPercentages(e,t){let r=Math.ceil(this.viewport.width*e),o=Math.ceil(this.viewport.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:r,y:o,button:"left",clickCount:0}}),{x:r,y:o}}async clickMouseFromPositionPercentages(e,t,r){let o=Math.ceil(this.viewport.width*t),i=Math.ceil(this.viewport.height*r);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:o,y:i,button:"left",clickCount:e==="down"?1:0},timeout:1e3})}async scrollFromPositionPercentages(e,t,r,o){let i=Math.ceil(this.viewport.width*e),s=Math.ceil(this.viewport.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:i,deltaY:s,x:r,y:o}}),{deltaX:i,deltaY:s}}canSolveCaptchas(){return!!El}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,t,r,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,fp(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${r}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!Tl(e)){let l=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(l),this.logToUserConsole(this.page,"error",l);return}let r=t?.trim()||kO(e),o=CO(e),i=NO(e),s=Qc[i];this.page.once("filechooser",async l=>{this.logger.info({filePath:e,fileName:r},"File chooser triggered");try{if(!Tl(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await l.setFiles({name:r,buffer:o,mimeType:Cy.getType(e)||"application/octet-stream"},{timeout:8e3})}catch(c){this.logger.error({err:c},"Error handling file chooser"),this.logToUserConsole(this.page,"error",c.message)}});let a=o.toString("base64");await(await this.getActivePageOrFrame()).evaluate(({fileName:l,base64Data:c,mimeType:p})=>{let d=window;d.momenticFileName=l,d.momenticFileBase64=c;let u=atob(c),m=new Array(u.length);for(let g=0;g<u.length;g++)m[g]=u.charCodeAt(g);let h=new Uint8Array(m);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([h],{type:p})}isSameEntry(g){return g.name===this.name}queryPermission(g){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(g){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let g=new Blob([h]);return new File([g],d.momenticFileName,{type:p})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},d.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new d.MomenticFile])},{fileName:r,base64Data:a,mimeType:s})}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){let e={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},e}async copy(e){try{await this.evaluateFunctionInPage(t=>navigator.clipboard.writeText(t),e)}catch(t){if(t instanceof Error&&t.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(r=>navigator.clipboard.writeText(r),e);return}throw t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(new RegExp(e))}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}};import tk from"fetch-cookie";import{cloneDeep as nk}from"lodash-es";import{CookieJar as rk}from"tough-cookie";import{z as vt}from"zod";var Pne=vt.object({doubleClick:vt.boolean().optional(),rightClick:vt.boolean().optional(),force:vt.boolean().optional(),waitForDownload:vt.boolean().optional(),waitForUrl:vt.string().optional(),delayMs:vt.number().optional(),downloadTimeoutMs:vt.number().optional(),relativePosition:vt.object({x:vt.number(),y:vt.number()}).optional()}),Lne=vt.object({repeat:vt.number().optional(),convertMeta:vt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:vt.number().optional()});var Op=(n,e,t)=>{let[r,...o]=e.split("."),i=r;return o.length>=1?Op(n[i],o.join("."),t):n[i]=t,n};async function ur(n,e={}){let t=await n.getBrowserState(e),r=t.serialize();return e.logger?.debug({tree:r.length>4e5?"REDACTED_DUE_TO_LENGTH":r,activeFrame:n.getActiveFrameConfig()},"Got a11y tree"),{serializedTree:r,tree:t}}var ni=3.1783027;function zO(n){let e=0;for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);!(r>=48&&r<=57)&&!(r>=65&&r<=90)&&!(r>=97&&r<=122)&&e++}return e}function Es(n){return Math.ceil(kp(n)/ni)}function kp(n){let e=0;if(typeof n=="string"){let t=n;t=t.replaceAll(`
|
|
3606
|
-
`,""),t=t.replaceAll(" ","");let
|
|
3607
|
-
`),c=0,p=[],d=0,
|
|
3608
|
-
`),tokenLength:d}),p=[],d=0,u
|
|
3609
|
-
`),tokenLength:d}),
|
|
3610
|
-
${n}`;default:return n}}var XO=15;async function Up({command:n,fixtures:e}){if(!n.assertion.trim())throw new R("ActionFailureError","Assertion command is missing the assertion content");let{browser:t,logger:r}=e,o=n.timeout?n.timeout*1e3:t.smartWaitingTimeout,i=ZO(o),s=0,a=Date.now(),l,c,p;try{await Cn({action:()=>t.clearHighlights(),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:t,logger:r})}catch(u){r.warn({err:u},"Failed to clear highlights before AI assertion, continuing...")}let d;for(;s<XO&&(!d||d-a<o);){e.abortSignal.throwIfAborted(),s!==0&&(r.info(`Waiting ${i}ms before retrying AI assertion`),await te(i,e.abortSignal)),d=Date.now();try{let u=await Cn({action:async()=>{let m=await Qb(t,r,e.abortSignal);return c&&c.serializedTree===m.serializedTree&&c.screenshotBuff.equals(m.screenshotBuff)?!1:(c=m,ew({command:n,state:m,fixtures:e,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:s}))},frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,logger:r,browser:t});if(!u)continue;l=u;break}catch(u){e.abortSignal.throwIfAborted(),p=u instanceof Error?u:new Error(`${u}`),r.info({err:u},`AI_WAIT assert attempt ${s} failed, retrying...`)}finally{s++}}if(!l)try{l=await Cn({action:async()=>ew({command:n,state:await Qb(t,r,e.abortSignal),fixtures:e,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:s}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,logger:r,browser:t})}catch(u){e.abortSignal.throwIfAborted(),p=u instanceof Error?u:new Error(`${u}`)}finally{s++}if(!l){let u=`AI assertion still failing after ${s} attempts.`;throw p&&(u+=` Latest result: ${p.message}`),new R("AssertionFailureError",u,{lastScreenshotBuffer:c?.screenshotBuff})}return l}async function Qb(n,e,t){let[r,o]=await Promise.all([ur(n,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),n.screenshot({retries:1,respectActiveFrame:!0})]);return{...r,screenshotBuff:o}}async function ew({command:n,state:e,fixtures:t,useConsensus:r,highlightElementsOnFailure:o,attemptNumber:i}){let{browser:s,logger:a,generator:l,abortSignal:c}=t,p={type:"ASSERTION"},{serializedTree:d,tree:u}=e,m=e.screenshotBuff,h=s.url(),g=d;g=await Xr({type:"assertion",serializedTree:d,description:n.assertion,flagStore:t.flagStore,tree:u,generator:l,logger:a,signal:c}),g!==d&&(p.ragUsed=!0),p.pageState=g;let f={goal:n.assertion,url:h,browserState:g,screenshot:m.toString("base64"),contextChoice:n.contextChoice},x=await(n.contextChoice==="VISION_ONLY"?(v,b)=>l.getVisualAssertionResult(v,b):(v,b)=>l.getAssertionResult(v,b))(f,{useConsensus:r,attemptNumber:i,disableCache:!!n.disableCache,logger:a,abortSignal:c,loggerTags:We(a)});if((x.result||o)&&x.relevantElements&&(p.relevantElementsSerialized=x.relevantElements.map(v=>s.getSerializedFormFromA11yId(v)).filter(v=>!!v),await QO(x.relevantElements,s,a)),!x.result)throw new R("AssertionFailureError",x.thoughts);return{succeedImmediately:!1,thoughts:x.thoughts,urlAfterCommand:h,afterScreenshotOverride:m}}function ZO(n){let e;return n>10*60*1e3?e=2*60*1e3:n>60*1e3?e=20*1e3:n>10*1e3?e=2*1e3:e=1e3,e}async function QO(n,e,t){let r=Date.now();for(let o of n){if(Date.now()-r>2e3){t.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await D(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var ek=3e4;async function tw({command:n,logger:e,baseUrl:t,fetchImplementation:r=fetch}){let o=n.timeout??ek/1e3,i=new AbortController,s=Object.fromEntries(Object.entries(n.headers||{}).filter(([d,u])=>d&&u)),a;if(Jo(n.url)&&(a=n.url),t&&Xo(n.url,t)&&(a=new URL(n.url,t).toString()),!a)throw new R("ActionFailureError",`Invalid URL: ${n.url}`);let c=await D((async()=>{try{return await r(a,{headers:s,method:"POST",body:JSON.stringify({query:n.query,variables:n.variables}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!c)throw new R("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!c.ok){let d;try{d=await c.json()}catch{throw new R("ActionFailureError",`GraphQL request failed with status ${c.status}: ${await c.text()}`)}throw d?.errors?.length&&d?.errors[0]?.message?new R("ActionFailureError",`GraphQL request failed with status ${c.status}: ${d.errors[0].message}`):new R("ActionFailureError",`GraphQL request failed with status ${c.status}: ${await c.text()}`)}let p={};return c.headers.forEach((d,u)=>{p[u]=d}),{status:c.status,headers:p,json:await c.json()}}var ri=class{flagStore;orgId;scratchPadId;slowMoMs;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;analytics;recordAbortController=null;registeredListeners={};constructor({browser:e,generator:t,logger:r,analytics:o,flagStore:i,storage:s,orgId:a,localCodeEvalTools:l,uploadedFileStorage:c,visualDiffScreenshotStorage:p,scratchPadId:d,slowMoMs:u}){this.orgId=a,this.scratchPadId=d,this.slowMoMs=u,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=s,this.uploadedFileStorage=c,this.visualDiffScreenshotStorage=p,this.localCodeEvalTools=l,this.generator=t,this.logger=r,this.analytics=o,this.flagStore=i}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}setLogger(e){this.logger=e}async evaluateAiAction({goal:e,startingScreenshot:t,history:r,disableCache:o,langfuseSessionId:i,lastError:s,logger:a=this.logger}){let[l,c]=await Promise.all([ur(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),p=await Xr({type:"ai-action",description:e,serializedTree:l.serializedTree,tree:l.tree,logger:a,generator:this.generator,flagStore:this.flagStore,softTokenLimit:25e3,hardTokenLimit:5e4}),d=`data:image/jpeg;base64,${c.toString("base64")}`,u={url:this.browser.url(),browserState:p,startingScreenshot:t,history:r,goal:e,screenshot:d,lastError:s};return await this.generator.getMultiturnAiActionEvaluation(u,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...We(a)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:r,actionHint:o,disableCache:i,logger:s=this.logger,langfuseSessionId:a}){let l=this.browser.url(),[c,p]=await Promise.all([ur(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${p.toString("base64")}`,u=await Xr({type:"ai-action",description:e,serializedTree:c.serializedTree,tree:c.tree,logger:s,generator:this.generator,flagStore:this.flagStore,softTokenLimit:25e3,hardTokenLimit:5e4}),m={url:l,browserState:u,startingScreenshot:t,history:r,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...We(s)},langfuseSessionId:a})}catch(h){throw new R("InternalWebAgentError",`Error generating command: ${h instanceof Error?h.message:h}`,{errOptions:{cause:h}})}}async getBrowserState(e){return ur(this.browser,e)}async locateElement(e){return Dp(e,this.getControllerFixtures())}async locateElementWithSelector(e,t){return Cn({action:async()=>{let r=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:r}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,flagStore:this.flagStore,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:r,targetNames:o,descriptions:i,caches:s,action:a,options:l,retriesWithAI:c=1}){let p=[];for(let d=0;d<i.length;d++){let u=i[d],m=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:r,target:u,cache:s[d],action:async h=>h,options:{...l,skipFetchTree:d!==0,targetName:o[d]}});p.push(m)}try{return{result:await a(...p.map(u=>u.result)),elementInteractedDisplayStrings:p.map(u=>u.elementInteractedDisplayString),newTargets:p.map(u=>u.newTarget)}}catch(d){if(this.throwIfClosed(),c>0)return this.logger.debug({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:r,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:a,options:l,retriesWithAI:c-1});throw new R("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let t=this.logger.child({commandId:e.command.id}),r;for(let o=0;o<2;o++)try{return await Cn({action:()=>this.wrapElementTargetingCommandHelper(e),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:t})}catch(i){if(r=i,this.flagStore.isBooleanFlagEnabled("visual_actions")&&Zc(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.flagStore.isBooleanFlagEnabled("visual_actions")&&Hi(i)){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}throw i}throw r instanceof R?r:new R("ActionFailureError",r?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:r,options:o,command:i}){let s=this.logger.child({commandId:i.id}),{targetName:a="target"}=o;if(t.type!=="description")throw new R("ActionFailureError","Cannot use selector with non-description target");let l=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:a,logger:s});return{result:await r({locator:l.locator}),elementInteractedDisplayString:l.displayString,newTarget:{cache:{id:-1,selector:t.elementDescriptor,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()}}}}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:r,target:o,action:i,options:s,command:a}=e,{disableCache:l,useSelector:c,targetName:p="target",targetHealingInProgress:d,source:u}=s,m=this.logger.child({commandId:a.id}),h=s.retriesWithAI??1,g=!1,f=e.cache;if((!f||l)&&!sc(o))throw new R("ActionFailureError","Cannot target element with no cached data or element descriptor");if(c)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(m.debug("Cache explicitly disabled for this step"),g=!0,f=void 0),f?.inputDescription&&!Zb(o.elementDescriptor,f.inputDescription)&&(m.warn({old:f.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),g=!0,f=void 0);let S=!!f&&Fu(f);if(!f){let x=new Date;m.debug({targetHealingInProgress:d},"Prompting AI for an updated element location"),g&&await te(this.browser.smartWaitingTimeout,this.executeAbortController.signal),h--;let v=await Dp({description:o.elementDescriptor,disableCache:l,iframeUrl:s.iframeUrl,source:u},this.getControllerFixtures(t));v.frameConfig&&this.browser.setActiveFrameConfig(v.frameConfig);let b=s.disableGlobalLocatorRedirect?{locator:v.resolution.locator}:await this.attemptLocatorRedirect(v.resolution.locator,m),E=await i(b),C;if(d){r.heal({healType:"AI"}),this.analytics.track({type:"execution:step_heal",heal_type:"AI",step_type:"PRESET_ACTION",command_type:a.type,duration_ms:Date.now()-x.getTime()}),v.target.targetSource="AI_HEALED",v.target.targetUpdateTime=new Date().toUTCString();let I=v.resolution.pageState;if(I)try{C=await this.getReverseMappedDescription({browserState:I,targetId:v.target.id,disableCache:!0,screenshot:v.screenshot})}catch(_){m.warn({err:_},"Failed to reverse map element auto-healed by AI, continuing...")}}return{result:E,elementInteractedDisplayString:v.resolution.displayString,newTarget:{cache:v.target,thoughts:v.thoughts,description:C}}}try{let x=new Date;if(f.frameCache&&this.flagStore.isBooleanFlagEnabled("auto_expand_iframes")){let C=await this.browser.resolveAutoFrameCache(f.frameCache);this.browser.setActiveFrameConfig(C)}let v=await this.browser.resolveTarget(t,f,{targetName:p,logger:m}),b=s.disableGlobalLocatorRedirect?{locator:v.locator}:await this.attemptLocatorRedirect(v.locator,m),E=await i(b);if(S){let C=v.decisions.filter(I=>I.matched);if(C.length!==1)m.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let I=C[0].type;r.heal({healType:I}),this.analytics.track({type:"execution:step_heal",heal_type:I,step_type:"PRESET_ACTION",command_type:a.type,duration_ms:Date.now()-x.getTime()})}}return{result:E,elementInteractedDisplayString:v.displayString,newTarget:{cache:f}}}catch(x){this.throwIfClosed();let v=xh(x)&&!Zc(x)&&!Hi(x);if(x instanceof R&&!v)throw x;if(h>0&&o)return m.debug({err:x,cache:f},"Failed to execute action with cached target, retrying with AI"),this.wrapElementTargetingCommand({ctx:t,tracer:r,command:a,target:o,cache:void 0,action:i,options:{...s,retriesWithAI:h,targetHealingInProgress:!0}});throw new R("ActionFailureError",x.message,{errOptions:{cause:x}})}}async attemptLocatorRedirect(e,t){return this.flagStore.isBooleanFlagEnabled("global_locator_redirect")?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return bs(this.browser,e)}async executePresetCommand(e,t,r,o,i){this.slowMoMs&&await te(this.slowMoMs);let s;try{s=await this.resolveCommandTemplateStrings(r,o)}catch(a){throw this.throwIfClosed(),new R("ActionFailureError",`Failed to substitute template strings in command: ${a.message}`,{errOptions:{cause:a}})}try{let a=(await this.browser.getOpenPages()).map(m=>m.url),l=this.browser.url(),c=await this.executePresetCommandHelper(e,t,r,o,i);this.flagStore.isBooleanFlagEnabled("visual_actions")&&zu(r)?await this.browser.waitForDOMStability():this.flagStore.isBooleanFlagEnabled("visual_actions")&&["PRESS","TYPE"].includes(r.type)&&await this.browser.waitForDOMStability({timeout:1e3});let p=!0;(r.type==="NAVIGATE"||r.type==="NEW_TAB"||r.type==="TAB"||r.type==="REFRESH"||r.type==="WAIT_FOR_URL")&&(p=!1);let d=(await this.browser.getOpenPages()).map(m=>m.url),u=this.browser.url();if(p&&d.length!==a.length)for(let m=d.length-1;m>=a.length;m--){let h=d[m];if(ar(h,this.logger)&&h!==l&&h!==u){this.logger.info({beforePages:a,afterPages:d,beforeUrl:l},"Auto-following new tab after preset action"),await this.browser.switchToPage({type:"INDEX",index:String(m)});break}}return c}catch(a){throw a.name!=="AbortError"&&this.logger.error({err:a},"Error thrown in action controller"),a}finally{this.restoreCommandTemplateReplacements(r,s)}}restoreCommandTemplateReplacements(e,t={}){for(let[r,o]of Object.entries(t))Op(e,r,o)}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>hp(e)}}async resolveCommandTemplateStrings(e,t){return Yo({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools,flagStore:this.flagStore})}async executePresetCommandHelper(e,t,r,o,i){switch(i=i||"disableCache"in r&&!!r.disableCache,r.type){case"SUCCESS":let s=r.condition;return s?.assertion.trim()?Up({command:s,fixtures:this.getControllerFixtures(e)}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_WAIT":case"AI_ASSERTION":{if(!r.assertion.trim())throw new R("ActionFailureError","Missing assertion");if(r.timeout&&r.timeout>1800)throw new R("AssertionFailureError",`AI assertion timeout of ${r.timeout} exceeds the maximum allowed value of 30 minutes.`);return Up({command:{...r,type:"AI_ASSERTION"},fixtures:this.getControllerFixtures(e)})}case"AI_EXTRACT":{if(!r.goal.trim())throw new R("ActionFailureError","Cannot perform AI extraction without goal");let m=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let g=await this.generator.getTextExtraction({goal:r.goal,browserState:m,returnSchema:r.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:We(this.logger)});if(g.result==="NOT_FOUND")throw new R("ActionFailureError","No relevant data found for extraction goal on this page");if(g.thoughts?.includes("MaxGenerationLengthExceededError"))throw new R("UserConfigurationError",g.thoughts);return{thoughts:g.thoughts||void 0,data:g.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(g){let f=g.message;throw f.includes("MaxGenerationLengthExceededError")?new R("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):f.includes("AIProviderError")&&f.includes("time")?new R("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:g}}):g}}case"NAVIGATE":if(!Jo(r.url)&&!Xo(r.url,this.browser.baseUrl))throw new R("ActionFailureError",`Invalid URL provided to navigate command: ${r.url}`);await this.browser.navigate({url:r.url,loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(r.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let a=await this.browser.solveCaptcha();a&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:r,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:m=>this.browser.click(m,this.createCallbacksForBrowser(this.orgId),{}),options:{disableCache:i,useSelector:!!r.useSelector,iframeUrl:r.iframeUrl}}),await this.browser.type(a,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let m,h=[];if(r.target&&yn(r.target))await this.browser.hoverUsingVisualCoordinates(r.target.pixels);else if(r.target&&r.target.elementDescriptor.trim()){let{newTarget:g,elementInteractedDisplayString:f}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:r,target:r.target,cache:r.cache?.target,action:S=>this.browser.hover(S),options:{disableGlobalLocatorRedirect:!0,disableCache:i,useSelector:!!r.useSelector,iframeUrl:r.iframeUrl}});m=f,h.push(g)}switch(r.type){case"SCROLL_UP":await this.browser.scrollVertical(-(r.deltaY??0));break;case"SCROLL_DOWN":await this.browser.scrollVertical(r.deltaY);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(r.deltaX??0));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(r.deltaX);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,newTargets:h}}case"WAIT_FOR_URL":{if(r.timeout&&r.timeout>1800)throw new R("UserConfigurationError",`Wait for URL timeout of ${r.timeout} exceeds the maximum allowed value of 30 minutes.`);let m=r.matcher;if(!m&&r.url&&(m={type:"GLOB",glob:r.url}),!m)throw new R("UserConfigurationError","No URL matcher provided for wait for URL command");await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:m},{timeout:r.timeout?r.timeout*1e3:void 0,negated:r.negated,caseInsensitive:r.caseInsensitive});break}case"WAIT":if(r.delay>1800)throw new R("UserConfigurationError",`Wait timeout of ${r.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=r.delay*1e3;await te(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"CLICK":{if(yn(r.target)){await this.browser.clickUsingVisualCoordinates(r.target.pixels,r);break}let m=this.browser.url(),h={disableCache:i,useSelector:!!r.useSelector,iframeUrl:r.iframeUrl},{elementInteractedDisplayString:g,newTarget:f,result:S}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:r.target,command:r,cache:r.cache?.target,action:v=>this.browser.click(v,this.createCallbacksForBrowser(this.orgId),r),options:h});f.cache&&(r.cache={target:f.cache});let x={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,newTargets:[f],data:S};return el(m,x.urlAfterCommand)&&(x.succeedImmediately=!0,x.succeedImmediatelyReason="URL changed"),x}case"COPY":return await this.browser.copy(r.value),{succeedImmediately:!1,data:r.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(yn(r.fromTarget)&&yn(r.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(r.fromTarget.pixels,r.toTarget.pixels,{hoverSeconds:r.hoverSeconds});break}if(yn(r.fromTarget)||yn(r.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{newTargets:m,elementInteractedDisplayStrings:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:r,targetNames:["from target","to target"],descriptions:[r.fromTarget,r.toTarget],caches:[r.cache?.fromTarget,r.cache?.toTarget],action:(g,f)=>this.browser.dragAndDrop(g.locator,f.locator,{hoverSeconds:r.hoverSeconds,steps:r.steps}),options:{useSelector:!!r.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h[0],newTargets:m}}case"MOUSE_DRAG":{let m=parseInt(r.deltaX),h=parseInt(r.deltaY),g=r.steps??5;if(isNaN(m)||isNaN(h))throw new R("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${r.deltaX}, ${r.deltaY})`);if(r.target&&yn(r.target)){await this.browser.mouseDragUsingVisualCoordinates(m,h,g,r.target.pixels,{force:r.force});break}let f,S,x=[];if(r.target?.elementDescriptor){let{newTarget:v,elementInteractedDisplayString:b,result:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:r,target:r.target,cache:r.cache?.target,action:async C=>C.locator,options:{useSelector:!!r.useSelector,iframeUrl:r.iframeUrl,disableCache:i}});f=E,S=b,x.push(v)}return await this.browser.mouseDrag(m,h,g,f,{force:r.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:S,newTargets:x}}case"SELECT_OPTION":{if(!Vn(r.target))throw new Error("Select with x/y is not supported yet");let m=r.target.elementDescriptor,h=r.choice??{type:"VALUE",value:r.option},{newTarget:g,elementInteractedDisplayString:f}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:r,target:{type:"description",elementDescriptor:m},cache:r.cache?.target,action:S=>this.browser.selectOption(S,h,r.force),options:{disableCache:i,useSelector:!!r.useSelector,iframeUrl:r.iframeUrl,source:Pi(r)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,newTargets:[g]}}case"TAB":{let m={loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0,retry:!0};if(r.url)await this.browser.switchToPage({type:"SUBSTRING",substring:r.url},m);else if(r.action)await this.browser.switchToPage(r.action,m);else throw new R("UserConfigurationError","No method definition was specified for the tab switch command");break}case"NEW_TAB":await this.browser.createNewTab(r.url,{loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"COOKIE":if(!r.value)break;let c=await this.browser.setCookie(r.value);this.logger.debug({results:c},"Set cookies");break;case"LOCAL_STORAGE":if(!r.value||!r.key)break;await this.browser.setLocalStorage(r.key,r.value);break;case"JAVASCRIPT":{let m;try{r.environment==="BROWSER"?(m=await this.browser.evaluateCodeInPage({code:r.code,fragment:r.fragment??!1,context:o.toObjectCopy(),timeoutMs:r.timeout?r.timeout*1e3:void 0}),this.logger.debug({result:m},"Executed JavaScript in browser")):m=await Dn({orgId:this.orgId,code:r.code,fragment:!!r.fragment,context:o,timeoutMs:r.timeout?r.timeout*1e3:void 0,logger:this.logger,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,flagStore:this.flagStore,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.scratchPadId){this.logger.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.scratchPadId,orgId:this.orgId,updates:h,logger:this.logger})}}})}catch(h){throw this.throwIfClosed(),new R("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(m)}catch(h){throw new R("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:m}}case"TYPE":{if(r.target&&yn(r.target)){await this.browser.clickUsingVisualCoordinates(r.target.pixels,r),await this.browser.type(r.value,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter},!0);break}let m=this.browser.url(),h,g=[],f=nk(r.target);if(f){let{elementInteractedDisplayString:x,newTarget:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:r,target:f,cache:r.cache?.target,action:b=>this.browser.typeIntoTarget(r.value,b,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter}),options:{disableCache:i,useSelector:!!r.useSelector,iframeUrl:r.iframeUrl,disableGlobalLocatorRedirect:!0,source:Pi(r)}});g.push(v),h=x}else await this.browser.type(r.value,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter},!0);let S={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,newTargets:g};return el(m,S.urlAfterCommand)&&(S.succeedImmediately=!0,S.succeedImmediatelyReason="URL changed"),S}case"HOVER":{if(yn(r.target)){await this.browser.hoverUsingVisualCoordinates(r.target.pixels);break}let{newTarget:m,elementInteractedDisplayString:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:r,target:r.target,cache:r.cache?.target,action:g=>this.browser.hover(g),options:{disableCache:i,useSelector:!!r.useSelector,iframeUrl:r.iframeUrl}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h,newTargets:[m]}}case"FOCUS":{if(!Vn(r.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:m,newTarget:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:r,target:r.target,cache:r.cache?.target,action:g=>this.browser.focus(g),options:{disableCache:i,useSelector:!!r.useSelector,iframeUrl:r.iframeUrl}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,newTargets:[h]}}case"BLUR":{if(r.target&&!Vn(r.target))throw new Error("Blur with x/y is not supported yet");if(!r.target||!r.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{newTarget:m,elementInteractedDisplayString:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:r.target,command:r,cache:r.cache?.target,action:g=>this.browser.blur(g),options:{disableCache:i,useSelector:!!r.useSelector,iframeUrl:r.iframeUrl}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h,newTargets:[m]}}case"PRESS":let p=this.browser.url();await this.browser.press(r.value,{repeat:r.repeat,convertMeta:r.convertMeta??!0,delayMs:r.delayMs});let d={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return el(p,d.urlAfterCommand)&&(d.succeedImmediately=!0,d.succeedImmediatelyReason="URL changed"),d;case"REQUEST":{let m=new rk,h=tk(fetch,m),g;try{g=new URL(r.url).hostname}catch{}return{data:{...await tl({command:r,baseUrl:this.browser.baseUrl,logger:this.logger,fetchImplementation:h}),cookies:Sa(m,g)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await tw({command:r,baseUrl:this.browser.baseUrl,logger:this.logger}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return ZS({ctx:e,tracer:t,command:r,disableCache:i,browser:this.browser,logger:this.logger,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:m=>this.wrapElementTargetingCommand(m)});case"FILE_UPLOAD":{let m,h;if(r.fileSource.type==="URL"?(h=r.fileSource.url,m=await Vy({uri:r.fileSource.url,logger:this.logger,orgId:this.orgId})):r.fileSource.type==="USER_FILE"&&(h=r.fileSource.name,m=await this.uploadedFileStorage?.getFileForUpload(r.fileSource.name,this.orgId)),!m)throw new R("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...m,filename:r.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let m;if(!r.storageState.trim())m=void 0;else if(m=await Dn({orgId:this.orgId,code:r.storageState,fragment:!1,context:o,logger:this.logger,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,flagStore:this.flagStore}),typeof m!="object")throw new R("ActionFailureError",`Credentials must evaluate to an object (received ${typeof m} instead)`);let h;try{h=fa.optional().parse(m)}catch(g){throw new R("ActionFailureError",`Credentials provided do not follow the required format: ${g}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let m=(r.timeout??wn)*1e3,h=await JS({command:r,tracer:t,timeoutMs:m,targetingWrapper:g=>this.wrapElementTargetingCommand(g),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!h.success,data:h.data,elementInteracted:h.elementInteractedDisplayString,newTargets:h.newTarget?[h.newTarget]:[],thoughts:h.err?.message??h.thoughts??`Element assertion ${h.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let m=await Cn({action:async()=>nl({assertion:r.assertion,browser:this.browser,logger:this.logger,timeout:r.timeout,signal:this.executeAbortController.signal,flagStore:this.flagStore}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:this.browser,logger:this.logger});return{fail:!m.success,data:m.data,thoughts:m.success?"Page assertion passed.":m.err?.message??`Page assertion still failing after ${r.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let h=this.browser.registerRequestListener(r.pattern).then(async g=>{let f={status:g?.status(),headers:g.headers()};return(await g.headerValue("content-type"))?.includes("json")?f.json=await g.json():(await g.headerValue("content-type"))?.includes("text")&&(f.text=await g.text()),f});return this.registeredListeners[r.key]=h,{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let m=this.registeredListeners[r.key];if(!m)throw new R("ActionFailureError",`No listener registered with key: ${r.key}`);return{data:await D(m,{milliseconds:(r.timeout??10)*1e3,message:`Request listener timed out after ${r.timeout} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:r,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:r,abortSignal:this.executeAbortController.signal,loggerTags:We(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:t,isClickToRecord:r}){this.recordAbortController=t;let o=new yl({signal:t.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,r),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:We(this.logger)})}async runFailureRecovery(e){return this.generator.getFailureRecoveryProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:We(this.logger)})}};var ok=4;async function nw({socket:n,logger:e,analytics:t,storage:r,uploadedFileStorage:o,visualDiffScreenshotStorage:i,serviceMocker:s,devicePixelRatio:a,generatorFactory:l,enricherFactory:c,browserbase:p,authorization:d,flagStoreFactory:u,settingsFactory:m}){let h=n.id,g=n.handshake.query.testId;if(!g)throw new Error("Socket connection request is missing testId");let f=await r.getOrgId({type:"e2e",testId:g});e=e.child({testId:g,orgId:f,sessionId:h});let S=await l(f,e),x=await c(f,e),v=await u(f),b=await m(f,e),{testMetadata:E,baseUrl:C,envName:I,localBrowserConfig:_,environmentVariables:L,localCodeEvalTools:z}=await Zr({testId:g,orgId:f,logger:e,storage:r,authorization:d,flagStore:v,settings:b}),j=Z.getSession(h);if(j)return e.info("Associating connection with existing session (likely reconnect)"),await j.controller.browser.clearAllCdpHighlights(),{type:"e2e",sessionId:h,orgId:f,testId:g};let O=n.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:O,event:"connect",args:n.handshake.query},"Websocket event (connect)"),O&&Z.getCurrentConnectionsByIp(O)>=ok)throw e.error({clientIp:O,sessions:Z.getCurrentSessionsByIp(),...n.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close duplicate tabs and try again later.");Z.reserveCapacityByIp(O);try{await ik({socket:n,baseUrl:C,envName:I,testMetadata:E,orgId:f,sessionId:h,logger:e,analytics:t,environmentVariables:L,clientIp:O,devicePixelRatio:a,storage:r,uploadedFileStorage:o,visualDiffScreenshotStorage:i,serviceMocker:s,localCodeEvalTools:z,generator:S,enricher:x,browserbase:p,localBrowserConfig:_,flagStore:v})}catch(U){throw e.warn({err:U},"Error setting up socket session, possibly due to client closing the connection"),Z.releaseCapacityByIp(O),U}return{type:"e2e",sessionId:h,testId:g,orgId:f}}async function ik({socket:n,baseUrl:e,envName:t,devicePixelRatio:r,testMetadata:o,orgId:i,sessionId:s,logger:a,analytics:l,storage:c,uploadedFileStorage:p,visualDiffScreenshotStorage:d,serviceMocker:u,localCodeEvalTools:m,generator:h,environmentVariables:g,localBrowserConfig:f,clientIp:S,enricher:x,flagStore:v}){let b={viewport:o.advanced?.viewport??Ut};r&&(b.deviceScaleFactor=r);let E=o.id,C=await u?.initializeServicesForTest(i,E),I=await cl({advanced:{...f,...o.advanced},orgId:i,baseUrl:e,envName:t,localTools:m,envVariables:g,logger:a,customHeaders:void 0,flagStore:v});a=a.child({orgId:i,sessionId:s,testId:E});let _=!1,L=v.isBooleanFlagEnabled("icon_knowledge_base")?await c.fetchIconKnowledgeBase(i,a):null,z=await fn.init({baseUrl:e,userBrowserSettings:I,enricher:x,storage:c,flagStore:v,mockedServices:C,logger:a,contextArgs:b,iconKnowledgeBase:L,onTabsChange:(G,N)=>{n.emit("tabs",{tabs:G,activeTab:N})},callbacks:{onScreencastFrame:(G,N)=>{let X=n;_&&(X=n.compress(!0)),X.emit("screenshot",{buffer:G},()=>{N()})},onSvgsCollected:G=>{n.emit("newIconDetected",{numIcons:G.newSvgs.length}),c.saveNewIcons(i,G,a)}}});await z.navigate({url:e,initialNavigation:!0});let j=new ri({browser:z,generator:h,logger:a,analytics:l,flagStore:v,orgId:i,scratchPadId:void 0,storage:c,localCodeEvalTools:m,uploadedFileStorage:p,visualDiffScreenshotStorage:d,slowMoMs:I.slowMoMs}),O=PS(n,s,a),U=async()=>{O.timers.forEach(G=>clearInterval(G))},P=new It({baseUrl:e,currentUrl:j.browser.url(),variablesFromEnvironment:g,envName:t});if(!n.connected)throw await z.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");n.emit("session",{url:e,userAgent:fn.USER_AGENT,viewport:j.browser.getViewport(),sessionId:s}),Z.registerSession({controller:j,context:P,sessionId:s,cleanup:U,clientIp:S})}async function Zr({testId:n,orgId:e,logger:t,storage:r,authorization:o,flagStore:i,settings:s}){let a=await r.fetchTestMetadata(n,e,t);if(!a)throw new Error(`Test metadata could not found for test ${n}`);let l;o?.type==="API_KEY"&&(l=new ir({httpClient:new Mt({...o,logger:t}),fakerSeed:void 0}));let c=a.envs?.find(g=>g.default),p;c&&(p=await r.fetchEnvironment(e,c.name,t));let d=p&&"browser"in p?p.browser:void 0,u={...s.browser,...d},m=a.baseUrl||p?.variables?.[Ie];if(!m)throw new Error("Base URL is empty in both test options and the configured environment");let h={...p?.variables};return await Promise.all((a.parameters??[]).map(async g=>{let f=await Ht({orgId:e,s:g.defaultValue,context:It.dummyContext(p?.name,h),logger:t,flagStore:i,localTools:l});h[g.name]=f})),{localCodeEvalTools:l,baseUrl:m,envName:p?.name,localBrowserConfig:u,environmentVariables:h,testMetadata:a}}import{diff as sk}from"deep-object-diff";var Bp=class{parentTracer=null;socket;step;constructor({step:e,socket:t,parentTracer:r}){this.socket=t,this.parentTracer=r,this.step=e}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}heal(){}async finish(e){switch(e.step.status){case"SUCCESS":this.socket.emit("success",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"FAILED":this.socket.emit("failure",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"CANCELLED":this.socket.emit("cancelled",{...e,parentStepIdChain:this.getParentStepIdChain()});return}}async startSubSteps(){return new Cl({parentStep:this.step,socket:this.socket,parentTracer:this})}},Cl=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:t,parentTracer:r}){this.parentTracer=r,this.parentStep=e,this.socket=t}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:this.getParentStepIdChain()}),new Bp({step:e.step,parentTracer:this,socket:this.socket})}},Rl=class{constructor(e,t,r,o,i){this.socket=e;this.storage=t;this.orgId=r;this.testId=o;this.stepsBeforeRun=i}trackStatus(){}attachConsoleLogs(){}attachNetworkLogs(){}async finish(e){this.socket.emit("finished");let{logger:t,result:r,updatedSteps:o}=e;if(r?.status==="PASSED"&&o){let i=o.steps,s=sk(this.stepsBeforeRun,i);if(Object.keys(s).length>0){t.debug({changes:s},"Updating steps post-run success");let{cachesToSave:a}=await Ze({stepLists:{steps:i},cacheCreationParams:{testId:this.testId,orgId:this.orgId}});try{await this.storage.saveStepCacheEntries(a,this.testId,t)}catch(l){t.warn({err:l},"Failed to save step cache entries after execution success")}}else t.debug("No changes detected in steps post-run success")}}async startStepList(){return new Cl({parentStep:null,parentTracer:null,socket:this.socket})}};var zp={currentlyExecutingRequests:{}},lk=n=>async(e,t)=>{let{testId:r,orgId:o}=n.metadata,i=await n.flagStoreFactory(o),s=await n.settingsFactory(o,n.logger),a,l=await Zr({testId:r,orgId:o,logger:n.logger,storage:n.storage,authorization:n.authorization,flagStore:i,settings:s}),c=`${r}|${l.baseUrl}`;try{let p=zp.currentlyExecutingRequests[c]??0;zp.currentlyExecutingRequests[c]=p+1,a=await ck({...n,...e,...l,done:t})}finally{n.logger.info({result:a,sessionId:n.metadata.sessionId},"Test execution complete"),zp.currentlyExecutingRequests[c]--}},ck=async({socket:n,steps:e,baseUrl:t,testMetadata:r,reInitialize:o,toStep:i,fromStep:s,storage:a,metadata:l,logger:c,analytics:p,envName:d,environmentVariables:u,localCodeEvalTools:m,done:h})=>{let{testId:g,sessionId:f,orgId:S}=l,x=f,v=Z.getSession(f);if(!v)throw new Error("No active session found");let{controller:b,context:E}=v;b.setOpen(),c=c.child({testId:g,orgId:S,sessionId:f,runId:x}),c.info({steps:e.map(N=>`${N.type}${"command"in N?` - ${N.command.type}`:""}`),toStep:i,fromStep:s,reInitialize:o,envName:d,baseUrl:t,context:E,flags:b.flagStore.getAllFlags()},"Socket execution parameters");let C=u??{},I=async()=>{o&&(await b.browser.reset({newUrl:t}),E.reset({baseUrl:t,currentUrl:b.browser.url(),variablesFromEnvironment:C,envName:d}))},_=async()=>{try{await a.resolveStepCacheEntries({schemaVersion:r.schemaVersion,organizationId:S,testId:g,steps:e,logger:c})}catch(N){c.error({err:N},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await Ki({promiseGenerator:async()=>Promise.all([I(),_()]),signal:b.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),b.setOpen()}catch(N){if(n.emit("finished"),N.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${N}`)}let L=ak(e),z={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},j={orgId:S,runId:x,testMetadata:r,steps:e,fromStep:s,toStep:i},O={controller:b,context:E,storage:a,debugDataStorage:new kr,codeEvalTools:m,billingReporter:new Eo,logger:c,analytics:p},U={test:{},step:{onDynamicAIActionStatusUpdateEvent:N=>{n.emit("dynamicCommandStatusUpdate",N)},onDynamicAIActionEvaluatingEvent:N=>{n.emit("dynamicCommandEvaluating",N)},onDynamicCommandGenerated:N=>{n.emit("dynamicCommandGenerated",N)},onDynamicCommandExecuted:N=>{n.emit("dynamicCommandExecuted",N)}}},P=new Rl(n,a,S,g,L),G=await ll({fixtures:O,options:z,callbacks:U,inputs:j,testParams:{tracer:P}});return await P.finish({logger:c,result:G,updatedSteps:{steps:e}}),h?.(G),G.status};var rw={event:"execute",createHandler:lk};import{cloneDeep as dk}from"lodash-es";var pk=n=>async({command:e},t)=>{let{logger:r,generatorFactory:o,metadata:i}=n,s=dk(e),a=Ug(s);if(a.category!=="NO_DESCRIPTION_PROVIDED"){if(a.category!=="NONE"){t?.({result:a});return}"cache"in s&&(s.cache=void 0,s.id=void 0);try{let c=await(await o(i.orgId,r)).getLintStepResult({command:s},{logger:r});t?.({result:c})}catch(l){r.error({event:"lint",err:l},"Failed to lint step"),t?.({result:void 0})}}},ow={event:"lintStep",createHandler:pk};var uk=({metadata:n,logger:e,storage:t})=>{let{sessionId:r}=n;return async(o,i)=>{let{description:s,command:a,testMetadata:l,returnScreenshot:c}=o;e.info({params:o},`Locate handler called - ${s}`);let p=Z.getSession(r);if(!p)throw new Error("No active session found");let{controller:d,context:u}=p;d.setOpen();let m=wo.parse(l.advanced??{}),h={},g;if(s){if("useSelector"in a&&a.useSelector)try{let f=await d.locateElementWithSelector(s,"iframeUrl"in a?a.iframeUrl:void 0);g=f.resolution.locator,h={target:f.target,thoughts:f.thoughts}}catch(f){e.warn({err:f},"Failed resolving target with selector"),i({err:`Failed locating element: ${f.message}`,decisions:f instanceof Yn?f.decisions:void 0});return}else try{let f=await d.locateElement({description:s,disableCache:m.disableAICaching,iframeUrl:"iframeUrl"in a?a.iframeUrl:void 0,skipWait:!0,testContext:u,source:Pi(a)});h={target:f.target,thoughts:f.thoughts},g=f.resolution.locator}catch(f){(async()=>{try{let S=await d.browser.getCondensedHtml({skipWait:!0});e.warn({err:f,html:S.slice(0,1e5)},"Failed locating element with AI")}catch(S){e.warn({err:S},"Failed grabbing HTML after trying to locate element with AI")}})(),i({err:`Failed locating element with AI: ${f.message}`});return}if(a.type==="SELECT_OPTION"&&g)try{h.options=await d.browser.getSelectOptions(g)}catch(f){e.warn({err:f},"Failed getting select options"),i({err:`Failed getting select options: ${f.message}`});return}e.info({result:h},"Locate handler result")}if(c)try{let{buffer:f,width:S,height:x}=await d.screenshotWithDimensions({clearHighlights:!0,locator:g,hideCaret:!0}),v=await t.uploadScreenshot(f);h.screenshot={data:v,width:S,height:x},e.info({width:S,height:x},"Captured screenshot during locate")}catch(f){e.error({err:f},"Error capturing screenshot during locate"),i({err:`Error taking screenshot: ${f.message}`});return}if(i({result:h}),g)try{await Promise.all([d.browser.scrollIntoView(g),d.browser.highlight(g)])}catch(f){e.warn({err:f},"Error highlighting element, continuing...")}}},iw={event:"locate",createHandler:uk};var mk=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async({event:r,percentX:o,percentY:i})=>{let s=Z.getSession(t);if(!s)throw new Error("No active session found");let a=s.controller.browser;if(a.closed||a.getActivePage().isClosed()){e.warn("Ignoring mouse move because the browser is closed");return}try{await a.clickMouseFromPositionPercentages(r,o,i)}catch(l){e.error({err:l},"Error performing click during cloud recording in control mode")}}},sw={event:"mouseClickEvent",createHandler:mk};var hk=({metadata:n,generatorFactory:e,logger:t,socket:r})=>{let{sessionId:o,orgId:i,testId:s}=n;return async({stepId:a,parentStepIdChain:l,attribute:c})=>{let p=Z.getSession(o);if(!p)throw new Error("No active session found");let{controller:d}=p,u=await e(i,t);d.setOpen(),p.browserBehavior.showOverlay=!0;let m=new AbortController;m.signal.addEventListener("abort",async()=>{try{p.browserBehavior.showOverlay=!1,await d.stopRecordMode()}catch(f){t.warn({err:f},"Failed to stop record mode in target click socket handler")}});let h=!1,g=(f,S)=>{S.type!=="PRESET_ACTION"||S.command.type!=="CLICK"||(r.emit("targetRecordingUpdate",{type:f,stepId:a,parentStepIdChain:l,command:S.command,attribute:c}),m.abort(),h=!0)};setTimeout(()=>{h||(m.abort(),r.emit("targetRecordingUpdate",{type:"error",err:"Timed out waiting for click event",stepId:a,parentStepIdChain:l,attribute:c}))},1e4),await d.startRecordMode({params:{generator:u,logger:t,testId:s,orgId:i,callbacks:{onActionReceived:f=>g("clickReceived",f),onStepRecorded:f=>g("descriptionGenerated",f)}},abortController:m,isClickToRecord:!0}),r.emit("targetRecordingUpdate",{type:"listenersInitialized",stepId:a,parentStepIdChain:l,attribute:c})}},aw={event:"recordTargetClick",createHandler:hk};var gk=["Dead","Meta","AudioVolumeUp","AudioVolumeDown"],fk=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async({key:r})=>{let o=Z.getSession(t);if(!o)throw new Error("No active session found");if(gk.includes(r))return;let{controller:i}=o;if(i.browser.closed||i.browser.getActivePage().isClosed()){e.debug({sessionId:t},"Browser is closed, ignoring keyboard press socket event");return}try{i.setOpen(),r.length>1?await i.browser.press(r,{}):await i.browser.type(r,{clearContent:!1,pressKeysSequentially:!0})}catch(s){if(s.message.includes("has been closed")){e.debug({sessionId:t,err:s},"Browser is closed, ignoring keyboard press socket event error");return}throw s}}},lw={event:"keyboardPressEvent",createHandler:fk};var Sk=({metadata:n,logger:e})=>{let{sessionId:t}=n,r,o=0,i=(l,c)=>{let p=async()=>{r=void 0};clearTimeout(r),r=setTimeout(p,Math.min(1e3,250*(o+1)))},s,a=0;return async l=>{let c=Z.getSession(t);if(!c)throw new Error("No active session found");let{controller:p,browserBehavior:d}=c,u=p.browser;if(u.closed||u.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}if(l.event==="scroll"){let m=await u.scrollFromPositionPercentages(l.percentX,l.percentY,s?.x??0,s?.y??0),h=c.browserBehavior.recordingState?.transformer;h&&m&&h.recordScroll(m);return}d.showOverlay&&i(u,l);try{let m=await u.moveMouseFromPositionPercentages(l.percentX,l.percentY);a=0,s=m}catch(m){a++,a%5===0&&e.warn({err:m,mouseErrors:a},"Error in socket mouse move handler")}}},cw={event:"mouseMoveEvent",createHandler:Sk};var yk=({metadata:n,generatorFactory:e,socket:t,logger:r})=>{let{sessionId:o,orgId:i,testId:s}=n;return async({stepId:a})=>{let l=Z.getSession(o);if(!l)throw new Error("No active session found");let{controller:c,browserBehavior:p}=l,d=await e(i,r);r.info("Starting cloud recording");let u=new AbortController,m=await c.startRecordMode({params:{generator:d,logger:r,testId:s,orgId:i,callbacks:{onActionReceived:(h,g)=>{t.emit("stepRecorded",{stepId:a,step:h,offset:g})},onStepRecorded:(h,g)=>{t.emit("stepRecorded",{stepId:a,step:h,offset:g})}}},abortController:u,isClickToRecord:!1});p.recordingState={transformer:m}}},dw={event:"recordingStart",createHandler:yk};var bk=({metadata:n,logger:e})=>{let{sessionId:t}=n;return async()=>{let r=Z.getSession(t);if(!r)throw new Error("No active session found");e.info("Stopping cloud recording"),await r.controller.stopRecordMode(),r.browserBehavior.recordingState=void 0,r.browserBehavior.showOverlay=!1}},pw={event:"recordingStop",createHandler:bk};var wk=({socket:n,metadata:e,logger:t,storage:r,authorization:o,flagStoreFactory:i,settingsFactory:s})=>async(a,l)=>{let{testId:c,sessionId:p,orgId:d}=e;t.info({testId:c,sessionId:p},"Refresh event received");let u=await i(d),m=await s(d,t),{baseUrl:h}=await Zr({testId:c,orgId:d,logger:t,storage:r,authorization:o,flagStore:u,settings:m}),g=Z.getSession(p);if(!g){n.emit("error",{message:"No session to refresh"});return}let{controller:f}=g;f.setOpen(),await f.browser.refresh();let S=f.browser.getViewport();t.info({baseUrl:h,viewport:S},`Session refreshed for test ${c} at ${h}`),l()},uw={event:"refresh",createHandler:wk};var vk=({socket:n,metadata:e,logger:t,storage:r,authorization:o,flagStoreFactory:i,settingsFactory:s})=>async()=>{let{testId:a,sessionId:l,orgId:c}=e;t.info({testId:a,sessionId:l},"Reset event received");let p=await i(c),d=await s(c,t),{baseUrl:u,envName:m,environmentVariables:h}=await Zr({testId:a,orgId:c,logger:t,storage:r,authorization:o,flagStore:p,settings:d}),g=Z.getSession(l);if(!g){n.emit("error",{message:"No session to reset"});return}let{controller:f,context:S}=g;await f.browser.reset({newUrl:u});let x=f.browser.baseUrl;S.reset({baseUrl:x,currentUrl:f.browser.url(),variablesFromEnvironment:h,envName:m});let v=f.browser.getViewport(),b=fn.USER_AGENT;t.info({baseUrl:u,viewport:v},`Session reset for test ${a} at ${x}`),n.emit("session",{url:x,userAgent:b,viewport:v,sessionId:l})},mw={event:"reset",createHandler:vk};var xk=({metadata:n})=>{let{sessionId:e}=n;return async({url:t})=>{let r=Z.getSession(e);if(!r)throw new Error("No active session found");await r.controller.browser.switchToPage({type:"SUBSTRING",substring:t})}},hw={event:"switchTab",createHandler:xk};async function gw(n){let{socket:e}=n;return e.handshake.query.type==="api-test"?jS(n):nw(n)}var fw=[VS,rw,iw,mw,uw,$S,hw,ow,aw,dw,pw,cw,sw,lw,HS,LS,GS,WS];var Sw=n=>{let{logger:e}=n,t=new Tk(n.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0});return t.on("connection",async r=>{let o;try{e.info({event:"connection",transport:r.conn.transport.name},"Websocket connection established"),o=await gw({...n,socket:r,logger:e}),e=e.child(o)}catch(i){e.error({event:"connection",type:"websocket",err:i},"Failed to setup connection"),r.emit("error",{message:i instanceof Error?i.message:`${i}`}),r.disconnect(!0);return}fw.forEach(i=>Ek(i,{socket:r,metadata:o,...n,logger:e}))}),t},Ek=(n,e)=>{let t=n.createHandler(e),r=(...o)=>{["mouseMoveEvent","keyboardPressEvent","mouseClickEvent"].includes(n.event)||e.logger.debug({...e.metadata,event:n.event,args:o},`Websocket event (${n.event})`);let i=s=>{e.logger.error({event:n.event,type:"websocket",args:o,err:s instanceof Error?s:new Error(`${s}`)},"Unhandled exception in socket handler"),e.socket.emit("error",{message:s instanceof Error?s.message:`${s}`})};try{let s=t.apply(void 0,o);s&&typeof s.catch=="function"&&s.catch(i)}catch(s){i(s)}};e.socket.on(n.event,r)};import{Router as kk}from"express";import Wp from"fs";import Pk from"path";import bw,{multistream as Ck}from"pino";import Rk from"pino-pretty";var yw=["lastScreenshotBuffer"];var jp=new Map,Ak=!0,Hp=class n{consoleLogger;ddClientToken;hostname;bindingAttributes;disableConsoleLogs;site="https://http-intake.logs.us5.datadoghq.com/api/v2/logs";constructor({bindings:e,clientToken:t,hostname:r,disableConsoleLogs:o}){this.ddClientToken=t,this.hostname=r,this.disableConsoleLogs=o,this.bindingAttributes={...e,env:"production"};let i={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=Ak?bw(i):bw(i,Ck([{stream:Rk({colorize:!0})}]))}child(e){return new n({clientToken:this.ddClientToken,bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs})}flush(e){this.disableConsoleLogs||this.consoleLogger.flush(e)}log(e,t,r,...o){if(t&&r===void 0&&(r=`${t}`,t={}),this.disableConsoleLogs||this.consoleLogger[e](e==="error"?t:{testId:t.testId,runId:t.runId},r,...o),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error){let s={};for(let a of Object.getOwnPropertyNames(t.err))yw.includes(a)||(s[a]=t.err[a]);s.name=t.err.name,t.err=s}let i=Object.assign({},this.bindingAttributes,t&&typeof t=="object"?t:{});o.length>0&&(i.args=o),(async()=>{try{let s=await fetch(this.site,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","DD-API-KEY":this.ddClientToken},body:JSON.stringify([{ddsource:this.bindingAttributes.app,ddtags:["env:production"],hostname:this.hostname??"vercel",service:"momentic",message:{message:r||"",...i,level:e}}])});if(!s.ok)throw new Error(`Failed to log to Datadog: ${s.statusText})}`)}catch(s){this.disableConsoleLogs||this.consoleLogger.warn({obj:t,msg:r,args:o,err:s},"Failed to log to Datadog")}})()}debug(e,t,...r){this.log("debug",e,t,...r)}info(e,t,...r){this.log("info",e,t,...r)}warn(e,t,...r){this.log("warn",e,t,...r)}error(e,t,...r){this.log("error",e,t,...r)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){this.consoleLogger.level=e}enableConsoleLogs(){this.disableConsoleLogs=!1}},Al=({app:n,clientToken:e,hostname:t,disableConsoleLogs:r})=>{if(!process.env.DD_CLIENT_TOKEN&&!process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN&&!e)throw new Error("Missing DD_CLIENT_TOKEN");return jp.has(n)||jp.set(n,new Hp({bindings:{app:n},hostname:t,clientToken:e||process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN||process.env.DD_CLIENT_TOKEN,disableConsoleLogs:r})),jp.get(n)};import{hostname as Ik}from"os";var qe=Al({app:"desktop-server",clientToken:"pubcfd7516a5c0ba852b42675cd97bee027",hostname:Ik(),disableConsoleLogs:!0}),ww=n=>{qe.addBinding("version",n)};var Lk=new gl(10,60*1e3),qp="https://api.momentic.ai",Kp,$p,vw=n=>{qp=n},Il=()=>qp,xw=(n,e)=>{Kp=n,$p?.abort(),$p=new AbortController;let t=$p.signal,r=[n.configFilePath];n.config.environments?.forEach(o=>{if(!o.envFile)return;let i=Pk.resolve(n.rootDir,o.envFile);try{if(Wp.lstatSync(i).isSymbolicLink())return;Wp.existsSync(i)&&r.push(i)}catch(s){qe.warn({err:s},`Failed to check if env file ${i} exists`)}});try{Ok({filesToWatch:r,revalidator:e,signal:t,project:n})}catch(o){qe.error({err:o},"Failed to start config file watchers")}},ge=()=>Kp,oi,Gp,Vp,Tw=async n=>{if(oi)return oi;let e=new st({baseUrl:qp,apiKey:n,logger:qe});try{let t=await e.getAuthInfo();return oi=t.orgId,Gp=t.userId,Vp=n,oi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},mr=()=>{if(!oi)throw new Error("Your organization ID is invalid.");return oi},Pl=()=>{if(!Gp)throw new Error("Your user ID is invalid.");return Gp},Ew=()=>{if(!Vp)throw new Error("Your API key is invalid.");return Vp};function Ok({filesToWatch:n,revalidator:e,signal:t,project:r}){n.forEach(o=>{Wp.watch(o,{signal:t,persistent:!1,recursive:!1},(i,s)=>{s&&(Lk.increment("setLocalProject")&&y.warn(`A file change under the ${r.rootDir} directory has caused Momentic to reload its configuration more than 10 times in the last minute. Please avoid making rapid changes to files in this directory as this may cause performance issues.`),Kp=e(r.configFilePath))})})}function we(n){return function(...e){let t=e[e.length-1],r=n(...e);Promise.resolve(r).catch(t)}}var Cw=kk();Cw.get("/",we((n,e)=>{let t=xf(ge(),qe);e.status(200).json(t)}));var Rw=Cw;import{Router as Nk}from"express";var Ll=class extends Wo{constructor(t,r){super(t,r);this.client=t;this.orgId=r}async getOrgId(t){return this.orgId}async fetchTestMetadata(t,r,o){let i=ge(),a=Oe(i,o).tests[t];if(a)return Oa(a.relativePath,i)}async fetchApiTestMetadata(t,r,o){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(t,r,o){let i=ge();return Qi(r,i,Nr)}async fetchIconKnowledgeBase(t,r){try{return await this.client.fetchIconKnowledgeBase(t,r)}catch(o){return r.error({err:o},"Failed to fetch icon knowledge base"),null}}};var Aw=Nk();Aw.get("/",we((n,e)=>{e.status(200).json({userId:Pl(),orgId:mr()})}));var Iw=Aw;import{Router as _k}from"express";var Pw=_k();Pw.get("/",we((n,e)=>{let t=ge(),r=Oe(t,y),o=new Set;r?.tests&&Object.values(r.tests).forEach(s=>{s.labels?.forEach(a=>o.add(a))});let i=Array.from(o).sort();e.status(200).json(i)}));var Lw=Pw;import{Router as Mk}from"express";import Ow from"fs";import Fk from"path";var Cs=Mk();Cs.get("/",we(async(n,e)=>{let t=ge(),r=Oe(t,y),i=(await La(r,qe)).filter(s=>s.enabled!==!1).map(s=>{let a=r.modules[s.moduleId];if(!a){y.warn(`Found a dangling module with ID ${s.moduleId} that could not be found on disk.`);return}return{...a,content:s}}).filter(s=>s!==void 0);e.status(200).json(i)}));Cs.post("/",we(async(n,e)=>{let t;try{t=Lh.parse(n.body)}catch(a){e.status(400).json({error:`Invalid request body: ${a}`});return}try{To(t.name)}catch(a){e.status(400).json({error:`Invalid module name: ${a}`});return}let r=ge(),o=Oe(r,y).modules;if(Object.values(o).find(a=>a.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let i=Fk.join(r.rootDir,t.folderPath??"");if(!Ow.existsSync(i)||!Ow.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let s=await yf({...t,folder:i,project:r});e.status(201).json(s)}));Cs.get("/:moduleId",we(async(n,e)=>{if(!n.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=Oe(ge(),y),r=t.modules[n.params.moduleId];if(!r){e.status(404).json({error:"Module not found."});return}try{let o=await fd(r,t,y);e.json(o)}catch(o){e.status(400).json({err:o})}}));Cs.patch("/:moduleId/metadata",we(async(n,e)=>{if(!n.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=Oh.parse(n.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let r=ge(),o=Oe(r,y);Sf({moduleId:n.params.moduleId,content:t,momenticFiles:o,logger:y,project:r}),e.status(201).json({message:"ok"})}));var kw=Cs;import{Router as Dk}from"express";var Ol=Dk();Ol.get("/",we((n,e)=>{let t=Wd().map(r=>({name:r.config.name,configFilePath:r.configFilePath}));e.status(200).json(t)}));Ol.get("/current",we((n,e)=>{let t=ge(),r={name:t.config.name,configFilePath:t.configFilePath};e.status(200).json(r)}));Ol.post("/set",we((n,e)=>{let t;try{t=Nh.parse(n.body)}catch(r){e.status(400).json({error:`Invalid request body: ${r}`});return}try{let r=mn({configFilePath:t.configFilePath});xw(r,o=>mn({configFilePath:o}))}catch(r){e.status(400).json({error:`Error setting project: ${r}`});return}e.sendStatus(204)}));var Nw=Ol;import{Router as Uk}from"express";var _w=Uk();_w.get("/",we((n,e)=>{let r={ai:ge().config.ai};e.status(200).json(r)}));var Mw=_w;import{Router as jk}from"express";import Fw from"fs";import Qr from"path";import{v4 as Dw}from"uuid";import Hk from"yaml";import{randomUUID as Bk}from"node:crypto";import{PostHog as zk}from"posthog-node";var ii=class{identify(){return this}child(){return this}track(){return this}async shutdown(){}},si=class n{bindings;client;options;constructor(e,t={}){this.bindings=e,this.options=t,this.client=new zk("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...t})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new n({...this.bindings,...e},this.options)}track(e,t){if(!ih(this.bindings))return console.error(`Cannot track ${e.type} event without required bindings.`,this.bindings),this;let{type:r,...o}=e;return this.client.capture({distinctId:Bk(),event:r,timestamp:t?.timestamp,properties:{...this.bindings,...o}}),this}};var ai=new si({platform:"local_app"},{flushAt:1,flushInterval:0});var hr=jk();function Uw(n){let e=Oe(n,y);return Object.values(e.tests)}hr.get("/",we((n,e)=>{let t=Uw(ge());e.status(200).json(t)}));hr.post("/",we(async(n,e)=>{let t;try{t=Ih.parse(n.body)}catch(p){e.status(400).json({error:`Invalid request body: ${p}`});return}try{To(t.name)}catch(p){e.status(400).json({error:p.message});return}let o={id:Dw(),name:t.name,description:t.description,baseUrl:t.baseUrl,schemaVersion:je,advanced:{disableAICaching:!1,browserType:t.browserType??"Chromium",viewport:t.viewport??Ut},retries:0,steps:[]};t.environment&&(o.envs=[{name:t.environment,default:!0}]);let i=ge();if(Uw(i).find(p=>p.name===t.name)){e.status(400).send(`A test with the name "${t.name}" already exists. Please use a different name.`);return}let a=Qr.join(i.rootDir,t.folderPath??""),l=await bf({test:o,name:t.name,folder:a}),c={...o,relativeFilePath:Qr.relative(i.rootDir,l)};ai.track({type:"test_editor:test_create"}),e.status(201).json(c)}));hr.get("/:testPath",we(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r=ge(),o=Oe(r,y),i;try{i=await Zi(Qr.join(r.rootDir,t),qe,o),e.status(200).json(i)}catch(s){e.status(400).send({error:s.message});return}(async()=>{try{let{stepsToSave:s,moduleUpdates:a}=await Ze({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});a.forEach(l=>{gd({content:l,schemaVersion:je,momenticFiles:o,project:r})}),Hr(t,s,je,r)}catch(s){qe.error({err:s},"Failed to save migrated test to disk after initial fetch")}})()}));hr.patch("/:testPath/metadata",we(async(n,e)=>{if(!n.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=Ah.parse(n.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o={message:"ok",newRelativeTestPath:Sd(n.params.testPath,t,ge()).newRelativeTestPath};e.status(200).json(o)}));hr.patch("/:testPath",we(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=Rh.parse(n.body)}catch(d){e.status(400).json({error:`Invalid request body: ${d}`});return}let o=ge(),i=Oe(o,y),s;try{s=Oa(t,o)}catch(d){e.status(400).json({error:`Existing test file on disk is invalid: ${d}`});return}let{stepsToSave:a,moduleUpdates:l,cachesToSave:c}=await Ze({stepLists:r.stepLists,cacheCreationParams:{testId:s.id,orgId:mr()}});await new st({apiKey:Ew(),baseUrl:Il(),logger:qe}).updateStepCaches({entries:c,testId:s.id}),l.forEach(d=>{gd({content:d,schemaVersion:r.schemaVersion,momenticFiles:i,project:o})}),Hr(t,a,r.schemaVersion,o),e.status(201).json({message:"ok"})}));hr.patch("/:testPath/environments",we(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=kh.parse(n.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}Sd(t,{envs:r.defaultEnv?[{name:r.defaultEnv,default:!0}]:[]},ge()),e.status(201).json({message:"ok"})}));hr.post("/:testPath/duplicate",we(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=Ph.parse(n.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{To(r.name)}catch(f){e.status(400).json({error:f.message});return}let o=ge(),i=Qr.join(o.rootDir,t);if(!Fw.existsSync(i)){e.status(404).json({error:"Test not found."});return}let s=Oe(o,y),a;try{a=await Zi(i,qe,s)}catch(f){e.status(400).send({error:f.message});return}let l=Dw(),c=Xt.parse({...a,name:r.name,id:l}),{stepsToSave:p}=await Ze({stepLists:{steps:a.steps,beforeSteps:a.beforeSteps,afterSteps:a.afterSteps},createNewStepIds:!0,cacheCreationParams:{createNewCacheIds:!0,testId:l,orgId:mr()}}),d=_n({fileType:fe.TEST,...c,beforeSteps:p.beforeSteps??void 0,steps:p.steps,afterSteps:p.afterSteps??void 0}),u=Qr.dirname(i),m=Qr.join(u,`${r.name}.${Nt.TEST}`),h=Hk.stringify(d);Fw.writeFileSync(m,h,"utf-8");let g={relativeFilePath:Qr.relative(o.rootDir,m)};ai.track({type:"test_editor:test_create"}),e.status(201).json(g)}));var Bw=hr;var Rs=class{async prepareGoldenScreenshotForComparison(e,t,r){return await new jo(ge(),!1).prepareGoldenScreenshotForComparison(e,t,r)}};async function $w(n){let{momenticServerUrl:e,apiKey:t,serverPort:r,staticDir:o,devicePixelRatio:i,version:s,logger:a=qe}=n;ww(s),e&&vw(e),a.debug(n,"Initializing desktop server"),await Tw(t);let l=mr(),c=Pl();ai.identify({user_id:c,org_id:l}),a.debug({orgId:l,userId:c},"Checking API key successful");let p=Kk(o,r,a),d=`http://localhost:${r}`;y.info(`Desktop server is running at ${d}`),await new Promise(v=>{try{p.listen(r,()=>{a.info(`Desktop server is running at ${d}`),v()})}catch(b){b.message.includes("EADDRINUSE")?Ww(r):y.error(`An unexpected error occurred while starting the server: ${b.message}`),process.exit(1)}});let m={type:"API_KEY",baseUrl:Il(),apiKey:t,logger:a},h=new Vo(m),g=new Gr(m,h),f=new st(m),S=new Ll(f,mr()),x=new Rs;Sw({baseServer:p,generatorFactory:async()=>h,enricherFactory:async()=>g,flagStoreFactory:async v=>{let b=ge(),E=Ho.initIfConfigHasOverrides(a,b.config)??f;return Ko.init(v,E)},settingsFactory:async()=>{let v=ge();return{ai:v.config.ai||{},browser:v.config.browser||{}}},storage:S,logger:a,devicePixelRatio:i,authorization:m,visualDiffScreenshotStorage:x,analytics:ai})}var Hw="25mb";function Kk(n,e,t){let r=jw();r.use($k()),r.use(zw.json({limit:Hw})),r.use(zw.urlencoded({extended:!1,limit:Hw}));let o=Vk();if(o.use("/tests",Bw),o.use("/modules",kw),o.use("/environments",Rw),o.use("/projects",Nw),o.use("/labels",Lw),o.use("/settings",Mw),o.use("/identify",Iw),r.use("/api",o),r.use((s,a,l)=>{s.path!=="/healthcheck"&&!s.path.startsWith("/assets")&&t.debug({url:s.url,path:s.path,query:s.query,method:s.method,body:s.body,headers:s.rawHeaders,client:s.ip},"Received desktop-server request"),a.on("close",()=>{a.statusCode>=400&&t.error({url:s.url,method:s.method,statusCode:a.statusCode},"Request completed in error")}),l()}),r.use((s,a,l,c)=>{if(s instanceof Error&&s.message.includes("BadRequestError: request aborted")){l.status(400).send("Client disconnected");return}t.error({stack:s.stack,msg:s.message,err:s,url:a.url,method:a.method},"Unhandled exception leading to 500 on desktop-server"),y.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${s.message}
|
|
3611
|
-
${
|
|
3607
|
+
`)}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(p){this.logger.warn({err:p},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,t,n={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:1e3});if(!o)throw new A("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,s=n.steps??5;await this.page.mouse.move(i,a,{steps:s}),await Q(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o){o&&await this.hover({locator:o});let i=await(await this.getActivePageOrFrame()).evaluate(fp);i||(this.logger.debug("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await Q(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await Zr({func:async t=>{await t.locator.scrollIntoViewIfNeeded({timeout:1e3});let n=await t.locator.boundingBox({timeout:1e3});if(!n)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(n.x+n.width/2,n.y+n.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await Zr({func:t=>t.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let t=await this.getActivePageOrFrame();await qe({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurCommand"});return}await this.highlight(e.locator),await Zr({func:t=>t.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,t,n=!1){await this.highlight(e.locator),await Zr({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(t.type==="INDEX"){let i=Number(t.index);if(isNaN(i))throw new A("UserConfigurationError",`Page index ${t.index} is not a number`)}await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?Number(t.index):void 0},{force:n,timeout:3e3})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=db(e);o!==e&&(this.logger.debug({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<n;o++)await this.page.keyboard.press(e,{delay:t.delayMs??0})}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let n=0,o=2;for(;n<o;){n++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});break}catch(i){this.logger.warn({err:i,attempt:n},`Failed to reload page${n<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"})}async getBrowserState(e){let{logger:t=this.logger,maxAttempts:n=2,skipWaitForPageLoad:o}=e,i=e.abortSignal??this.abortSignal;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:t,signal:i});let a=0,s;for(;a<n;){a++;try{return await D(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:i,logger:t,filterByViewport:e.filterByViewport}),{milliseconds:this.pageLoadTimeout*a,signal:i,message:"Getting browser state took too long"})}catch(l){if(i?.throwIfAborted(),s=l instanceof Error?l.message:`${l}`,a>=n)throw l;t.debug({err:l,url:this.url()},"Error getting a11y tree, retrying...")}}throw new A("ActionFailureError",`Getting page content failed after ${n} attempts. Error: ${s}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await qe({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:async()=>{},codePath:"getViewportOffsetDetails"});return{upperBound:t,lowerBound:t+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:n=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=m=>{i.value=Date.now()},s=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",s);let l=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>l);let c=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",c);let p=()=>a("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",p);let d=()=>a("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",d);try{await this.waitForDOMStabilityHelper(i,t,n,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",s),this.cdpClient.removeListener("Page.frameDetached",l),this.cdpClient.removeListener("Page.frameStartedLoading",c),this.cdpClient.removeListener("Page.navigatedWithinDocument",p),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),s,l={quality:25,retries:0,hideCaret:!0,disableAnimations:!0},c=!1,p=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await Q(500,this.abortSignal),s)try{let m=await this.screenshot(l);if(!m.equals(s)){s=m,c=!1;continue}c=!0}catch(m){p++,p%3===0&&t.warn({err:m,screenshotErrors:p},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{s=await this.screenshot(l)}catch(m){p++,p%3===0&&t.warn({err:m,screenshotErrors:p},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<750)){i=!0;break}}let d={duration:Date.now()-a,a11yStableReceived:i,lastTreeUpdateMillisecondsAgo:Date.now()-e.value,screenshotStable:c};i||t.warn(d,"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,t){let{x:n,y:o}=e,i=this.url(),a=(await ri(this.context)).map(s=>s.url);this.logger.debug({x:n,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(n,o,{button:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1}),t.waitForUrl&&await this.waitForUrl({beforeUrl:i,beforePages:a,matcher:{type:"GLOB",glob:t.waitForUrl}})}async dragAndDropUsingVisualCoordinates(e,t,n){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await Q(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,t,n,o){await this.hoverUsingVisualCoordinates(o);let i=await(await this.getActivePageOrFrame()).evaluate(fp);i||(this.logger.debug("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await Q(250),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),n=await D(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&n===1&&(n=2);let o=t.documents[0],i=o.layout,a=o.nodes,s=a.nodeName||[],l=a.backendNodeId||[],c=i.nodeIndex,p=i.bounds,d=-1;for(let x=0;x<s.length;x++)if(l[x]===e){d=c.indexOf(x);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[m=0,u=0,h=0,g=0]=p[d];m/=n,u/=n,h/=n,g/=n;let f=m+h/2,S=u+g/2;return{centerX:f,centerY:S}}async scrollVertical(e){return wp({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:0,directionX:null,deltaY:e?Math.abs(e):null,directionY:e&&e>0?"down":"up",signal:this.abortSignal,callbacks:this.getBrowserCallbacks()})}async scrollHorizontal(e){return wp({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks()})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout})}async createRawCDPSession(e){let t=await D(this.context.newCDPSession(this.page),{milliseconds:e??this.pageLoadTimeout,fallback:()=>{throw this.logger.error(`Timed out creating new CDP session for ${this.page.url()}`),new A("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${this.page.url()})`)}});return this.logger.debug(`Created new CDP session for ${this.page.url()}`),t}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async changeActivePage(e,t){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let n=!0,o,i=Date.now();for(;n||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){n=!1;try{await this.switchToPageHelper(e,t);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await Q(500)}}throw o}async switchToPageHelper(e,t){let n=this.context.pages().map((i,a)=>({page:i,url:i.url(),index:a})),o;if(e.type==="INDEX"){let i=Number(e.index);if(isNaN(i))throw new A("UserConfigurationError",`Page index ${e.index} is not a number`);if(i<0||i>=n.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(n.map(a=>a.url))}`);o=n[i]}else{let i=n.filter(a=>e.type==="SUBSTRING"?a.url.includes(e.substring):a.url.match(e.pattern));i.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(i.map(a=>a.url))}`),o=i[i.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
|
|
3608
|
+
Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!lr(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.debug(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,t?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let t;return typeof e=="string"?t=fs(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let n=await this.getActivePageOrFrame();await D(n.evaluate(([o,i])=>{o&&localStorage.setItem(o,i||"")},[e,t]),{milliseconds:2e3})}async solveCaptcha(){await this.getBrowserState({});let e;for(let s of Object.values(this.stateManager.a11yIdToNodeMap))if(s.role==="image"&&s.name.toLowerCase().includes("captcha")){if(!s.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,s.backendNodeId);break}if(!e){let s=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!s.captchas||!s.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:El,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let s=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},s),new Error(s)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<6e4;){await Q(2500);let s=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:El,taskId:o})});if(!s.ok){let c=`Captcha solution API returned error response: ${s.statusText}`;throw this.logger.error({text:await s.text()},c),new Error(c)}let l=await s.json();if(l.errorId){let c=`Captcha solution API returned error ID ${l.errorId}`;throw this.logger.error(c),new Error(c)}if(l.status==="ready"){a=l.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&yb({event:t,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async startRecordingCrons(e){if(e.aborted)return;let t,n=(await this.getOpenPages()).map(s=>s.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let s;try{s=(await this.getOpenPages()).map(c=>c.url),o=0}catch(c){this.logger.debug({err:c},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let l=this.url();for(let c=s.length-1;c>=n.length;c--){let p=s[c];lr(p,this.logger)&&p!==l&&this.logger.info({lastActivePages:n,currentUrl:l,newOpenPages:s},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(c)});break}n=s};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(s){this.logger.error({err:s},"Error while checking pages during recording")}finally{i=!1}}},500),e.addEventListener("abort",async()=>{clearInterval(t)})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(o=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!0,i._MOMENTIC_CLICK_RECORD_ACTIVE=o},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page),e.addEventListener("abort",async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let o=window;o._MOMENTIC_RECORDING_ACTIVE=!1,o._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:1e3})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await Hr({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let s=a;if(s.name==="AbortError")throw new Error(`The page with URL ${_e(i,50)} did not load within the configured timeout (${o}ms): ${s}`);if(!s.message.includes("detached"))throw s}try{await Hr({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlPageLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){this.logger.warn({err:a,codePath:n,url:i},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return sk.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:t,error:n}=await qe({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getCondensedHtmlTree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new A("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}async registerDialogHandler(e){let t=async n=>{try{e==="ACCEPT"?await n.accept():await n.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",t)}async evaluateFunctionInAllFrames(e,t){return this.stateManager.executeFunctionInAllFrames(e,t)}async evaluateFunctionInPage(e,t){let n=await this.getActivePageOrFrame();return D(n.evaluate(e,t),{milliseconds:2e3})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=Yn}){let i=nb(),a={code:e,fragment:t,context:n},{result:s}=await D(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new A("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return s}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new A("InternalWebAgentError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:s}=await this.getViewportOffsetDetails(e),l=Math.round(a),c=Math.round(s),p=Math.ceil(o*t),d=Math.ceil(i*n),m=p+c,u=d+l;return this.getDomNodeFromPixelPosition(m,u)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:Ly,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:1e3,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:1e3})}catch{}}async getTargetFromPixelPosition(e,t=!0){let n=await this.getActivePageOrFrame(),o=await this.getDomNodeFromPixelPosition(e.x,e.y);return this.getTargetFromBackendNodeId(n,o.backendNodeId,t)}async getTargetFromPositionPercentages(e,t=!0){let n=await this.getActivePageOrFrame(),o=await this.getDomNodeFromPositionPercentages(n,e);return this.getTargetFromBackendNodeId(n,o.backendNodeId,t)}async getTargetFromBackendNodeId(e,t,n){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[wt],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let s=e.locator(`[${wt}="${i}"]`);if(n){for(let d of Object.values(this.stateManager.a11yIdToNodeMap)){if(d.backendNodeId!==t)continue;let m={id:d.id,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString()};return await this.saveNodeDetailsToCache({node:d,target:m,locator:s,dataMomenticId:parseInt(i),generateNewCssSelectors:!0}),this.logger.debug({target:m},"Tied backend id to existing a11y node"),{target:m,locator:s}}let p=hl(`${i}`,this.stateManager.domGraph,this.logger);for(let d of p){let m=parseInt(d.attributes?.[wt]??"");if(isNaN(m))continue;let u=e.locator(`[${wt}="${m}"]`),h=this.stateManager.dataMomenticIdToNodeMap[m],g=h?.id;if(!g)continue;let f={id:g,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString()};return await this.saveNodeDetailsToCache({node:h,target:f,dataMomenticId:parseInt(i),locator:u,generateNewCssSelectors:!0}),this.logger.debug({target:f},"Tied backend id on non-accessible element to nearest a11y node"),{target:f,locator:u}}}let l=await this.fetchHtmlAttributes(s,this.logger),c={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...l};return this.logger.debug({target:c},"Tied backend id to html node"),{target:c,locator:s}}async performTargetRedirection(e,t,n){try{return await e.scrollIntoViewIfNeeded({timeout:3e3}),await D(this.performTargetRedirectionHelper(e,t,n),{milliseconds:3e3})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,n){let o=Date.now(),i=await gn(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:1e3})),!n){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:a,y:s,width:l,height:c}=n,p=this.getViewport();if(a<0||s<0||a+l>p.width||s+c>p.height){t.debug("Skipping locator redirection because the element is outside the viewport");return}let d=await this.getActivePageOrFrame(),{dataMomenticId:m,mPathSelector:u,error:h,serializedElement:g,point:f,force:S,logs:x}=await e.evaluate(b=>{let E=window;if(!E.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return E.performTargetRedirection(b)},void 0,{timeout:1e3}),v=Date.now()-o;if(h){t.warn({error:h,serializedElement:g,duration:v,force:S,logs:x},"Got error from target redirection with bounding box");return}else{if(m)return t.debug({newDataMomenticId:m,serializedElement:g,duration:v,force:S,logs:x},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(`[data-momentic-id="${m}"]`),hints:{clickableXY:f,force:S}};if(u)return t.debug({newMPathSelector:u,serializedElement:g,duration:v,force:S,logs:x},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(u),hints:{clickableXY:f,force:S}};if(f)return t.debug({point:f,serializedElement:g,duration:v,force:S,logs:x},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:S}};if(S)return t.debug({serializedElement:g,duration:v,force:S,logs:x},"Forcing click on original element"),{locator:e,hints:{force:S}}}}async fetchHtmlAttributes(e,t=this.logger){let n=await e.evaluate(o=>{let i=window;return i.generateHtmlCacheAttributes?i.generateHtmlCacheAttributes(o):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},void 0,{timeout:2e3});if("error"in n)throw new Error(n.error);return n.warnings.length?t.warn(n,"Got warnings while generating HTML attributes for target"):t.debug(n,"Generated HTML attributes for target"),n.attributes}async moveMouseFromPositionPercentages(e,t){let n=Math.ceil(this.viewport.width*e),o=Math.ceil(this.viewport.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:n,y:o,button:"left",clickCount:0}}),{x:n,y:o}}async clickMouseFromPositionPercentages(e,t,n){let o=Math.ceil(this.viewport.width*t),i=Math.ceil(this.viewport.height*n);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:o,y:i,button:"left",clickCount:e==="down"?1:0},timeout:1e3})}async scrollFromPositionPercentages(e,t,n,o){let i=Math.ceil(this.viewport.width*e),a=Math.ceil(this.viewport.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:i,deltaY:a,x:n,y:o}}),{deltaX:i,deltaY:a}}canSolveCaptchas(){return!!El}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,t,n,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,gp(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!Tl(e)){let l=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(l),this.logToUserConsole(this.page,"error",l);return}let n=t?.trim()||dk(e),o=ok(e),i=pk(e),a=Xc[i];this.page.once("filechooser",async l=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!Tl(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await l.setFiles({name:n,buffer:o,mimeType:Ty.getType(e)||"application/octet-stream"},{timeout:8e3})}catch(c){this.logger.error({err:c},"Error handling file chooser"),this.logToUserConsole(this.page,"error",c.message)}});let s=o.toString("base64");await(await this.getActivePageOrFrame()).evaluate(({fileName:l,base64Data:c,mimeType:p})=>{let d=window;d.momenticFileName=l,d.momenticFileBase64=c;let m=atob(c),u=new Array(m.length);for(let g=0;g<m.length;g++)u[g]=m.charCodeAt(g);let h=new Uint8Array(u);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([h],{type:p})}isSameEntry(g){return g.name===this.name}queryPermission(g){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(g){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let g=new Blob([h]);return new File([g],d.momenticFileName,{type:p})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},d.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new d.MomenticFile])},{fileName:n,base64Data:s,mimeType:a})}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){let e={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},e}async copy(e){try{await this.evaluateFunctionInPage(t=>navigator.clipboard.writeText(t),e)}catch(t){if(t instanceof Error&&t.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e);return}throw t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(new RegExp(e))}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}};import Nk from"fetch-cookie";import{cloneDeep as Mk}from"lodash-es";import{CookieJar as _k}from"tough-cookie";import{z as vt}from"zod";var rne=vt.object({doubleClick:vt.boolean().optional(),rightClick:vt.boolean().optional(),force:vt.boolean().optional(),waitForDownload:vt.boolean().optional(),waitForUrl:vt.string().optional(),delayMs:vt.number().optional(),downloadTimeoutMs:vt.number().optional(),relativePosition:vt.object({x:vt.number(),y:vt.number()}).optional()}),one=vt.object({repeat:vt.number().optional(),convertMeta:vt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:vt.number().optional()});var Ep=(r,e,t)=>{let[n,...o]=e.split("."),i=n;return o.length>=1?Ep(r[i],o.join("."),t):r[i]=t,r};async function mr(r,e={}){let t=await r.getBrowserState(e),n=t.serialize();return e.logger?.debug({tree:n.length>4e5?n.slice(0,4e5):n,activeFrame:r.getActiveFrameConfig()},"Got a11y tree"),{serializedTree:n,tree:t}}var ai=3.1783027;function yk(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function Ca(r){return Math.ceil(Cp(r)/ai)}function Cp(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
|
|
3609
|
+
`,""),t=t.replaceAll(" ","");let n=yk(t);return t.length-n+ai*n}if(typeof r>"u")return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=Cp(t)}),e;if(typeof r=="object"){let t=r;return Object.keys(t).forEach(n=>{e+=String(n).length,n==="image_url"?(t[n]??{}).detail==="high"?e+=1105*ai:e+=85*ai:e+=Cp(t[n])}),e}if(typeof r=="boolean")return r?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof r}': ${r}`)}var Ib={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},Pb={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:15e3,maxLineLength:500},Rb=/<(\S+) id="(\d+)".*?>/g,bk=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,Lb=["h1","h2","section","footer","nav","aside","form","label","dialog"],wk=[...Lb,"span","div","h3"],vk=["table","select","form","ul","ol","menu","pre","code","dialog"],xk=["table","form","dialog","nav","section","ul","select"];function Ap(r){return r.serializedTree.length>r.maxCharacterLength&&(r.logger.warn({serializedTreeLength:r.serializedTree.length},"Serialized condensed tree is too long to chunk, truncating before chunking"),r.serializedTree=r.serializedTree.slice(0,r.maxCharacterLength)),Tk(r)}function Tk({serializedTree:r,options:e,logger:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=e,s=[],l=r.split(`
|
|
3610
|
+
`),c=0,p=[],d=0,m=[],u=[],h=!1;for(;c<l.length;){h&&(s.push({ids:m,content:p.join(`
|
|
3611
|
+
`),tokenLength:d}),p=[],d=0,m=u.length?[u[u.length-1].id]:[],h=!1);let g=l[c],f=Ca(g);d+=f,g.length>a&&(g=g.slice(0,a));let v=Array.from(g.matchAll(Rb)).map(P=>P&&P.length>=3?{tagName:P[1],id:P[2]}:void 0).filter(P=>!!P),E=Array.from(g.matchAll(bk)).map(P=>P&&(P[2]||P[4])).filter(P=>!!P);E.reverse();let C=g.replace(/ id="[0-9]+"/g,"");p.push(C);for(let P of v)m.push(P.id),u.push(P);for(let P of E){let V=u[u.length-1];V&&V.tagName===P&&u.pop()}let I=u.some(P=>vk.includes(P.tagName)),M=l[c+1]??"",L=Ca(M),j=Array.from(M.matchAll(Rb)).map(P=>P&&P.length>2?P[1]:void 0).filter(P=>!!P),k=j.some(P=>Lb.includes(P)),U=j.some(P=>wk.includes(P));d+L>=i&&(h=!0),d>=n&&(k&&!I||E.some(P=>xk.includes(P)))&&(h=!0),d>=o&&U&&!I&&(h=!0),c++}return p.length&&s.push({ids:m,content:p.join(`
|
|
3612
|
+
`),tokenLength:d}),s.forEach((g,f)=>{t.debug({chunk:g},`Chunk for page filtering (index ${f+1}/${s.length})`)}),{chunks:s}}var Rp=4e4,Ip=8e4;async function Qr(r){let{serializedTree:e,logger:t,flagStore:n,softTokenLimit:o=Rp}=r;if(Ca(e)<o)return e;let a=n.isBooleanFlagEnabled("rag_v2"),s;a?s=Ap({serializedTree:e,options:Pb,logger:t,maxCharacterLength:1e6}):s=Ap({serializedTree:e,options:Ib,logger:t,maxCharacterLength:3e6});try{return a?await D(Ek({...r,chunks:s.chunks}),{milliseconds:2e4}):await D(Ak({...r,chunkResult:s}),{milliseconds:15e3})}catch(l){t.warn({err:l},"Error executing page filtering, attempting AI keyword fallback");try{return await Ck({...r,chunks:s.chunks})}catch(c){return t.warn({err:c},"Error executing page filtering using keyword matching, using naive truncation"),e.slice(0,Ip*ai)}}}async function Ek({chunks:r,generator:e,description:t,type:n,logger:o,signal:i,tree:a,softTokenLimit:s=Rp,hardTokenLimit:l=Ip}){let c=await e.rankChunksWithAi({chunks:r,description:t,type:n,softTokenLimit:s,hardTokenLimit:l},{abortSignal:i,logger:o,loggerTags:We(o)}),p=[];r.forEach((m,u)=>{c.indices.includes(u)&&(p=p.concat(m.ids))});let d=a.pruneUsingRelevantIds(new Set(p)).serialize();return o.debug({description:t,type:n,selectedChunks:c,tree:d},"Pruned a11y tree with AI page filtering"),d}async function Ck(r){let{type:e,description:t,generator:n,tree:o,logger:i,hardTokenLimit:a=Ip}=r;if(!t.trim())throw new Error("Empty description passed to page filtering");let s=await n.getExtractedKeywords({goal:t},{logger:r.logger,loggerTags:We(r.logger)});for(let l of s.keywords){let c=r.chunks.filter(u=>u.content.toLowerCase().includes(l.toLowerCase()));if(!c.length||c.reduce((u,h)=>u+h.tokenLength,0)>a&&c.length>1)continue;let d=c.flatMap(u=>u.ids),m=o.pruneUsingRelevantIds(new Set(d)).serialize();return i.debug({description:t,type:e,selectedChunks:c,tree:m},"Pruned a11y tree with keyword page filtering"),m}throw new Error("No keywords were unique enough for page filtering")}async function Ak(r){let{description:e,generator:t,tree:n,logger:o,signal:i,chunkResult:a,softTokenLimit:s=Rp}=r,l=await t.rankChunksWithRag({description:e,chunks:a.chunks,tokenLimit:s},{abortSignal:i,logger:o,loggerTags:We(o)});if(l.ids.length===0)throw new Error("RAG returned no important ids");{let c=n.pruneUsingRelevantIds(new Set(l.ids.map(p=>`${p}`))).serialize();return o.debug({browserState:c},"Pruned a11y tree with RAG"),c}}async function Lp(r,e){if(!r.description)throw new A("ActionFailureError","Cannot locate element with empty description");return Cn({action:async()=>Rk(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:e.logger})}async function Rk(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a}=r,{ctx:s,orgId:l,logger:c,browser:p,localCodeEvalTools:d,generator:m,abortSignal:u,flagStore:h}=e,g=r.description;n&&(g=await jt({orgId:l,s:g,context:n,logger:e.logger,localTools:d,signal:e.abortSignal,flagStore:h})),a&&(g=Ik(g,a));let{serializedTree:f,tree:S}=await mr(p,{filterByViewport:o,abortSignal:u,skipWait:i,logger:c}),x,v=Date.now(),b;for(;!x&&Date.now()-v<3e3;){u.throwIfAborted();try{x=await p.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(P){b=P}}if(!x)throw new A("InternalWebAgentError",`Failed to take screenshot of page to locate element: ${b?.message}`);let E=f,C=!1;E=await Qr({type:"locator",description:g,serializedTree:f,flagStore:e.flagStore,tree:S,logger:c,generator:m}),E!==f&&(C=!0);let M=`data:image/jpeg;base64,${x.toString("base64")}`,L=await m.getElementLocation({browserState:E,goal:g,screenshot:M,source:a},{disableCache:t,abortSignal:u,loggerTags:We(c)});c.debug({usedRag:C,result:L},"Got locator result");let z=L.id>0;if(s?.details?.push({type:"AI_LOCATION",matched:z,pageState:E,ragUsed:C,thoughts:L.thoughts}),!z)throw new A("ActionFailureError",`Could not find any relevant element: ${L.thoughts}`);let{resolution:j,target:k,frameConfig:U}=await p.createTargetFromA11yId({id:L.id,description:g,targetSource:"AI",logger:c});if(j.a11yNode?.properties?.hidden&&j.a11yNode?.properties?.hidden!=="false")throw new A("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${j.displayString}`);return{thoughts:L.thoughts,target:k,resolution:j,frameConfig:U,screenshot:M}}var kb="<select> element:",Ob="text input or contenteditable element:",Nb="Element exactly matching the description below. Interpret the description narrowly and do not assume there are any typos or errors. Err on the side of returning -1 unless there is a perfect match. Description:",Pp=[kb,Ob,Nb];function Mb(r,e){if(r===e)return!0;for(let t of Pp){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Pp.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Pp.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function Ik(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${kb} ${r}`;case"TYPE":return`${Ob} ${r}`;case"NEGATED_CHECK":return`${Nb}
|
|
3613
|
+
${r}`;default:return r}}var Pk=15;async function kp({command:r,fixtures:e}){if(!r.assertion.trim())throw new A("ActionFailureError","Assertion command is missing the assertion content");let{browser:t,logger:n}=e,o=r.timeout?r.timeout*1e3:t.smartWaitingTimeout,i=Lk(o),a=0,s=Date.now(),l,c,p;try{await Cn({action:()=>t.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:t,logger:n})}catch(m){n.warn({err:m},"Failed to clear highlights before AI assertion, continuing...")}let d;for(;a<Pk&&(!d||d-s<o);){e.abortSignal.throwIfAborted(),a!==0&&(n.info(`Waiting ${i}ms before retrying AI assertion`),await Q(i,e.abortSignal)),d=Date.now();try{let m=await Cn({action:async()=>{let u=await _b(t,n,e.abortSignal);return c&&c.serializedTree===u.serializedTree&&c.screenshotBuff.equals(u.screenshotBuff)?!1:(c=u,Fb({command:r,state:u,fixtures:e,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:a}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:n,browser:t});if(!m)continue;l=m;break}catch(m){e.abortSignal.throwIfAborted(),p=m instanceof Error?m:new Error(`${m}`),n.info({err:m},`AI_WAIT assert attempt ${a} failed, retrying...`)}finally{a++}}if(!l)try{l=await Cn({action:async()=>Fb({command:r,state:await _b(t,n,e.abortSignal),fixtures:e,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:a}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:n,browser:t})}catch(m){e.abortSignal.throwIfAborted(),p=m instanceof Error?m:new Error(`${m}`)}finally{a++}if(!l){let m=`AI assertion still failing after ${a} attempts.`;throw p&&(m+=` Latest result: ${p.message}`),new A("AssertionFailureError",m,{lastScreenshotBuffer:c?.screenshotBuff})}return l}async function _b(r,e,t){let[n,o]=await Promise.all([mr(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function Fb({command:r,state:e,fixtures:t,useConsensus:n,highlightElementsOnFailure:o,attemptNumber:i}){let{browser:a,logger:s,generator:l,abortSignal:c}=t,p={type:"ASSERTION"},{serializedTree:d,tree:m}=e,u=e.screenshotBuff,h=a.url(),g=d;g=await Qr({type:"assertion",serializedTree:d,description:r.assertion,flagStore:t.flagStore,tree:m,generator:l,logger:s,signal:c}),g!==d&&(p.ragUsed=!0),p.pageState=g;let f={goal:r.assertion,url:h,browserState:g,screenshot:u.toString("base64"),contextChoice:r.contextChoice},x=await(r.contextChoice==="VISION_ONLY"?(v,b)=>l.getVisualAssertionResult(v,b):(v,b)=>l.getAssertionResult(v,b))(f,{useConsensus:n,attemptNumber:i,disableCache:!!r.disableCache,logger:s,abortSignal:c,loggerTags:We(s)});if((x.result||o)&&x.relevantElements&&(p.relevantElementsSerialized=x.relevantElements.map(v=>a.getSerializedFormFromA11yId(v)).filter(v=>!!v),await kk(x.relevantElements,a,s)),!x.result)throw new A("AssertionFailureError",x.thoughts);return{succeedImmediately:!1,thoughts:x.thoughts,urlAfterCommand:h,afterScreenshotOverride:u}}function Lk(r){let e;return r>10*60*1e3?e=2*60*1e3:r>60*1e3?e=20*1e3:r>10*1e3?e=2*1e3:e=1e3,e}async function kk(r,e,t){let n=Date.now();for(let o of r){if(Date.now()-n>2e3){t.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await D(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var Ok=3e4;async function Db({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??Ok/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,m])=>d&&m)),s;if(ei(r.url)&&(s=r.url),t&&ti(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new A("ActionFailureError",`Invalid URL: ${r.url}`);let c=await D((async()=>{try{return await n(s,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!c)throw new A("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!c.ok){let d;try{d=await c.json()}catch{throw new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${await c.text()}`)}throw d?.errors?.length&&d?.errors[0]?.message?new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${d.errors[0].message}`):new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${await c.text()}`)}let p={};return c.headers.forEach((d,m)=>{p[m]=d}),{status:c.status,headers:p,json:await c.json()}}var si=class{flagStore;orgId;scratchPadId;slowMoMs;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;analytics;recordAbortController=null;registeredListeners={};constructor({browser:e,generator:t,logger:n,analytics:o,flagStore:i,storage:a,orgId:s,localCodeEvalTools:l,uploadedFileStorage:c,visualDiffScreenshotStorage:p,scratchPadId:d,slowMoMs:m}){this.orgId=s,this.scratchPadId=d,this.slowMoMs=m,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=a,this.uploadedFileStorage=c,this.visualDiffScreenshotStorage=p,this.localCodeEvalTools=l,this.generator=t,this.logger=n,this.analytics=o,this.flagStore=i}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[l,c]=await Promise.all([mr(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),p=await Qr({type:"ai-action",description:e,serializedTree:l.serializedTree,tree:l.tree,logger:s,generator:this.generator,flagStore:this.flagStore,softTokenLimit:25e3,hardTokenLimit:5e4}),d=`data:image/jpeg;base64,${c.toString("base64")}`,m={url:this.browser.url(),browserState:p,startingScreenshot:t,history:n,goal:e,screenshot:d,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...We(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let l=this.browser.url(),[c,p]=await Promise.all([mr(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${p.toString("base64")}`,m=await Qr({type:"ai-action",description:e,serializedTree:c.serializedTree,tree:c.tree,logger:a,generator:this.generator,flagStore:this.flagStore,softTokenLimit:25e3,hardTokenLimit:5e4}),u={url:l,browserState:m,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(u,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...We(a)},langfuseSessionId:s})}catch(h){throw new A("InternalWebAgentError",`Error generating command: ${h instanceof Error?h.message:h}`,{errOptions:{cause:h}})}}async getBrowserState(e){return mr(this.browser,e)}async locateElement(e){return Lp(e,this.getControllerFixtures())}async locateElementWithSelector(e,t){return Cn({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:t?{type:"url",url:t}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,flagStore:this.flagStore,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}async wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:a,action:s,options:l,retriesWithAI:c=1}){let p=[];for(let d=0;d<i.length;d++){let m=i[d],u=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:m,cache:a[d],action:async h=>h,options:{...l,skipFetchTree:d!==0,targetName:o[d]}});p.push(u)}try{return{result:await s(...p.map(m=>m.result)),elementInteractedDisplayStrings:p.map(m=>m.elementInteractedDisplayString),newTargets:p.map(m=>m.newTarget)}}catch(d){if(this.throwIfClosed(),c>0)return this.logger.debug({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:l,retriesWithAI:c-1});throw new A("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let t=this.logger.child({commandId:e.command.id}),n;for(let o=0;o<2;o++)try{return await Cn({action:()=>this.wrapElementTargetingCommandHelper(e),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:t})}catch(i){if(n=i,this.flagStore.isBooleanFlagEnabled("visual_actions")&&Jc(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.flagStore.isBooleanFlagEnabled("visual_actions")&&Wi(i)){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}throw i}throw n instanceof A?n:new A("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:s="target"}=o;if(t.type!=="description")throw new A("ActionFailureError","Cannot use selector with non-description target");let l=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:s,logger:a});return{result:await n({locator:l.locator}),elementInteractedDisplayString:l.displayString,newTarget:{cache:{id:-1,selector:t.elementDescriptor,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()}}}}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,action:i,options:a,command:s}=e,{disableCache:l,useSelector:c,targetName:p="target",targetHealingInProgress:d,source:m}=a,u=this.logger.child({commandId:s.id}),h=a.retriesWithAI??1,g=!1,f=e.cache;if((!f||l)&&!oc(o))throw new A("ActionFailureError","Cannot target element with no cached data or element descriptor");if(c)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(u.debug("Cache explicitly disabled for this step"),g=!0,f=void 0),f?.inputDescription&&!Mb(o.elementDescriptor,f.inputDescription)&&(u.warn({old:f.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),g=!0,f=void 0);let S=!!f&&Lu(f);if(!f){let x=new Date;u.debug({targetHealingInProgress:d,cacheBustedBeforeAction:g},"Prompting AI for an updated element location"),g&&await Q(this.browser.smartWaitingTimeout,this.executeAbortController.signal),h--;let v=await Lp({description:o.elementDescriptor,disableCache:l,iframeUrl:a.iframeUrl,source:m},this.getControllerFixtures(t));v.frameConfig&&this.browser.setActiveFrameConfig(v.frameConfig);let b=a.disableGlobalLocatorRedirect?{locator:v.resolution.locator}:await this.attemptLocatorRedirect(v.resolution.locator,u),E=await i(b),C;if(d){n.heal({healType:"AI"}),this.analytics.track({type:"execution:step_heal",heal_type:"AI",step_type:"PRESET_ACTION",command_type:s.type,duration_ms:Date.now()-x.getTime()}),v.target.targetSource="AI_HEALED",v.target.targetUpdateTime=new Date().toUTCString();let I=v.resolution.pageState;if(I)try{C=await this.getReverseMappedDescription({browserState:I,targetId:v.target.id,disableCache:!0,screenshot:v.screenshot})}catch(M){u.warn({err:M},"Failed to reverse map element auto-healed by AI, continuing...")}}return{result:E,elementInteractedDisplayString:v.resolution.displayString,newTarget:{cache:v.target,thoughts:v.thoughts,description:C}}}try{let x=new Date,v=await this.browser.resolveTarget(t,f,{targetName:p,logger:u});(this.flagStore.isBooleanFlagEnabled("global_locator_redirect")||this.flagStore.isBooleanFlagEnabled("visual_actions"))&&await v.locator.scrollIntoViewIfNeeded({timeout:2e3});let b=a.disableGlobalLocatorRedirect?{locator:v.locator}:await this.attemptLocatorRedirect(v.locator,u),E=await i(b);if(S){let C=v.decisions.filter(I=>I.matched);if(C.length!==1)u.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let I=C[0].type;n.heal({healType:I}),this.analytics.track({type:"execution:step_heal",heal_type:I,step_type:"PRESET_ACTION",command_type:s.type,duration_ms:Date.now()-x.getTime()})}}return{result:E,elementInteractedDisplayString:v.displayString,newTarget:{cache:f}}}catch(x){this.throwIfClosed();let v=fh(x)&&!Jc(x)&&!Wi(x);if(x instanceof A&&!v)throw x;if(h>0&&o)return u.debug({err:x,cache:f},"Failed to execute action with cached target, retrying with AI"),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:s,target:o,cache:void 0,action:i,options:{...a,retriesWithAI:h,targetHealingInProgress:!0}});throw new A("ActionFailureError",x.message,{errOptions:{cause:x}})}}async attemptLocatorRedirect(e,t){return this.flagStore.isBooleanFlagEnabled("global_locator_redirect")?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return va(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.slowMoMs&&await Q(this.slowMoMs);let a;try{a=await this.resolveCommandTemplateStrings(n,o)}catch(s){throw this.throwIfClosed(),new A("ActionFailureError",`Failed to substitute template strings in command: ${s.message}`,{errOptions:{cause:s}})}try{let s=(await this.browser.getOpenPages()).map(u=>u.url),l=this.browser.url(),c=await this.executePresetCommandHelper(e,t,n,o,i);this.flagStore.isBooleanFlagEnabled("visual_actions")&&Mu(n)?await this.browser.waitForDOMStability():this.flagStore.isBooleanFlagEnabled("visual_actions")&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:1e3});let p=!0;(n.type==="NAVIGATE"||n.type==="NEW_TAB"||n.type==="TAB"||n.type==="REFRESH"||n.type==="WAIT_FOR_URL")&&(p=!1);let d=(await this.browser.getOpenPages()).map(u=>u.url),m=this.browser.url();if(p&&d.length!==s.length)for(let u=d.length-1;u>=s.length;u--){let h=d[u];if(lr(h,this.logger)&&h!==l&&h!==m){this.logger.info({beforePages:s,afterPages:d,beforeUrl:l},"Auto-following new tab after preset action"),await this.browser.switchToPage({type:"INDEX",index:String(u)});break}}return c}catch(s){throw s.name!=="AbortError"&&this.logger.error({err:s},"Error thrown in action controller"),s}finally{this.restoreCommandTemplateReplacements(n,a)}}restoreCommandTemplateReplacements(e,t={}){for(let[n,o]of Object.entries(t))Ep(e,n,o)}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>mp(e)}}async resolveCommandTemplateStrings(e,t){return Qo({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools,flagStore:this.flagStore})}async executePresetCommandHelper(e,t,n,o,i){switch(i=i||"disableCache"in n&&!!n.disableCache,n.type){case"SUCCESS":let a=n.condition;return a?.assertion.trim()?kp({command:a,fixtures:this.getControllerFixtures(e)}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_WAIT":case"AI_ASSERTION":{if(!n.assertion.trim())throw new A("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new A("AssertionFailureError",`AI assertion timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return kp({command:{...n,type:"AI_ASSERTION"},fixtures:this.getControllerFixtures(e)})}case"AI_EXTRACT":{if(!n.goal.trim())throw new A("ActionFailureError","Cannot perform AI extraction without goal");let u=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let g=await this.generator.getTextExtraction({goal:n.goal,browserState:u,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:We(this.logger)});if(g.result==="NOT_FOUND")throw new A("ActionFailureError","No relevant data found for extraction goal on this page");if(g.thoughts?.includes("MaxGenerationLengthExceededError"))throw new A("UserConfigurationError",g.thoughts);return{thoughts:g.thoughts||void 0,data:g.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(g){let f=g.message;throw f.includes("MaxGenerationLengthExceededError")?new A("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):f.includes("AIProviderError")&&f.includes("time")?new A("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:g}}):g}}case"NAVIGATE":if(!ei(n.url)&&!ti(n.url,this.browser.baseUrl))throw new A("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let s=await this.browser.solveCaptcha();s&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:u=>this.browser.click(u,this.createCallbacksForBrowser(this.orgId),{}),options:{disableCache:i,useSelector:!!n.useSelector,iframeUrl:n.iframeUrl}}),await this.browser.type(s,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let u,h=[];if(n.target&&yn(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{newTarget:g,elementInteractedDisplayString:f}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:S=>this.browser.hover(S),options:{disableGlobalLocatorRedirect:!0,disableCache:i,useSelector:!!n.useSelector,iframeUrl:n.iframeUrl}});u=f,h.push(g)}switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??0));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??0));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:u,newTargets:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new A("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let u=n.matcher;if(!u&&n.url&&(u={type:"GLOB",glob:n.url}),!u)throw new A("UserConfigurationError","No URL matcher provided for wait for URL command");await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:u},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new A("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await Q(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(yn(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let u=this.browser.url(),h={disableCache:i,useSelector:!!n.useSelector,iframeUrl:n.iframeUrl},{elementInteractedDisplayString:g,newTarget:f,result:S}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:v=>this.browser.click(v,this.createCallbacksForBrowser(this.orgId),n),options:h});f.cache&&(n.cache={target:f.cache});let x={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,newTargets:[f],data:S};return nl(u,x.urlAfterCommand)&&(x.succeedImmediately=!0,x.succeedImmediatelyReason="URL changed"),x}case"COPY":return await this.browser.copy(n.value),{succeedImmediately:!1,data:n.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(yn(n.fromTarget)&&yn(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(yn(n.fromTarget)||yn(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{newTargets:u,elementInteractedDisplayStrings:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["from target","to target"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(g,f)=>this.browser.dragAndDrop(g.locator,f.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h[0],newTargets:u}}case"MOUSE_DRAG":{let u=parseInt(n.deltaX),h=parseInt(n.deltaY),g=n.steps??5;if(isNaN(u)||isNaN(h))throw new A("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&yn(n.target)){await this.browser.mouseDragUsingVisualCoordinates(u,h,g,n.target.pixels,{force:n.force});break}let f,S,x=[];if(n.target?.elementDescriptor){let{newTarget:v,elementInteractedDisplayString:b,result:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async C=>C.locator,options:{useSelector:!!n.useSelector,iframeUrl:n.iframeUrl,disableCache:i}});f=E,S=b,x.push(v)}return await this.browser.mouseDrag(u,h,g,f,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:S,newTargets:x}}case"SELECT_OPTION":{if(!qn(n.target))throw new Error("Select with x/y is not supported yet");let u=n.target.elementDescriptor,h=n.choice??{type:"VALUE",value:n.option},{newTarget:g,elementInteractedDisplayString:f}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:u},cache:n.cache?.target,action:S=>this.browser.selectOption(S,h,n.force),options:{disableCache:i,useSelector:!!n.useSelector,iframeUrl:n.iframeUrl,source:Oi(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,newTargets:[g]}}case"TAB":{let u={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};if(n.url)await this.browser.switchToPage({type:"SUBSTRING",substring:n.url},u);else if(n.action)await this.browser.switchToPage(n.action,u);else throw new A("UserConfigurationError","No method definition was specified for the tab switch command");break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let c=await this.browser.setCookie(n.value);this.logger.debug({results:c},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let u;try{n.environment==="BROWSER"?(u=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),this.logger.debug({result:u},"Executed JavaScript in browser")):u=await Fn({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:this.logger,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,flagStore:this.flagStore,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.scratchPadId){this.logger.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.scratchPadId,orgId:this.orgId,updates:h,logger:this.logger})}}})}catch(h){throw this.throwIfClosed(),new A("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(u)}catch(h){throw new A("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:u}}case"TYPE":{if(n.target&&yn(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let u=this.browser.url(),h,g=[],f=Mk(n.target);if(f){let{elementInteractedDisplayString:x,newTarget:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:f,cache:n.cache?.target,action:b=>this.browser.typeIntoTarget(n.value,b,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter}),options:{disableCache:i,useSelector:!!n.useSelector,iframeUrl:n.iframeUrl,disableGlobalLocatorRedirect:!0,source:Oi(n)}});g.push(v),h=x}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let S={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,newTargets:g};return nl(u,S.urlAfterCommand)&&(S.succeedImmediately=!0,S.succeedImmediatelyReason="URL changed"),S}case"HOVER":{if(yn(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{newTarget:u,elementInteractedDisplayString:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:g=>this.browser.hover(g),options:{disableCache:i,useSelector:!!n.useSelector,iframeUrl:n.iframeUrl}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h,newTargets:[u]}}case"FOCUS":{if(!qn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:u,newTarget:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:g=>this.browser.focus(g),options:{disableCache:i,useSelector:!!n.useSelector,iframeUrl:n.iframeUrl}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:u,newTargets:[h]}}case"BLUR":{if(n.target&&!qn(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{newTarget:u,elementInteractedDisplayString:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:g=>this.browser.blur(g),options:{disableCache:i,useSelector:!!n.useSelector,iframeUrl:n.iframeUrl}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h,newTargets:[u]}}case"PRESS":let p=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let d={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return nl(p,d.urlAfterCommand)&&(d.succeedImmediately=!0,d.succeedImmediatelyReason="URL changed"),d;case"REQUEST":{let u=new _k,h=Nk(fetch,u),g;try{g=new URL(n.url).hostname}catch{}return{data:{...await rl({command:n,baseUrl:this.browser.baseUrl,logger:this.logger,fetchImplementation:h}),cookies:ys(u,g)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await Db({command:n,baseUrl:this.browser.baseUrl,logger:this.logger}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return JS({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:this.logger,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:u=>this.wrapElementTargetingCommand(u)});case"FILE_UPLOAD":{let u,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,u=await Wy({uri:n.fileSource.url,logger:this.logger,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,u=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!u)throw new A("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...u,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let u;if(!n.storageState.trim())u=void 0;else if(u=await Fn({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:this.logger,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,flagStore:this.flagStore}),typeof u!="object")throw new A("ActionFailureError",`Credentials must evaluate to an object (received ${typeof u} instead)`);let h;try{h=Ss.optional().parse(u)}catch(g){throw new A("ActionFailureError",`Credentials provided do not follow the required format: ${g}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let u=(n.timeout??wn)*1e3,h=await KS({command:n,tracer:t,timeoutMs:u,targetingWrapper:g=>this.wrapElementTargetingCommand(g),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!h.success,data:h.data,elementInteracted:h.elementInteractedDisplayString,newTargets:h.newTarget?[h.newTarget]:[],thoughts:h.err?.message??h.thoughts??`Element assertion ${h.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let u=await Cn({action:async()=>ol({assertion:n.assertion,browser:this.browser,logger:this.logger,timeout:n.timeout,signal:this.executeAbortController.signal,flagStore:this.flagStore}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:this.logger});return{fail:!u.success,data:u.data,thoughts:u.success?"Page assertion passed.":u.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let h=this.browser.registerRequestListener(n.pattern).then(async g=>{let f={status:g?.status(),headers:g.headers()};return(await g.headerValue("content-type"))?.includes("json")?f.json=await g.json():(await g.headerValue("content-type"))?.includes("text")&&(f.text=await g.text()),f});return this.registeredListeners[n.key]=h,{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let u=this.registeredListeners[n.key];if(!u)throw new A("ActionFailureError",`No listener registered with key: ${n.key}`);return{data:await D(u,{milliseconds:(n.timeout??10)*1e3,message:`Request listener timed out after ${n.timeout} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}default:return(u=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:We(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:t,isClickToRecord:n}){this.recordAbortController=t;let o=new wl({signal:t.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,n),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:We(this.logger)})}async runFailureRecovery(e){return this.generator.getFailureRecoveryProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:We(this.logger)})}};var Fk=4;async function Ub({socket:r,logger:e,analytics:t,storage:n,uploadedFileStorage:o,visualDiffScreenshotStorage:i,serviceMocker:a,devicePixelRatio:s,generatorFactory:l,enricherFactory:c,browserbase:p,authorization:d,flagStoreFactory:m,settingsFactory:u}){let h=r.id,g=r.handshake.query.testId;if(!g)throw new Error("Socket connection request is missing testId");let f=await n.getOrgId({type:"e2e",testId:g});e=e.child({testId:g,orgId:f,sessionId:h});let S=await l(f,e),x=await c(f,e),v=await m(f),b=await u(f,e),{testMetadata:E,baseUrl:C,envName:I,localBrowserConfig:M,environmentVariables:L,localCodeEvalTools:z}=await eo({testId:g,orgId:f,logger:e,storage:n,authorization:d,flagStore:v,settings:b}),j=Z.getSession(h);if(j)return e.info("Associating connection with existing session (likely reconnect)"),await j.controller.browser.clearAllCdpHighlights(),{type:"e2e",sessionId:h,orgId:f,testId:g};let k=r.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:k,event:"connect",args:r.handshake.query},"Websocket event (connect)"),k&&Z.getCurrentConnectionsByIp(k)>=Fk)throw e.error({clientIp:k,sessions:Z.getCurrentSessionsByIp(),...r.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close duplicate tabs and try again later.");Z.reserveCapacityByIp(k);try{await Dk({socket:r,baseUrl:C,envName:I,testMetadata:E,orgId:f,sessionId:h,logger:e,analytics:t,environmentVariables:L,clientIp:k,devicePixelRatio:s,storage:n,uploadedFileStorage:o,visualDiffScreenshotStorage:i,serviceMocker:a,localCodeEvalTools:z,generator:S,enricher:x,browserbase:p,localBrowserConfig:M,flagStore:v})}catch(U){throw e.warn({err:U},"Error setting up socket session, possibly due to client closing the connection"),Z.releaseCapacityByIp(k),U}return{type:"e2e",sessionId:h,testId:g,orgId:f}}async function Dk({socket:r,baseUrl:e,envName:t,devicePixelRatio:n,testMetadata:o,orgId:i,sessionId:a,logger:s,analytics:l,storage:c,uploadedFileStorage:p,visualDiffScreenshotStorage:d,serviceMocker:m,localCodeEvalTools:u,generator:h,environmentVariables:g,localBrowserConfig:f,clientIp:S,enricher:x,flagStore:v}){let b={viewport:o.advanced?.viewport??Dt,locale:o.advanced?.locale??Pr,timezoneId:o.advanced?.timezone??Lr};n&&(b.deviceScaleFactor=n);let E=o.id,C=await m?.initializeServicesForTest(i,E),I=await pl({advanced:{...f,...o.advanced},orgId:i,baseUrl:e,envName:t,localTools:u,envVariables:g,logger:s,customHeaders:void 0,flagStore:v});s=s.child({orgId:i,sessionId:a,testId:E});let M=!1,L=v.isBooleanFlagEnabled("icon_knowledge_base")?await c.fetchIconKnowledgeBase(i,s):null,z=await fn.init({baseUrl:e,userBrowserSettings:I,enricher:x,storage:c,flagStore:v,mockedServices:C,logger:s,contextArgs:b,iconKnowledgeBase:L,onTabsChange:(V,N)=>{r.emit("tabs",{tabs:V,activeTab:N})},callbacks:{onScreencastFrame:(V,N)=>{let X=r;M&&(X=r.compress(!0)),X.emit("screenshot",{buffer:V},()=>{N()})},onSvgsCollected:V=>{r.emit("newIconDetected",{numIcons:V.newSvgs.length}),c.saveNewIcons(i,V,s)}}});await z.navigate({url:e,initialNavigation:!0});let j=new si({browser:z,generator:h,logger:s,analytics:l,flagStore:v,orgId:i,scratchPadId:void 0,storage:c,localCodeEvalTools:u,uploadedFileStorage:p,visualDiffScreenshotStorage:d,slowMoMs:I.slowMoMs}),k=RS(r,a,s),U=async()=>{k.timers.forEach(V=>clearInterval(V))},P=new It({baseUrl:e,currentUrl:j.browser.url(),variablesFromEnvironment:g,envName:t});if(!r.connected)throw await z.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");r.emit("session",{url:e,userAgent:fn.USER_AGENT,viewport:j.browser.getViewport(),sessionId:a}),Z.registerSession({controller:j,context:P,sessionId:a,cleanup:U,clientIp:S})}async function eo({testId:r,orgId:e,logger:t,storage:n,authorization:o,flagStore:i,settings:a}){let s=await n.fetchTestMetadata(r,e,t);if(!s)throw new Error(`Test metadata could not found for test ${r}`);let l;o?.type==="API_KEY"&&(l=new ar({httpClient:new _t({...o,logger:t}),fakerSeed:void 0}));let c=s.envs?.find(g=>g.default),p;c&&(p=await n.fetchEnvironment(e,c.name,t));let d=p&&"browser"in p?p.browser:void 0,m={...a.browser,...d},u=s.baseUrl||p?.variables?.[Ie];if(!u)throw new Error("Base URL is empty in both test options and the configured environment");let h={...p?.variables};return await Promise.all((s.parameters??[]).map(async g=>{let f=await jt({orgId:e,s:g.defaultValue,context:It.dummyContext(p?.name,h),logger:t,flagStore:i,localTools:l});h[g.name]=f})),{localCodeEvalTools:l,baseUrl:u,envName:p?.name,localBrowserConfig:m,environmentVariables:h,testMetadata:s}}import{diff as Uk}from"deep-object-diff";var Op=class{parentTracer=null;socket;step;constructor({step:e,socket:t,parentTracer:n}){this.socket=t,this.parentTracer=n,this.step=e}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}heal(){}async finish(e){switch(e.step.status){case"SUCCESS":this.socket.emit("success",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"FAILED":this.socket.emit("failure",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"CANCELLED":this.socket.emit("cancelled",{...e,parentStepIdChain:this.getParentStepIdChain()});return}}async startSubSteps(){return new Cl({parentStep:this.step,socket:this.socket,parentTracer:this})}},Cl=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:t,parentTracer:n}){this.parentTracer=n,this.parentStep=e,this.socket=t}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:this.getParentStepIdChain()}),new Op({step:e.step,parentTracer:this,socket:this.socket})}},Al=class{constructor(e,t,n,o,i){this.socket=e;this.storage=t;this.orgId=n;this.testId=o;this.stepsBeforeRun=i}trackStatus(){}attachConsoleLogs(){}attachNetworkLogs(){}async finish(e){this.socket.emit("finished");let{logger:t,result:n,updatedSteps:o}=e;if(n?.status==="PASSED"&&o){let i=o.steps,a=Uk(this.stepsBeforeRun,i);if(Object.keys(a).length>0){t.debug({changes:a},"Updating steps post-run success");let{cachesToSave:s}=await Qe({stepLists:{steps:i},cacheCreationParams:{testId:this.testId,orgId:this.orgId}});try{await this.storage.saveStepCacheEntries(s,this.testId,t)}catch(l){t.warn({err:l},"Failed to save step cache entries after execution success")}}else t.debug("No changes detected in steps post-run success")}}async startStepList(){return new Cl({parentStep:null,parentTracer:null,socket:this.socket})}};var Np={currentlyExecutingRequests:{}},zk=r=>async(e,t)=>{let{testId:n,orgId:o}=r.metadata,i=await r.flagStoreFactory(o),a=await r.settingsFactory(o,r.logger),s,l=await eo({testId:n,orgId:o,logger:r.logger,storage:r.storage,authorization:r.authorization,flagStore:i,settings:a}),c=`${n}|${l.baseUrl}`;try{let p=Np.currentlyExecutingRequests[c]??0;Np.currentlyExecutingRequests[c]=p+1,s=await jk({...r,...e,...l,done:t})}finally{r.logger.info({result:s,sessionId:r.metadata.sessionId},"Test execution complete"),Np.currentlyExecutingRequests[c]--}},jk=async({socket:r,steps:e,baseUrl:t,testMetadata:n,reInitialize:o,toStep:i,fromStep:a,storage:s,metadata:l,logger:c,analytics:p,envName:d,environmentVariables:m,localCodeEvalTools:u,done:h})=>{let{testId:g,sessionId:f,orgId:S}=l,x=f,v=Z.getSession(f);if(!v)throw new Error("No active session found");let{controller:b,context:E}=v;b.setOpen(),c=c.child({testId:g,orgId:S,sessionId:f,runId:x}),c.info({steps:e.map(N=>`${N.type}${"command"in N?` - ${N.command.type}`:""}`),toStep:i,fromStep:a,reInitialize:o,envName:d,baseUrl:t,context:E,flags:b.flagStore.getAllFlags()},"Socket execution parameters");let C=m??{},I=async()=>{o&&(await b.browser.reset({newUrl:t}),E.reset({baseUrl:t,currentUrl:b.browser.url(),variablesFromEnvironment:C,envName:d}))},M=async()=>{try{await s.resolveStepCacheEntries({schemaVersion:n.schemaVersion,organizationId:S,testId:g,steps:e,logger:c})}catch(N){c.error({err:N},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await Ji({promiseGenerator:async()=>Promise.all([I(),M()]),signal:b.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),b.setOpen()}catch(N){if(r.emit("finished"),N.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${N}`)}let L=Bk(e),z={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},j={orgId:S,runId:x,testMetadata:n,steps:e,fromStep:a,toStep:i},k={controller:b,context:E,storage:s,debugDataStorage:new _r,codeEvalTools:u,billingReporter:new Io,logger:c,analytics:p},U={test:{},step:{onDynamicAIActionStatusUpdateEvent:N=>{r.emit("dynamicCommandStatusUpdate",N)},onDynamicAIActionEvaluatingEvent:N=>{r.emit("dynamicCommandEvaluating",N)},onDynamicCommandGenerated:N=>{r.emit("dynamicCommandGenerated",N)},onDynamicCommandExecuted:N=>{r.emit("dynamicCommandExecuted",N)}}},P=new Al(r,s,S,g,L),V=await dl({fixtures:k,options:z,callbacks:U,inputs:j,testParams:{tracer:P}});return await P.finish({logger:c,result:V,updatedSteps:{steps:e}}),h?.(V),V.status};var Bb={event:"execute",createHandler:zk};import{cloneDeep as Hk}from"lodash-es";var $k=r=>async({command:e},t)=>{let{logger:n,generatorFactory:o,metadata:i}=r,a=Hk(e),s=Fg(a);if(s.category!=="NO_DESCRIPTION_PROVIDED"){if(s.category!=="NONE"){t?.({result:s});return}"cache"in a&&(a.cache=void 0,a.id=void 0);try{let c=await(await o(i.orgId,n)).getLintStepResult({command:a},{logger:n});t?.({result:c})}catch(l){n.error({event:"lint",err:l},"Failed to lint step"),t?.({result:void 0})}}},zb={event:"lintStep",createHandler:$k};var Wk=({metadata:r,logger:e,storage:t})=>{let{sessionId:n}=r;return async(o,i)=>{let{description:a,command:s,testMetadata:l,returnScreenshot:c}=o;e.info({params:o},`Locate handler called - ${a}`);let p=Z.getSession(n);if(!p)throw new Error("No active session found");let{controller:d,context:m}=p;d.setOpen();let u=Eo.parse(l.advanced??{}),h={},g;if(a){if("useSelector"in s&&s.useSelector)try{let f=await d.locateElementWithSelector(a,"iframeUrl"in s?s.iframeUrl:void 0);g=f.resolution.locator,h={target:f.target,thoughts:f.thoughts}}catch(f){e.warn({err:f},"Failed resolving target with selector"),i({err:`Failed locating element: ${f.message}`,decisions:f instanceof Jn?f.decisions:void 0});return}else try{let f=await d.locateElement({description:a,disableCache:u.disableAICaching,iframeUrl:"iframeUrl"in s?s.iframeUrl:void 0,skipWait:!0,testContext:m,source:Oi(s)});h={target:f.target,thoughts:f.thoughts},g=f.resolution.locator}catch(f){(async()=>{try{let S=await d.browser.getCondensedHtml({skipWait:!0});e.warn({err:f,html:S.slice(0,1e5)},"Failed locating element with AI")}catch(S){e.warn({err:S},"Failed grabbing HTML after trying to locate element with AI")}})(),i({err:`Failed locating element with AI: ${f.message}`});return}if(s.type==="SELECT_OPTION"&&g)try{h.options=await d.browser.getSelectOptions(g)}catch(f){e.warn({err:f},"Failed getting select options"),i({err:`Failed getting select options: ${f.message}`});return}e.info({result:h},"Locate handler result")}if(c)try{let{buffer:f,width:S,height:x}=await d.screenshotWithDimensions({clearHighlights:!0,locator:g,hideCaret:!0}),v=await t.uploadScreenshot(f);h.screenshot={data:v,width:S,height:x},e.info({width:S,height:x},"Captured screenshot during locate")}catch(f){e.error({err:f},"Error capturing screenshot during locate"),i({err:`Error taking screenshot: ${f.message}`});return}if(i({result:h}),g)try{await Promise.all([d.browser.scrollIntoView(g),d.browser.highlight(g)])}catch(f){e.warn({err:f},"Error highlighting element, continuing...")}}},jb={event:"locate",createHandler:Wk};var Gk=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async({event:n,percentX:o,percentY:i})=>{let a=Z.getSession(t);if(!a)throw new Error("No active session found");let s=a.controller.browser;if(s.closed||s.getActivePage().isClosed()){e.warn("Ignoring mouse move because the browser is closed");return}try{await s.clickMouseFromPositionPercentages(n,o,i)}catch(l){e.error({err:l},"Error performing click during cloud recording in control mode")}}},Hb={event:"mouseClickEvent",createHandler:Gk};var Vk=({metadata:r,generatorFactory:e,logger:t,socket:n})=>{let{sessionId:o,orgId:i,testId:a}=r;return async({stepId:s,parentStepIdChain:l,attribute:c})=>{let p=Z.getSession(o);if(!p)throw new Error("No active session found");let{controller:d}=p,m=await e(i,t);d.setOpen(),p.browserBehavior.showOverlay=!0;let u=new AbortController;u.signal.addEventListener("abort",async()=>{try{p.browserBehavior.showOverlay=!1,await d.stopRecordMode()}catch(f){t.warn({err:f},"Failed to stop record mode in target click socket handler")}});let h=!1,g=(f,S)=>{S.type!=="PRESET_ACTION"||S.command.type!=="CLICK"||(n.emit("targetRecordingUpdate",{type:f,stepId:s,parentStepIdChain:l,command:S.command,attribute:c}),u.abort(),h=!0)};setTimeout(()=>{h||(u.abort(),n.emit("targetRecordingUpdate",{type:"error",err:"Timed out waiting for click event",stepId:s,parentStepIdChain:l,attribute:c}))},1e4),await d.startRecordMode({params:{generator:m,logger:t,testId:a,orgId:i,callbacks:{onActionReceived:f=>g("clickReceived",f),onStepRecorded:f=>g("descriptionGenerated",f)}},abortController:u,isClickToRecord:!0}),n.emit("targetRecordingUpdate",{type:"listenersInitialized",stepId:s,parentStepIdChain:l,attribute:c})}},$b={event:"recordTargetClick",createHandler:Vk};var qk=["Dead","Meta","AudioVolumeUp","AudioVolumeDown"],Kk=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async({key:n})=>{let o=Z.getSession(t);if(!o)throw new Error("No active session found");if(qk.includes(n))return;let{controller:i}=o;if(i.browser.closed||i.browser.getActivePage().isClosed()){e.debug({sessionId:t},"Browser is closed, ignoring keyboard press socket event");return}try{i.setOpen(),n.length>1?await i.browser.press(n,{}):await i.browser.type(n,{clearContent:!1,pressKeysSequentially:!0})}catch(a){if(a.message.includes("has been closed")){e.debug({sessionId:t,err:a},"Browser is closed, ignoring keyboard press socket event error");return}throw a}}},Wb={event:"keyboardPressEvent",createHandler:Kk};var Yk=({metadata:r,logger:e})=>{let{sessionId:t}=r,n,o=0,i=(l,c)=>{let p=async()=>{n=void 0};clearTimeout(n),n=setTimeout(p,Math.min(1e3,250*(o+1)))},a,s=0;return async l=>{let c=Z.getSession(t);if(!c)throw new Error("No active session found");let{controller:p,browserBehavior:d}=c,m=p.browser;if(m.closed||m.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}if(l.event==="scroll"){let u=await m.scrollFromPositionPercentages(l.percentX,l.percentY,a?.x??0,a?.y??0),h=c.browserBehavior.recordingState?.transformer;h&&u&&h.recordScroll(u);return}d.showOverlay&&i(m,l);try{let u=await m.moveMouseFromPositionPercentages(l.percentX,l.percentY);s=0,a=u}catch(u){s++,s%5===0&&e.warn({err:u,mouseErrors:s},"Error in socket mouse move handler")}}},Gb={event:"mouseMoveEvent",createHandler:Yk};var Jk=({metadata:r,generatorFactory:e,socket:t,logger:n})=>{let{sessionId:o,orgId:i,testId:a}=r;return async({stepId:s})=>{let l=Z.getSession(o);if(!l)throw new Error("No active session found");let{controller:c,browserBehavior:p}=l,d=await e(i,n);n.info("Starting cloud recording");let m=new AbortController,u=await c.startRecordMode({params:{generator:d,logger:n,testId:a,orgId:i,callbacks:{onActionReceived:(h,g)=>{t.emit("stepRecorded",{stepId:s,step:h,offset:g})},onStepRecorded:(h,g)=>{t.emit("stepRecorded",{stepId:s,step:h,offset:g})}}},abortController:m,isClickToRecord:!1});p.recordingState={transformer:u}}},Vb={event:"recordingStart",createHandler:Jk};var Xk=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async()=>{let n=Z.getSession(t);if(!n)throw new Error("No active session found");e.info("Stopping cloud recording"),await n.controller.stopRecordMode(),n.browserBehavior.recordingState=void 0,n.browserBehavior.showOverlay=!1}},qb={event:"recordingStop",createHandler:Xk};var Zk=({socket:r,metadata:e,logger:t,storage:n,authorization:o,flagStoreFactory:i,settingsFactory:a})=>async(s,l)=>{let{testId:c,sessionId:p,orgId:d}=e;t.info({testId:c,sessionId:p},"Refresh event received");let m=await i(d),u=await a(d,t),{baseUrl:h}=await eo({testId:c,orgId:d,logger:t,storage:n,authorization:o,flagStore:m,settings:u}),g=Z.getSession(p);if(!g){r.emit("error",{message:"No session to refresh"});return}let{controller:f}=g;f.setOpen(),await f.browser.refresh();let S=f.browser.getViewport();t.info({baseUrl:h,viewport:S},`Session refreshed for test ${c} at ${h}`),l()},Kb={event:"refresh",createHandler:Zk};var Qk=({socket:r,metadata:e,logger:t,storage:n,authorization:o,flagStoreFactory:i,settingsFactory:a})=>async()=>{let{testId:s,sessionId:l,orgId:c}=e;t.info({testId:s,sessionId:l},"Reset event received");let p=await i(c),d=await a(c,t),{baseUrl:m,envName:u,environmentVariables:h}=await eo({testId:s,orgId:c,logger:t,storage:n,authorization:o,flagStore:p,settings:d}),g=Z.getSession(l);if(!g){r.emit("error",{message:"No session to reset"});return}let{controller:f,context:S}=g;await f.browser.reset({newUrl:m});let x=f.browser.baseUrl;S.reset({baseUrl:x,currentUrl:f.browser.url(),variablesFromEnvironment:h,envName:u});let v=f.browser.getViewport(),b=fn.USER_AGENT;t.info({baseUrl:m,viewport:v},`Session reset for test ${s} at ${x}`),r.emit("session",{url:x,userAgent:b,viewport:v,sessionId:l})},Yb={event:"reset",createHandler:Qk};var eO=({metadata:r})=>{let{sessionId:e}=r;return async({url:t})=>{let n=Z.getSession(e);if(!n)throw new Error("No active session found");await n.controller.browser.switchToPage({type:"SUBSTRING",substring:t})}},Jb={event:"switchTab",createHandler:eO};async function Xb(r){let{socket:e}=r;return e.handshake.query.type==="api-test"?BS(r):Ub(r)}var Zb=[WS,Bb,jb,Yb,Kb,jS,Jb,zb,$b,Vb,qb,Gb,Hb,Wb,zS,IS,$S,HS];var Qb=r=>{let{logger:e}=r,t=new tO(r.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0});return t.on("connection",async n=>{let o;try{e.info({event:"connection",transport:n.conn.transport.name},"Websocket connection established"),o=await Xb({...r,socket:n,logger:e}),e=e.child(o)}catch(i){e.error({event:"connection",type:"websocket",err:i},"Failed to setup connection"),n.emit("error",{message:i instanceof Error?i.message:`${i}`}),n.disconnect(!0);return}Zb.forEach(i=>nO(i,{socket:n,metadata:o,...r,logger:e}))}),t},nO=(r,e)=>{let t=r.createHandler(e),n=(...o)=>{["mouseMoveEvent","keyboardPressEvent","mouseClickEvent","lintStep"].includes(r.event)||e.logger.debug({...e.metadata,event:r.event,args:o},`Websocket event (${r.event})`);let i=a=>{e.logger.error({event:r.event,type:"websocket",args:o,err:a instanceof Error?a:new Error(`${a}`)},"Unhandled exception in socket handler"),e.socket.emit("error",{message:a instanceof Error?a.message:`${a}`})};try{let a=t.apply(void 0,o);a&&typeof a.catch=="function"&&a.catch(i)}catch(a){i(a)}};e.socket.on(r.event,n)};import{Router as dO}from"express";import Dp from"fs";import sO from"path";import tw,{multistream as rO}from"pino";import oO from"pino-pretty";var ew=["lastScreenshotBuffer"];var Mp=new Map,iO=!0,_p=class r{consoleLogger;ddClientToken;hostname;bindingAttributes;disableConsoleLogs;site="https://http-intake.logs.us5.datadoghq.com/api/v2/logs";constructor({bindings:e,clientToken:t,hostname:n,disableConsoleLogs:o}){this.ddClientToken=t,this.hostname=n,this.disableConsoleLogs=o,this.bindingAttributes={...e,env:"production"};let i={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=iO?tw(i):tw(i,rO([{stream:oO({colorize:!0})}]))}child(e){return new r({clientToken:this.ddClientToken,bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs})}flush(e){this.disableConsoleLogs||this.consoleLogger.flush(e)}log(e,t,n,...o){if(t&&n===void 0&&(n=`${t}`,t={}),this.disableConsoleLogs||this.consoleLogger[e](e==="error"?t:{testId:t.testId,runId:t.runId},n,...o),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error){let a={};for(let s of Object.getOwnPropertyNames(t.err))ew.includes(s)||(a[s]=t.err[s]);a.name=t.err.name,t.err=a}let i=Object.assign({},this.bindingAttributes,t&&typeof t=="object"?t:{});o.length>0&&(i.args=o),(async()=>{try{let a=await fetch(this.site,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","DD-API-KEY":this.ddClientToken},body:JSON.stringify([{ddsource:this.bindingAttributes.app,ddtags:["env:production"],hostname:this.hostname??"vercel",service:"momentic",message:{message:n||"",...i,level:e}}])});if(!a.ok)throw new Error(`Failed to log to Datadog: ${a.statusText})}`)}catch(a){this.disableConsoleLogs||this.consoleLogger.warn({obj:t,msg:n,args:o,err:a},"Failed to log to Datadog")}})()}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){this.consoleLogger.level=e}enableConsoleLogs(){this.disableConsoleLogs=!1}},Rl=({app:r,clientToken:e,hostname:t,disableConsoleLogs:n})=>{if(!process.env.DD_CLIENT_TOKEN&&!process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN&&!e)throw new Error("Missing DD_CLIENT_TOKEN");return Mp.has(r)||Mp.set(r,new _p({bindings:{app:r},hostname:t,clientToken:e||process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN||process.env.DD_CLIENT_TOKEN,disableConsoleLogs:n})),Mp.get(r)};import{hostname as aO}from"os";var Ke=Rl({app:"desktop-server",clientToken:"pubcfd7516a5c0ba852b42675cd97bee027",hostname:aO(),disableConsoleLogs:!0}),nw=r=>{Ke.addBinding("version",r)};var lO=new Sl(10,60*1e3),zp="https://api.momentic.ai",jp,Fp,rw=r=>{zp=r},Il=()=>zp,ow=(r,e)=>{jp=r,Fp?.abort(),Fp=new AbortController;let t=Fp.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=sO.resolve(r.rootDir,o.envFile);try{if(Dp.lstatSync(i).isSymbolicLink())return;Dp.existsSync(i)&&n.push(i)}catch(a){Ke.warn({err:a},`Failed to check if env file ${i} exists`)}});try{cO({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){Ke.error({err:o},"Failed to start config file watchers")}},ge=()=>jp,li,Up,Bp,iw=async r=>{if(li)return li;let e=new at({baseUrl:zp,apiKey:r,logger:Ke});try{let t=await e.getAuthInfo();return li=t.orgId,Up=t.userId,Bp=r,li}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},hr=()=>{if(!li)throw new Error("Your organization ID is invalid.");return li},Pl=()=>{if(!Up)throw new Error("Your user ID is invalid.");return Up},aw=()=>{if(!Bp)throw new Error("Your API key is invalid.");return Bp};function cO({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{Dp.watch(o,{signal:t,persistent:!1,recursive:!1},(i,a)=>{a&&(lO.increment("setLocalProject")&&y.warn(`A file change under the ${n.rootDir} directory has caused Momentic to reload its configuration more than 10 times in the last minute. Please avoid making rapid changes to files in this directory as this may cause performance issues.`),jp=e(n.configFilePath))})})}function we(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var sw=dO();sw.get("/",we((r,e)=>{let t=wf(ge(),Ke);e.status(200).json(t)}));var lw=sw;import{Router as pO}from"express";var Ll=class extends Ko{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async getOrgId(t){return this.orgId}async fetchTestMetadata(t,n,o){let i=ge(),s=ke(i,o).tests[t];if(s)return Ns(s.relativePath,i)}async fetchApiTestMetadata(t,n,o){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(t,n,o){let i=ge();return ta(n,i,Fr)}async fetchIconKnowledgeBase(t,n){try{return await this.client.fetchIconKnowledgeBase(t,n)}catch(o){return n.error({err:o},"Failed to fetch icon knowledge base"),null}}};var cw=pO();cw.get("/",we((r,e)=>{e.status(200).json({userId:Pl(),orgId:hr()})}));var dw=cw;import{Router as uO}from"express";var pw=uO();pw.get("/",we((r,e)=>{let t=ge(),n=ke(t,y),o=new Set;n?.tests&&Object.values(n.tests).forEach(a=>{a.labels?.forEach(s=>o.add(s))});let i=Array.from(o).sort();e.status(200).json(i)}));var uw=pw;import{Router as mO}from"express";import mw from"fs";import hO from"path";var Aa=mO();Aa.get("/",we(async(r,e)=>{let t=ge(),n=ke(t,y),i=(await Os(n,Ke)).map(a=>{let s=n.modules[a.moduleId];if(!s){y.warn(`Found a dangling module with ID ${a.moduleId} that could not be found on disk.`);return}return{...s,content:a}}).filter(a=>a!==void 0);e.status(200).json(i)}));Aa.post("/",we(async(r,e)=>{let t;try{t=Eh.parse(r.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{Ro(t.name)}catch(s){e.status(400).json({error:`Invalid module name: ${s}`});return}let n=ge(),o=ke(n,y).modules;if(Object.values(o).find(s=>s.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let i=hO.join(n.rootDir,t.folderPath??"");if(!mw.existsSync(i)||!mw.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let a=await ff({...t,folder:i,project:n});e.status(201).json(a)}));Aa.get("/:moduleId",we(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=ke(ge(),y),n=t.modules[r.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await gd(n,t,y);e.json(o)}catch(o){e.status(400).json({err:o})}}));Aa.patch("/:moduleId/metadata",we(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=Ch.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ge(),o=ke(n,y);gf({moduleId:r.params.moduleId,content:t,momenticFiles:o,logger:y,project:n}),e.status(201).json({message:"ok"})}));var hw=Aa;import{Router as gO}from"express";var kl=gO();kl.get("/",we((r,e)=>{let t=$d().map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(t)}));kl.get("/current",we((r,e)=>{let t=ge(),n={name:t.config.name,configFilePath:t.configFilePath};e.status(200).json(n)}));kl.post("/set",we((r,e)=>{let t;try{t=Rh.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=mn({configFilePath:t.configFilePath});ow(n,o=>mn({configFilePath:o}))}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var gw=kl;import{Router as fO}from"express";var fw=fO();fw.get("/",we((r,e)=>{let n={ai:ge().config.ai};e.status(200).json(n)}));var Sw=fw;import{Router as bO}from"express";import yw from"fs";import to from"path";import{v4 as bw}from"uuid";import wO from"yaml";import{randomUUID as SO}from"node:crypto";import{PostHog as yO}from"posthog-node";var ci=class{identify(){return this}child(){return this}track(){return this}async shutdown(){}},di=class r{bindings;client;options;constructor(e,t={}){this.bindings=e,this.options=t,this.client=new yO("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...t})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new r({...this.bindings,...e},this.options)}track(e,t){if(!Qm(this.bindings))return console.error(`Cannot track ${e.type} event without required bindings.`,this.bindings),this;let{type:n,...o}=e;return this.client.capture({distinctId:SO(),event:n,timestamp:t?.timestamp,properties:{...this.bindings,...o}}),this}};var pi=new di({platform:"local_app"},{flushAt:1,flushInterval:0});var gr=bO();function ww(r){let e=ke(r,y);return Object.values(e.tests)}gr.get("/",we((r,e)=>{let t=ww(ge());e.status(200).json(t)}));gr.post("/",we(async(r,e)=>{let t;try{t=xh.parse(r.body)}catch(p){e.status(400).json({error:`Invalid request body: ${p}`});return}try{Ro(t.name)}catch(p){e.status(400).json({error:p.message});return}let o={id:bw(),name:t.name,description:t.description,baseUrl:t.baseUrl,schemaVersion:je,advanced:{disableAICaching:!1,browserType:t.browserType??"Chromium",viewport:t.viewport??Dt},retries:0,steps:[]};t.environment&&(o.envs=[{name:t.environment,default:!0}]);let i=ge();if(ww(i).find(p=>p.name===t.name)){e.status(400).send(`A test with the name "${t.name}" already exists. Please use a different name.`);return}let s=to.join(i.rootDir,t.folderPath??""),l=await Sf({test:o,name:t.name,folder:s}),c={...o,relativeFilePath:to.relative(i.rootDir,l)};pi.track({type:"test_editor:test_create"}),e.status(201).json(c)}));gr.get("/:testPath",we(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n=ge(),o=ke(n,y),i;try{i=await ea(to.join(n.rootDir,t),Ke,o),e.status(200).json(i)}catch(a){e.status(400).send({error:a.message});return}(async()=>{try{let{stepsToSave:a,moduleUpdates:s}=await Qe({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});s.forEach(l=>{hd({content:l,schemaVersion:je,momenticFiles:o,project:n})}),Gr(t,a,je,n)}catch(a){Ke.error({err:a},"Failed to save migrated test to disk after initial fetch")}})()}));gr.patch("/:testPath/metadata",we(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=vh.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o={message:"ok",newRelativeTestPath:fd(r.params.testPath,t,ge()).newRelativeTestPath};e.status(200).json(o)}));gr.patch("/:testPath",we(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=wh.parse(r.body)}catch(d){e.status(400).json({error:`Invalid request body: ${d}`});return}let o=ge(),i=ke(o,y),a;try{a=Ns(t,o)}catch(d){e.status(400).json({error:`Existing test file on disk is invalid: ${d}`});return}let{stepsToSave:s,moduleUpdates:l,cachesToSave:c}=await Qe({stepLists:n.stepLists,cacheCreationParams:{testId:a.id,orgId:hr()}});await new at({apiKey:aw(),baseUrl:Il(),logger:Ke}).updateStepCaches({entries:c,testId:a.id}),l.forEach(d=>{hd({content:d,schemaVersion:n.schemaVersion,momenticFiles:i,project:o})}),Gr(t,s,n.schemaVersion,o),e.status(201).json({message:"ok"})}));gr.patch("/:testPath/environments",we(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Ah.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}fd(t,{envs:n.defaultEnv?[{name:n.defaultEnv,default:!0}]:[]},ge()),e.status(201).json({message:"ok"})}));gr.post("/:testPath/duplicate",we(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Th.parse(r.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{Ro(n.name)}catch(f){e.status(400).json({error:f.message});return}let o=ge(),i=to.join(o.rootDir,t);if(!yw.existsSync(i)){e.status(404).json({error:"Test not found."});return}let a=ke(o,y),s;try{s=await ea(i,Ke,a)}catch(f){e.status(400).send({error:f.message});return}let l=bw(),c=Xt.parse({...s,name:n.name,id:l}),{stepsToSave:p}=await Qe({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps},createNewStepIds:!0,cacheCreationParams:{createNewCacheIds:!0,testId:l,orgId:hr()}}),d=Nn({fileType:fe.TEST,...c,beforeSteps:p.beforeSteps??void 0,steps:p.steps,afterSteps:p.afterSteps??void 0}),m=to.dirname(i),u=to.join(m,`${n.name}.${Nt.TEST}`),h=wO.stringify(d);yw.writeFileSync(u,h,"utf-8");let g={relativeFilePath:to.relative(o.rootDir,u)};pi.track({type:"test_editor:test_create"}),e.status(201).json(g)}));var vw=gr;var Ra=class{async prepareGoldenScreenshotForComparison(e,t,n){return await new Go(ge(),!1).prepareGoldenScreenshotForComparison(e,t,n)}};async function Cw(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,staticDir:o,devicePixelRatio:i,version:a,logger:s=Ke}=r;nw(a),e&&rw(e),await iw(t);let l=hr(),c=Pl();pi.identify({user_id:c,org_id:l}),s.debug({params:r,orgId:l,userId:c},"Desktop server init and api key check done");let p=AO(o,n,s),d=`http://localhost:${n}`;y.info(`Desktop server is running at ${d}`),await new Promise(v=>{try{p.listen(n,()=>{s.info(`Desktop server is running at ${d}`),v()})}catch(b){b.message.includes("EADDRINUSE")?Aw(n):y.error(`An unexpected error occurred while starting the server: ${b.message}`),process.exit(1)}});let u={type:"API_KEY",baseUrl:Il(),apiKey:t,logger:s},h=new Jo(u),g=new Kr(u,h),f=new at(u),S=new Ll(f,hr()),x=new Ra;Qb({baseServer:p,generatorFactory:async()=>h,enricherFactory:async()=>g,flagStoreFactory:async v=>{let b=ge(),E=Vo.initIfConfigHasOverrides(s,b.config)??f;return Zo.init(v,E)},settingsFactory:async()=>{let v=ge();return{ai:v.config.ai||{},browser:v.config.browser||{}}},storage:S,logger:s,devicePixelRatio:i,authorization:u,visualDiffScreenshotStorage:x,analytics:pi})}var Ew="25mb";function AO(r,e,t){let n=Tw();n.use(vO()),n.use(xw.json({limit:Ew})),n.use(xw.urlencoded({extended:!1,limit:Ew}));let o=EO();if(o.use("/tests",vw),o.use("/modules",hw),o.use("/environments",lw),o.use("/projects",gw),o.use("/labels",uw),o.use("/settings",Sw),o.use("/identify",dw),n.use("/api",o),n.use((a,s,l)=>{a.path!=="/healthcheck"&&!a.path.startsWith("/assets")&&t.debug({url:a.url,path:a.path,query:a.query,method:a.method,body:a.body,headers:a.rawHeaders,client:a.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&t.error({url:a.url,method:a.method,statusCode:s.statusCode},"Request completed in error")}),l()}),n.use((a,s,l,c)=>{if(a instanceof Error&&a.message.includes("BadRequestError: request aborted")){l.status(400).send("Client disconnected");return}t.error({stack:a.stack,msg:a.message,err:a,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),y.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${a.message}
|
|
3614
|
+
${a.stack}`),l.status(500).send("Internal Server Error")}),r){let a=Tw.static(r,{setHeaders:s=>{s.setHeader("Cache-Control","no-cache")}});n.use("/",a),n.use("*",a)}let i=CO.createServer(n);return i.once("error",a=>{"code"in a&&a.code==="EADDRINUSE"?(Aw(e),process.exit(1)):console.error("An unexpected server error occurred:",a.message)}),i}TO.setMaxListeners(50);process.on("warning",r=>{Ke.warn({err:r},`Node warning received on desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{Ke.error({err:r},"Uncaught exception leading to exit on desktop-server"),y.error(`Oh no! The Momentic desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",(r,e)=>{Ke.error({reason:`${r}`,promise:`${e}`,stack:r?.stack},"Uncaught exception leading to exit on desktop-server (promise rejection)"),y.error(`Oh no! The Momentic desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function Aw(r){y.error(xO`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
3612
3615
|
Using Bash on MacOS or Linux:
|
|
3613
3616
|
lsof -t -i :58888 | xargs kill -9
|
|
3614
3617
|
|
|
3615
3618
|
Using Command Prompt on Windows:
|
|
3616
3619
|
for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
|
|
3617
|
-
`)}import
|
|
3618
|
-
|
|
3619
|
-
`)}`):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 tv({project:n}){let e=Oe(n,y),t=Object.values(e.tests),r=await La(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 gN}from"lodash-es";async function Ml({client:n,skipPrompts:e,project:t}){let r=await n.getAllEnvironments(),o=gN(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[Ie],delete i.variables[Ie],s.envVariables=i.variables;else{let a=i.variables[Ie];delete i.variables[Ie],o.environments.push({name:i.name,baseUrl:a,envVariables:i.variables})}}Bo(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 nv}from"crypto";import rv from"fs";async function iv({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=ov(l,fe.TEST);!r&&!await Qp(p)||(s+=1,rv.writeFileSync(p,c,"utf-8"),Q.info({checksum:nv("md5").update(c).digest("hex")},`Wrote '${p}'`))}let a=0;for(let[l,c]of Object.entries(i)){let p=ov(l,fe.MODULE);!r&&!await Qp(p)||(a+=1,rv.writeFileSync(p,c,"utf-8"),Q.info({checksum:nv("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 ov(n,e){switch(e){case fe.TEST:return`${Pe(n)}.${Nt.TEST}`;case fe.MODULE:return`${Pe(n)}.${Nt.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function sv(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 Ml({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 iv({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 Wt from"fs";import eo from"path";import fN from"yaml";function av(){As("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:fs,environments:[]};y.info("Migrating environments");let e=lv(["momentic/environments"],SN);for(let r of e){let o=fN.parse(Wt.readFileSync(r,"utf-8"));try{let i=Xs.parse(o),s=i.variables[Ie]??"";delete i.variables[Ie],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=yd("./momentic",y);for(let r of t){let o=eo.join(...r.fullPathSegments),i=eo.join(eo.dirname(o),`${r.fileName.slice(0,-5)}.test.yaml`);y.info(`Moving test ${o} to ${i}`),Wt.renameSync(o,i)}if(As("momentic/modules")){y.info("Migrating modules");for(let r of Wt.readdirSync("./momentic/modules")){if(!r.endsWith(".yaml"))continue;let o=eo.resolve(eo.join("./momentic/modules",r));if(!Wt.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}`),Wt.renameSync(o,s)}}return y.info("Writing new project configuration file"),Bo(n,"momentic.config.yaml"),Wt.rmSync("./momentic/environments",{recursive:!0,force:!0}),Wt.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 lv(n,e,t=new Set){for(let r of n){let o=eo.resolve(r),i=!1;try{i=Wt.existsSync(o)&&Wt.statSync(o).isDirectory()}catch(s){y.error({err:s},`Error reading path ${o} during collect paths`)}if(o&&i){let s=Wt.readdirSync(o).map(a=>eo.join(o,a));lv(s,e,t);continue}if(o.endsWith(".yaml")){try{if(!Wt.existsSync(o)||!Wt.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 SN(n){return n.endsWith(".yaml")?Wt.readFileSync(n,"utf8").includes("momentic/environment")?!0:(y.warn(`Skipping YAML that is not a Momentic environment: ${n}`),!1):!1}import{Argument as li,Option as ke}from"@commander-js/extra-typings";import{validateHeaderValue as yN}from"http";import{cpus as cv}from"os";import{parse as due}from"yaml";import{z as q}from"zod";var Fl=58888,eu=30*60*1e3,zn=new ke("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var."),gr=new ke("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise."),fr=new ke("-y, --yes","Skip all confirmation prompts."),tu=new ke("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),nu=new ke("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified. Defaults to ${eu/1e3} seconds.`),Dl=new ke("--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."),ru=new ke("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),pv=new ke("--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(Di)),uv=new ke("--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."),ou=new ke("--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."),mv=new ke("--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."),hv=new ke("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),iu=new ke("--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."),gv=new ke("--port <port>",`Port to run the app on. Defaults to ${Fl}.`),su=new ke("--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."),Ul=new ke("--env <env>","Name of the environment to use when running tests."),Bl=new ke("--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."),fv=new ke("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>parseInt(n,10)),Sr=new ke("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file (*.momentic.config.yaml)"),au=new ke("-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."),Sv=new ke("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(n=>parseInt(n,10)),yv=new ke("--fix","Attempt to fix any issues found. This option will write changes to your local file system."),bv=new li("<tests...>",`One or more test paths to queue on Momentic Cloud.
|
|
3620
|
+
`)}import KN from"events";import Bv from"fs";import YN from"open";import nc from"path";import{fileURLToPath as JN}from"url";import GO from"diff-lines";import{gt as VO}from"semver";import{execSync as RO}from"child_process";import{platform as IO}from"os";function Hp(){return Rw()?(y.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),y.dimmed(`If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
|
|
3621
|
+
`),2):(y.dimmed("Setting device pixel ratio to 1."),y.dimmed(`If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
|
|
3622
|
+
l.`),1)}function Rw(){return IO()==="darwin"&&RO("system_profiler SPDisplaysDataType").toString().includes("Retina")}function $p(r){Rw()&&r===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 PO from"@actions/exec";import LO from"@actions/io";import kO from"quote";import OO from"string-argv";async function Iw(r,e=!0){let t=OO(r),n=await LO.which(t[0],!0),o=t.slice(1),i=PO.exec(kO(n),o,{delay:100});if(e)return i}import{existsSync as NO,statSync as MO}from"fs";var Ol=!!process.env.CI||!process.stdout.isTTY||!!process.env.TF_BUILD;function Ia(r){try{return NO(r)&&MO(r).isDirectory()}catch(e){return y.error({err:e},`Error reading path ${r} during directory existence check`),!1}}import _O from"csv-parser";import{createReadStream as FO}from"fs";function Wp(r){return new Promise((e,t)=>{let n=[];FO(r).pipe(_O()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>t(o))})}import Nl from"semver";import{z as Ml}from"zod";var Ht="1.5.1",DO="https://registry.npmjs.org/momentic",UO=Ml.object({versions:Ml.record(Ml.string(),Ml.unknown()).optional()});async function Pw(r){try{await BO(r)}catch(e){y.warn({err:e},"Failed to check CLI version against NPM servers")}}async function BO(r){if(!Ht){r.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let n=0;n<2;n++)try{let o=await D(fetch(DO),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=UO.parse(i).versions;break}catch(o){r.warn({err:o},"Failed to fetch npm registry data")}if(!e){r.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let n of Object.keys(e))Nl.valid(n)&&(!t||Nl.gt(n,t))&&Nl.gt(n,Ht)&&Nl.lt(n,"2.0.0")&&!n.includes("alpha")&&(t=n);t&&(y.warn(`Update available: v${Ht} -> v${t}`),y.warn("This version may be missing critical fixes, features, and security updates."),y.warn(`Run "npx momentic@${t} -V" to update`))}import{existsSync as jO,mkdirSync as HO,statSync as $O}from"fs";import{dirname as WO}from"path";import kw from"readline/promises";import{hostname as zO}from"os";var ee=Rl({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:zO(),disableConsoleLogs:!0}).child({version:"1.5.1"});var Gp=!1,Ow=(()=>{try{return $O("/.dockerenv"),!0}catch{return!1}})();async function st(r,e){if(Ol||Gp||Ow)return!0;ee.flush(),await new Promise(a=>setTimeout(a,500));let t=kw.createInterface({input:process.stdin,output:process.stdout}),n=r.split("."),o;if(n.length===1)o=r;else{let a=`${n.slice(0,n.length-1).join(".").trim()}.`;e?y.warn(a):y.log(a),o=n[n.length-1].trim()}let i=await t.question(`${o} ('y' for yes / n for no / 'A' to accept all) `);return t.close(),i==="A"?(Gp=!0,setTimeout(()=>{Gp=!1},3e3),!0):i.toLowerCase()==="y"}async function Vp(r){let e=WO(r);return Ia(e)?jO(r)?st(`File '${Lw(r)}' already exists. Overwrite existing content?`,!0):!0:await st(`Directory '${Lw(e)}' doesn't exist. Create it now?`,!0)?(HO(e,{recursive:!0}),!0):!1}function Lw(r){return r.replace(/(\s+)/g,"\\$1")}async function Nw(r,e){if(Ol||Ow)return e;let t=kw.createInterface({input:process.stdin,output:process.stdout}),n=await t.question(`${r} `);return t.close(),n.trim()||e}async function Mw({test:r,fragment:e,entities:t,client:n,logger:o,yes:i}){VO(e.schemaVersion,je)&&(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)),Rg(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 st("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let s=r.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<s&&!i&&!await st("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=Qi(r.fullFilePath,o,t),c=l.steps;if(!Array.isArray(c))throw new Error(`Test ${r.fullFilePath} is missing steps array`);let p,d;if(e.schemaVersion!==je){let{steps:g,newVersion:f}=await Ki({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:m,moduleUpdates:u}=await Qe({stepLists:{steps:d}});m.beforeSteps=l.beforeSteps??void 0,m.afterSteps=l.afterSteps??void 0;let h=GO(JSON.stringify(c,void 0,2),JSON.stringify(m,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 st("Do you want to apply this patch?")&&(y.dimmed("Cancelled."),process.exit(1)),Gr(r.relativePath,m,p??e.schemaVersion,t.project),y.success("Patch applied successfully."),await n.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as av}from"crypto";var Bn=" ".repeat(6);import iv from"chalk";import $t from"fs";import no from"path";import qO from"yaml";function _w(){Ia("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 r={name:"default",include:ya,environments:[]};y.info("Migrating environments");let e=Fw(["momentic/environments"],KO);for(let n of e){let o=qO.parse($t.readFileSync(n,"utf-8"));try{let i=Za.parse(o),a=i.variables[Ie]??"";delete i.variables[Ie],r.environments?.push({name:i.name,baseUrl:a,envVariables:i.variables})}catch(i){y.error(`${n} failed to parse as a valid environment file.`),y.error(i),process.exit(1)}}y.info("Migrating tests");let t=Sd("./momentic",y);for(let n of t){let o=no.join(...n.fullPathSegments),i=no.join(no.dirname(o),`${n.fileName.slice(0,-5)}.test.yaml`);y.info(`Moving test ${o} to ${i}`),$t.renameSync(o,i)}if(Ia("momentic/modules")){y.info("Migrating modules");for(let n of $t.readdirSync("./momentic/modules")){if(!n.endsWith(".yaml"))continue;let o=no.resolve(no.join("./momentic/modules",n));if(!$t.readFileSync(o,"utf-8").includes("schemaVersion")){y.warn(`Skipping file ${o} since it does not have valid Momentic module contents`);continue}let a=`${o.slice(0,-5)}.module.yaml`;y.info(`Moving module ${o} to ${a}`),$t.renameSync(o,a)}}return y.info("Writing new project configuration file"),$o(r,"momentic.config.yaml"),$t.rmSync("./momentic/environments",{recursive:!0,force:!0}),$t.rmSync("./momentic/fixtures",{recursive:!0,force:!0}),y.success("Migration succeeded!"),y.info("Going forward:"),y.info(` - You can store test and module files anywhere under the project root (${process.cwd()})`),y.info(" - Environment details and other common options are tracked in the root momentic.config.yaml file"),r}function Fw(r,e,t=new Set){for(let n of r){let o=no.resolve(n),i=!1;try{i=$t.existsSync(o)&&$t.statSync(o).isDirectory()}catch(a){y.error({err:a},`Error reading path ${o} during collect paths`)}if(o&&i){let a=$t.readdirSync(o).map(s=>no.join(o,s));Fw(a,e,t);continue}if(o.endsWith(".yaml")){try{if(!$t.existsSync(o)||!$t.statSync(o).isFile()){y.warn(`File not found or unreadable: ${o}`);continue}}catch(a){y.error({err:a},`Error reading file ${o} during collect paths`);continue}if(!e(o))continue;t.add(o)}}return t}function KO(r){return r.endsWith(".yaml")?$t.readFileSync(r,"utf8").includes("momentic/environment")?!0:(y.warn(`Skipping YAML that is not a Momentic environment: ${r}`),!1):!1}import{Argument as ro,Option as Oe}from"@commander-js/extra-typings";import{validateHeaderValue as YO}from"http";import{cpus as Dw}from"os";import{parse as ope}from"yaml";import{z as q}from"zod";var _l=58888,qp=30*60*1e3,zn=new Oe("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var."),fr=new Oe("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise."),Sr=new Oe("-y, --yes","Skip all confirmation prompts."),Kp=new Oe("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),Yp=new Oe("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified. Defaults to ${qp/1e3} seconds.`),Fl=new Oe("--custom-headers <customHeaders...>","Specify custom headers in the form HEADER=VALUE to be sent with each request during the test. Multiple entries can be provided."),Jp=new Oe("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),Bw=new Oe("--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(Bi)),zw=new Oe("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml. Defaults to 'reports' if unset."),Xp=new Oe("--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."),jw=new Oe("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),Hw=new Oe("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),Zp=new Oe("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio."),$w=new Oe("--port <port>",`Port to run the app on. Defaults to ${_l}.`),Qp=new Oe("--input-csv <inputCsv>","Path to a CSV file on disk where each row represents a set of inputs that will be made available to all tests that are ran. The first line of the CSV must be the input names."),Dl=new Oe("--env <env>","Name of the environment to use when running tests."),Ul=new Oe("--url-override <urlOverride>","Fully qualified url (e.g. https://www.google.com) to start all tests from. Overrides any default starting url set from the test or environment."),Ww=new Oe("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(r=>parseInt(r,10)),yr=new Oe("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file (*.momentic.config.yaml)"),eu=new Oe("-f, --filter <filter>","Run tests within the project that has a name equal to the filter provided. This option cannot be used together with file path or directory arguments, but substring matches are allowed."),Gw=new Oe("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(r=>parseInt(r,10)),Vw=new Oe("--fix","Attempt to fix any issues found. This option will write changes to your local file system."),qw=new ro("<tests...>",`One or more test paths to queue on Momentic Cloud.
|
|
3620
3623
|
|
|
3621
|
-
A test path is a lowercased version of your test name where spaces are replaced with dashes: 'npx momentic@latest pull hello-world'.`),
|
|
3624
|
+
A test path is a lowercased version of your test name where spaces are replaced with dashes: 'npx momentic@latest pull hello-world'.`),Kw=new ro("<tests...>",`One or more test paths to import from Momentic Cloud.
|
|
3622
3625
|
|
|
3623
|
-
|
|
3626
|
+
A test path is a lowercased version of your test name where spaces are replaced with dashes: 'npx momentic@latest import-from-cloud hello-world'.`).argOptional(),Yw=new ro("<tests...>","One or more test file path or folders that exist on the local machine: 'npx momentic@latest run hello-world.test.yaml'.").argOptional(),Jw=new ro("<suites...>",`One or more suite paths that exist on Momentic Cloud.
|
|
3627
|
+
|
|
3628
|
+
The suite path is a lowercased version of your suite name where spaces and special characters are replaced with dashes, such as 'production-tests'.`),lpe=new ro("<envs...>","One or more environment names to push").argOptional(),Xw=new ro("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),Zw=new ro("<results>","Path to the results archive.").argRequired(),Uw=q.object({apiKey:q.preprocess(r=>r!==void 0?r:process.env.MOMENTIC_API_KEY,q.string()),server:q.string().default("https://api.momentic.ai"),config:q.string().optional(),filter:q.string().optional(),yes:q.preprocess(r=>process.env.CI?!0:r,q.boolean().optional()),fix:q.boolean().optional(),pixelRatio:q.coerce.number().optional(),port:q.coerce.number().default(_l).optional(),wait:q.preprocess(r=>!!r,q.boolean()).optional(),waitTimeout:q.coerce.number().optional(),start:q.string().optional(),waitOn:q.string().optional(),waitOnTimeout:q.coerce.number().default(60).optional(),customHeaders:q.string().array().optional(),env:q.string().optional(),urlOverride:q.string().url().optional(),all:q.boolean().optional(),parallel:q.coerce.number().optional(),retries:q.coerce.number().optional(),shardIndex:q.coerce.number().optional(),shardCount:q.coerce.number().optional(),inputCsv:q.string().optional(),updateGoldenFiles:q.boolean().optional().default(!1),tests:q.array(q.string()).optional(),suites:q.array(q.string()).optional(),paths:q.array(q.string()).optional(),envs:q.array(q.string()).optional(),include:q.array(q.string()).optional(),exclude:q.array(q.string()).optional(),labels:q.array(q.string()).optional(),report:q.preprocess(()=>!!process.env.CI,q.boolean().optional()),reporter:q.nativeEnum(Bi).optional(),reporterDir:q.string().optional(),outputDir:q.string().optional()}),Sn=async r=>{let e={},t;try{let n=Object.assign(e,Uw.partial().parse(r));t=Uw.parse(n)}catch(n){y.error(`Error parsing command line arguments: ${n.message}`),process.exit(1)}try{JO(t)}catch(n){y.error(`Invalid command line arguments: ${n.message}`),process.exit(1)}return t};var JO=r=>{for(let[e,t]of Object.entries(r))switch(e){case"shardIndex":if(!r.shardCount)throw new Error("The --shard-count flag must be provided alongside --shard-index");if(r.shardCount&&r.shardIndex&&r.shardIndex>r.shardCount)throw new Error("Shard index cannot be greater than shard count");if(r.shardIndex!==void 0&&r.shardIndex<1)throw new Error("Shard index must be greater than 0");break;case"waitTimeout":case"pixelRatio":try{r[e]=q.number().int().optional().parse(t)}catch{throw new Error(`Invalid ${e} provided does not parse a number: ${t}`)}break;case"urlOverride":if(t===void 0)break;try{q.string().url().parse(t)}catch(n){throw new Error(`Invalid URL provided for ${e}`,{cause:n})}break;case"server":if(typeof t!="string")throw new Error(`Expected a string for ${e}`);if(!t.startsWith("http"))throw new Error("--server option must be a fully qualified URL beginning with http");break;case"parallel":if(t===void 0)break;if(typeof t!="number"||isNaN(t))throw new Error(`Expected a number for ${e}`);Dw().length<t*2&&y.warn(`You requested to run tests in parallel ${t} at a time on a machine with ${Dw().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`);break;default:break}};function Bl(r){if(r===void 0)return;let e={};for(let t of r){let n=t.indexOf("=");if(n===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,n),i=t.slice(n+1);YO(o,i),e[o]=i}return e}import ZO from"fs";import{tmpdir as QO}from"os";import eN from"path";import{registry as zl}from"playwright-core/lib/server";import Qw from"proper-lockfile";var ev=eN.join(QO(),"momenticBrowserInstallation"),tu=["chrome","chromium"];function tv(r){let e=r.executablePath();return ZO.existsSync(e)}function tN(r,e){let t=[],n=[];for(let o of r){let i=zl.findExecutable(o);if(!i||i.installType==="none")t.push(o);else{if(!e&&tv(i))return[];n.push(i)}}return n}async function nN(r,e){let t=tN([r],e);if(!t.length){y.debug(`Browser '${r}' is already installed, skipping...`);return}y.info(`Installing browser '${r}'...`);try{await zl.installDeps(t,!1),await zl.install(t,!1)}catch(n){if(n.message.includes("Lock file is already being held")){y.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=zl.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!tv(o);)y.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}function nv(r){for(let e of r)tu.includes(e)||(y.error(`Got invalid browser ${e} to install`),process.exit(1));return Array.from(new Set(r))}async function oo(r,e=!1){try{await Qw.lock(ev,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(t){y.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${t}. Continuing without installation...`);return}try{for(let t of r)try{await nN(t,e)}catch(n){y.error(`Failed to install the ${t} browser: ${n}`)}}finally{await Qw.unlock(ev,{realpath:!1})}}async function nu(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(y.error(`Node.js version 18 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),y.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return y.debug("Got auth info from API"),r.installBrowsers&&(await oo(["chromium"]),y.debug("Installed Chromium browser")),n}import{Console as rv}from"console";import{format as Pa}from"util";var ru=class extends Error{constructor(e,t,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},jl=class r extends rv{_buffer=[];_groupDepth=0;Console=rv;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new ru(void 0,r.write).stack;if(!i)return e;let a=i.split(`
|
|
3624
3629
|
`).slice(o).filter(Boolean).join(`
|
|
3625
|
-
`);return e.push({message:
|
|
3630
|
+
`);return e.push({message:n,origin:a,type:t}),e}_log(e,t){r.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",Pa(e,...t))}error(e,...t){this._log("error",Pa(e,...t))}info(e,...t){this._log("info",Pa(e,...t))}log(e,...t){this._log("log",Pa(e,...t))}warn(e,...t){this._log("warn",Pa(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function ov(r){let e=globalThis.console,t=new jl;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
|
|
3626
3631
|
`);process.stderr.write(`${o}
|
|
3627
|
-
`),globalThis.console=e}}var RN=5;async function $l({getResults:n,checkDone:e,name:t,timeoutMs:r=eu}){let o=Date.now(),i=0;for(;Date.now()-o<r;){let s;i>RN&&(y.error(`Failed to fetch ${t} status too many times.`),process.exit(1));try{s=await n(),i=0}catch(c){i++,Q.warn({err:c},"Failed to fetch run status, retrying..."),y.warn({err:c},"Failed to fetch run status, retrying..."),await new Promise(p=>setTimeout(p,1500*i));continue}if(e(s))return s;let l=Math.max(1e4,Math.floor(r/100));await new Promise(c=>setTimeout(c,l))}y.error(`Timeout elapsed waiting for ${t} to complete (${Math.floor(r/1e3)}s).`),process.exit(1)}function ci({results:n,startTime:e,entity:t,getDisplayLine:r,onFailed:o}){let i=n.filter(l=>l.status==="PASSED"),s=n.filter(l=>l.status==="FAILED"),a=n.filter(l=>l.status==="CANCELLED");return Pv(()=>{s.forEach(l=>{y.log(""),o(l)}),s.length&&(y.log(""),y.error(`${s.length} ${t}s failed:`),s.forEach(l=>{y.dimmed(r(l))})),a.length&&(y.log(""),y.warn(`${a.length} ${t}s cancelled:`),a.forEach(l=>{y.dimmed(r(l))})),i.length&&(y.log(""),y.success(`${i.length} ${t}s passed:`),i.forEach(l=>{y.dimmed(r(l))})),y.log(""),y.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{passed:i.length,failed:s.length,cancelled:a.length}}var Wl=(n,e)=>{if(!n.failureDetails||!n.failureReason)return;let t=Zs[n.failureDetails?.classification?.reason||n.failureReason],r=n.failureDetails?.classification?.summary||bo[n.failureReason];y.error(e),y.log(` Reason: ${Lv.red(t)}`),y.log(` Description: ${Lv.red(r)}`)};function Ov(n){return n?Pe(n):"Unknown suite"}async function kv({client:n,orgId:e,suitePaths:t,wait:r,waitTimeout:o,...i}){let{suiteRunIds:s,runGroupIds:a}=await n.queueSuiteRuns({paths:t,...i});Q.info({orgId:e,suiteRunIds:s,runGroupIds:a,suitePaths:t},"Queued suites remotely"),y.dimmed(`Queued ${t.length} suites.`),r||process.exit(0);let l=Date.now();y.dimmed(`Waiting for ${t.length} suites to complete.`);let c=new Set,p=[],d=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(x=>x.status==="FAILED"&&(x.failureReason||x.finishedAt&&Date.now()-x.finishedAt.getTime()>30*1e3)||x.status==="PASSED"||x.status==="CANCELLED"),u=await $l({name:"suites",getResults:async()=>{let f=a.filter(v=>!p.some(b=>b.id===v)),S=await n.bulkGetRunGroupStatus(f),x=[];for(let v of S)d(v)?p.push(v):x.push(v);return[...p,...x]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(S=>{S.status==="RUNNING"&&(c.has(S.id)||(c.add(S.id),y.log(`${c.size}/${a.length} ${Ov(S.suite?.name)}`)))}),f.every(d))}),m=n.getAppUrl(),g=ci({results:u,startTime:l,onFailed:f=>{let S=Ov(f.suite?.name),x=f.runs.filter(b=>b.status==="FAILED").length,v=f.runs.length;y.error(`${S} (${x}/${v} tests failed):`);for(let b of f.runs)if(b.status==="FAILED"){let E=b.testName||b.test?.name;y.error(` ${E?Pe(E):"Unknown test"} (${m}/runs/${b.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?Pe(f.suite.name):"Unknown suite name"} (${m}/run-groups/${f.id})`});process.exit(g.failed>0?1:0)}async function Nv({tests:n,client:e,orgId:t,...r}){!r.yes&&!await at(`This command will queue ${n.length} tests to run remotely on Momentic's infrastructure. Results will be available on ${e.getAppUrl()}. Continue?`)&&process.exit(1);let{queuedTests:o,runIds:i}=await e.queueTests({testPaths:n,...r});if(Q.info({queuedTests:o,runIds:i,orgId:t},"Queued tests remotely"),y.dimmed(`Queued ${o.length} tests. Processing time may depend on a variety of factors, including how many tests have already been queued from your organization.`),r.wait||process.exit(0),!i.length)return;y.dimmed(`Waiting for ${o.length} tests to complete.`);let s=new Set,a=[],l=m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED",c=e.getAppUrl(),p=Date.now(),d=await $l({name:"runs",getResults:async()=>{let m=i.filter(f=>!a.some(S=>S.id===f)),h=await e.bulkGetRunStatus(m),g=[];for(let f of h)l(f)?a.push(f):g.push(f);return[...a,...g]},timeoutMs:r.waitTimeout?r.waitTimeout*1e3:void 0,checkDone:m=>(m.forEach(h=>{if(h.status==="RUNNING"&&!s.has(h.id)){s.add(h.id);let g=h.testName||h.test?.name;g&&y.log(`${s.size}/${o.length} ${Pe(g)}`)}}),m.every(l))}),u=ci({results:d,startTime:p,onFailed:m=>{let h=m.testName||m.test?.name;Wl(m,h?Pe(h):"Unknown test")},getDisplayLine:m=>{let h=m.testName||m.test?.name,g=` ${h?Pe(h):"Unknown test"}`;return m.id&&(g+=` (${c}/runs/${m.id})`),g},entity:"test"});process.exit(u.failed>0?1:0)}import ui,{supportsColor as c_}from"chalk";import{existsSync as BN,mkdirSync as zN,statSync as jN}from"fs";import{randomUUID as pu}from"crypto";import Gl from"fs";import{hostname as AN}from"os";import Ps from"path";async function Vl(n,e,t,r,o){if(r){let i=Ps.extname(r),s=`${pu()}-screenshot${i}`,a=Ps.join(t,s),c=await(await fetch(r)).arrayBuffer();return Gl.writeFileSync(a,Buffer.from(c)),s}if(o){let i=await e.getScreenshot(n,o);if(i){let s=`${o}-screenshot.jpeg`,a=Ps.join(t,s);return Gl.writeFileSync(a,i),s}}}async function IN(n,e,t,r){let o=r.runId??pu(),i={uuid:o,historyId:o,testCaseId:r.test.id,fullName:r.test.name,name:Pe(r.test.name),status:r.status==="PASSED"?"passed":r.status==="CANCELLED"?"skipped":"failed",start:r.lastAttemptStartedAt.getTime(),stop:r.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:t.suiteName},{name:"host",value:AN()},{name:"platform",value:"momentic"},{name:"attempts",value:r.attempts.toString()}],steps:[]};r.runId&&i.labels?.push({name:"runUrl",value:`https://app.momentic.ai/runs/${r.runId}`});for(let[a,l]of Object.entries(r.parameters))l!=null&&i.parameters.push({name:a,value:JSON.stringify(l)});r.results&&await PN(n,e,t.folder,i.steps,r.results);let s=`${o}-result.json`;Gl.writeFileSync(Ps.join(t.folder,s),JSON.stringify(i,void 0,2))}async function di(n,e,t,r){let o={name:ln(r),start:r.startedAt.getTime(),stop:r.finishedAt.getTime(),status:r.status==="SUCCESS"?"passed":r.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};r.beforeUrl&&o.labels?.push({name:"URL before step",value:r.beforeUrl}),r.afterUrl&&o.labels?.push({name:"URL after step",value:r.afterUrl});let i=await Vl(n,e,t,r.beforeScreenshot,r.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let s=await Vl(n,e,t,r.afterScreenshot,r.afterSnapshot);if(s&&o.attachments.push({name:"Screenshot after step",source:s,type:"image/jpeg"}),r.message&&(o.statusDetails={message:r.message}),r.data){let a=`${pu()}-attachment.json`,l=Ps.join(t,a);Gl.writeFileSync(l,JSON.stringify(r.data,null,2)),o.attachments.push({name:"Step output data",source:a,type:"text/plain"})}return o}async function PN(n,e,t,r,o){for(let i of o)switch(i.type){case"PRESET_ACTION":{r.push(await di(n,e,t,i));break}case"CONDITIONAL":{let s=await di(n,e,t,i);s.steps=[],i.assertion&&s.steps.push(await di(n,e,t,i.assertion)),s.steps.push(...await Promise.all(i.results.map(a=>di(n,e,t,a)))),r.push(s);break}case"AI_ACTION":case"IFRAME":case"SECTION":case"MODULE":{let s=await di(n,e,t,i);if(s.steps=await Promise.all(i.results.map(a=>di(n,e,t,a))),i.type==="MODULE"&&i.inputs){s.parameters=[];for(let[a,l]of Object.entries(i.inputs))s.parameters.push({name:a,value:l})}r.push(s)}}}async function _v(n,e,t,r){for(let o of r.runs)await IN(n,e,{folder:t,suiteName:r.suiteName},o)}import Mv from"junit-report-builder";import Fv from"path";function LN(n,e){let t=e??Mv.testCase();if(t.name(n.test.name).className(n.test.name).file(Fv.relative(".",n.filePath)).property("id",n.test.id),n.baseUrl&&t.property("baseUrl",n.baseUrl),n.runId&&t.property("runUrl",`https://app.momentic.ai/runs/${n.runId}`),n.status==="FAILED"){if(n.failureReason){let r=Zs[n.failureDetails?.classification?.reason||n.failureReason],o=n.failureDetails?.classification?.summary||bo[n.failureReason];n.runId&&(o+=` See details: https://app.momentic.ai/runs/${n.runId}`),t.failure(o,r)}n.failureDetails?.errorStack&&t.stacktrace(n.failureDetails.errorStack)}else n.status==="CANCELLED"&&t.skipped();t.time((n.finishedAt.getTime()-n.lastAttemptStartedAt.getTime())/1e3).property("startedAt",n.lastAttemptStartedAt.toISOString()).property("finishedAt",n.finishedAt.toISOString()).property("attempts",n.attempts.toString());for(let r of["testInputs","customHeaders"]){let o=n.parameters[r];Object.keys(o??{}).length>0&&t.multilineProperty(r,JSON.stringify(o))}for(let r of["envName","urlOverride"])n.parameters[r]!==void 0&&t.property(r,n.parameters[r]);return Object.keys(n.outputs).length&&t.multilineProperty("testOutputs",JSON.stringify(n.outputs)),t}function ON(n,{suiteId:e,suiteName:t,startedAt:r,finishedAt:o,runs:i}){let s=n.testSuite().name(t);e&&s.property("id",e),s.timestamp(r).property("startedAt",r.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-r.getTime())/1e3);for(let a of i){let l=s.testCase();LN(a,l)}return s}function Dv(n,e){let t=Mv.newBuilder();ON(t,e),t.writeTo(Fv.join(n,`${e.suiteName}.xml`))}import kN from"fs";import NN from"path";function Uv(n){return{title:ln(n),duration:n.finishedAt.getTime()-n.startedAt.getTime(),error:n.status==="FAILED"?{value:n.failureReason}:void 0,steps:n.results&&n.type!=="PRESET_ACTION"?n.results.map(Uv):[]}}async function _N(n,e,t,r){if(r.results?.length){let o=await Vl(n,e,t,r.results[r.results.length-1].afterScreenshot,r.results[r.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function MN(n,e,t,r){return{status:r.status==="PASSED"?"passed":r.status==="CANCELLED"?"interrupted":"failed",duration:r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime(),error:r.status==="FAILED"&&r.failureReason?{value:r.failureDetails?.classification?.reason||r.failureReason,message:r.failureDetails?.classification?.summary||bo[r.failureReason]}:void 0,retry:r.attempts-1,steps:r.results?.map(Uv)||[],startTime:r.lastAttemptStartedAt.toISOString(),attachments:await _N(n,e,t,r)}}async function FN(n,e,t,r){return{expectedStatus:"passed",status:r.status==="PASSED"?"expected":"unexpected",results:[await MN(n,e,t,r)]}}async function DN(n,e,t,r){return{tags:[],title:r.test.name,ok:r.status==="PASSED",tests:[await FN(n,e,t,r)],id:r.runId,file:r.filePath}}function uu(n,e){return n.reduce((t,r)=>e(r)?t+1:t,0)}async function UN(n,e,t,r){return{suites:[{title:r.suiteName,file:r.projectConfigPath,specs:await Promise.all(r.runs.map(o=>DN(n,e,t,o)))}],errors:[],stats:{startTime:r.startedAt.toISOString(),duration:r.finishedAt.getTime()-r.startedAt.getTime(),expected:uu(r.runs,o=>o.status==="PASSED"),unexpected:uu(r.runs,o=>o.status!=="PASSED"),flaky:uu(r.runs,o=>!!o.isFlake),skipped:0}}}async function Bv(n,e,t,r){let o=await UN(n,e,t,r);kN.writeFileSync(NN.join(t,`${r.suiteName}.json`),JSON.stringify(o,null,2))}async function zv(n,e,t,r,o){switch(BN(o)?jN(o).isDirectory()||(y.error(`The specified reporter output directory '${o}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(y.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),zN(o,{recursive:!0})),t){case"junit":Dv(o,r);return;case"allure":case"allure-json":await _v(n,e,o,r);return;case"playwright-json":await Bv(n,e,o,r);return;default:throw new Error(`Unknown reporter format requested: '${t}'`)}}import d_ from"wait-on";import mu from"fs";import{compact as HN}from"lodash-es";import hu from"path";import{cwd as $N}from"process";import WN from"semver";async function jv({tests:n,momenticFiles:e,project:t,yes:r,include:o,exclude:i,labels:s}){let a=new Set;if(n&&n.length>0){let c=n.some(d=>mu.existsSync(d)),p=$N();c?(p!==t.rootDir&&y.warn(`The current working directory ('${p}') is different from the project root directory ('${t.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),y.info(`Reading tests from the following local file paths:
|
|
3628
|
-
${
|
|
3632
|
+
`),globalThis.console=e}}var rN=5;async function Hl({getResults:r,checkDone:e,name:t,timeoutMs:n=qp}){let o=Date.now(),i=0;for(;Date.now()-o<n;){let a;i>rN&&(y.error(`Failed to fetch ${t} status too many times.`),process.exit(1));try{a=await r(),i=0}catch(c){i++,ee.warn({err:c},"Failed to fetch run status, retrying..."),y.warn({err:c},"Failed to fetch run status, retrying..."),await new Promise(p=>setTimeout(p,1500*i));continue}if(e(a))return a;let l=Math.max(1e4,Math.floor(n/100));await new Promise(c=>setTimeout(c,l))}y.error(`Timeout elapsed waiting for ${t} to complete (${Math.floor(n/1e3)}s).`),process.exit(1)}function ui({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(l=>l.status==="PASSED"),a=r.filter(l=>l.status==="FAILED"),s=r.filter(l=>l.status==="CANCELLED");return ov(()=>{a.forEach(l=>{y.log(""),o(l)}),a.length&&(y.log(""),y.error(`${a.length} ${t}s failed:`),a.forEach(l=>{y.dimmed(n(l))})),s.length&&(y.log(""),y.warn(`${s.length} ${t}s cancelled:`),s.forEach(l=>{y.dimmed(n(l))})),i.length&&(y.log(""),y.success(`${i.length} ${t}s passed:`),i.forEach(l=>{y.dimmed(n(l))})),y.log(""),y.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{passed:i.length,failed:a.length,cancelled:s.length}}var $l=(r,e)=>{if(!r.failureDetails||!r.failureReason)return;let t=Qa[r.failureDetails?.classification?.reason||r.failureReason],n=r.failureDetails?.classification?.summary||To[r.failureReason];y.error(e),y.log(` Reason: ${iv.red(t)}`),y.log(` Description: ${iv.red(n)}`)};async function sv({fix:r,project:e}){let t=ke(e,y),n=Object.values(t.tests),o={},i={},a=new Set,s=0;for(let l of n)try{let c=Qi(l.fullFilePath,ee,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=Ot.parse(c),m=await dd(d,p,y),u=!1,h=!1;m.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?(s++,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}`),r&&(u=!0,g.id=av())):o[g.id]={testId:l.id,testRelativePath:l.relativePath},g.type!=="PRESET_ACTION")return;let v=g.command.id,b=i[v]?.testId,E=i[v]?.testRelativePath;b?(s++,h=!0,b===l.id?y.error(`Multiple commands in the test '${l.name}' (${l.relativePath}) have the same ID '${v}'`):y.error(`Command ${f} in test '${l.name}' (${l.relativePath}) has the ID ${v} which is duplicated in test ${E}`),r&&(u=!0,g.command.id=av())):i[v]={testId:l.id,testRelativePath:l.relativePath}}),h&&y.dimmed("=".repeat(80)),u&&r&&(Gr(l.relativePath,{beforeSteps:c.beforeSteps,steps:m.steps,afterSteps:c.afterSteps},je,e),a.add(l.fullFilePath))}catch(c){y.error({err:c},`Failed to parse test ${l.name} (${l.relativePath})`);continue}s>0?(y.error(`Found errors in ${s} steps`),r?y.warn(`Modified the following files:
|
|
3633
|
+
${[...a].map(l=>`${Bn}- ${l}`).join(`
|
|
3634
|
+
`)}`):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 lv({project:r}){let e=ke(r,y),t=Object.values(e.tests),n=await Os(e,ee),o={},i={},a={},s={},l=new Set,c=new Set,p=new Set,d=new Set;for(let u of t)o[u.id]?a[u.id]?a[u.id].push(u.fullFilePath):a[u.id]=[o[u.id],u.fullFilePath]:o[u.id]=u.fullFilePath,i[u.name]?s[u.name]?s[u.name].push(u.fullFilePath):s[u.name]=[i[u.name],u.fullFilePath]:i[u.name]=u.fullFilePath;for(let u of n)d.has(u.moduleId)&&l.add(u.moduleId),p.has(u.name)&&c.add(u.name),d.add(u.moduleId),p.add(u.name);if(Object.entries(a).length>0||Object.entries(s).length>0||l.size>0||c.size>0){for(let[u,h]of Object.entries(a))for(let g of h)y.error(`Test ID ${u} is duplicated in ${g}`);for(let[u,h]of Object.entries(s))for(let g of h)y.error(`Test Name ${u} is duplicated in ${g}`);for(let u of l)y.error(`Module id ${u} is duplicated in your project`);for(let u of c)y.error(`Module name ${u} 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 oN}from"lodash-es";async function Wl({client:r,skipPrompts:e,project:t}){let n=await r.getAllEnvironments(),o=oN(t.config);o.environments||(o.environments=[]);for(let i of n){let a=o.environments?.find(s=>s.name===i.name);if(a)!e&&!await st(`Environment ${i.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),a.baseUrl=i.variables[Ie],delete i.variables[Ie],a.envVariables=i.variables;else{let s=i.variables[Ie];delete i.variables[Ie],o.environments.push({name:i.name,baseUrl:s,envVariables:i.variables})}}$o(o,t.configFilePath),y.success(`Pulled ${n.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as cv}from"crypto";import dv from"fs";async function ou({testsToFetch:r,client:e,all:t,yes:n}){let{tests:o,modules:i}=await e.getTestYAMLExport({paths:r,all:t}),a=0;for(let[l,c]of Object.entries(o)){let p=pv(l,fe.TEST);!n&&!await Vp(p)||(a+=1,dv.writeFileSync(p,c,"utf-8"),ee.info({checksum:cv("md5").update(c).digest("hex")},`Wrote '${p}'`))}let s=0;for(let[l,c]of Object.entries(i)){let p=pv(l,fe.MODULE);!n&&!await Vp(p)||(s+=1,dv.writeFileSync(p,c,"utf-8"),ee.info({checksum:cv("md5").update(c).digest("hex")},`Wrote '${p}'`))}a===0?y.success("Pulled 0 tests."):y.success(`Pulled ${a} test${a>1?"s":""}${s?` and ${s} module${s>1?"s":""}`:""}!`)}function pv(r,e){switch(e){case fe.TEST:return`${Pe(r)}.${Nt.TEST}`;case fe.MODULE:return`${Pe(r)}.${Nt.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function uv(r){let{project:e,client:t,skipPrompts:n}=r;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 st("Are you sure you want to proceed?",!0)||(y.info("Aborting..."),process.exit(1)),await Wl({client:t,project:e,skipPrompts:n}),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 ou({testsToFetch:[],client:t,all:!0,yes:n}),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.")}async function mv(r){let{client:e,skipPrompts:t,paths:n}=r;await ou({testsToFetch:n,client:e,all:void 0,yes:t}),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.")}function hv(r){return r?Pe(r):"Unknown suite"}async function gv({client:r,orgId:e,suitePaths:t,wait:n,waitTimeout:o,...i}){let{suiteRunIds:a,runGroupIds:s}=await r.queueSuiteRuns({paths:t,...i});ee.info({orgId:e,suiteRunIds:a,runGroupIds:s,suitePaths:t},"Queued suites remotely"),y.dimmed(`Queued ${t.length} suites.`),n||process.exit(0);let l=Date.now();y.dimmed(`Waiting for ${t.length} suites to complete.`);let c=new Set,p=[],d=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(x=>x.status==="FAILED"&&(x.failureReason||x.finishedAt&&Date.now()-x.finishedAt.getTime()>30*1e3)||x.status==="PASSED"||x.status==="CANCELLED"),m=await Hl({name:"suites",getResults:async()=>{let f=s.filter(v=>!p.some(b=>b.id===v)),S=await r.bulkGetRunGroupStatus(f),x=[];for(let v of S)d(v)?p.push(v):x.push(v);return[...p,...x]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(S=>{S.status==="RUNNING"&&(c.has(S.id)||(c.add(S.id),y.log(`${c.size}/${s.length} ${hv(S.suite?.name)}`)))}),f.every(d))}),u=r.getAppUrl(),g=ui({results:m,startTime:l,onFailed:f=>{let S=hv(f.suite?.name),x=f.runs.filter(b=>b.status==="FAILED").length,v=f.runs.length;y.error(`${S} (${x}/${v} tests failed):`);for(let b of f.runs)if(b.status==="FAILED"){let E=b.testName||b.test?.name;y.error(` ${E?Pe(E):"Unknown test"} (${u}/runs/${b.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?Pe(f.suite.name):"Unknown suite name"} (${u}/run-groups/${f.id})`});process.exit(g.failed>0?1:0)}async function fv({tests:r,client:e,orgId:t,...n}){!n.yes&&!await st(`This command will queue ${r.length} tests to run remotely on Momentic's infrastructure. Results will be available on ${e.getAppUrl()}. Continue?`)&&process.exit(1);let{queuedTests:o,runIds:i}=await e.queueTests({testPaths:r,...n});if(ee.info({queuedTests:o,runIds:i,orgId:t},"Queued tests remotely"),y.dimmed(`Queued ${o.length} tests. Processing time may depend on a variety of factors, including how many tests have already been queued from your organization.`),n.wait||process.exit(0),!i.length)return;y.dimmed(`Waiting for ${o.length} tests to complete.`);let a=new Set,s=[],l=u=>u.status==="FAILED"&&u.failureReason||u.status==="PASSED"||u.status==="CANCELLED",c=e.getAppUrl(),p=Date.now(),d=await Hl({name:"runs",getResults:async()=>{let u=i.filter(f=>!s.some(S=>S.id===f)),h=await e.bulkGetRunStatus(u),g=[];for(let f of h)l(f)?s.push(f):g.push(f);return[...s,...g]},timeoutMs:n.waitTimeout?n.waitTimeout*1e3:void 0,checkDone:u=>(u.forEach(h=>{if(h.status==="RUNNING"&&!a.has(h.id)){a.add(h.id);let g=h.testName||h.test?.name;g&&y.log(`${a.size}/${o.length} ${Pe(g)}`)}}),u.every(l))}),m=ui({results:d,startTime:p,onFailed:u=>{let h=u.testName||u.test?.name;$l(u,h?Pe(h):"Unknown test")},getDisplayLine:u=>{let h=u.testName||u.test?.name,g=` ${h?Pe(h):"Unknown test"}`;return u.id&&(g+=` (${c}/runs/${u.id})`),g},entity:"test"});process.exit(m.failed>0?1:0)}import gi,{supportsColor as jN}from"chalk";import{existsSync as SN,mkdirSync as yN,statSync as bN}from"fs";import{randomUUID as iu}from"crypto";import Gl from"fs";import{hostname as iN}from"os";import La from"path";async function Vl(r,e,t,n,o){if(n){let i=La.extname(n),a=`${iu()}-screenshot${i}`,s=La.join(t,a),c=await(await fetch(n)).arrayBuffer();return Gl.writeFileSync(s,Buffer.from(c)),a}if(o){let i=await e.getScreenshot(r,o);if(i){let a=`${o}-screenshot.jpeg`,s=La.join(t,a);return Gl.writeFileSync(s,i),a}}}async function aN(r,e,t,n){let o=n.runId??iu(),i={uuid:o,historyId:o,testCaseId:n.test.id,fullName:n.test.name,name:Pe(n.test.name),status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"skipped":"failed",start:n.lastAttemptStartedAt.getTime(),stop:n.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:t.suiteName},{name:"host",value:iN()},{name:"platform",value:"momentic"},{name:"attempts",value:n.attempts.toString()}],steps:[]};n.runId&&i.labels?.push({name:"runUrl",value:`https://app.momentic.ai/runs/${n.runId}`});for(let[s,l]of Object.entries(n.parameters))l!=null&&i.parameters.push({name:s,value:JSON.stringify(l)});n.results&&await sN(r,e,t.folder,i.steps,n.results);let a=`${o}-result.json`;Gl.writeFileSync(La.join(t.folder,a),JSON.stringify(i,void 0,2))}async function mi(r,e,t,n){let o={name:ln(n),start:n.startedAt.getTime(),stop:n.finishedAt.getTime(),status:n.status==="SUCCESS"?"passed":n.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};n.beforeUrl&&o.labels?.push({name:"URL before step",value:n.beforeUrl}),n.afterUrl&&o.labels?.push({name:"URL after step",value:n.afterUrl});let i=await Vl(r,e,t,n.beforeScreenshot,n.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let a=await Vl(r,e,t,n.afterScreenshot,n.afterSnapshot);if(a&&o.attachments.push({name:"Screenshot after step",source:a,type:"image/jpeg"}),n.message&&(o.statusDetails={message:n.message}),n.data){let s=`${iu()}-attachment.json`,l=La.join(t,s);Gl.writeFileSync(l,JSON.stringify(n.data,null,2)),o.attachments.push({name:"Step output data",source:s,type:"text/plain"})}return o}async function sN(r,e,t,n,o){for(let i of o)switch(i.type){case"PRESET_ACTION":{n.push(await mi(r,e,t,i));break}case"CONDITIONAL":{let a=await mi(r,e,t,i);a.steps=[],i.assertion&&a.steps.push(await mi(r,e,t,i.assertion)),a.steps.push(...await Promise.all(i.results.map(s=>mi(r,e,t,s)))),n.push(a);break}case"AI_ACTION":case"IFRAME":case"SECTION":case"MODULE":{let a=await mi(r,e,t,i);if(a.steps=await Promise.all(i.results.map(s=>mi(r,e,t,s))),i.type==="MODULE"&&i.inputs){a.parameters=[];for(let[s,l]of Object.entries(i.inputs))a.parameters.push({name:s,value:l})}n.push(a)}}}async function Sv(r,e,t,n){for(let o of n.runs)await aN(r,e,{folder:t,suiteName:n.suiteName},o)}import yv from"junit-report-builder";import bv from"path";function lN(r,e){let t=e??yv.testCase();if(t.name(r.test.name).className(r.test.name).file(bv.relative(".",r.filePath)).property("id",r.test.id),r.baseUrl&&t.property("baseUrl",r.baseUrl),r.runId&&t.property("runUrl",`https://app.momentic.ai/runs/${r.runId}`),r.status==="FAILED"){if(r.failureReason){let n=Qa[r.failureDetails?.classification?.reason||r.failureReason],o=r.failureDetails?.classification?.summary||To[r.failureReason];r.runId&&(o+=` See details: https://app.momentic.ai/runs/${r.runId}`),t.failure(o,n)}r.failureDetails?.errorStack&&t.stacktrace(r.failureDetails.errorStack)}else r.status==="CANCELLED"&&t.skipped();t.time((r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime())/1e3).property("startedAt",r.lastAttemptStartedAt.toISOString()).property("finishedAt",r.finishedAt.toISOString()).property("attempts",r.attempts.toString());for(let n of["testInputs","customHeaders"]){let o=r.parameters[n];Object.keys(o??{}).length>0&&t.multilineProperty(n,JSON.stringify(o))}for(let n of["envName","urlOverride"])r.parameters[n]!==void 0&&t.property(n,r.parameters[n]);return Object.keys(r.outputs).length&&t.multilineProperty("testOutputs",JSON.stringify(r.outputs)),t}function cN(r,{suiteId:e,suiteName:t,startedAt:n,finishedAt:o,runs:i}){let a=r.testSuite().name(t);e&&a.property("id",e),a.timestamp(n).property("startedAt",n.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-n.getTime())/1e3);for(let s of i){let l=a.testCase();lN(s,l)}return a}function wv(r,e){let t=yv.newBuilder();cN(t,e),t.writeTo(bv.join(r,`${e.suiteName}.xml`))}import dN from"fs";import pN from"path";function vv(r){return{title:ln(r),duration:r.finishedAt.getTime()-r.startedAt.getTime(),error:r.status==="FAILED"?{value:r.failureReason}:void 0,steps:r.results&&r.type!=="PRESET_ACTION"?r.results.map(vv):[]}}async function uN(r,e,t,n){if(n.results?.length){let o=await Vl(r,e,t,n.results[n.results.length-1].afterScreenshot,n.results[n.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function mN(r,e,t,n){return{status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"interrupted":"failed",duration:n.finishedAt.getTime()-n.lastAttemptStartedAt.getTime(),error:n.status==="FAILED"&&n.failureReason?{value:n.failureDetails?.classification?.reason||n.failureReason,message:n.failureDetails?.classification?.summary||To[n.failureReason]}:void 0,retry:n.attempts-1,steps:n.results?.map(vv)||[],startTime:n.lastAttemptStartedAt.toISOString(),attachments:await uN(r,e,t,n)}}async function hN(r,e,t,n){return{expectedStatus:"passed",status:n.status==="PASSED"?"expected":"unexpected",results:[await mN(r,e,t,n)]}}async function gN(r,e,t,n){return{tags:[],title:n.test.name,ok:n.status==="PASSED",tests:[await hN(r,e,t,n)],id:n.runId,file:n.filePath}}function au(r,e){return r.reduce((t,n)=>e(n)?t+1:t,0)}async function fN(r,e,t,n){return{suites:[{title:n.suiteName,file:n.projectConfigPath,specs:await Promise.all(n.runs.map(o=>gN(r,e,t,o)))}],errors:[],stats:{startTime:n.startedAt.toISOString(),duration:n.finishedAt.getTime()-n.startedAt.getTime(),expected:au(n.runs,o=>o.status==="PASSED"),unexpected:au(n.runs,o=>o.status!=="PASSED"),flaky:au(n.runs,o=>!!o.isFlake),skipped:0}}}async function xv(r,e,t,n){let o=await fN(r,e,t,n);dN.writeFileSync(pN.join(t,`${n.suiteName}.json`),JSON.stringify(o,null,2))}async function Tv(r,e,t,n,o){switch(SN(o)?bN(o).isDirectory()||(y.error(`The specified reporter output directory '${o}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(y.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),yN(o,{recursive:!0})),t){case"junit":wv(o,n);return;case"allure":case"allure-json":await Sv(r,e,o,n);return;case"playwright-json":await xv(r,e,o,n);return;default:throw new Error(`Unknown reporter format requested: '${t}'`)}}import HN from"wait-on";import su from"fs";import{compact as wN}from"lodash-es";import lu from"path";import{cwd as vN}from"process";import xN from"semver";async function Ev({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,labels:a}){let s=new Set;if(r&&r.length>0){let c=r.some(d=>su.existsSync(d)),p=vN();c?(p!==t.rootDir&&y.warn(`The current working directory ('${p}') is different from the project root directory ('${t.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),y.info(`Reading tests from the following local file paths:
|
|
3635
|
+
${r.map(d=>`${Bn}- ${d}`).join(`
|
|
3629
3636
|
`)}
|
|
3630
|
-
`),
|
|
3631
|
-
${
|
|
3632
|
-
`)}`),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=hu.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 Zi(c,Q,e);if(WN.gt(p.schemaVersion,je)&&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:hu.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(HN)}import{cloneDeep as Vv}from"lodash-es";async function Hv({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 Ht({orgId:n,s:c,localTools:e,logger:t,context:o,flagStore:i})}return s}async function $v({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 cl({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 to(["chrome"]);let x=g.isBooleanFlagEnabled("icon_knowledge_base")?await i.fetchIconKnowledgeBase(l,p):null,v;try{v=await fn.init({baseUrl:n,logger:p,userBrowserSettings:f,storage:i,flagStore:g,enricher:new Gr(S,a),contextArgs:{viewport:o.advanced.viewport??Ut,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 to(lu,!0),v=await fn.init({baseUrl:n,logger:p,userBrowserSettings:f,storage:i,flagStore:g,enricher:new Gr(S,a),contextArgs:{viewport:o.advanced.viewport??Ut,deviceScaleFactor:t},iconKnowledgeBase:x});else throw C}let b=new ri({browser:v,generator:a,logger:p,orgId:l,scratchPadId:void 0,storage:i,flagStore:g,localCodeEvalTools:s,visualDiffScreenshotStorage:h,analytics:new ii,slowMoMs:f.slowMoMs}),E=new It({baseUrl:n,currentUrl:b.browser.url(),variablesFromEnvironment:c,envName:e});return o.parameters&&await Promise.all(o.parameters.map(async C=>{let{name:I,defaultValue:_,required:L}=C,z=u?.[I];L&&z===void 0&&(y.error(`Required parameter '${I}' is required by test '${o.name}' but not provided`),process.exit(1));let j=await Ht({orgId:l,s:z??_,localTools:s,logger:p,context:It.dummyContext(E.getEnvName()),flagStore:g});E.setMomenticSystemVariable(I,j)})),{controller:b,context:E}}import{randomUUID as GN}from"crypto";async function Wv({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 Gv({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:v,noReport:b}=n;h.info(`Running test '${x.name}' locally${b?"":` 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||GN(),runAttemptId:s,testMetadata:x,steps:x.steps,beforeSteps:x.beforeSteps,afterSteps:x.afterSteps},I={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await Wv({noReport:b,currentAttempt:r,testId:x.id,flagStore:c,apiClient:g,testAdvancedSettings:x.advanced,aiSettingsFromEnv:v.ai,logger:h})};return await ll({fixtures:E,inputs:C,options:I,callbacks:{step:{},test:{onTestComplete:async()=>{await a.browser.cleanup()},onProposedTestSteps:async z=>g.uploadProposedSteps(z,h)}},testParams:{tracer:S}})}async function qv(n){let{testDefinition:e,logger:t}=n,r=new Date;try{return await VN(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 VN(n){let{testDefinition:e,project:t,apiClient:r,orgId:o,urlOverride:i,runSigIntHandlers:s,runGroupTracer:a,logger:l}=n,c=new Wo(r,o),p=Vv(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??KN(e),u,m={};if(d){try{u=Qi(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[Ie];typeof S=="string"&&(h=S)}if(!h){let S=`Cannot run test with no base URL and no ${Ie} 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{let S=await qN({...n,variables:m,envName:d,stepsWithCaches:p,resolvedEnv:u,baseUrl:h,storageClient:c,tracer:g,logger:f});return await g.finish({logger:l,status:S.status,finishedAt:S.finishedAt,failureDetails:S.failureDetails,failureReason:S.failureReason,isFlake:S.isFlake}),{runId:g.runId,...S}}finally{s?.pop()}}async function qN(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:v,tracer:b,logger:E,flagStore:C}=n,I=new Date,_=new jo(r,o),L={ai:r.config.ai},z={envName:p,urlOverride:d,customHeaders:u,testInputs:m},j,O=Math.abs(S??r.config.retries??e.retries??0),U=[];E.info({labels:e.labels,name:e.name},"Starting test run using CLI");for(let P=0;P<=O;P++){let G=await b.startAttempt(),N=E.child(G.loggerBindings||{}),X={...e,steps:Vv(t)};P!==0&&v("RETRY",`attempt ${P+1}/${O+1}`);let re=new Date,Tt=new ir({httpClient:new Mt({baseUrl:i.baseUrl,apiKey:i.apiKey,logger:N}),fakerSeed:C.isBooleanFlagEnabled("faker_constant_seed")?ph:void 0});try{let{controller:ce,context:Se}=await $v({baseUrl:a,envName:p,apiClient:i,devicePixelRatio:x,logger:N,storageClient:l,codeEvalTools:Tt,test:X,generator:s,orgId:c,variables:h,customHeaders:u,testInputs:m,localBrowserConfig:{...r.config.browser||{},...g?.browser||{}},visualDiffScreenshotStorage:_,flagStore:C});j=await Gv({attemptMetadata:{attemptNumber:P+1,orgId:c,runId:b.runId},attemptFixtures:{logger:N,storageClient:l,billingReporter:new Eo,analytics:new ii,debugDataStorage:new kr,codeEvalTools:Tt,flagStore:C,apiClient:i,context:Se,controller:ce,tracer:G},attemptInputs:{test:X,orgSettings:L,noReport:f}});let De=new Date;await G.finish({logger:N,result:j,updatedSteps:{steps:X.steps,beforeSteps:X.beforeSteps,afterSteps:X.afterSteps}}),U.unshift(j.status);let Ft=await Hv({orgId:c,codeEvalTools:Tt,logger:N,outputDefinitions:e.outputs??[],testContext:Se,flagStore:C}),gt=$m(U),Dt=P+1;if(j.status!=="FAILED")return{...j,parameters:z,test:X,filePath:X.relativeFilePath,startedAt:I,lastAttemptStartedAt:re,finishedAt:De,attempts:Dt,baseUrl:a,outputs:Ft,isFlake:gt};let W=j.failedStepResult,$n=W?.message||"Unknown failure",Wn=W?.failureReason??vh($n)??"UnknownError",mi=N.child({errResult:W,failureReason:Wn,errorMessage:$n,numAttempts:O+1,name:X.name});if(P<O){mi.warn(`Retrying failed execution attempt for run: ${$n}`);continue}return mi.error(`Test failed after all exhausting attempts: ${$n}`),{...j,parameters:z,failureDetails:{errorMessage:$n},failureReason:Wn,test:X,filePath:X.relativeFilePath,startedAt:I,lastAttemptStartedAt:re,finishedAt:De,attempts:P+1,baseUrl:a,outputs:Ft}}catch(ce){let Se=`Encountered fatal platform error while running test '${X.name}': ${ce}`,De=new Date,Ft=P+1;N.error({err:ce},Se),y.error(Se);let gt={errorMessage:ce.message,errStack:ce.stack},Dt={status:"FAILED",failureDetails:gt,failureReason:"InternalPlatformError",finishedAt:De};return await G.finish({logger:N,result:{status:"FAILED",results:[]}}),{...Dt,parameters:z,test:X,filePath:X.relativeFilePath,startedAt:I,lastAttemptStartedAt:re,finishedAt:new Date,attempts:Ft,baseUrl:a,outputs:{}}}}throw new Error("This code should not be reachable")}function KN(n){for(let e of n.envs??[])if(e.default)return e.name}import{diff as YN}from"deep-object-diff";async function pi(n,e,t,r,o){let i=Bi(o.type);if(i&&await e.reportCreditsUsed(n,o.type,i,{testId:t,testName:r}),"command"in o){let s=zi(o.command);s&&await e.reportCreditsUsed(n,o.command.type,s,{testId:t,testName:r})}}var gu=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 ql(this.testId,this.testName,this.billingReporter,this.asyncWork)}},ql=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(pi(t,this.billingReporter,this.testId,this.testName,r)),new gu(this.testId,this.testName,this.billingReporter,this.asyncWork)}},fu=class{constructor(e,t,r,o,i,s,a){this.orgId=e;this.testId=t;this.testName=r;this.client=o;this.billingReporter=i;this.originalSteps=s;this.asyncWork=a}trackStatus(){}attachNetworkLogs(){}attachConsoleLogs(){}async finish(e){let{logger:t,result:r,updatedSteps:o}=e;if(r?.status!=="PASSED"||!o)return;let i=YN(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 Ze({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 ql(this.testId,this.testName,this.billingReporter,this.asyncWork)}},Su=class{constructor(e,t,r,o,i,s,a){this.orgId=e;this.testId=t;this.testName=r;this.client=o;this.billingReporter=i;this.originalSteps=s;this.asyncWork=a}async finish(){}trackStatus(){}async startAttempt(){return new fu(this.orgId,this.testId,this.testName,this.client,this.billingReporter,this.originalSteps,this.asyncWork)}},Kl=class{constructor(e,t,r){this.orgId=e;this.client=t;this.billingReporter=r}asyncWork=[];async finish(){await Promise.allSettled(this.asyncWork)}trackStatus(){}async startRun(e){return this.asyncWork.push(this.billingReporter.reportBillableEvent(e.logger,"test-run",{testId:e.testId,testName:e.testName})),new Su(this.orgId,e.testId,e.testName,this.client,this.billingReporter,e.originalSteps,this.asyncWork)}};import{randomUUID as Kv}from"crypto";import{diff as i_}from"deep-object-diff";import JN from"adm-zip";import jn from"fs";import no from"path";var Ls=class n{constructor(e){this.filePath=e;jn.rmSync(this.filePath,{recursive:!0,force:!0}),jn.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new n(no.join(this.filePath,e))}storeFile(e){let{name:t,contents:r}=e,o=no.join(this.filePath,t);jn.writeFileSync(o,r)}createRunArchive(e){return new yu(no.join(this.filePath,"runs"),e)}},yu=class{constructor(e,t){this.filePath=e;this.tempPath=no.join(e,`.${t}`),this.finalPath=no.join(e,`${t}.zip`),jn.rmSync(this.tempPath,{recursive:!0,force:!0}),jn.rmSync(this.finalPath,{recursive:!0,force:!0}),jn.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;cd(e){return new Ls(no.join(this.tempPath,e))}storeFile(e){let{name:t,contents:r}=e,o=no.join(this.tempPath,t);jn.writeFileSync(o,r)}close(){let e=new JN;e.addLocalFolder(this.tempPath,void 0,r=>r!==".DS_Store");let t=e.toBuffer();jn.writeFileSync(this.finalPath,t),jn.rmSync(this.tempPath,{recursive:!0,force:!0})}};import XN from"simple-git";var Ce=XN();function Yl(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 Re(n){try{return(await n).trim()}catch(e){Q.error({err:e},"Failed to run git command");return}}function ZN(){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 QN(){let[n,e,t,r]=await Promise.all([Re(Ce.show(["--no-patch","--format=%ci"])),Re(Ce.listRemote(["--get-url","origin"])),Re(Ce.show(["-s","--pretty=%B"])),Re(Ce.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 e_(){let[n,e,t]=await Promise.all([Re(Ce.listRemote(["--get-url","origin"])),Re(Ce.show(["-s","--pretty=%B"])),Re(Ce.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 t_(){let[n,e,t,r]=await Promise.all([Re(Ce.show(["--no-patch","--format=%ci"])),Re(Ce.listRemote(["--get-url","origin"])),Re(Ce.show(["-s","--pretty=%B"])),Re(Ce.show(["-s","--pretty=%an"]))]),o=e?.includes("github.com"),i=e?.includes("gitlab.com"),s=e?Yl(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 n_(){let[n,e,t]=await Promise.all([Re(Ce.show(["--no-patch","--format=%ci"])),Re(Ce.show(["-s","--pretty=%B"])),Re(Ce.show(["-s","--pretty=%an"]))]),r=process.env.BUILDKITE_REPO,o=r?.includes("github.com"),i=r?.includes("gitlab.com"),s=r?Yl(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 r_(){let[n,e,t]=await Promise.all([Re(Ce.show(["--no-patch","--format=%ci"])),Re(Ce.show(["-s","--pretty=%B"])),Re(Ce.show(["-s","--pretty=%an"]))]),r=process.env["Build.Repository.Uri"],o=r?.includes("github.com"),i=r?.includes("gitlab.com"),s=r?Yl(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 o_(){let[n,e,t,r,o,i,s]=await Promise.all([Re(Ce.revparse(["HEAD"])),Re(Ce.revparse(["--short","HEAD"])),Re(Ce.revparse(["--abbrev-ref","HEAD"])),Re(Ce.listRemote(["--get-url","origin"])),Re(Ce.show(["--no-patch","--format=%ci"])),Re(Ce.show(["-s","--pretty=%B"])),Re(Ce.show(["-s","--pretty=%an"]))]),a=r?.includes("github.com"),l=r?.includes("gitlab.com"),c=r?Yl(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 Jl(n){let e=ZN();if(!e)return n.debug("No CI run environment detected, falling back to git"),o_();switch(n.debug(`Using CI runner environment variables from ${e} to get git metadata`),e){case"GithubActions":return QN();case"GitlabCI":return e_();case"CircleCI":return t_();case"Buildkite":return n_();case"AzureDevOps":return r_()}}function s_(n){switch(n){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function a_(n){switch(n){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var bu=class{constructor(e,t,r,o,i,s){this.testId=e;this.testName=t;this.metadata=r;this.diskStorage=o;this.billingReporter=i;this.asyncWork=s}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:r}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:"before.jpeg",contents:r})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:r}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:"after.jpeg",contents:r})}attachBeforeHtmlSnapshot(e){let{snapshotId:t,html:r}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:"before.html",contents:r})}attachAfterHtmlSnapshot(e){let{snapshotId:t,html:r}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:"after.html",contents:r})}heal(e){let{healType:t}=e;this.metadata.healMetadata={healType:t,healedAt:new Date}}async finishInternal(e){if(this.finished)return;this.finished=!0,await Promise.all(this.children.map(r=>r.finish({status:a_(e.status),finishedAt:e.finishedAt})));let t={...this.metadata,status:e.status,finishedAt:e.finishedAt,message:e.message};this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)})}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=this.diskStorage.cd("substeps"),t=new Xl(this.testId,this.testName,e,this.billingReporter,this.asyncWork);return this.children.push(t),t}},Xl=class{constructor(e,t,r,o,i){this.testId=e;this.testName=t;this.diskStorage=r;this.billingReporter=o;this.asyncWork=i}children=[];finished=!1;getParentStepIdChain(){return[]}async startStep(e){let{logger:t,step:r}=e;this.asyncWork.push(pi(t,this.billingReporter,this.testId,this.testName,r));let o=this.diskStorage.cd(r.id),i={step:r,status:"RUNNING",startedAt:new Date};o.storeFile({name:"metadata.json",contents:JSON.stringify(i,null,2)});let s=new bu(this.testId,this.testName,i,o,this.billingReporter,this.asyncWork);return this.children.push(s),s}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:s_(e.status),finishedAt:e.finishedAt}))))}},wu=class{constructor(e,t,r,o,i,s,a,l,c){this.orgId=e;this.testId=t;this.testName=r;this.originalSteps=o;this.metadata=i;this.client=s;this.diskStorage=a;this.billingReporter=l;this.asyncWork=c}finished=!1;children=[];trackStatus(){}attachNetworkLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(t,null,2)})}attachConsoleLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(t,null,2)})}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,result:r,updatedSteps:o}=e,i={...this.metadata,status:r.status,finishedAt:new Date,results:r.results,beforeResults:r.beforeResults,afterResults:r.afterResults};if(await Promise.all(this.children.map(a=>a.finish({status:i.status,finishedAt:i.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(i,null,2)}),r?.status!=="PASSED"||!o)return;let s=i_(this.originalSteps,o);if(Object.keys(s).length!==0){t.debug({changes:s},"Updating steps post-run success in cli");try{let{cachesToSave:a}=await Ze({stepLists:o,cacheCreationParams:{testId:this.testId,orgId:this.orgId}});await this.client.updateStepCaches({testId:this.testId,entries:a})}catch(a){t.error({err:a},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async startStepList(){let e=this.diskStorage.cd("steps"),t=new Xl(this.testId,this.testName,e,this.billingReporter,this.asyncWork);return this.children.push(t),t}},vu=class{constructor(e,t,r,o,i,s,a,l,c,p){this.orgId=e;this.testId=t;this.testName=r;this.internalRunId=o;this.originalSteps=i;this.metadata=s;this.client=a;this.diskStorage=l;this.billingReporter=c;this.asyncWork=p}children=[];finished=!1;get envVarBindings(){return{[sl]:this.internalRunId}}async finish(e){if(this.finished)return;this.finished=!0;let t={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1};await Promise.all(this.children.map(r=>r.finish({logger:e.logger,result:{status:t.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}trackStatus(){}async startAttempt(){this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let e=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),t={startedAt:new Date,status:"RUNNING"};e.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)});let r=new wu(this.orgId,this.testId,this.testName,this.originalSteps,t,this.client,e,this.billingReporter,this.asyncWork);return this.children.push(r),r}},Zl=class n{constructor(e,t,r,o,i,s){this.orgId=e;this.runGroupId=t;this.metadata=r;this.client=o;this.diskStorage=i;this.billingReporter=s;this.asyncWork=[]}children=[];finished=!1;asyncWork;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start(e,t,r,o){let i=await Jl(y),s=Kv(),a={...i,trigger:Pt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:$t||je},l=new Ls(t);return l.storeFile({name:"metadata.json",contents:JSON.stringify(a,null,2)}),new n(e,s,a,r,l,o)}async finish(e){if(this.finished)return;this.finished=!0;let{status:t}=e,r={...this.metadata,status:t,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:r.status,finishedAt:r.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)}),await Promise.allSettled(this.asyncWork)}trackStatus(){}async startRun(e){let t=Kv(),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:$t,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0};r.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)}),this.asyncWork.push(this.billingReporter.reportBillableEvent(e.logger,"test-run",{eventId:t,testId:e.testId,testName:e.testName}));let i=new vu(this.orgId,e.testId,e.testName,t,e.originalSteps,o,this.client,r,this.billingReporter,this.asyncWork);return this.children.push(i),i}};import{diff as l_}from"deep-object-diff";var xu=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 Ql(this.orgId,this.testId,this.testName,this.runId,this.attemptId,this.originalSteps,this.client,this.analytics,this.debugDataStorage,this.billingReporter,this.asyncWork)}},Ql=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(pi(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 xu(this.orgId,this.testId,this.testName,this.runId,this.attemptId,r,this.originalSteps,this.client,o,this.debugDataStorage,this.billingReporter,this.asyncWork)}},Tu=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=l_(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 Ze({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 Ql(this.orgId,this.testId,this.testName,this.runId,this.attemptId,this.originalSteps,this.client,this.analytics,this.debugDataStorage,this.billingReporter,this.asyncWork)}},Eu=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{[sl]: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 Tu(this.orgId,this.testId,this.testName,this.runId,e,this.originalSteps,this.client,this.analytics,this.debugDataStorage,this.billingReporter,this.asyncWork)}},ec=class n{constructor(e,t,r,o,i,s,a,l){this.orgId=e;this.runGroupId=t;this.gitMetadata=r;this.client=o;this.analytics=i;this.debugDataStorage=s;this.billingReporter=a;this.startedAt=l;this.asyncWork=[]}asyncWork;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.gitMetadata.gitBranchName}}static async start(e,t,r,o,i){let s=await Jl(y),a=new Date,{id:l}=await t.createRunGroup({...s,trigger:Pt.CLI,startedAt:a,status:"RUNNING",cliVersion:$t}),c=r.child({commit_sha:s?.gitCommitSha,commit_sha_short:s?.gitCommitShaShort,branch_name:s?.gitBranchName,origin_url:s?.gitOriginUrl,commit_timestamp:s?.gitCommitTimestamp,github_repository:s?.githubRepository,gitlab_project_path:s?.gitlabProjectPath,pipeline_id:s?.pipelineId,run_group_id:l});return new n(e,l,s,t,c,o,i,a)}async finish(e){let{status:t}=e,r=new Date;await this.client.updateRunGroup(this.runGroupId,{status:t,finishedAt:r});let o=r.getTime()-this.startedAt.getTime();switch(t){case"PASSED":this.analytics.track({type:"execution:run_group_success",duration_ms:o});break;case"FAILED":this.analytics.track({type:"execution:run_group_fail",duration_ms:o});break;case"CANCELLED":this.analytics.track({type:"execution:run_group_cancel",duration_ms:o});break}await Promise.allSettled(this.asyncWork)}trackStatus(){}async startRun(e){let{id:t}=await this.client.createRun({stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,labels:e.testLabels,trigger:"CLI",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,cliVersion:$t,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 Eu(this.orgId,e.testId,e.testName,t,e.originalSteps,this.client,r,this.debugDataStorage,this.billingReporter,this.asyncWork)}};async function Yv(n){let{logger:e,tests:t,yes:r,start:o,waitOn:i,client:s,debugDataStorage:a,billingReporter:l,flagStore:c,analytics:p,project:d,report:u,retriesOverride:m,urlOverride:h,envName:g,orgId:f,devicePixelRatio:S,customHeaders:x,testInputMatrix:v,reporter:b,include:E,exclude:C,labels:I,reporterDir:_="reports",outputDir:L,waitOnTimeout:z=60,parallel:j=d.config.parallel??1,shardIndex:O=1,shardCount:U=1,regenerateGoldenFiles:P}=n;o&&(e.info({orgId:f},`Executing start command: ${o}`),await Vw(o,!1)),i&&(e.info({orgId:f},`Waiting for url: ${i} with timeout: ${z} seconds.`),await d_({resources:[i],interval:2500,timeout:z*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let G=new Vo({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:e}),N=Oe(d,y),X=await jv({tests:t,momenticFiles:N,yes:r,project:d,include:E,exclude:C,labels:I}),re=[];X.forEach((Ke,yr)=>{v?v.forEach((oo,ft)=>{re.push({testIndex:yr,inputs:oo,inputIndex:ft})}):re.push({testIndex:yr,inputs:void 0,inputIndex:void 0})}),U&&U>1&&(re=p_(re,O,U));let Tt=`Running ${re.length} tests with ${j} workers`;e.info({allTestsToRunWithInputs:re,shardCount:U,shardIndex:O,orgId:f},Tt),y.dimmed(Tt),re.forEach(Ke=>{y.dimmed(` - ${[X[Ke.testIndex].relativeFilePath]}${typeof Ke.inputIndex=="number"?` with input set ${Ke.inputIndex}`:""}`)}),y.log("");let ce=[],Se=new Date,De=new Set,Ft=()=>{let Ke=s.getAppUrl(),yr=ci({results:ce,startTime:Se.getTime(),onFailed:ft=>{Wl(ft,ft.filePath)},getDisplayLine:ft=>{let br=` - ${ft.filePath}${ft.proposedTest?" [AUTO-HEALED] ":""}`;return u&&ft.runId&&(br+=` (${Ke}/runs/${ft.runId})`),br},entity:"test"}),oo=ce.filter(ft=>!!ft.proposedTest);return oo.length>0&&y.warn(`${oo.length} tests passed with auto-healing. Please use the run links printed above to review proposed changes and apply them locally.`),yr},gt=new Kl(f,s,l);L?gt=await Zl.start(f,L,s,l):u&&(gt=await ec.start(f,s,p,a,l));let Dt=e.child(gt.loggerBindings||{}),W=[],$n=async()=>{y.warn("SIGINT received. Stopping tests and printing latest results..."),await gt.finish({logger:Dt,status:"CANCELLED"}),Ft(),await Promise.allSettled(W.map(Ke=>Ke())),process.exit(1)};process.on("SIGINT",$n);let Wn={};for(let Ke=0;Ke<re.length;Ke++){let yr=Object.values(Wn);yr.length===j&&await Promise.race(yr.map(br=>br.promise));let oo=re[Ke],ft=`test-${Ke}`;Wn[ft]={done:!1,promise:(async({testIndex:br,inputs:Ru})=>{let hi=X[br];De.add({testIndex:br,inputs:Ru});let sx=hi.relativeFilePath.includes("..")?hi.fullFilePath:hi.relativeFilePath,Os=(lt,gi)=>{let io=(rc,Au)=>{let lx=Math.floor((Au-rc.length)/2);return rc.padStart(lx+rc.length).padEnd(Au)};lt=lt.toUpperCase();let Ln=lt;lt.includes("FAIL")?Ln=ui.bgRed.white(io("FAIL",8)):lt.includes("PASS")?Ln=ui.bgGreen.white(io("PASS",8)):lt.includes("START")?Ln=ui.bgBlue.white(io("START",8)):lt.includes("CANCEL")?Ln=ui.bgYellow.white(io("CANCEL",8)):lt.includes("RETRY")?Ln=ui.bgYellow.white(io("RETRY",8)):lt.includes("RUN")||lt.includes("PROG")?Ln=ui.bgMagenta.white(io("RUNNING",8)):Dt.warn(`Unknown status tried to be logged in run test locally: ${lt}`),c_||(Ln=`[${Ln}]`),y.log(`${Ln} ${sx} ${gi?`${gi} `:""}(${De.size}/${re.length})`)};Os("START");let ax=setInterval(()=>Os("RUN"),5*60*1e3);try{let lt=await qv({testDefinition:hi,project:d,testInputs:Ru,orgId:f,devicePixelRatio:S,apiClient:s,runGroupTracer:gt,generator:G,retriesOverride:m,urlOverride:h,envName:g,noReport:!u,customHeaders:x,regenerateGoldenFiles:P,logUpdate:Os,runSigIntHandlers:u?W:void 0,logger:Dt,flagStore:c});Os(lt.status),ce.push(lt)}catch(lt){let gi=`Encountered unexpected fatal error when running test '${hi.name}': ${lt.message}`;y.error(gi),Dt.error(gi)}finally{clearInterval(ax),Wn[ft].done=!0,delete Wn[ft]}})(oo)}}await Promise.allSettled(Object.values(Wn).map(Ke=>Ke.promise));let mi="PASSED";return ce.some(Ke=>Ke.status==="FAILED")&&(mi="FAILED"),await gt.finish({logger:Dt,status:mi}),process.off("SIGINT",$n),b&&await zv(Dt,a,b,{projectConfigPath:d.configFilePath,suiteName:d.config.name,startedAt:Se,finishedAt:new Date,runs:ce},_??"reports"),Ft()}function p_(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 Hn from"fs";import ro from"path";var Jv={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 Xv(n,e){let t=n[e];if(!t)throw new Error(`No metadata value found for key: ${e}`);return t}function u_(n,e,t){let r=Xv(n,t),o=Xv(e,t);if(t in Jv){let i=Jv[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 Zv(n,e){Hn.rmSync(n,{recursive:!0,force:!0});let t=Hn.readdirSync(e).filter(s=>s!==".DS_Store").map(s=>ro.join(e,s));Hn.mkdirSync(n,{recursive:!0});let r=ro.join(t[0],"metadata.json"),o=sd.parse(JSON.parse(Hn.readFileSync(r,"utf-8")));for(let s of t){let a=ro.join(s,"runs");if(!Hn.existsSync(a))continue;let l=Hn.readdirSync(a);for(let d of l){let u=ro.join(a,d),m=ro.join(n,"runs",d);Hn.cpSync(u,m,{recursive:!0})}let c=ro.join(s,"metadata.json"),p=sd.parse(JSON.parse(Hn.readFileSync(c,"utf-8")));for(let d in p){let u=d;o[u]=u_(o,p,u)}}let i=ro.join(n,"metadata.json");Hn.writeFileSync(i,JSON.stringify(o,null,2))}import Qv from"adm-zip";import m_ from"fs";import tc from"path";function ex(n){let e=new Qv;e.addLocalFile(tc.join(n,"metadata.json"));for(let t of m_.readdirSync(tc.join(n,"runs"))){if(!t.endsWith(".zip"))continue;let r=t.replace(/\.zip$/,""),o=new Qv(tc.join(n,"runs",t));for(let i of o.getEntries())i.isDirectory||e.addFile(tc.join("runs",r,i.entryName),i.getData())}return e.toBuffer()}var tx=new si({platform:"cli"},{flushAt:1,flushInterval:0});ic||Q.warn("Sentry is not enabled in this environment due to unsupported node version");var b_=process.argv.some(n=>n.includes("--log-level"))&&process.argv.some(n=>n.includes("debug")),Cu=n=>{b_&&y.dimmed(n)},xt=new h_;xt.name("momentic").description("CLI").version($t||"unknown");xt.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 to(Av(n),e.force)});xt.addOption(new on("--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())});xt.addOption(new on("--verbose","enable verbose logging")).on("option:verbose",()=>{Q.enableConsoleLogs(),y.setMinLevel(0)});xt.command("check-config").addOption(Sr).action(async n=>{mn({configFilePath:n.config})});var rx=xt.command("checks").alias("check").description("Perform various project checks");rx.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(Sr).addOption(yv).action(async n=>{let e=await Sn(n),t=mn({configFilePath:n.config});await ev({project:t,fix:e.fix})});rx.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(Sr).action(async n=>{let e=mn({configFilePath:n.config});await tv({project:e})});var w_=xt.command("migrate").description("Migrate and upgrade tooling");w_.command("v0-v1").addOption(fr).addOption(zn).action(async n=>{let e=await Sn(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),!av().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=mn({}),s=new st({baseUrl:o,apiKey:r,logger:Q});await Ml({client:s,project:i,skipPrompts:e.yes}),y.success("Successfully imported environments from Momentic Cloud.")}});xt.command("import-from-cloud").addOption(zn).addOption(gr).addOption(Sr).addOption(fr).action(async n=>{let e=await Sn(n),{apiKey:t,server:r,config:o,yes:i}=e,s=mn({configFilePath:o}),a=new st({baseUrl:r,apiKey:t,logger:Q});await sv({client:a,project:s,skipPrompts:i}),process.exit(0)});xt.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new on("--name <name>","Name of the project")).action(async n=>{y.info(`Welcome to the Momentic project setup wizard! \u{1F680}
|
|
3633
|
-
`),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."),
|
|
3634
|
-
/*! Bundled license information:
|
|
3635
|
-
|
|
3636
|
-
is-buffer/index.js:
|
|
3637
|
-
(*!
|
|
3638
|
-
* Determine if an object is a Buffer
|
|
3639
|
-
*
|
|
3640
|
-
* @author Feross Aboukhadijeh <https://feross.org>
|
|
3641
|
-
* @license MIT
|
|
3642
|
-
*)
|
|
3643
|
-
*/
|
|
3637
|
+
`),r.forEach(d=>{if(!su.existsSync(d))throw new Error(`Path '${d}' does not exist.`);let m,u;try{m=su.statSync(d),u=m.isDirectory()}catch(g){y.warn({err:g},`Skipping path ${d} because it cannot be read`);return}let h=lu.resolve(d);Object.values(e.tests).filter(g=>u?g.fullFilePath.startsWith(h):g.fullFilePath===h).forEach(g=>{s.add(g.fullFilePath)})})):(y.info(`Reading all tests from the project and running those matching the following substring filters:
|
|
3638
|
+
${r.map(d=>`${Bn}- ${d}`).join(`
|
|
3639
|
+
`)}`),Object.values(e.tests).forEach(d=>{r.some(m=>d.relativePath.includes(m))&&s.add(d.fullFilePath)}))}else{!n&&!await st("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=>{s.add(p.fullFilePath)})}for(let c of s){let p=lu.relative(t.rootDir,c);o&&!o.some(d=>new RegExp(d).test(p))&&s.delete(c),i&&i.some(d=>new RegExp(d).test(p))&&s.delete(c)}let l=Array.from(s).map(async c=>{try{let p=await ea(c,ee,e);if(xN.gt(p.schemaVersion,je)&&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(a&&a.length>0){let d=p.labels||[];if(!a.some(u=>d.includes(u)))return null}return{...p,fullFilePath:c,relativeFilePath:lu.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(wN)}import{cloneDeep as Pv}from"lodash-es";async function Cv({orgId:r,codeEvalTools:e,logger:t,outputDefinitions:n,testContext:o,flagStore:i}){let a={};for(let s of n){let{name:l,value:c}=s;a[l]=await jt({orgId:r,s:c,localTools:e,logger:t,context:o,flagStore:i})}return a}async function Av({baseUrl:r,envName:e,devicePixelRatio:t,apiClient:n,test:o,storageClient:i,codeEvalTools:a,generator:s,orgId:l,variables:c,logger:p,customHeaders:d,testInputs:m,localBrowserConfig:u,visualDiffScreenshotStorage:h,flagStore:g}){let f=await pl({advanced:{...u,...o.advanced},customHeaders:d,envVariables:c,envName:e,baseUrl:r,logger:p,localTools:a,orgId:l,flagStore:g}),S={baseUrl:n.baseUrl,apiKey:n.apiKey,logger:ee};f.browserType==="Google Chrome"&&await oo(["chrome"]);let x=g.isBooleanFlagEnabled("icon_knowledge_base")?await i.fetchIconKnowledgeBase(l,p):null,v;try{v=await fn.init({baseUrl:r,logger:p,userBrowserSettings:f,storage:i,flagStore:g,enricher:new Kr(S,s),contextArgs:{viewport:o.advanced.viewport??Dt,locale:o.advanced.locale??Pr,timezoneId:o.advanced.timezone??Lr,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 oo(tu,!0),v=await fn.init({baseUrl:r,logger:p,userBrowserSettings:f,storage:i,flagStore:g,enricher:new Kr(S,s),contextArgs:{viewport:o.advanced.viewport??Dt,locale:o.advanced.locale??Pr,timezoneId:o.advanced.timezone??Lr,deviceScaleFactor:t},iconKnowledgeBase:x});else throw C}let b=new si({browser:v,generator:s,logger:p,orgId:l,scratchPadId:void 0,storage:i,flagStore:g,localCodeEvalTools:a,visualDiffScreenshotStorage:h,analytics:new ci,slowMoMs:f.slowMoMs}),E=new It({baseUrl:r,currentUrl:b.browser.url(),variablesFromEnvironment:c,envName:e});return o.parameters&&await Promise.all(o.parameters.map(async C=>{let{name:I,defaultValue:M,required:L}=C,z=m?.[I];L&&z===void 0&&(y.error(`Required parameter '${I}' is required by test '${o.name}' but not provided`),process.exit(1));let j=await jt({orgId:l,s:z??M,localTools:a,logger:p,context:It.dummyContext(E.getEnvName()),flagStore:g});E.setMomenticSystemVariable(I,j)})),{controller:b,context:E}}import{randomUUID as TN}from"crypto";async function Rv({testId:r,apiClient:e,testAdvancedSettings:t,aiSettingsFromEnv:n,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&&!n?.failureRecovery)return!1;let a;try{a=await e.getPastTestResults(r,{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 a.some(l=>l.status==="PASSED")?!0:(o.debug({recentRuns:a},"Test is not eligible for recovery because there are only failures in the past 7 days"),!1)}async function Iv({attemptInputs:r,attemptFixtures:e,attemptMetadata:t}){let{attemptNumber:n,orgId:o,runId:i,runAttemptId:a}=t,{controller:s,context:l,flagStore:c,analytics:p,codeEvalTools:d,storageClient:m,debugDataStorage:u,logger:h,apiClient:g,billingReporter:f,tracer:S}=e,{test:x,orgSettings:v,noReport:b}=r;h.info(`Running test '${x.name}' locally${b?"":` and reporting results to https://app.momentic.ai/runs/${i}`}`);let E={controller:s,storage:m,debugDataStorage:u,billingReporter:f,analytics:p,context:l,logger:h,codeEvalTools:d},C={orgId:o,runId:i||TN(),runAttemptId:a,testMetadata:x,steps:x.steps,beforeSteps:x.beforeSteps,afterSteps:x.afterSteps},I={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await Rv({noReport:b,currentAttempt:n,testId:x.id,flagStore:c,apiClient:g,testAdvancedSettings:x.advanced,aiSettingsFromEnv:v.ai,logger:h})};return await dl({fixtures:E,inputs:C,options:I,callbacks:{step:{},test:{onTestComplete:async()=>{await s.browser.cleanup()},onProposedTestSteps:async z=>g.uploadProposedSteps(z,h)}},testParams:{tracer:S}})}async function Lv(r){let{testDefinition:e,logger:t}=r,n=new Date;try{return await EN(r)}catch(o){let i="Fatal error running test";return y.error(`${i}: ${o.message}`),t.error({err:o},i),{parameters:r,failureReason:"UnknownError",failureDetails:{errorMessage:o.message,errorStack:o.stack},status:"FAILED",attempts:0,test:e,filePath:e.relativeFilePath,startedAt:n,lastAttemptStartedAt:n,finishedAt:new Date,outputs:{}}}}async function EN(r){let{testDefinition:e,project:t,apiClient:n,orgId:o,urlOverride:i,runSigIntHandlers:a,runGroupTracer:s,logger:l}=r,c=new Ko(n,o),p=Pv(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=r.envName??AN(e),m,u={};if(d){try{m=ta(d,t,l)}catch(S){let x=`Failed to resolve environment ${d} for test ${e.name}: ${S}`;throw new Error(x)}u=m.variables}let h=e.baseUrl;if(i)h=i;else if(!h){let S=u[Ie];typeof S=="string"&&(h=S)}if(!h){let S=`Cannot run test with no base URL and no ${Ie} variable defined in its environment`;throw new Error(S)}let g=await s.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])=>{u[S]=x});try{let S=await CN({...r,variables:u,envName:d,stepsWithCaches:p,resolvedEnv:m,baseUrl:h,storageClient:c,tracer:g,logger:f});return await g.finish({logger:l,status:S.status,finishedAt:S.finishedAt,failureDetails:S.failureDetails,failureReason:S.failureReason,isFlake:S.isFlake}),{runId:g.runId,...S}}finally{a?.pop()}}async function CN(r){let{testDefinition:e,stepsWithCaches:t,project:n,regenerateGoldenFiles:o,apiClient:i,generator:a,baseUrl:s,storageClient:l,orgId:c,envName:p,urlOverride:d,customHeaders:m,testInputs:u,variables:h,resolvedEnv:g,noReport:f,retriesOverride:S,devicePixelRatio:x,logUpdate:v,tracer:b,logger:E,flagStore:C}=r,I=new Date,M=new Go(n,o),L={ai:n.config.ai},z={envName:p,urlOverride:d,customHeaders:m,testInputs:u},j,k=Math.abs(S??n.config.retries??e.retries??0),U=[];E.info({labels:e.labels,name:e.name},"Starting test run using CLI");for(let P=0;P<=k;P++){let V=await b.startAttempt(),N=E.child(V.loggerBindings||{}),X={...e,steps:Pv(t)};P!==0&&v("RETRY",`attempt ${P+1}/${k+1}`);let oe=new Date,Tt=new ar({httpClient:new _t({baseUrl:i.baseUrl,apiKey:i.apiKey,logger:N}),fakerSeed:C.isBooleanFlagEnabled("faker_constant_seed")?ih:void 0});try{let{controller:se,context:Se}=await Av({baseUrl:s,envName:p,apiClient:i,devicePixelRatio:x,logger:N,storageClient:l,codeEvalTools:Tt,test:X,generator:a,orgId:c,variables:h,customHeaders:m,testInputs:u,localBrowserConfig:{...n.config.browser||{},...g?.browser||{}},visualDiffScreenshotStorage:M,flagStore:C});j=await Iv({attemptMetadata:{attemptNumber:P+1,orgId:c,runId:b.runId},attemptFixtures:{logger:N,storageClient:l,billingReporter:new Io,analytics:new ci,debugDataStorage:new _r,codeEvalTools:Tt,flagStore:C,apiClient:i,context:Se,controller:se,tracer:V},attemptInputs:{test:X,orgSettings:L,noReport:f}});let De=new Date;await V.finish({logger:N,result:j,updatedSteps:{steps:X.steps,beforeSteps:X.beforeSteps,afterSteps:X.afterSteps}}),U.unshift(j.status);let Ft=await Cv({orgId:c,codeEvalTools:Tt,logger:N,outputDefinitions:e.outputs??[],testContext:Se,flagStore:C}),gt=Dm(U),Wt=P+1;if(j.status!=="FAILED")return{...j,parameters:z,test:X,filePath:X.relativeFilePath,startedAt:I,lastAttemptStartedAt:oe,finishedAt:De,attempts:Wt,baseUrl:s,outputs:Ft,isFlake:gt};let G=j.failedStepResult,$n=G?.message||"Unknown failure",Wn=G?.failureReason??gh($n)??"UnknownError",fi=N.child({errResult:G,failureReason:Wn,errorMessage:$n,numAttempts:k+1,name:X.name});if(P<k){fi.warn(`Retrying failed execution attempt for run: ${$n}`);continue}return fi.error(`Test failed after all exhausting attempts: ${$n}`),{...j,parameters:z,failureDetails:{errorMessage:$n},failureReason:Wn,test:X,filePath:X.relativeFilePath,startedAt:I,lastAttemptStartedAt:oe,finishedAt:De,attempts:P+1,baseUrl:s,outputs:Ft}}catch(se){yi(se);let Se=`Encountered fatal platform error while running test '${X.name}': ${se}`,De=new Date,Ft=P+1;N.error({err:se},Se),y.error(Se);let gt={errorMessage:se.message,errStack:se.stack},Wt={status:"FAILED",failureDetails:gt,failureReason:"InternalPlatformError",finishedAt:De};return await V.finish({logger:N,result:{status:"FAILED",results:[]}}),{...Wt,parameters:z,test:X,filePath:X.relativeFilePath,startedAt:I,lastAttemptStartedAt:oe,finishedAt:new Date,attempts:Ft,baseUrl:s,outputs:{}}}}throw new Error("This code should not be reachable")}function AN(r){for(let e of r.envs??[])if(e.default)return e.name}import{diff as RN}from"deep-object-diff";async function hi(r,e,t,n,o){let i=ji(o.type);if(i&&await e.reportCreditsUsed(r,o.type,i,{testId:t,testName:n}),"command"in o){let a=Hi(o.command);a&&await e.reportCreditsUsed(r,o.command.type,a,{testId:t,testName:n})}}var cu=class{constructor(e,t,n,o){this.testId=e;this.testName=t;this.billingReporter=n;this.asyncWork=o}getParentStepIdChain(){return[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}heal(){}async finish(){}async startSubSteps(){return new ql(this.testId,this.testName,this.billingReporter,this.asyncWork)}},ql=class{constructor(e,t,n,o){this.testId=e;this.testName=t;this.billingReporter=n;this.asyncWork=o}getParentStepIdChain(){return[]}async startStep(e){let{logger:t,step:n}=e;return this.asyncWork.push(hi(t,this.billingReporter,this.testId,this.testName,n)),new cu(this.testId,this.testName,this.billingReporter,this.asyncWork)}},du=class{constructor(e,t,n,o,i,a,s){this.orgId=e;this.testId=t;this.testName=n;this.client=o;this.billingReporter=i;this.originalSteps=a;this.asyncWork=s}trackStatus(){}attachNetworkLogs(){}attachConsoleLogs(){}async finish(e){let{logger:t,result:n,updatedSteps:o}=e;if(n?.status!=="PASSED"||!o)return;let i=RN(this.originalSteps,o);if(Object.keys(i).length!==0){t.info({changes:i},"Updating steps post-run success in cli");try{let{cachesToSave:a}=await Qe({stepLists:o,cacheCreationParams:{testId:this.testId,orgId:this.orgId}});await this.client.updateStepCaches({testId:this.testId,entries:a})}catch(a){t.error({err:a},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async startStepList(){return new ql(this.testId,this.testName,this.billingReporter,this.asyncWork)}},pu=class{constructor(e,t,n,o,i,a,s){this.orgId=e;this.testId=t;this.testName=n;this.client=o;this.billingReporter=i;this.originalSteps=a;this.asyncWork=s}async finish(){}trackStatus(){}async startAttempt(){return new du(this.orgId,this.testId,this.testName,this.client,this.billingReporter,this.originalSteps,this.asyncWork)}},Kl=class{constructor(e,t,n){this.orgId=e;this.client=t;this.billingReporter=n}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 pu(this.orgId,e.testId,e.testName,this.client,this.billingReporter,e.originalSteps,this.asyncWork)}};import{randomUUID as kv}from"crypto";import{diff as DN}from"deep-object-diff";import IN from"adm-zip";import jn from"fs";import io from"path";var ka=class r{constructor(e){this.filePath=e;jn.rmSync(this.filePath,{recursive:!0,force:!0}),jn.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(io.join(this.filePath,e))}storeFile(e){let{name:t,contents:n}=e,o=io.join(this.filePath,t);jn.writeFileSync(o,n)}createRunArchive(e){return new uu(io.join(this.filePath,"runs"),e)}},uu=class{constructor(e,t){this.filePath=e;this.tempPath=io.join(e,`.${t}`),this.finalPath=io.join(e,`${t}.zip`),jn.rmSync(this.tempPath,{recursive:!0,force:!0}),jn.rmSync(this.finalPath,{recursive:!0,force:!0}),jn.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;cd(e){return new ka(io.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=io.join(this.tempPath,t);jn.writeFileSync(o,n)}close(){let e=new IN;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();jn.writeFileSync(this.finalPath,t),jn.rmSync(this.tempPath,{recursive:!0,force:!0})}};import PN from"simple-git";var Ce=PN();function Yl(r){if(r.startsWith("git@")){let e=r.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let n=t[0],o=t[1];return`${n}/${o}`}}}else if(r.startsWith("http")||r.startsWith("https")){let t=new URL(r).pathname.split("/").filter(Boolean);if(t.length>=2){let n=t[0],o=t[1].replace(".git","");return`${n}/${o}`}}}async function Ae(r){try{return(await r).trim()}catch(e){ee.error({err:e},"Failed to run git command");return}}function LN(){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 kN(){let[r,e,t,n]=await Promise.all([Ae(Ce.show(["--no-patch","--format=%ci"])),Ae(Ce.listRemote(["--get-url","origin"])),Ae(Ce.show(["-s","--pretty=%B"])),Ae(Ce.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:r?new Date(r):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:`${process.env.GITHUB_RUN_ID}:${process.env.GITHUB_RUN_ATTEMPT}`}}async function ON(){let[r,e,t]=await Promise.all([Ae(Ce.listRemote(["--get-url","origin"])),Ae(Ce.show(["-s","--pretty=%B"])),Ae(Ce.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:r,gitCommitMessage:e,gitCommitAuthorName:t,gitlabProjectPath:process.env.CI_SERVER_HOST,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function NN(){let[r,e,t,n]=await Promise.all([Ae(Ce.show(["--no-patch","--format=%ci"])),Ae(Ce.listRemote(["--get-url","origin"])),Ae(Ce.show(["-s","--pretty=%B"])),Ae(Ce.show(["-s","--pretty=%an"]))]),o=e?.includes("github.com"),i=e?.includes("gitlab.com"),a=e?Yl(e):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:r?new Date(r):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:o?a:void 0,gitlabProjectPath:i?a:void 0,pipelineId:`${process.env.CIRCLE_WORKFLOW_ID}:${process.env.CIRCLE_WORKFLOW_JOB_ID}`}}async function MN(){let[r,e,t]=await Promise.all([Ae(Ce.show(["--no-patch","--format=%ci"])),Ae(Ce.show(["-s","--pretty=%B"])),Ae(Ce.show(["-s","--pretty=%an"]))]),n=process.env.BUILDKITE_REPO,o=n?.includes("github.com"),i=n?.includes("gitlab.com"),a=n?Yl(n):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:r?new Date(r):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:n,gitCommitMessage:e,gitCommitAuthorName:t,githubRepository:o?a:void 0,gitlabProjectPath:i?a:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function _N(){let[r,e,t]=await Promise.all([Ae(Ce.show(["--no-patch","--format=%ci"])),Ae(Ce.show(["-s","--pretty=%B"])),Ae(Ce.show(["-s","--pretty=%an"]))]),n=process.env["Build.Repository.Uri"],o=n?.includes("github.com"),i=n?.includes("gitlab.com"),a=n?Yl(n):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:r?new Date(r):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:n,gitCommitMessage:e,gitCommitAuthorName:t,githubRepository:o?a:void 0,gitlabProjectPath:i?a:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function FN(){let[r,e,t,n,o,i,a]=await Promise.all([Ae(Ce.revparse(["HEAD"])),Ae(Ce.revparse(["--short","HEAD"])),Ae(Ce.revparse(["--abbrev-ref","HEAD"])),Ae(Ce.listRemote(["--get-url","origin"])),Ae(Ce.show(["--no-patch","--format=%ci"])),Ae(Ce.show(["-s","--pretty=%B"])),Ae(Ce.show(["-s","--pretty=%an"]))]),s=n?.includes("github.com"),l=n?.includes("gitlab.com"),c=n?Yl(n):void 0;return{gitCommitSha:r,gitCommitShaShort:e,gitBranchName:t,gitOriginUrl:n,gitCommitTimestamp:o?new Date(o):void 0,gitCommitMessage:i,gitCommitAuthorName:a,githubRepository:s?c:void 0,gitlabProjectPath:l?c:void 0,pipelineId:void 0}}async function Jl(r){let e=LN();if(!e)return r.debug("No CI run environment detected, falling back to git"),FN();switch(r.debug(`Using CI runner environment variables from ${e} to get git metadata`),e){case"GithubActions":return kN();case"GitlabCI":return ON();case"CircleCI":return NN();case"Buildkite":return MN();case"AzureDevOps":return _N()}}function UN(r){switch(r){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function BN(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var mu=class{constructor(e,t,n,o,i,a){this.testId=e;this.testName=t;this.metadata=n;this.diskStorage=o;this.billingReporter=i;this.asyncWork=a}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:"before.jpeg",contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:"after.jpeg",contents:n})}attachBeforeHtmlSnapshot(e){let{snapshotId:t,html:n}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:"before.html",contents:n})}attachAfterHtmlSnapshot(e){let{snapshotId:t,html:n}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:"after.html",contents:n})}heal(e){let{healType:t}=e;this.metadata.healMetadata={healType:t,healedAt:new Date}}async finishInternal(e){if(this.finished)return;this.finished=!0,await Promise.all(this.children.map(n=>n.finish({status:BN(e.status),finishedAt:e.finishedAt})));let t={...this.metadata,status:e.status,finishedAt:e.finishedAt,message:e.message};this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)})}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=this.diskStorage.cd("substeps"),t=new Xl(this.testId,this.testName,e,this.billingReporter,this.asyncWork);return this.children.push(t),t}},Xl=class{constructor(e,t,n,o,i){this.testId=e;this.testName=t;this.diskStorage=n;this.billingReporter=o;this.asyncWork=i}children=[];finished=!1;getParentStepIdChain(){return[]}async startStep(e){let{logger:t,step:n}=e;this.asyncWork.push(hi(t,this.billingReporter,this.testId,this.testName,n));let o=this.diskStorage.cd(n.id),i={step:n,status:"RUNNING",startedAt:new Date};o.storeFile({name:"metadata.json",contents:JSON.stringify(i,null,2)});let a=new mu(this.testId,this.testName,i,o,this.billingReporter,this.asyncWork);return this.children.push(a),a}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:UN(e.status),finishedAt:e.finishedAt}))))}},hu=class{constructor(e,t,n,o,i,a,s,l,c){this.orgId=e;this.testId=t;this.testName=n;this.originalSteps=o;this.metadata=i;this.client=a;this.diskStorage=s;this.billingReporter=l;this.asyncWork=c}finished=!1;children=[];trackStatus(){}attachNetworkLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(t,null,2)})}attachConsoleLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(t,null,2)})}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,result:n,updatedSteps:o}=e,i={...this.metadata,status:n.status,finishedAt:new Date,results:As(n.results,t),beforeResults:n.beforeResults?As(n.beforeResults,t):void 0,afterResults:n.afterResults?As(n.afterResults,t):void 0};if(await Promise.all(this.children.map(s=>s.finish({status:i.status,finishedAt:i.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(i,null,2)}),n?.status!=="PASSED"||!o)return;let a=DN(this.originalSteps,o);if(Object.keys(a).length!==0){t.info({changes:a},"Updating steps post-run success in cli");try{let{cachesToSave:s}=await Qe({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"),t=new Xl(this.testId,this.testName,e,this.billingReporter,this.asyncWork);return this.children.push(t),t}},gu=class{constructor(e,t,n,o,i,a,s,l,c,p){this.orgId=e;this.testId=t;this.testName=n;this.runId=o;this.originalSteps=i;this.metadata=a;this.client=s;this.diskStorage=l;this.billingReporter=c;this.asyncWork=p}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}get envVarBindings(){return{[ll]:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let t={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1};await Promise.all(this.children.map(n=>n.finish({logger:e.logger,result:{status:t.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}trackStatus(){}async startAttempt(){this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let e=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),t={startedAt:new Date,status:"RUNNING"};e.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)});let n=new hu(this.orgId,this.testId,this.testName,this.originalSteps,t,this.client,e,this.billingReporter,this.asyncWork);return this.children.push(n),n}},Zl=class r{constructor(e,t,n,o,i,a){this.orgId=e;this.runGroupId=t;this.metadata=n;this.client=o;this.diskStorage=i;this.billingReporter=a;this.asyncWork=[]}children=[];finished=!1;asyncWork;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start(e,t,n,o){let i=await Jl(y),a=kv(),s={...i,trigger:Pt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Ht||je},l=new ka(t);return l.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)}),new r(e,a,s,n,l,o)}async finish(e){if(this.finished)return;this.finished=!0;let{status:t}=e,n={...this.metadata,status:t,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:n.status,finishedAt:n.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)}),await Promise.allSettled(this.asyncWork)}trackStatus(){}async startRun(e){let t=kv(),n=this.diskStorage.createRunArchive(t),o={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,labels:e.testLabels,trigger:"CLI",status:"RUNNING",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,cliVersion:Ht,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0};n.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)}),this.asyncWork.push(this.billingReporter.reportBillableEvent(e.logger,"test-run",{eventId:t,testId:e.testId,testName:e.testName}));let i=new gu(this.orgId,e.testId,e.testName,t,e.originalSteps,o,this.client,n,this.billingReporter,this.asyncWork);return this.children.push(i),i}};import{diff as zN}from"deep-object-diff";var fu=class{constructor(e,t,n,o,i,a,s,l,c,p,d,m){this.orgId=e;this.testId=t;this.testName=n;this.runId=o;this.attemptId=i;this.step=a;this.originalSteps=s;this.client=l;this.analytics=c;this.debugDataStorage=p;this.billingReporter=d;this.asyncWork=m}startedAt=new Date;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{logger:t,snapshotId:n,screenshot:o}=e;this.asyncWork.push(this.debugDataStorage.storeScreenshot(t,n,o))}attachAfterScreenshot(e){let{logger:t,snapshotId:n,screenshot:o}=e;this.asyncWork.push(this.debugDataStorage.storeScreenshot(t,n,o))}attachBeforeHtmlSnapshot(e){let{logger:t,snapshotId:n,html:o}=e;this.asyncWork.push(this.debugDataStorage.storeHtmlSnapshot(t,n,o))}attachAfterHtmlSnapshot(e){let{logger:t,snapshotId:n,html:o}=e;this.asyncWork.push(this.debugDataStorage.storeHtmlSnapshot(t,n,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,n=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:n.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:n.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:n.getTime()-this.startedAt.getTime()});break;default:throw new Error(`Unexpected status: ${t.status}`)}}async startSubSteps(){return new Ql(this.orgId,this.testId,this.testName,this.runId,this.attemptId,this.originalSteps,this.client,this.analytics,this.debugDataStorage,this.billingReporter,this.asyncWork)}},Ql=class{constructor(e,t,n,o,i,a,s,l,c,p,d){this.orgId=e;this.testId=t;this.testName=n;this.runId=o;this.attemptId=i;this.originalSteps=a;this.client=s;this.analytics=l;this.debugDataStorage=c;this.billingReporter=p;this.asyncWork=d}getParentStepIdChain(){return[]}async startStep(e){let{logger:t,step:n}=e;this.asyncWork.push(hi(t,this.billingReporter,this.testId,this.testName,n));let o=this.analytics.child({step_id:n.id});return o.track({type:"execution:step_start",step_type:n.type==="RESOLVED_MODULE"?"MODULE":n.type,command_type:"command"in n?n.command.type:void 0}),new fu(this.orgId,this.testId,this.testName,this.runId,this.attemptId,n,this.originalSteps,this.client,o,this.debugDataStorage,this.billingReporter,this.asyncWork)}},Su=class{constructor(e,t,n,o,i,a,s,l,c,p,d){this.orgId=e;this.testId=t;this.testName=n;this.runId=o;this.attemptId=i;this.originalSteps=a;this.client=s;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:n}=e;this.asyncWork.push(this.debugDataStorage.storeNetworkLogsForRunAttempt(t,this.runId,this.attemptId,n))}attachConsoleLogs(e){let{logger:t,logs:n}=e;this.asyncWork.push(this.debugDataStorage.storeConsoleLogsForRunAttempt(t,this.runId,this.attemptId,n))}async finish(e){let{logger:t,result:n,updatedSteps:o}=e;if(await this.client.updateRunAttempt(this.runId,this.attemptId,{status:n.status,finishedAt:new Date,results:n.results,beforeResults:n.beforeResults,afterResults:n.afterResults}),n?.status!=="PASSED"||!o)return;let i=zN(this.originalSteps,o);if(Object.keys(i).length!==0){t.info({changes:i},"Updating steps post-run success in cli");try{let{cachesToSave:a}=await Qe({stepLists:o,cacheCreationParams:{testId:this.testId,orgId:this.orgId}});await this.client.updateStepCaches({testId:this.testId,entries:a})}catch(a){t.error({err:a},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async startStepList(){return new Ql(this.orgId,this.testId,this.testName,this.runId,this.attemptId,this.originalSteps,this.client,this.analytics,this.debugDataStorage,this.billingReporter,this.asyncWork)}},yu=class{constructor(e,t,n,o,i,a,s,l,c,p){this.orgId=e;this.testId=t;this.testName=n;this.runId=o;this.originalSteps=i;this.client=a;this.analytics=s;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{[ll]:this.runId}}async finish(e){let t=e.finishedAt||new Date,n=t.getTime()-this.startedAt.getTime();switch(e.status){case"PASSED":this.analytics.track({type:"execution:test_success",attempt_count:this.attempts,duration_ms:n,is_flake:e.isFlake||!1});break;case"CANCELLED":this.analytics.track({type:"execution:test_cancel",duration_ms:n,attempt_count:this.attempts});break;case"FAILED":this.analytics.track({type:"execution:test_fail",attempt_count:this.attempts,duration_ms:n,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 Su(this.orgId,this.testId,this.testName,this.runId,e,this.originalSteps,this.client,this.analytics,this.debugDataStorage,this.billingReporter,this.asyncWork)}},ec=class r{constructor(e,t,n,o,i,a,s,l){this.orgId=e;this.runGroupId=t;this.gitMetadata=n;this.client=o;this.analytics=i;this.debugDataStorage=a;this.billingReporter=s;this.startedAt=l;this.asyncWork=[]}asyncWork;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.gitMetadata.gitBranchName}}static async start(e,t,n,o,i){let a=await Jl(y),s=new Date,{id:l}=await t.createRunGroup({...a,trigger:Pt.CLI,startedAt:s,status:"RUNNING",cliVersion:Ht}),c=n.child({commit_sha:a?.gitCommitSha,commit_sha_short:a?.gitCommitShaShort,branch_name:a?.gitBranchName,origin_url:a?.gitOriginUrl,commit_timestamp:a?.gitCommitTimestamp,github_repository:a?.githubRepository,gitlab_project_path:a?.gitlabProjectPath,pipeline_id:a?.pipelineId,run_group_id:l});return new r(e,l,a,t,c,o,i,s)}async finish(e){let{status:t}=e,n=new Date;await this.client.updateRunGroup(this.runGroupId,{status:t,finishedAt:n});let o=n.getTime()-this.startedAt.getTime();switch(t){case"PASSED":this.analytics.track({type:"execution:run_group_success",duration_ms:o});break;case"FAILED":this.analytics.track({type:"execution:run_group_fail",duration_ms:o});break;case"CANCELLED":this.analytics.track({type:"execution:run_group_cancel",duration_ms:o});break}await Promise.allSettled(this.asyncWork)}trackStatus(){}async startRun(e){let{id:t}=await this.client.createRun({stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,labels:e.testLabels,trigger:"CLI",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,cliVersion:Ht,schemaVersion:e.schemaVersion}),n=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})),n.track({type:"execution:test_start"}),new yu(this.orgId,e.testId,e.testName,t,e.originalSteps,this.client,n,this.debugDataStorage,this.billingReporter,this.asyncWork)}};async function Ov(r){let{logger:e,tests:t,yes:n,start:o,waitOn:i,client:a,debugDataStorage:s,billingReporter:l,flagStore:c,analytics:p,project:d,report:m,retriesOverride:u,urlOverride:h,envName:g,orgId:f,devicePixelRatio:S,customHeaders:x,testInputMatrix:v,reporter:b,include:E,exclude:C,labels:I,reporterDir:M="reports",outputDir:L,waitOnTimeout:z=60,parallel:j=d.config.parallel??1,shardIndex:k=1,shardCount:U=1,regenerateGoldenFiles:P}=r;o&&(e.info({orgId:f},`Executing start command: ${o}`),await Iw(o,!1)),i&&(e.info({orgId:f},`Waiting for url: ${i} with timeout: ${z} seconds.`),await HN({resources:[i],interval:2500,timeout:z*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let V=new Jo({baseUrl:a.baseUrl,apiKey:a.apiKey,logger:e}),N=ke(d,y),X=await Ev({tests:t,momenticFiles:N,yes:n,project:d,include:E,exclude:C,labels:I}),oe=[];X.forEach((Ye,br)=>{v?v.forEach((so,ft)=>{oe.push({testIndex:br,inputs:so,inputIndex:ft})}):oe.push({testIndex:br,inputs:void 0,inputIndex:void 0})}),U&&U>1&&(oe=$N(oe,k,U));let Tt=`Running ${oe.length} tests with ${j} workers:`;e.info({allTestsToRunWithInputs:oe,shardCount:U,shardIndex:k,orgId:f},Tt),y.info(Tt),oe.forEach(Ye=>{y.info(`${Bn}- ${[X[Ye.testIndex].relativeFilePath]}${typeof Ye.inputIndex=="number"?` with input set ${Ye.inputIndex}`:""}`)}),y.log("");let se=[],Se=new Date,De=new Set,Ft=()=>{let Ye=a.getAppUrl(),br=ui({results:se,startTime:Se.getTime(),onFailed:ft=>{$l(ft,ft.filePath)},getDisplayLine:ft=>{let wr=`${Bn}- ${ft.filePath}${ft.proposedTest?" [AUTO-HEALED] ":""}`;return m&&ft.runId&&(wr+=` (${Ye}/runs/${ft.runId})`),wr},entity:"test"}),so=se.filter(ft=>!!ft.proposedTest);return so.length>0&&y.warn(`${so.length} tests passed with auto-healing. Please use the run links printed above to review proposed changes and apply them locally.`),br},gt=new Kl(f,a,l);L?gt=await Zl.start(f,L,a,l):m&&(gt=await ec.start(f,a,p,s,l));let Wt=e.child(gt.loggerBindings||{}),G=[],$n=async()=>{y.warn("SIGINT received. Stopping tests and printing latest results..."),await gt.finish({logger:Wt,status:"CANCELLED"}),Ft(),await Promise.allSettled(G.map(Ye=>Ye())),process.exit(1)};process.on("SIGINT",$n);let Wn={};for(let Ye=0;Ye<oe.length;Ye++){let br=Object.values(Wn);br.length===j&&await Promise.race(br.map(wr=>wr.promise));let so=oe[Ye],ft=`test-${Ye}`;Wn[ft]={done:!1,promise:(async({testIndex:wr,inputs:wu})=>{let lo=X[wr];De.add({testIndex:wr,inputs:wu});let $v=lo.relativeFilePath.includes("..")?lo.fullFilePath:lo.relativeFilePath,Oa=(lt,Si)=>{lt=lt.toUpperCase();let Ln=lt,Gn;lt.includes("FAIL")?(Ln=gi.bgRed.white("FAIL"),Gn=3):lt.includes("PASS")?(Ln=gi.bgGreen.white("PASS"),Gn=3):lt.includes("START")?(Ln=gi.bgBlue.white("START"),Gn=2):lt.includes("CANCEL")?(Ln=gi.bgRgb(191,68,11).white("CANCEL"),Gn=1):lt.includes("RETRY")?(Ln=gi.bgRgb(191,68,11).white("RETRY"),Gn=2):lt.includes("RUN")||lt.includes("PROG")?(Ln=gi.bgMagenta.white("RUNNING"),Gn=0):(Wt.warn(`Unknown status tried to be logged in run test locally: ${lt}`),Gn=0),jN||(Ln=`${Ln}`),y.log(`${Ln}${" ".repeat(Gn)} ${$v} ${Si?`${Si} `:""}(${De.size}/${oe.length})`)};Oa("START");let Wv=setInterval(()=>Oa("RUN"),5*60*1e3),vu=Wt.child({testId:lo.id});try{let lt=await Lv({testDefinition:lo,project:d,testInputs:wu,orgId:f,devicePixelRatio:S,apiClient:a,runGroupTracer:gt,generator:V,retriesOverride:u,urlOverride:h,envName:g,noReport:!m,customHeaders:x,regenerateGoldenFiles:P,logUpdate:Oa,runSigIntHandlers:m?G:void 0,logger:vu,flagStore:c});Oa(lt.status),se.push(lt)}catch(lt){let Si=`Encountered unexpected fatal error when running test '${lo.name}': ${lt.message}`;y.error(Si),vu.error(Si)}finally{clearInterval(Wv),Wn[ft].done=!0,delete Wn[ft]}})(so)}}await Promise.allSettled(Object.values(Wn).map(Ye=>Ye.promise));let fi="PASSED";return se.some(Ye=>Ye.status==="FAILED")&&(fi="FAILED"),await gt.finish({logger:Wt,status:fi}),process.off("SIGINT",$n),b&&await Tv(Wt,s,b,{projectConfigPath:d.configFilePath,suiteName:d.config.name,startedAt:Se,finishedAt:new Date,runs:se},M??"reports"),Ft()}function $N(r,e,t){if(t>r.length&&(y.warn(`Shard count ${t} is greater than the number of tests ${r.length}! Some workers won't have any tests to run.`),t=Math.max(t,r.length),e>t))return[];let n=Math.floor((e-1)*(r.length/t)),o=Math.floor(e*(r.length/t));return r.sort().filter((a,s)=>s>=n&&s<o)}import Hn from"fs";import ao from"path";var Nv={status:(r,e)=>{if(r===e)return r;if(r==="PASSED"&&e==="PASSED")return"PASSED";if(r==="FAILED"||e==="FAILED")return"FAILED";if(r==="CANCELLED"||e==="CANCELLED")return"PASSED";throw new Error("Invalid run status merge")},startedAt:(r,e)=>{if(!r||!e)throw new Error("Invalid start time merge");return r<e?r:e},updatedAt:(r,e)=>{if(!r||!e)throw new Error("Invalid update time merge");return r>e?r:e},finishedAt:(r,e)=>{if(!r||!e)throw new Error("Invalid finish time merge");return r>e?r:e},gitCommitTimestamp:(r,e)=>{if(!(!r&&!e)){if(!r||!e||r.getTime()!==e.getTime())throw new Error("Git commit timestamps must match to be merged");return r}}};function Mv(r,e){let t=r[e];if(!t)throw new Error(`No metadata value found for key: ${e}`);return t}function WN(r,e,t){let n=Mv(r,t),o=Mv(e,t);if(t in Nv){let i=Nv[t];return i(n,o)}if(n!==o)throw new Error(`Metadata values for key "${t}" do not match: "${n}" vs "${o}"`);return n}function _v(r,e){Hn.rmSync(r,{recursive:!0,force:!0});let t=Hn.readdirSync(e).filter(a=>a!==".DS_Store").map(a=>ao.join(e,a));Hn.mkdirSync(r,{recursive:!0});let n=ao.join(t[0],"metadata.json"),o=od.parse(JSON.parse(Hn.readFileSync(n,"utf-8")));for(let a of t){let s=ao.join(a,"runs");if(!Hn.existsSync(s))continue;let l=Hn.readdirSync(s);for(let d of l){let m=ao.join(s,d),u=ao.join(r,"runs",d);Hn.cpSync(m,u,{recursive:!0})}let c=ao.join(a,"metadata.json"),p=od.parse(JSON.parse(Hn.readFileSync(c,"utf-8")));for(let d in p){let m=d;o[m]=WN(o,p,m)}}let i=ao.join(r,"metadata.json");Hn.writeFileSync(i,JSON.stringify(o,null,2))}import Fv from"adm-zip";import GN from"fs";import tc from"path";function Dv(r){let e=new Fv;e.addLocalFile(tc.join(r,"metadata.json"));for(let t of GN.readdirSync(tc.join(r,"runs"))){if(!t.endsWith(".zip"))continue;let n=t.replace(/\.zip$/,""),o=new Fv(tc.join(r,"runs",t));for(let i of o.getEntries())i.isDirectory||e.addFile(tc.join("runs",n,i.entryName),i.getData())}return e.toBuffer()}var Uv=new di({platform:"cli"},{flushAt:1,flushInterval:0});rc||ee.warn("Sentry is not enabled in this environment due to unsupported node version");var XN=process.argv.some(r=>r.includes("--log-level"))&&process.argv.some(r=>r.includes("debug")),bu=r=>{XN&&y.dimmed(r)},xt=new VN;xt.name("momentic").description("CLI").version(Ht||"unknown");xt.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(r,e)=>{await oo(nv(r),e.force)});xt.addOption(new on("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",r=>{r==="debug"&&y.info("Enabling debug logging"),y.setMinLevel(r.toLowerCase())});xt.addOption(new on("--verbose","enable verbose logging")).on("option:verbose",()=>{ee.enableConsoleLogs(),y.setMinLevel(0)});xt.command("check-config").addOption(yr).action(async r=>{mn({configFilePath:r.config})});var zv=xt.command("checks").alias("check").description("Perform various project checks");zv.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(yr).addOption(Vw).action(async r=>{let e=await Sn(r),t=mn({configFilePath:r.config});await sv({project:t,fix:e.fix})});zv.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(yr).action(async r=>{let e=mn({configFilePath:r.config});await lv({project:e})});var ZN=xt.command("migrate").description("Migrate and upgrade tooling");ZN.command("v0-v1").addOption(Sr).addOption(zn).action(async r=>{let e=await Sn(r);if(!e.yes&&!await st("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),!_w().environments?.length&&await st("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:n,server:o}=e,i=mn({}),a=new at({baseUrl:o,apiKey:n,logger:ee});await Wl({client:a,project:i,skipPrompts:e.yes}),y.success("Successfully imported environments from Momentic Cloud.")}});xt.command("import-from-cloud").addOption(zn).addOption(fr).addOption(yr).addOption(Sr).addArgument(Kw).action(async(r,e)=>{let t=await Sn(e),{apiKey:n,server:o,config:i,yes:a}=t,s=mn({configFilePath:i}),l=new at({baseUrl:o,apiKey:n,logger:ee});!r||r.length===0?await uv({client:l,project:s,skipPrompts:a}):await mv({client:l,project:s,paths:r,skipPrompts:a}),process.exit(0)});xt.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new on("--name <name>","Name of the project")).action(async r=>{y.info(`Welcome to the Momentic project setup wizard! \u{1F680}
|
|
3640
|
+
`),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."),Bv.existsSync(Ho)&&(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:r.name??await Nw("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:ya};$o(t,Ho),y.success(`Initialized Momentic project file at ${nc.resolve(Ho)}`)});xt.command("app").addOption(zn).addOption(fr).addOption(Sr).addOption(Zp).addOption($w).addOption(yr).action(async r=>{let e=await Sn(r),{apiKey:t,port:n=_l,yes:o,server:i,pixelRatio:a}=e,s=new at({baseUrl:i,apiKey:t,logger:ee});await nu({client:s,skipPrompts:o,installBrowsers:!0});let l=JN(import.meta.url),c=nc.dirname(l),p=nc.resolve(c,"..","static"),d=nc.resolve(c,"..","assets"),m=a??Hp();$p(m),await Cw({momenticServerUrl:i,apiKey:t,serverPort:n,appPort:n,staticDir:p,assetsDir:d,devicePixelRatio:m,version:"1.5.1"});let u=`http://localhost:${n}`;await YN(u)});var jv=xt.command("queue").description("Queue tests or suites to run on Momentic Cloud");jv.command("suites").description("Run one or more suites on Momentic Cloud").addOption(zn).addOption(fr).addOption(Kp).addOption(Yp).addOption(Sr).addArgument(Jw).addOption(Ul).addOption(Dl).addOption(Fl).action(async(r,e)=>{let{apiKey:t,server:n,wait:o,waitTimeout:i,env:a,urlOverride:s,customHeaders:l}=await Sn(e),c=new at({baseUrl:n,apiKey:t,logger:ee});(!r||!Array.isArray(r)||!r.length)&&(y.error("Must pass at least one suite to run."),process.exit(1));let{orgId:p}=await c.getAuthInfo();await gv({client:c,orgId:p,wait:o,suitePaths:r,waitTimeout:i,env:a,urlOverride:s,customHeaders:Bl(l)})});jv.command("tests").description("Run one or more tests on Momentic Cloud").addOption(zn).addOption(fr).addOption(Sr).addOption(Fl).addOption(Qp).addOption(Ul).addOption(Dl).addOption(Kp).addOption(Yp).addArgument(qw).action(async(r,e)=>{let t=await Sn(e),{all:n,apiKey:o,customHeaders:i,env:a,server:s,inputCsv:l,urlOverride:c,wait:p,waitTimeout:d,yes:m}=t,u=Bl(i);for(let S of r)(S.endsWith(".yaml")||Bv.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 at({baseUrl:s,apiKey:o,logger:ee}),{orgId:g}=await h.getAuthInfo(),f;l&&(f=await Wp(l)),await fv({client:h,orgId:g,tests:r,all:n,customHeaders:u,env:a,urlOverride:c,wait:p,waitTimeout:d,testInputMatrix:f,yes:m}),process.exit(0)});var QN=xt.command("run").alias("test").description("Run tests on the local machine");QN.addOption(zn).addOption(fr).addOption(yr).addOption(eu).addOption(Sr).addOption(Fl).addOption(Qp).addOption(Dl).addOption(Ul).addOption(Jp).addOption(Zp).addOption(new on("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new on("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new on("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.")).addOption(new on("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.")).addOption(new on("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.")).addOption(new on("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new on("--update-golden-files","Update locally stored golden files for steps that this is enabled for.")).addOption(Jp).addOption(Bw).addOption(zw).addOption(Xp).addOption(Ww).addOption(Gw).addOption(jw).addOption(Hw).addArgument(Yw).action(async(r,e)=>{y.debug("Run tests invoked");let t=await Sn(e);y.debug(t,"Parsed CLI options");let n=Bl(t.customHeaders),o=mn({configFilePath:t.config,nameFilter:t.filter});y.debug({projectName:o.config.name},"Identified project config");let i=new at({baseUrl:t.server,apiKey:t.apiKey,logger:ee});y.debug("Checking API key and dependencies");let{orgId:a,userId:s}=await nu({client:i,skipPrompts:t.yes,installBrowsers:!0});y.debug("API key check and browser installation complete");let l=new Qs(i),c=new el(i),p=t.outputDir??o.config.outputDir,d=ee.child({orgId:a,userId:s,cliVersion:Ht,trigger:"CLI"}),m=Vo.initIfConfigHasOverrides(d,o.config)??i,u=await Zo.init(a,m),h=Uv.child({org_id:a,user_id:s,cli_version:Ht,trigger:"CLI"}),g;t.inputCsv&&(g=await Wp(t.inputCsv));let f=t.pixelRatio??Hp();$p(f);try{(await Ov({...t,retriesOverride:t.retries,devicePixelRatio:f,tests:r,project:o,client:i,debugDataStorage:c,billingReporter:l,analytics:h,flagStore:u,outputDir:p,customHeaders:n,envName:t.env,orgId:a,testInputMatrix:g,logger:d,regenerateGoldenFiles:t.updateGoldenFiles})).failed>0?process.exit(1):process.exit(0)}catch(S){y.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),y.error(S),process.exit(1)}});var eM=xt.command("apply").description("Apply an operation to local resources");eM.command("patch").addOption(zn).addOption(fr).addOption(yr).addOption(eu).addOption(Sr).addOption(new on("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new on("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async r=>{let e=await Sn(r),{apiKey:t,server:n,config:o,yes:i}=e,a=mn({configFilePath:o}),s=new at({baseUrl:n,apiKey:t,logger:ee}),l=ke(a,y),c=l.tests[r.to]??Object.values(l.tests).find(d=>Pe(d.name)===r.to.trim());c||(y.error(`No test matching '${r.to}' could be found in the current project.`),process.exit(1));let p=await s.fetchTestFragment(r.from);await Mw({client:s,test:c,fragment:p,yes:i,entities:l,logger:ee}),process.exit(0)});var Hv=xt.command("results").description("Merge and upload test results.");Hv.command("merge").description("Merge test results files.").addOption(Xp).addArgument(Xw).action(async(r,e)=>{let t=await Sn(e),{outputDir:n}=t;n||(y.error("Output directory is required."),process.exit(1)),_v(n,r)});Hv.command("upload").description("Upload test results to Momentic cloud.").addOption(zn).addOption(fr).addArgument(Zw).action(async(r,e)=>{let t=await Sn(e),{apiKey:n,server:o}=t,i=new at({baseUrl:o,apiKey:n,logger:ee}),a=new tl(i);try{let s=Dv(r),l=await a.uploadResultsArchive(s),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(s){let l;s instanceof Error?l=s.message:typeof s=="string"?l=s:l="Unknown error",y.error(`Failed to upload test results: ${l}.`),process.exit(1)}});async function tM(){bu("Main program started"),await Pw(ee),bu("CLI version check complete");try{await xt.parseAsync(process.argv)}catch(r){let e={};try{e.playwrightVersion=qN("npx playwright --version").toString()}catch(t){ee.error({err:t},"Error fetching debug information")}ee.error({err:r,debugInfo:e},"Uncaught error in CLI"),ee.flush(),yi(r,e),y.error(r),process.exit(1)}}KN.setMaxListeners(50);process.on("warning",r=>{ee.warn({err:r},`Node warning received on CLI: ${r.message}`)});bu("CLI parsing setup complete");tM();
|
|
3644
3641
|
//# sourceMappingURL=cli.js.map
|
|
3645
|
-
//# debugId=
|
|
3642
|
+
//# debugId=ae9ffd6a-f90f-5f7a-8942-0748965aeb1f
|