@checksum-ai/runtime 1.1.59 → 1.1.61
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/.env +1 -1
- package/cli.js +2 -2
- package/index.js +2 -2
- package/package.json +1 -1
package/.env
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
BUILD_TIME=2025-02-
|
|
1
|
+
BUILD_TIME=2025-02-25T13:59:10.962Z
|
package/cli.js
CHANGED
|
@@ -1402,7 +1402,7 @@ Please see the 3.x to 4.x migration guide for details on how to update your app.
|
|
|
1402
1402
|
</body>
|
|
1403
1403
|
</html>
|
|
1404
1404
|
`}e(D9n,"createHtmlDocument");function S9n(){return e(function(){this.error(404)},"notFound")}e(S9n,"createNotFoundDirectoryListener");function E9n(){return e(function(o){if(this.hasTrailingSlash()){this.error(404);return}var u=jtr.original(this.req);u.path=null,u.pathname=b9n(u.pathname+"/");var p=h9n(v9n.format(u)),v=D9n("Redirecting","Redirecting to "+g9n(p));o.statusCode=301,o.setHeader("Content-Type","text/html; charset=UTF-8"),o.setHeader("Content-Length",Buffer.byteLength(v)),o.setHeader("Content-Security-Policy","default-src 'none'"),o.setHeader("X-Content-Type-Options","nosniff"),o.setHeader("Location",p),o.end(v)},"redirect")}e(E9n,"createRedirectDirectoryListener")});var jwr=Ni((QJ,Bwr)=>{"use strict";var Xht=qer(),C9n=require("events").EventEmitter,Owr=x5r(),Lwr=JTr(),T9n=Qer(),w9n=etr(),Rwr=mwr(),Mwr=Fwr();QJ=Bwr.exports=A9n;function A9n(){var s=e(function(o,u,p){s.handle(o,u,p)},"app");return Owr(s,C9n.prototype,!1),Owr(s,Lwr,!1),s.request=Object.create(Rwr,{app:{configurable:!0,enumerable:!0,writable:!0,value:s}}),s.response=Object.create(Mwr,{app:{configurable:!0,enumerable:!0,writable:!0,value:s}}),s.init(),s}e(A9n,"createApplication");QJ.application=Lwr;QJ.request=Rwr;QJ.response=Mwr;QJ.Route=T9n;QJ.Router=w9n;QJ.json=Xht.json;QJ.query=utr();QJ.raw=Xht.raw;QJ.static=Iwr();QJ.text=Xht.text;QJ.urlencoded=Xht.urlencoded;var k9n=["bodyParser","compress","cookieSession","session","logger","cookieParser","favicon","responseTime","errorHandler","timeout","methodOverride","vhost","csrf","directory","limit","multipart","staticCache"];k9n.forEach(function(s){Object.defineProperty(QJ,s,{get:e(function(){throw new Error("Most middleware (like "+s+") is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.")},"get"),configurable:!0})})});var Uwr=Ni((dri,qwr)=>{"use strict";qwr.exports=jwr()});var zwr=Ni((_ri,Jwr)=>{"use strict";var Vwr=Object.getOwnPropertySymbols,P9n=Object.prototype.hasOwnProperty,F9n=Object.prototype.propertyIsEnumerable;function N9n(s){if(s==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(s)}e(N9n,"toObject");function I9n(){try{if(!Object.assign)return!1;var s=new String("abc");if(s[5]="de",Object.getOwnPropertyNames(s)[0]==="5")return!1;for(var o={},u=0;u<10;u++)o["_"+String.fromCharCode(u)]=u;var p=Object.getOwnPropertyNames(o).map(function(b){return o[b]});if(p.join("")!=="0123456789")return!1;var v={};return"abcdefghijklmnopqrst".split("").forEach(function(b){v[b]=b}),Object.keys(Object.assign({},v)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}e(I9n,"shouldUseNative");Jwr.exports=I9n()?Object.assign:function(s,o){for(var u,p=N9n(s),v,b=1;b<arguments.length;b++){u=Object(arguments[b]);for(var S in u)P9n.call(u,S)&&(p[S]=u[S]);if(Vwr){v=Vwr(u);for(var T=0;T<v.length;T++)F9n.call(u,v[T])&&(p[v[T]]=u[v[T]])}}return p}});var $wr=Ni((hri,Wwr)=>{(function(){"use strict";var s=zwr(),o=Mtr(),u={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function p(z){return typeof z=="string"||z instanceof String}e(p,"isString");function v(z,Y){if(Array.isArray(Y)){for(var le=0;le<Y.length;++le)if(v(z,Y[le]))return!0;return!1}else return p(Y)?z===Y:Y instanceof RegExp?Y.test(z):!!Y}e(v,"isOriginAllowed");function b(z,Y){var le=Y.headers.origin,ye=[],ve;return!z.origin||z.origin==="*"?ye.push([{key:"Access-Control-Allow-Origin",value:"*"}]):p(z.origin)?(ye.push([{key:"Access-Control-Allow-Origin",value:z.origin}]),ye.push([{key:"Vary",value:"Origin"}])):(ve=v(le,z.origin),ye.push([{key:"Access-Control-Allow-Origin",value:ve?le:!1}]),ye.push([{key:"Vary",value:"Origin"}])),ye}e(b,"configureOrigin");function S(z){var Y=z.methods;return Y.join&&(Y=z.methods.join(",")),{key:"Access-Control-Allow-Methods",value:Y}}e(S,"configureMethods");function T(z){return z.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}e(T,"configureCredentials");function P(z,Y){var le=z.allowedHeaders||z.headers,ye=[];return le?le.join&&(le=le.join(",")):(le=Y.headers["access-control-request-headers"],ye.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),le&&le.length&&ye.push([{key:"Access-Control-Allow-Headers",value:le}]),ye}e(P,"configureAllowedHeaders");function I(z){var Y=z.exposedHeaders;if(Y)Y.join&&(Y=Y.join(","));else return null;return Y&&Y.length?{key:"Access-Control-Expose-Headers",value:Y}:null}e(I,"configureExposedHeaders");function B(z){var Y=(typeof z.maxAge=="number"||z.maxAge)&&z.maxAge.toString();return Y&&Y.length?{key:"Access-Control-Max-Age",value:Y}:null}e(B,"configureMaxAge");function J(z,Y){for(var le=0,ye=z.length;le<ye;le++){var ve=z[le];ve&&(Array.isArray(ve)?J(ve,Y):ve.key==="Vary"&&ve.value?o(Y,ve.value):ve.value&&Y.setHeader(ve.key,ve.value))}}e(J,"applyHeaders");function j(z,Y,le,ye){var ve=[],Ie=Y.method&&Y.method.toUpperCase&&Y.method.toUpperCase();Ie==="OPTIONS"?(ve.push(b(z,Y)),ve.push(T(z,Y)),ve.push(S(z,Y)),ve.push(P(z,Y)),ve.push(B(z,Y)),ve.push(I(z,Y)),J(ve,le),z.preflightContinue?ye():(le.statusCode=z.optionsSuccessStatus,le.setHeader("Content-Length","0"),le.end())):(ve.push(b(z,Y)),ve.push(T(z,Y)),ve.push(I(z,Y)),J(ve,le),ye())}e(j,"cors");function W(z){var Y=null;return typeof z=="function"?Y=z:Y=e(function(le,ye){ye(null,z)},"optionsCallback"),e(function(ye,ve,Ie){Y(ye,function(Be,st){if(Be)Ie(Be);else{var ct=s({},u,st),lt=null;ct.origin&&typeof ct.origin=="function"?lt=ct.origin:ct.origin&&(lt=e(function(Ge,ot){ot(null,ct.origin)},"originCallback")),lt?lt(ye.headers.origin,function(Ge,ot){Ge||!ot?Ie(Ge):(ct.origin=ot,j(ct,ye,ve,Ie))}):Ie()}})},"corsMiddleware")}e(W,"middlewareWrapper"),Wwr.exports=W})()});var H0t="checksum";var TVt=(P=>(P.UploadsCompleteWithErrors="uploads-complete-with-errors",P.UploadsComplete="uploads-complete",P.ReportComplete="report-complete",P.UploadProgress="upload-progress",P.Log="log",P.Trace="trace",P.PlaywrightConfig="playwrightConfig",P.Port="port",P))(TVt||{});var WA=ox(require("path")),Tpe=require("fs");var wVt=(p=>(p.Alert="alert",p.Confirm="confirm",p.Prompt="prompt",p))(wVt||{});var C3=e(s=>new Promise(o=>setTimeout(o,s)),"awaitSleep"),Hw=e(async(s,o=1e3,u)=>{if(o===null)return s;let p="guard-timed-out",v=e(async()=>(await C3(o+1e3),p),"guard"),b=await Promise.race([s,v()]);if(typeof b=="string"&&b===p)throw typeof u=="function"?new Error(u()):new Error(u??"guardReturnTimedOut");return b},"guardReturn");function gqe(s=5,o="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"){let u="";for(let p=s;p>0;--p)u+=o[Math.floor(Math.random()*o.length)];return u}e(gqe,"randomString");function AVt(s){return!!s&&!["navigation","keystroke","wait","get_more_items","custom_code","native_accept","native_dismiss","login"].includes(s)}e(AVt,"isActionOnElement");function c0r(s){return{click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",upload_files:"upload_files",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",reset:void 0,save:void 0,fail:void 0,wait:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,get_more_items:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0}[s]}e(c0r,"getActionEventCode");var sse=e((s,o="page")=>o+"."+G0t(s,o),"injectBaseToLocatorString"),G0t=e((s,o="page")=>s.replace(".and(locator(",`.and(${o}.locator(`).replace(".or(locator(",`.or(${o}.locator(`),"injectBaseToLogicalLocatorString");async function d0r(s,o){let p=e(()=>{let P=RZr(s,o);if((0,Tpe.existsSync)(P)||P.endsWith(".data")&&(P=P.replace(".data",".esra"),(0,Tpe.existsSync)(P)))return P;throw new Error(`Could not find metadata file for test ${o}`)},"getFilePath")(),{ungzip:v}=f0r(),b=await v((0,Tpe.readFileSync)(p)),S=JSON.parse(b),T=Object.keys(S);return T.length>0&&!S[T[0]].esraMetadata?T.reduce((P,I)=>({...P,[I]:{esraMetadata:S[I]}}),{}):S}e(d0r,"getMetadataForTestId");function RZr(s,o){return WA.join(MZr(s),`${o}.checksum.data`)}e(RZr,"getMetadataFilePath");function MZr(s){return WA.join(_0r(s),"esra")}e(MZr,"getMetadataFolderPath");function _0r(s){return WA.join(s,"test-data")}e(_0r,"getTestDataPath");var m0r=e((s,o,u)=>{if(!o)return s;if(!u||!u.length)return s.locator(o);let p=s.frameLocator(u[0]);for(let v of u.slice(1))p=p.frameLocator(v);return p.locator(o)},"makeLocator");function kVt(){return process.env.CHECKSUM_ROOT_FOLDER?process.env.CHECKSUM_ROOT_FOLDER:WA.join(__dirname,"..","..","..","checksum")}e(kVt,"checksumFolder");function h0r({isInit:s,excludeLogin:o}){return[...s?["example.checksum.spec.ts","github-actions.example.yml"]:[],...o?[]:["login.ts"],"checksum.config.ts","playwright.config.ts","README.md",".gitignore.example"]}e(h0r,"getRuntimeFiles");function g0r(s,o){try{let u=s.filter(p=>p.endsWith("checksum.config.ts")&&WA.dirname(p).endsWith("checksum"));return u.find(p=>p==="checksum/checksum.config.ts")?"checksum":u.length===1?WA.dirname(u[0]):o?WA.dirname(BZr(u,o)):WA.dirname(u.sort((p,v)=>v.length-p.length)[0])}catch{return"checksum"}}e(g0r,"findChecksumRootFolder");function BZr(s,o){let u=e(T=>T.split(WA.sep).filter(P=>P.length>0),"splitPath"),p=e((T,P)=>{let I=u(T),B=u(P),J=Math.min(I.length,B.length),j=Math.abs(I.length-B.length);for(let W=0;W<J;W++)if(I[W]!==B[W]){j+=2*(J-W);break}return j},"directoryDistance"),v=null,b=1/0,S=WA.dirname(o);return s.forEach(T=>{let P=p(S,T);P<b&&(b=P,v=T)}),v}e(BZr,"getClosestPath");function y0r(s,o=2){let u=[],p=[],v=e(S=>{if(u.includes(S))return;u.push(S);let T=(0,Tpe.readdirSync)(S);for(let P of T){let I=WA.join(S,P),B=(0,Tpe.statSync)(I);if(!(B.isSymbolicLink()||I.includes("node_modules"))){if(B.isDirectory())v(I);else if(P==="checksum.config.ts"){p.push(I);return}}}},"searchDirectory"),b=WA.dirname(s);try{for(let S=0;S<o&&(v(b),b=WA.join(b,".."),S===o-1&&S<9&&!p.length&&(o+=2),!(WA.resolve(b)==="/"||!b||WA.resolve(b)===WA.resolve(process.cwd())));S++);return p}catch{return p}}e(y0r,"findChecksumRootQualifyingPathsForTestFile");var jZr={generateSelectionData:!1,navigationTimeout:30*1e3,actionTimeout:5*1e3},FVt=class FVt{constructor(o,u,p,v,b,S){this.page=o;this.evaluateWithChecksum=u;this.checksumPage=p;this.pageInteractor=v;this.trace=b;this.options=S;this.API_BASE_DOMAIN="https://api.checksum.ai";this.didCancel=!1;this.timeout=15*60*1e3;this.canResolveAssertion=!1;this.page=o,this.options={...jZr,...S}}canResolve(o){return!(o.type==="assertion"&&!this.canResolveAssertion)}addMetadata(o){}cancel(){this.didCancel=!0}async execute(o,u,p,v=6e4){return v0r(o,u,p,v)}log(...o){MN(...o)}setThought(o){this.thought=o}setVariables(o){this.variables=o}get shouldSendToAnalytics(){return!0}getAnalyticsPayload(){return{}}toString(){return this.constructor.name}};e(FVt,"AbstractFallback");var J5e=FVt;var NVt=class NVt extends J5e{constructor(){super(...arguments);this.API_BASE_ROUTE="/client-api/runtime/esra-fallback"}init(u){let{apiKey:p,testId:v,apiURL:b,checksumId:S,fileName:T,timeout:P}=u;return this.data={...this.data,testId:v,checksumId:S,fileName:T},this.apiKey=p,b&&(this.API_BASE_DOMAIN=b.replace(/\/$/,"")),P&&(this.timeout=P),this.checksumRootFolder=process.env.CHECKSUM_ROOT_FOLDER??g0r(y0r(this.data.fileName),this.data.fileName),this}getRecoveryAttemptTitle(u){return`Checksum auto-heal: trying to locate the element using checksumSelector("${this.data.checksumId}")...`}async sendLog(u){let p=this.getLogPayload(u);try{fetch(`${this.getAPIBaseURL()}/log`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify(p)}).catch(v=>this.log("[ESRAFallback] Error sending log"))}catch(v){this.log("[ESRAFallback] Error sending log",v)}}getLogPayload(u){let p=process.env.CHECKSUM_TEST_SUITE_ID??"",{selector:v}=u,{checksumId:b,testId:S}=this.data;return this.logPayload={testSuiteId:p,testId:S,selector:v,checksumId:b,thought:this.thought},this.logPayload}async getMetadataForTestId(){return d0r(this.checksumRootFolder,this.data.testId)}getAPIBaseURL(){return this.API_BASE_DOMAIN+this.API_BASE_ROUTE}};e(NVt,"MetadataBaseFallback");var z5e=NVt;var Cen=require("jsdom");var Een=ox(Ape());var Pan=ox(zzt());var d1r=ox(f1r());var Hzt=class Hzt{constructor(o){this.toJSON=e(()=>this.data,"toJSON");this.data=o}getSimilar(o){let u=null,p=-1/0;for(let v of Object.keys(this.data)){let b=(0,d1r.levenshtein)([...o],[...v]);b>p&&(p=b,u=v)}return u?this.data[u]:null}};e(Hzt,"SimilarityRecord");var $zt=Hzt,ohe=class ohe extends $zt{constructor(o){super(ohe.preprocessRectangles(o))}getRectangleByTextAndSizeRanking(o,u){u=!u||!Number(u)?0:Number(u);let p=this.getSimilar(o);if(!p||p.length===0)return null;let v=Math.min(Math.max(u,0),p.length-1);return p[v]}};e(ohe,"RectangleIndex"),ohe.preprocessRectangles=e(o=>{let u=[...new Map([...o].map(v=>[JSON.stringify(v.vertices),v])).values()],p={};return u.forEach(v=>{p[v.text]||(p[v.text]=[]),p[v.text].push(v),p[v.text].sort((b,S)=>{let T=ohe.calculateArea(b.vertices),P=ohe.calculateArea(S.vertices);return T-P})}),p},"preprocessRectangles"),ohe.calculateArea=e(o=>{let u=Math.abs(o[1].x-o[0].x),p=Math.abs(o[3].y-o[0].y);return u*p},"calculateArea");var Gft=ohe;var b1r=require("fs"),D1r=require("path");function lL(s){return s._guid}e(lL,"getPageOrFrameGuid");async function Kft(s,o,u){let p=s,v=p._mainFrame;try{p._mainFrame=o,await u(p)}finally{p._mainFrame=v}}e(Kft,"executeOnPageWithFrame");var m1r={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html"},Gzt={click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",upload_files:"upload_files",wait:"wait",get_more_items:"get_more_items",reset:void 0,save:void 0,fail:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0,logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss"},h1r=Object.fromEntries(Object.entries(Gzt).map(s=>s.reverse())),Kzt={goto:"navigation",click:"click",dblclick:"double_click",dragTo:"drag_and_drop",check:"check",uncheck:"uncheck",fill:"input",hover:"hover",selectOption:"selectoption",waitForTimeout:"wait","keyboard.press":"keystroke",setInputFiles:"upload_files",getPage:"switch_tab",reauthenticate:"logout_and_login",canvasClick:"canvas_click"},g1r=Object.fromEntries(Object.entries(Kzt).map(s=>s.reverse()));var y1r={input:[1,2],selectoption:[1,2],keystroke:[1,2],wait:[1,2],navigation:[1,2],click:[0,1],double_click:[0,1],drag_and_drop:[1,2],upload_files:[1,2],canvas_click:[1,2],logout_and_login:[1],login:[1,2],click_and_type:[1,2],clear_and_type:[1,2],check:[0,1],uncheck:[0,1],hover:[0,1]},SCe={input:1,selectoption:1,keystroke:1,wait:-1,navigation:1,click:0,double_click:0,drag_and_drop:1,upload_files:1,canvas_click:-1,logout_and_login:-1,login:1,click_and_type:0,clear_and_type:0,check:0,uncheck:0,hover:0,native_accept:-1,native_dismiss:-1};var uan=e(s=>s.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\${/g,"\\${"),"escapeStringForTemplateLiteral"),v1r="variableStore",uhe=v1r+".",x1r=e((s,{alwaysIncludeInitializationLine:o=!1,onlyValueExpression:u=!1}={})=>[o?`const ${v1r} = {};`:"",...s.map(({name:v,value:b,valueExpression:S})=>{let T=typeof b=="string"&&!u?`\`${uan(b)}\``:S;return`${uhe}${v} = ${T};`})].join(`
|
|
1405
|
-
`),"variablesToString");var can=!0,_TestGenerationPageInteractor=class _TestGenerationPageInteractor{constructor(s,o,u,p,v,b,S){this.evaluateWithChecksum=s;this.getFrame=o;this.getTimeMachine=u;this.logger=p;this.options=v;this.pageInteractorAPI=b;this.loginFunction=S;this.activeDialog=null;this.newPagesIds=[];this.listeners={dialog:null,filechooser:null,page:null};this.listenToContextPage=e(()=>{this.getPage().context().on("page",s=>{this.newPagesIds.push(s._guid)})},"listenToContextPage");this.listenToFileChooser=e(()=>{this.listeners.filechooser=async s=>{this.logger.log("File chooser event detected"),this.fileChooser=s},this.getPage().on("filechooser",this.listeners.filechooser)},"listenToFileChooser");this.waitForDialog=e((s=!0,o=1e4)=>new Promise(u=>{let v=0,b=e(()=>{if(this.activeDialog){let S=this.activeDialog;s&&(this.activeDialog=null),u(S)}else v>=o?u(null):(v+=1e3,setTimeout(b,1e3))},"checkDialog");b()}),"waitForDialog");this.performFileUploadAction=e(async(s,o)=>{if(!await s.evaluate(p=>p.tagName==="INPUT"&&p.getAttribute("type")==="file"))throw new Error("File upload action performed on non-file input element");let u=o.files.map(p=>(0,D1r.join)(this.options.testAssetsDir,p)).filter(p=>(0,b1r.existsSync)(p)?!0:(this.logger.log(`Upload file not found: ${p}. Filtering out.`),!1));if(!u.length)throw new Error("No files to upload");await this.actionGuardReturn(s.setInputFiles(u),"Set input files timeout")},"performFileUploadAction");this.getSelectionDataForAction=e(async(s,o)=>s.checksumid?this.getSelectionDataForChecksumId(s.checksumid,o):s.position?await this.evaluateWithChecksum(async([u,p])=>window.checksum.testGenerator.getSelectorByPosition(u,p),[s.position.x,s.position.y]):s.selector?{selector:s.selector,locator:`locator("${s.selector}")`}:{selector:"",locator:""},"getSelectionDataForAction")}getPage(){return this.getFrame().page()}init(){this.listenToContextPage(),this.options.listenToFileChooser!==!1&&this.listenToFileChooser(),this.options.listenToDialog&&this.listenToDialog()}listenToDialog(){this.listeners.dialog=async s=>{this.activeDialog=s},this.getPage().on("dialog",this.listeners.dialog)}removeListener(s){try{switch(s){case"dialog":this.listeners.dialog&&(this.getPage().removeListener(s,this.listeners.dialog),this.listeners.dialog=null);break;case"filechooser":this.getPage().off(s,this.listeners.filechooser),this.listeners.filechooser=null;break;case"page":this.getPage().context().off(s,this.listeners.page),this.listeners.page=null;break}}catch(o){this.logger.logError(`Error removing listener: ${s}`,o)}}getOpenedFileChooser(){if(this.fileChooser){let s=this.fileChooser;return this.fileChooser=void 0,s}return null}async handleFileChooserEvent(s=[]){let o=this.getOpenedFileChooser();if(!o)return{};let u="fc_"+Math.random().toString(36).slice(2,4);return await this.evaluateWithChecksum(async([p,v])=>{window.checksum.testGenerator.addForceIncludeElement(v,p)},[u,o.element()]),{interruptionEvent:"fileUploadOpenedEvent",payload:{checksumid:u,customFiles:s}}}async addMoreItemsToDom(s,o){let u=s.querySelector(`[checksum-get-more-items='${o}']`);if(!u)throw new Error("Get more items root not found");let{items:p,hasMoreItems:v}=await this.getMoreItemsForTemplate(o);u.innerHTML=u.innerHTML+p,v||u.removeAttribute("checksum-get-more-items")}async getPageInfo(s){let o=lL(s);return{id:o,url:s.url(),title:await s.title(),new:this.newPagesIds.includes(o),active:o===lL(this.getPage())}}async getTabsInfo(){var p;let s=this.getPage(),o=await Promise.all(s.context().pages().map(v=>this.getPageInfo(v))),u=(p=this.getTimeMachine())==null?void 0:p.getPage();return u&&u!==s&&(o=o.filter(v=>v.id!==lL(u))),this.newPagesIds=[],o}async getSelectionDataFromSelectorGenerator(s,o,u={}){if(u={useCompoundSelector:!0,useCSSExtraction:!0,useVariables:!0,useArbitrarySelector:!0,...u},!s||!AVt(c0r(o.action.type))||!o.action.checksumid)return{};let p=await s.generateSelectionForAction(o,u);return p?{locator:`locator("${p.selector}")`,...p}:{}}async translateActionResponseToAgentPotentialAction(s,o=void 0,{pageId:u,makeStaticMetadataForESRA:p}={}){let v=structuredClone(s.actionHiddenOverride??s.action),{selector:b,selectorWithVars:S,locator:T,locatorWithVars:P,clickOffset:I,selectOptionValue:B,compoundSelector:J,alternateLocators:j,parentFramesSelectors:W}={...await this.getSelectionDataForAction(v,s.actionHiddenOverride),...await this.getSelectionDataFromSelectorGenerator(o,s)},z=await this.getESRAForSelector(b,W,p);if(!z&&b&&this.logger.logError("Error getting ESRA metadata"),(z==null?void 0:z.tag)==="select")switch(this.getActionEventCode(v.type)){case"input":v.type="selectoption";break;case"click":B&&(v.type="selectoption",v.value=B);break}let Y={eventCode:this.getActionEventCode(v.type),selector:b,selectorWithVars:S,parentFramesSelectors:W,locator:T,locatorWithVars:P,clickOffset:I,pageId:u,compoundSelector:J,alternateLocators:j,fillValue:v.value,fillValueName:v.valueName?`${uhe}${v.valueName}`:"",variables:s.variables,getMoreItemsId:v.getMoreItemsId,esraMetadata:z,thought:s.thought,userRole:v.userRole,canvas:v.canvas,id:v.id};switch(Y.eventCode){case"drag_and_drop":{let{selector:le,selectorWithVars:ye,locator:ve,locatorWithVars:Ie,parentFramesSelectors:Be}={...await this.getSelectionDataForAction({type:s.action.type,checksumid:s.action.dropTargetChecksumid}),...await this.getSelectionDataFromSelectorGenerator(o,{...s,action:{type:s.action.type,checksumid:s.action.dropTargetChecksumid}},{useCompoundSelector:!1})};Y.dropTarget={selector:le,locator:ve,parentFramesSelectors:Be,esraMetadata:await this.getESRAForSelector(le,Be,p)}}break;case"upload_files":Y.files=this.mapFileMIMETypeToFilename(v.files);break;case"switch_tab":{let le=this.getPage();Y.switchToTab={id:v.tabId,index:le.context().pages().findIndex(ye=>lL(ye)===v.tabId)};break}case"keystroke":Y.fillValue=v.value}return Y}async reauthenticate(s){let o=this.getPage();this.loginFunction&&(await Promise.all([o.context().clearCookies(),o.evaluate(()=>localStorage.clear())]),await this.loginFunction(o,{role:s}))}mapFileMIMETypeToFilename(s){return s.map(o=>{if(o.fileName)return o.fileName;switch(o.mimeType){case"image/png":return"image_200x200.png";case"image/jpeg":return"image_200x200.jpg";case"application/pdf":return"document.pdf";case"text/csv":return"data.csv";default:return"file.txt"}})}async performAction(s,{useLocator:o=!1,handleActionFailed:u,monitorFlashingHTML:p=!0,timeout:v,allowForceClick:b=!0}={}){try{if(s.executed){this.logger.log("[performAction] Action marked as executed, skipping...");return}let S=o?!!s.locator:!!s.selector;if(AVt(s.eventCode)&&!S)throw new Error("No selector provided for action. Try changing app rules preMapReducedHTMLSelectors to true");p&&(this.logger.log("starting flashing elements detection"),await this.evaluateWithChecksum(async()=>window.checksum.testGenerator.startFlashingElementsDetection())),this.logger.log(`Performing action: ${s.eventCode}. Selector: ${s.selector}, Position: ${s.clickOffset}, Parent frame: ${s.parentFramesSelectors}`);let T=e(()=>o?this.makeLocatorFromLocator(s.locator):this.makeLocator(s.selector,s.parentFramesSelectors),"getLocator"),P=e(async(I,B,J={})=>this.actionGuardReturn(I,B,{timeout:v,...J}),"performWithActionGuard");switch(s.eventCode){case"click":try{await P(T().click({position:s.clickOffset,timeout:v??this.options.actionTimeout}),"Click timeout")}catch(I){if(!b)throw I;this.logger.log("Error performing click, will attempt a force click",I.message),s.force=!0,await P(T().click({position:s.clickOffset,force:!0,timeout:v??this.options.actionTimeout}),"Force Click timeout")}break;case"double_click":try{await P(T().dblclick({position:s.clickOffset,timeout:v??this.options.actionTimeout}),"DoubleClick timeout")}catch(I){if(!b)throw I;this.logger.log("Error performing double click, will attempt a force double click",I),s.force=!0,await P(T().dblclick({position:s.clickOffset,timeout:v??this.options.actionTimeout,force:!0}),"Force DoubleClick timeout")}break;case"check":await P(T().check({timeout:v??this.options.actionTimeout}),"Check timeout");break;case"uncheck":await P(T().uncheck({timeout:v??this.options.actionTimeout}),"UnCheck timeout");break;case"drag_and_drop":await P(T().dragTo(o?this.makeLocatorFromLocator(s.dropTarget.locator):this.makeLocator(s.dropTarget.selector,s.dropTarget.parentFramesSelectors),{timeout:v??this.options.actionTimeout}),"DragAndDrop timeout");break;case"input":await P(T().fill(this.getActionFillValue(s),{timeout:v??this.options.actionTimeout}),"Fill timeout");break;case"click_and_type":await Hw(T().click({position:s.clickOffset,timeout:v??this.options.actionTimeout}),1e4,"Click before type timeout"),await Hw(T().pressSequentially(this.getActionFillValue(s),{timeout:v??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"clear_and_type":await Hw(T().clear({timeout:v??this.options.actionTimeout}),1e4,"Clear before type timeout"),await Hw(T().pressSequentially(this.getActionFillValue(s),{timeout:v??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"selectoption":await P(T().selectOption(this.getActionFillValue(s),{timeout:v??this.options.actionTimeout}),"SelectOption timeout");break;case"hover":await P(T().hover({timeout:v??this.options.actionTimeout}),"Hover timeout");break;case"navigation":await P(this.getFrame().goto(s.fillValue,{timeout:v??this.options.navigationTimeout}),"Navigation timeout",{isNavigation:!0});break;case"keystroke":{let I=this.getPage();await P(I.keyboard.press(s.fillValue),"Keystroke timeout");break}case"upload_files":await this.performFileUploadAction(T(),s);break;case"wait":await C3(this.options.waitActionDelay??1e3);break;case"custom_code":await Kft(this.getPage(),this.getFrame(),async I=>{let B=`async (page) => {${s.fillValue}}`;await(0,eval)(B)(I)});break;case"logout_and_login":await this.reauthenticate(s.userRole);break;case"canvas_click":await this.canvasClick(T(),s.canvas);break}}catch(S){throw this.logger.log(`Error performing action: ${s.eventCode}, will attempt a correction template`,S),await(u==null?void 0:u()),S}this.logger.log(`Successfully performed action ${s.eventCode} with description "${s.thought}"`)}async getTextDetection(s){return new Gft(await this.pageInteractorAPI.getTextDetection(s))}async canvasClick(s,o){try{if(!await s.evaluate(b=>b.tagName.toLowerCase()==="canvas"))throw new Error("Click attempted on a non-canvas element");let v=(await this.getTextDetection(await s.screenshot())).getRectangleByTextAndSizeRanking(o.canvasText,o.rectSizeIndex);if(!v)throw new Error(`Canvas click target not found for ${o.canvasText}`);this.logger.log(`Canvas click target: ${v}`),await this.actionGuardReturn(s.click({position:v.center}),"Canvas click could not be performed")}catch(u){throw this.logger.logError("Canvas click:",u.message),new Error("Canvas click action failed")}}getActionFillValue(s,o=!0){let u=s.fillValue;if(!u){let p=s.selector.match(/(?<=value.*)('|").*/);p&&(u=p[0].slice(1,-1))}return typeof u!="string"&&(u="X"),o&&(s.fillValue=u),u}actionGuardReturn(s,o,{isNavigation:u=!1,timeout:p}={}){return Hw(s,p??(u?this.options.navigationTimeout:this.options.actionTimeout),o)}makeLocator(s,o=[]){return m0r(this.getFrame(),s,o)}makeLocatorFromLocator(locator){return eval("this.getFrame()."+locator)}getCurrentURL(){return this.getFrame().url()}async getSelectionDataForChecksumId(s,o){if(o!=null&&o.selector)return{...o,selector:o.selector,locator:o.locator,clickOffset:o.position};if(!s)return this.logger.log(`[getSelectionDataForChecksumId] checksumid not provided (${s})`),{...o,selector:s,locator:`locator("${s}")`};let u=await this.evaluateWithChecksum(async p=>{let{selector:v,locator:b,clickOffset:S,parentFramesSelectors:T,invalid:P,rrwebId:I}=await window.checksum.testGenerator.getSelectorForChecksumId(p),B=await window.checksum.testGenerator.getElementForChecksumId(p),J=B instanceof HTMLOptionElement&&B.value?B.value:void 0;return{selector:v,locator:b,clickOffset:S,selectOptionValue:J,parentFramesSelectors:T,invalid:P,rrwebId:I}},s);if(can&&u.invalid&&u.rrwebId){this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${s}. Trying to use time machine...`);try{let p=await this.getSelectionDataForRRwebIdAtReduceHTMLTime(u.rrwebId);u={...u,...p}}catch{this.logger.log(`[getSelectionDataForChecksumId] error using time machine to get selector for checksumid: ${s}`)}this.logger.log(`[getSelectionDataForChecksumId] got selector: ${u.selector} for checksumid: ${s} from time machine`)}return u!=null&&u.selector||this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${s}. If checksumid is correct, try to change app rules preMapReducedHTMLSelectors to true`),u}async getSelectionDataForRRwebIdAtReduceHTMLTime(s){if(!this.rrwebEventAtLastReducedHTML)return;let o=this.getTimeMachine();if(o)return o.executeTask(u=>u.evaluate(async({rrwebId:p})=>await window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(p,{ignoredIframesSelectors:[".replayer-wrapper > iframe"],fromTimeMachine:!0}),{rrwebId:s}),this.rrwebEventAtLastReducedHTML.timestamp,{name:"getSelectionDataForRRwebIdAtReduceHTMLTime"})}async getESRAForSelector(s,o,u){let p=await this.evaluateWithChecksum(async({selector:v,parentFramesSelectors:b})=>window.checksum.testGenerator.getSelectionDataForSelector(v,b),{selector:s,parentFramesSelectors:o});return p!=null&&p.esraMetadata&&u&&(p.esraMetadata.staticMetadata=await u(p.esraMetadata,s)),p==null?void 0:p.esraMetadata}async getMoreItemsForTemplate(s){return await this.evaluateWithChecksum(async o=>window.checksum.testGenerator.getMoreItemsForTemplate(o,{}),s)??{items:"",hasMoreItems:!1}}async getCurrentReducedHTML({retriesLeft:s=3,retryWaitMS:o=2e3,initialChecksumId:u="0",extractESRAForInterpretationRequiredElements:p=!1,stopFlashingElementsDetection:v=!1,assignChecksumIdsToAllElements:b}={}){let S=new Date;this.logger.log("[getCurrentReducedHTML] Fetching reduced HTML...");try{let{reducedHTML:T,currentChecksumId:P,flashingHTML:I,elementsForNodeInterpretation:B,lastRRwebEvent:J}=await this.evaluateWithChecksum(async W=>window.checksum.testGenerator.reduceHTML({},W),{initialChecksumId:u,extractESRAForInterpretationRequiredElements:p,stopFlashingElementsDetection:v,assignChecksumIdsToAllElements:b}),j=new Date;return this.logger.log(`[getCurrentReducedHTML] Fetched reduced HTML in ${j.getTime()-S.getTime()}ms`),this.rrwebEventAtLastReducedHTML=J,{reducedHTML:T,flashingHTML:I,elementsForNodeInterpretation:B,currentChecksumId:P}}catch(T){if(s>0)return this.logger.logError(`[getCurrentReducedHTML] Error: ${T.message}`),this.logger.logError(`Failed do obtain reduced HTML, trying again in ${o/1e3} seconds, ${s-1} to go.`),await C3(o),this.getCurrentReducedHTML({retriesLeft:s-1,retryWaitMS:o});throw T}}getActionEventCode(s){return Gzt[s]}};e(_TestGenerationPageInteractor,"TestGenerationPageInteractor");var oUe=_TestGenerationPageInteractor;var _AlternateSelectorFallback=class _AlternateSelectorFallback extends z5e{constructor(){super(...arguments);this.timeout=5*1e3}init(o){return super.init(o),this}async resolve(params){var o;try{let{method,args}=params,{checksumId}=this.data,alternateLocators=[];try{let u=await this.getMetadataForTestId();if(!(checksumId in u)||!u[checksumId].alternateLocators)throw new Error(`No alternate selection metadata found for id ${checksumId}`);alternateLocators=u[checksumId].alternateLocators.locators}catch(u){throw super.log(`Could not read alternate selector metadata file, ${u.message}`),u}try{this.log("Resolving alternate selectors locators");let elementsMap=new Map;await Promise.all(alternateLocators.map(async locatorExpression=>{let locator=eval(sse(locatorExpression,"this.page"));try{await Hw(locator.first().waitFor({bypassChecksum:!0}),5e3),(await Hw(locator.elementHandles({bypassChecksum:!0}),1e3)).forEach(p=>{elementsMap.has(p)?elementsMap.set(p,elementsMap.get(p)+1):elementsMap.set(p,1)})}catch(u){return}}));let majorityElementHandle=(o=Array.from(elementsMap.entries()))==null?void 0:o.reduce((u,p)=>u[1]>p[1]?u:p)[0];if(!majorityElementHandle)throw this.errorMessage="No alternate element found",new Error(this.errorMessage);let totalElements=Array.from(elementsMap.values()).reduce((u,p)=>u+p,0),elementSelector=await this.evaluateWithChecksum(async({element:u})=>window.playwright.selector(u),{element:majorityElementHandle});this.log(`Resolved alternate selector: ${elementSelector}' With majority vote of ${elementsMap.get(majorityElementHandle)} out of ${totalElements} elements`),await this.checksumPage.wrapNoLocationSteps(async()=>this.execute(this.page.locator(elementSelector),method,args));let fallbackResult={selector:elementSelector,generatedLocator:`locator("${elementSelector}")`,esraMetadata:void 0};return this.sendLog(fallbackResult),this.logPayload=this.logPayload.concat({mejorityVote:`${elementsMap.get(majorityElementHandle)}/${totalElements}`}),this.checksumPage.addErrorMessage(params.error,`${this.thought?`"${this.thought}" auto-healed`:"Auto-healed"} using alternative selector "${elementSelector}"`),{steps:[{type:"action",...fallbackResult}]}}catch(u){throw new Error(`Failed to execute compound selection fallback action: ${u.message}`)}}catch(u){this.errorMessage=u.message,this.log(this.errorMessage);return}}getAnalyticsPayload(){return{fallbackType:"alternative-selector",...this.logPayload??{checksumId:this.data.checksumId,error:this.errorMessage}}}toString(){return`Checksum alternative selector (${this.data.checksumId})`}};e(_AlternateSelectorFallback,"AlternateSelectorFallback");var Yzt=_AlternateSelectorFallback;var Xzt=class Xzt{constructor(o){this.options=o;this.health=e(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(o=>(console.log(o),null)),"health");this.getCanvasDetection=e(async o=>{try{let u=o.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:u}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(u){return console.log(u),null}},"getCanvasDetection")}};e(Xzt,"ChecksumClient");var uUe=Xzt;var Qzt=class Qzt{constructor(){this.config={}}};e(Qzt,"PageInteractorAPI");var Yft=Qzt;var Zzt=class Zzt extends Yft{constructor(u){super();this.config=u;this.getTextDetection=e(async u=>{let p=await this.api.getCanvasDetection(u);if(!p)throw new Error("No data returned from canvas detection");return p},"getTextDetection");this.config=u,this.api=new uUe({apiKey:u.apiKey,apiURL:u.apiURL})}};e(Zzt,"RuntimePageInteractorAPI");var cUe=Zzt;var S1r=require("path");var eWt=class eWt{constructor(o){this.options=o;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=e(async o=>{let u=lL(o);if(this.trackedFramesGuid.includes(u))return this.frameNavigationPromises[u]=new Promise(async p=>{await this.loadScript(o),p()}),this.frameNavigationPromises[u]},"onFrameNavigated");this.loadScript=e(async(o,{retriesLeft:u=3,retryWaitMS:p=2e3,useWrapper:v=!0}={})=>{var P,I;if(v&&this.scriptLoadWrapper)return this.scriptLoadWrapper(()=>this.loadScript(o,{retriesLeft:u,retryWaitMS:p,useWrapper:!1}),o);if(!this.addScriptTagOptions){console.warn("[InjectedScriptManager] addScriptTagOptions not set, skipping loadScript");return}if(this.isFrameClosed(o))return;let b=!1;try{b=this.scriptLoadCheck?await((P=this.scriptLoadCheck)==null?void 0:P.call(this,o)):!1}catch{}if(b||this.isFrameClosed(o))return;try{await o.addScriptTag(this.addScriptTagOptions)}catch(B){if(u>0)return console.warn(`[InjectedScriptManager] Failed to add script to frame ${lL(o)}, trying again in ${p/1e3} seconds, ${u-1} retries left.`,B.message),await C3(p),this.loadScript(o,{retriesLeft:u-1,retryWaitMS:p,useWrapper:v});throw B}let S=lL(o),T=Date.now().toString(36)+Math.random().toString(36).substr(2);if(this.navigatingFrames[S]=T,this.options.scriptInitWait&&(console.log(`Waiting ${this.options.scriptInitWait}[ms] before onScriptLoad...`),await C3(this.options.scriptInitWait),console.log("Done waiting before onScriptLoad")),!this.isFrameClosed(o)){if(this.navigatingFrames[S]&&this.navigatingFrames[S]!==T)return console.log("Page navigated again, waiting on new promise..."),this.frameNavigationPromises[S];try{await((I=this.scriptLoadCallback)==null?void 0:I.call(this,o))}catch(B){console.error("[WebDriver] onScriptLoad error",B)}}},"loadScript");this.addScriptTagOptions=this.makeFrameInjectedScriptOptions()}setScriptLoadCallback(o){return this.scriptLoadCallback=o,this}setScriptLoadCheck(o){return this.scriptLoadCheck=o,this}setScriptLoadWrapper(o){return this.scriptLoadWrapper=o,this}async addTrackedFrame(o,u=!0){let p="mainFrame"in o?o.mainFrame():o,v=lL(p);if(this.trackedFramesGuid.includes(v)||this.trackedFramesGuid.push(v),u)return this.onFrameNavigated(p)}getNavigationPromise(o){if(!o){console.warn("[InjectedScriptManager] getNavigationPromise called with undefined argument");return}let u=typeof o=="string"?o:"mainFrame"in o?lL(o.mainFrame()):lL(o);return this.frameNavigationPromises[u]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,S1r.join)(process.cwd(),this.options.scriptFile)}:void 0;case"url":return this.options.scriptURL?{url:this.options.scriptURL}:void 0;default:return}}isFrameClosed(o){return o.isDetached()||o.page().isClosed()}};e(eWt,"InjectedScriptManager");var lUe=eWt;var d7e=ox(require("path")),iWt=require("fs");var Can=__dirname,k1r=d7e.join(__dirname,".."),Tan=(0,iWt.existsSync)(k1r)?k1r:Can;A1r().config({path:d7e.resolve(Tan,".env")});var Qft=process.env.DEV_MODE==="true";function F1r(){let s=__dirname;for(;!(0,iWt.existsSync)(d7e.join(s,"package.json"));)s=d7e.join(s,"..");return s}e(F1r,"findRoot");var P1r=d7e.join(F1r(),"vtg-build","index.html"),q7={isDevMode:Qft,logLevel:process.env.LOG_LEVEL??"warnings",checksumScript:{source:Qft?"url":"file",url:process.env.SCRIPT_URL,path:F1r()+"/checksumlib.js"},vtg:{writeLogFile:process.env.WRITE_LOG_FILE==="true",localBuildPath:P1r,appURL:Qft?process.env.VTG_APP_URL:`file://${P1r}`,useFakeStory:process.env.USE_FAKE_STORY==="true",recordEvents:process.env.RECORD_EVENTS==="true",fakeStory:{goal:process.env.FAKE_STORY_GOAL??"Send email via outreach list",instructions:process.env.FAKE_STORY_INSTRUCTIONS??"Make sure to select a user from the list first"},fakeTestGeneration:{internalTestId:process.env.FAKE_STORY_INTERNAL_TEST_ID??`tempID${Date.now().toString().slice(-5)}`,generationBatchId:process.env.FAKE_GENERATION_BATCH_ID??`tempID${Date.now().toString().slice(-5)}`},remoteDebugging:process.env.REMOTE_DEBUGGING==="true",taskTimeMachine:{showTaskTimeMachine:process.env.SHOW_TASK_TIME_MACHINE==="true",taskTimeout:parseInt(process.env.TASK_TIME_MACHINE_TIMEOUT??"240000")},aiAssertions:{disabled:process.env.AI_ASSERTIONS_DISABLED==="true",allowRefactoring:process.env.ALLOW_AI_ASSERTIONS_REFACTORING==="true"},aiLocators:{disabled:process.env.AI_LOCATORS_DISABLED==="true",useFakeAILocators:process.env.USE_FAKE_AI_LOCATORS==="true"}},testRun:{timeMachine:{active:!0,headless:!0},monitoring:{segment:{writeKey:process.env.MONITORING_SEGMENT_WRITE_KEY??"MfFJgdVFaFaD3NrBrgX3A9Blwfxs0pSD"}}},buildTime:process.env.BUILD_TIME??"unknown"};Qft&&console.log("Build",q7.buildTime);var aWt=class aWt{constructor(){this.frames={};this.pages=[];this.channels={};this.events=[]}register(o,u,p){if(this.frames[o])return;this.frames[o]=u;let v=u.page();this.pages.includes(v)||(this.pages.push(v),v.exposeFunction("checksumSendMessage",async(b,S)=>{let T=this.frames[b];if(!T)throw new Error(`Frame ${b} not found`);try{await T.evaluate(({message:P})=>{window.postMessage(P,"*")},{message:S})}catch{}}),v.exposeFunction("checksumSendBroadcastMessage",async(b,S)=>{let T=this.channels[b]??[];if(p){let P=require("fs"),I=require("path");this.events.push(...S),this.events.length%10===0&&P.writeFileSync(I.join(process.cwd(),"rrweb-player","events.json"),JSON.stringify(this.events))}T.forEach(async P=>{if(!(P.originFrameGuid&&P.originFrameGuid!==lL(u)))try{P.handler?await P.handler(S):await u.evaluate(({message:I})=>{window.postMessage(I,"*")},{message:S})}catch{}})}),v.exposeFunction("checksumBringPageToFront",async b=>{let S=this.frames[b];S&&await S.page().bringToFront()}))}subscribeToChannel(o,u,{originFrame:p,handler:v}={}){var b;(b=this.channels)[o]??(b[o]=[]),this.channels[o].push({frame:u,originFrameGuid:p?lL(p):void 0,handler:v})}unsubscribeFromChannel(o,u){var p;(p=this.channels)[o]??(p[o]=[]),this.channels[o]=this.channels[o].filter(v=>v.frame!==u)}};e(aWt,"FramesMsgBroker");var pUe=aWt;var I1r=require("@playwright/test");var fUe=require("jsdom");var sWt=class sWt{constructor(o){this.activeDOMType="checksumIds";this.rawReducedHTMLDom=new fUe.JSDOM(o),this.process()}process(){this.expandedChecksumIdsReducedDom=new fUe.JSDOM(this.rawReducedHTMLDom.serialize()),this.reducedHTMLDom=new fUe.JSDOM(this.rawReducedHTMLDom.serialize()),this.rrwebIdsReducedDom=new fUe.JSDOM(this.rawReducedHTMLDom.serialize());let o=e(S=>{S.window.document.body.querySelectorAll("[checksumid]:not([checksuminteractable])").forEach(P=>{P.removeAttribute("checksumid")})},"removeChecksumIdAttributeFromNonInteractable"),u=e((S,T)=>T.window.document.body.querySelectorAll(`[${S}]`).forEach(P=>P.removeAttribute(S)),"removeAttributeFromAllElements"),p=e(S=>u("checksuminteractable",S),"removeChecksumInteractableAttribute"),v=e(S=>u("checksumid",S),"removeChecksumIdAttribute"),b=e(S=>u("rrwebid",S),"removeRrwebIdAttribute");o(this.reducedHTMLDom),p(this.expandedChecksumIdsReducedDom),p(this.reducedHTMLDom),p(this.rrwebIdsReducedDom),b(this.expandedChecksumIdsReducedDom),b(this.reducedHTMLDom),v(this.rrwebIdsReducedDom)}getDOMForType(o){switch(o){default:case"checksumIds":return this.reducedHTMLDom;case"expandedChecksumIds":return this.expandedChecksumIdsReducedDom;case"rrwebIds":return this.rrwebIdsReducedDom}}async enrich(o){return await o(this.rawReducedHTMLDom),this.process(),this}setActiveDomType(o){this.activeDOMType=o}getActiveDom(){return this.getDOMForType(this.activeDOMType)}getActiveDOMString(){return this.getActiveDom().serialize()}getRrwebIdsReducedDomString(){return this.rrwebIdsReducedDom.serialize()}getDOMStringForType(o){return this.getDOMForType(o).serialize()}get raw(){return this.rawReducedHTMLDom}};e(sWt,"ReducedHTMLDOM");var dUe=sWt;var N1r=ox(require("path"));var uWt=class uWt{constructor(o="all"){this.listeners=[];this.logLevel=o}log(...o){try{let p=new Error().stack.split(`
|
|
1405
|
+
`),"variablesToString");var can=!0,_TestGenerationPageInteractor=class _TestGenerationPageInteractor{constructor(s,o,u,p,v,b,S){this.evaluateWithChecksum=s;this.getFrame=o;this.getTimeMachine=u;this.logger=p;this.options=v;this.pageInteractorAPI=b;this.loginFunction=S;this.activeDialog=null;this.newPagesIds=[];this.listeners={dialog:null,filechooser:null,page:null};this.listenToContextPage=e(()=>{this.getPage().context().on("page",s=>{this.newPagesIds.push(s._guid)})},"listenToContextPage");this.listenToFileChooser=e(()=>{this.listeners.filechooser=async s=>{this.logger.log("File chooser event detected"),this.fileChooser=s},this.getPage().on("filechooser",this.listeners.filechooser)},"listenToFileChooser");this.waitForDialog=e((s=!0,o=1e4)=>new Promise(u=>{let v=0,b=e(()=>{if(this.activeDialog){let S=this.activeDialog;s&&(this.activeDialog=null),u(S)}else v>=o?u(null):(v+=1e3,setTimeout(b,1e3))},"checkDialog");b()}),"waitForDialog");this.performFileUploadAction=e(async(s,o)=>{if(!await s.evaluate(p=>p.tagName==="INPUT"&&p.getAttribute("type")==="file"))throw new Error("File upload action performed on non-file input element");let u=o.files.map(p=>(0,D1r.join)(this.options.testAssetsDir,p)).filter(p=>(0,b1r.existsSync)(p)?!0:(this.logger.log(`Upload file not found: ${p}. Filtering out.`),!1));if(!u.length)throw new Error("No files to upload");await this.actionGuardReturn(s.setInputFiles(u),"Set input files timeout")},"performFileUploadAction");this.getSelectionDataForAction=e(async(s,o)=>s.checksumid?this.getSelectionDataForChecksumId(s.checksumid,o):s.position?await this.evaluateWithChecksum(async([u,p])=>window.checksum.testGenerator.getSelectorByPosition(u,p),[s.position.x,s.position.y]):s.selector?{selector:s.selector,locator:`locator("${s.selector}")`}:{selector:"",locator:""},"getSelectionDataForAction")}getPage(){return this.getFrame().page()}init(){this.listenToContextPage(),this.options.listenToFileChooser!==!1&&this.listenToFileChooser(),this.options.listenToDialog&&this.listenToDialog()}listenToDialog(){this.listeners.dialog=async s=>{this.activeDialog=s},this.getPage().on("dialog",this.listeners.dialog)}removeListener(s){try{switch(s){case"dialog":this.listeners.dialog&&(this.getPage().removeListener(s,this.listeners.dialog),this.listeners.dialog=null);break;case"filechooser":this.getPage().off(s,this.listeners.filechooser),this.listeners.filechooser=null;break;case"page":this.getPage().context().off(s,this.listeners.page),this.listeners.page=null;break}}catch(o){this.logger.logError(`Error removing listener: ${s}`,o)}}getOpenedFileChooser(){if(this.fileChooser){let s=this.fileChooser;return this.fileChooser=void 0,s}return null}async handleFileChooserEvent(s=[]){let o=this.getOpenedFileChooser();if(!o)return{};let u="fc_"+Math.random().toString(36).slice(2,4);return await this.evaluateWithChecksum(async([p,v])=>{window.checksum.testGenerator.addForceIncludeElement(v,p)},[u,o.element()]),{interruptionEvent:"fileUploadOpenedEvent",payload:{checksumid:u,customFiles:s}}}async addMoreItemsToDom(s,o){let u=s.querySelector(`[checksum-get-more-items='${o}']`);if(!u)throw new Error("Get more items root not found");let{items:p,hasMoreItems:v}=await this.getMoreItemsForTemplate(o);u.innerHTML=u.innerHTML+p,v||u.removeAttribute("checksum-get-more-items")}async getPageInfo(s){let o=lL(s);return{id:o,url:s.url(),title:await s.title(),new:this.newPagesIds.includes(o),active:o===lL(this.getPage())}}async getTabsInfo(){var p;let s=this.getPage(),o=await Promise.all(s.context().pages().map(v=>this.getPageInfo(v))),u=(p=this.getTimeMachine())==null?void 0:p.getPage();return u&&u!==s&&(o=o.filter(v=>v.id!==lL(u))),this.newPagesIds=[],o}async getSelectionDataFromSelectorGenerator(s,o,u={}){if(u={useCompoundSelector:!0,useCSSExtraction:!0,useVariables:!0,useArbitrarySelector:!0,...u},!s||!AVt(c0r(o.action.type))||!o.action.checksumid)return{};let p=await s.generateSelectionForAction(o,u);return p?{locator:`locator("${p.selector}")`,...p}:{}}async translateActionResponseToAgentPotentialAction(s,o=void 0,{pageId:u,makeStaticMetadataForESRA:p}={}){let v=structuredClone(s.actionHiddenOverride??s.action),{selector:b,selectorWithVars:S,locator:T,locatorWithVars:P,clickOffset:I,selectOptionValue:B,compoundSelector:J,alternateLocators:j,parentFramesSelectors:W}={...await this.getSelectionDataForAction(v,s.actionHiddenOverride),...await this.getSelectionDataFromSelectorGenerator(o,s)},z=await this.getESRAForSelector(b,W,p);if(!z&&b&&this.logger.logError("Error getting ESRA metadata"),(z==null?void 0:z.tag)==="select")switch(this.getActionEventCode(v.type)){case"input":v.type="selectoption";break;case"click":B&&(v.type="selectoption",v.value=B);break}let Y={eventCode:this.getActionEventCode(v.type),selector:b,selectorWithVars:S,parentFramesSelectors:W,locator:T,locatorWithVars:P,clickOffset:I,pageId:u,compoundSelector:J,alternateLocators:j,fillValue:v.value,fillValueName:v.valueName?`${uhe}${v.valueName}`:"",variables:s.variables,getMoreItemsId:v.getMoreItemsId,esraMetadata:z,thought:s.thought,userRole:v.userRole,canvas:v.canvas,id:v.id};switch(Y.eventCode){case"drag_and_drop":{let{selector:le,selectorWithVars:ye,locator:ve,locatorWithVars:Ie,parentFramesSelectors:Be}={...await this.getSelectionDataForAction({type:s.action.type,checksumid:s.action.dropTargetChecksumid}),...await this.getSelectionDataFromSelectorGenerator(o,{...s,action:{type:s.action.type,checksumid:s.action.dropTargetChecksumid}},{useCompoundSelector:!1})};Y.dropTarget={selector:le,locator:ve,parentFramesSelectors:Be,esraMetadata:await this.getESRAForSelector(le,Be,p)}}break;case"upload_files":Y.files=this.mapFileMIMETypeToFilename(v.files);break;case"switch_tab":{let le=this.getPage();Y.switchToTab={id:v.tabId,index:le.context().pages().findIndex(ye=>lL(ye)===v.tabId)};break}case"keystroke":Y.fillValue=v.value}return Y}async reauthenticate(s,o){let u=this.getPage();this.loginFunction&&(await Promise.all([u.context().clearCookies(),u.evaluate(()=>localStorage.clear())]),await this.loginFunction(o??u,{role:s}))}mapFileMIMETypeToFilename(s){return s.map(o=>{if(o.fileName)return o.fileName;switch(o.mimeType){case"image/png":return"image_200x200.png";case"image/jpeg":return"image_200x200.jpg";case"application/pdf":return"document.pdf";case"text/csv":return"data.csv";default:return"file.txt"}})}async performAction(s,{useLocator:o=!1,handleActionFailed:u,monitorFlashingHTML:p=!0,timeout:v,allowForceClick:b=!0}={}){try{if(s.executed){this.logger.log("[performAction] Action marked as executed, skipping...");return}let S=o?!!s.locator:!!s.selector;if(AVt(s.eventCode)&&!S)throw new Error("No selector provided for action. Try changing app rules preMapReducedHTMLSelectors to true");p&&(this.logger.log("starting flashing elements detection"),await this.evaluateWithChecksum(async()=>window.checksum.testGenerator.startFlashingElementsDetection())),this.logger.log(`Performing action: ${s.eventCode}. Selector: ${s.selector}, Position: ${s.clickOffset}, Parent frame: ${s.parentFramesSelectors}`);let T=e(()=>o?this.makeLocatorFromLocator(s.locator):this.makeLocator(s.selector,s.parentFramesSelectors),"getLocator"),P=e(async(I,B,J={})=>this.actionGuardReturn(I,B,{timeout:v,...J}),"performWithActionGuard");switch(s.eventCode){case"click":try{await P(T().click({position:s.clickOffset,timeout:v??this.options.actionTimeout}),"Click timeout")}catch(I){if(!b)throw I;this.logger.log("Error performing click, will attempt a force click",I.message),s.force=!0,await P(T().click({position:s.clickOffset,force:!0,timeout:v??this.options.actionTimeout}),"Force Click timeout")}break;case"double_click":try{await P(T().dblclick({position:s.clickOffset,timeout:v??this.options.actionTimeout}),"DoubleClick timeout")}catch(I){if(!b)throw I;this.logger.log("Error performing double click, will attempt a force double click",I),s.force=!0,await P(T().dblclick({position:s.clickOffset,timeout:v??this.options.actionTimeout,force:!0}),"Force DoubleClick timeout")}break;case"check":await P(T().check({timeout:v??this.options.actionTimeout}),"Check timeout");break;case"uncheck":await P(T().uncheck({timeout:v??this.options.actionTimeout}),"UnCheck timeout");break;case"drag_and_drop":await P(T().dragTo(o?this.makeLocatorFromLocator(s.dropTarget.locator):this.makeLocator(s.dropTarget.selector,s.dropTarget.parentFramesSelectors),{timeout:v??this.options.actionTimeout}),"DragAndDrop timeout");break;case"input":await P(T().fill(this.getActionFillValue(s),{timeout:v??this.options.actionTimeout}),"Fill timeout");break;case"click_and_type":await Hw(T().click({position:s.clickOffset,timeout:v??this.options.actionTimeout}),1e4,"Click before type timeout"),await Hw(T().pressSequentially(this.getActionFillValue(s),{timeout:v??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"clear_and_type":await Hw(T().clear({timeout:v??this.options.actionTimeout}),1e4,"Clear before type timeout"),await Hw(T().pressSequentially(this.getActionFillValue(s),{timeout:v??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"selectoption":await P(T().selectOption(this.getActionFillValue(s),{timeout:v??this.options.actionTimeout}),"SelectOption timeout");break;case"hover":await P(T().hover({timeout:v??this.options.actionTimeout}),"Hover timeout");break;case"navigation":await P(this.getFrame().goto(s.fillValue,{timeout:v??this.options.navigationTimeout}),"Navigation timeout",{isNavigation:!0});break;case"keystroke":{let I=this.getPage();await P(I.keyboard.press(s.fillValue),"Keystroke timeout");break}case"upload_files":await this.performFileUploadAction(T(),s);break;case"wait":await C3(this.options.waitActionDelay??1e3);break;case"custom_code":await Kft(this.getPage(),this.getFrame(),async I=>{let B=`async (page) => {${s.fillValue}}`;await(0,eval)(B)(I)});break;case"logout_and_login":await this.reauthenticate(s.userRole);break;case"canvas_click":await this.canvasClick(T(),s.canvas);break}}catch(S){throw this.logger.log(`Error performing action: ${s.eventCode}, will attempt a correction template`,S),await(u==null?void 0:u()),S}this.logger.log(`Successfully performed action ${s.eventCode} with description "${s.thought}"`)}async getTextDetection(s){return new Gft(await this.pageInteractorAPI.getTextDetection(s))}async canvasClick(s,o){try{if(!await s.evaluate(b=>b.tagName.toLowerCase()==="canvas"))throw new Error("Click attempted on a non-canvas element");let v=(await this.getTextDetection(await s.screenshot())).getRectangleByTextAndSizeRanking(o.canvasText,o.rectSizeIndex);if(!v)throw new Error(`Canvas click target not found for ${o.canvasText}`);this.logger.log(`Canvas click target: ${v}`),await this.actionGuardReturn(s.click({position:v.center}),"Canvas click could not be performed")}catch(u){throw this.logger.logError("Canvas click:",u.message),new Error("Canvas click action failed")}}getActionFillValue(s,o=!0){let u=s.fillValue;if(!u){let p=s.selector.match(/(?<=value.*)('|").*/);p&&(u=p[0].slice(1,-1))}return typeof u!="string"&&(u="X"),o&&(s.fillValue=u),u}actionGuardReturn(s,o,{isNavigation:u=!1,timeout:p}={}){return Hw(s,p??(u?this.options.navigationTimeout:this.options.actionTimeout),o)}makeLocator(s,o=[]){return m0r(this.getFrame(),s,o)}makeLocatorFromLocator(locator){return eval("this.getFrame()."+locator)}getCurrentURL(){return this.getFrame().url()}async getSelectionDataForChecksumId(s,o){if(o!=null&&o.selector)return{...o,selector:o.selector,locator:o.locator,clickOffset:o.position};if(!s)return this.logger.log(`[getSelectionDataForChecksumId] checksumid not provided (${s})`),{...o,selector:s,locator:`locator("${s}")`};let u=await this.evaluateWithChecksum(async p=>{let{selector:v,locator:b,clickOffset:S,parentFramesSelectors:T,invalid:P,rrwebId:I}=await window.checksum.testGenerator.getSelectorForChecksumId(p),B=await window.checksum.testGenerator.getElementForChecksumId(p),J=B instanceof HTMLOptionElement&&B.value?B.value:void 0;return{selector:v,locator:b,clickOffset:S,selectOptionValue:J,parentFramesSelectors:T,invalid:P,rrwebId:I}},s);if(can&&u.invalid&&u.rrwebId){this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${s}. Trying to use time machine...`);try{let p=await this.getSelectionDataForRRwebIdAtReduceHTMLTime(u.rrwebId);u={...u,...p}}catch{this.logger.log(`[getSelectionDataForChecksumId] error using time machine to get selector for checksumid: ${s}`)}this.logger.log(`[getSelectionDataForChecksumId] got selector: ${u.selector} for checksumid: ${s} from time machine`)}return u!=null&&u.selector||this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${s}. If checksumid is correct, try to change app rules preMapReducedHTMLSelectors to true`),u}async getSelectionDataForRRwebIdAtReduceHTMLTime(s){if(!this.rrwebEventAtLastReducedHTML)return;let o=this.getTimeMachine();if(o)return o.executeTask(u=>u.evaluate(async({rrwebId:p})=>await window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(p,{ignoredIframesSelectors:[".replayer-wrapper > iframe"],fromTimeMachine:!0}),{rrwebId:s}),this.rrwebEventAtLastReducedHTML.timestamp,{name:"getSelectionDataForRRwebIdAtReduceHTMLTime"})}async getESRAForSelector(s,o,u){let p=await this.evaluateWithChecksum(async({selector:v,parentFramesSelectors:b})=>window.checksum.testGenerator.getSelectionDataForSelector(v,b),{selector:s,parentFramesSelectors:o});return p!=null&&p.esraMetadata&&u&&(p.esraMetadata.staticMetadata=await u(p.esraMetadata,s)),p==null?void 0:p.esraMetadata}async getMoreItemsForTemplate(s){return await this.evaluateWithChecksum(async o=>window.checksum.testGenerator.getMoreItemsForTemplate(o,{}),s)??{items:"",hasMoreItems:!1}}async getCurrentReducedHTML({retriesLeft:s=3,retryWaitMS:o=2e3,initialChecksumId:u="0",extractESRAForInterpretationRequiredElements:p=!1,stopFlashingElementsDetection:v=!1,assignChecksumIdsToAllElements:b}={}){let S=new Date;this.logger.log("[getCurrentReducedHTML] Fetching reduced HTML...");try{let{reducedHTML:T,currentChecksumId:P,flashingHTML:I,elementsForNodeInterpretation:B,lastRRwebEvent:J}=await this.evaluateWithChecksum(async W=>window.checksum.testGenerator.reduceHTML({},W),{initialChecksumId:u,extractESRAForInterpretationRequiredElements:p,stopFlashingElementsDetection:v,assignChecksumIdsToAllElements:b}),j=new Date;return this.logger.log(`[getCurrentReducedHTML] Fetched reduced HTML in ${j.getTime()-S.getTime()}ms`),this.rrwebEventAtLastReducedHTML=J,{reducedHTML:T,flashingHTML:I,elementsForNodeInterpretation:B,currentChecksumId:P}}catch(T){if(s>0)return this.logger.logError(`[getCurrentReducedHTML] Error: ${T.message}`),this.logger.logError(`Failed do obtain reduced HTML, trying again in ${o/1e3} seconds, ${s-1} to go.`),await C3(o),this.getCurrentReducedHTML({retriesLeft:s-1,retryWaitMS:o});throw T}}getActionEventCode(s){return Gzt[s]}};e(_TestGenerationPageInteractor,"TestGenerationPageInteractor");var oUe=_TestGenerationPageInteractor;var _AlternateSelectorFallback=class _AlternateSelectorFallback extends z5e{constructor(){super(...arguments);this.timeout=5*1e3}init(o){return super.init(o),this}async resolve(params){var o;try{let{method,args}=params,{checksumId}=this.data,alternateLocators=[];try{let u=await this.getMetadataForTestId();if(!(checksumId in u)||!u[checksumId].alternateLocators)throw new Error(`No alternate selection metadata found for id ${checksumId}`);alternateLocators=u[checksumId].alternateLocators.locators}catch(u){throw super.log(`Could not read alternate selector metadata file, ${u.message}`),u}try{this.log("Resolving alternate selectors locators");let elementsMap=new Map;await Promise.all(alternateLocators.map(async locatorExpression=>{let locator=eval(sse(locatorExpression,"this.page"));try{await Hw(locator.first().waitFor({bypassChecksum:!0}),5e3),(await Hw(locator.elementHandles({bypassChecksum:!0}),1e3)).forEach(p=>{elementsMap.has(p)?elementsMap.set(p,elementsMap.get(p)+1):elementsMap.set(p,1)})}catch(u){return}}));let majorityElementHandle=(o=Array.from(elementsMap.entries()))==null?void 0:o.reduce((u,p)=>u[1]>p[1]?u:p)[0];if(!majorityElementHandle)throw this.errorMessage="No alternate element found",new Error(this.errorMessage);let totalElements=Array.from(elementsMap.values()).reduce((u,p)=>u+p,0),elementSelector=await this.evaluateWithChecksum(async({element:u})=>window.playwright.selector(u),{element:majorityElementHandle});this.log(`Resolved alternate selector: ${elementSelector}' With majority vote of ${elementsMap.get(majorityElementHandle)} out of ${totalElements} elements`),await this.checksumPage.wrapNoLocationSteps(async()=>this.execute(this.page.locator(elementSelector),method,args));let fallbackResult={selector:elementSelector,generatedLocator:`locator("${elementSelector}")`,esraMetadata:void 0};return this.sendLog(fallbackResult),this.logPayload=this.logPayload.concat({mejorityVote:`${elementsMap.get(majorityElementHandle)}/${totalElements}`}),this.checksumPage.addErrorMessage(params.error,`${this.thought?`"${this.thought}" auto-healed`:"Auto-healed"} using alternative selector "${elementSelector}"`),{steps:[{type:"action",...fallbackResult}]}}catch(u){throw new Error(`Failed to execute compound selection fallback action: ${u.message}`)}}catch(u){this.errorMessage=u.message,this.log(this.errorMessage);return}}getAnalyticsPayload(){return{fallbackType:"alternative-selector",...this.logPayload??{checksumId:this.data.checksumId,error:this.errorMessage}}}toString(){return`Checksum alternative selector (${this.data.checksumId})`}};e(_AlternateSelectorFallback,"AlternateSelectorFallback");var Yzt=_AlternateSelectorFallback;var Xzt=class Xzt{constructor(o){this.options=o;this.health=e(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(o=>(console.log(o),null)),"health");this.getCanvasDetection=e(async o=>{try{let u=o.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:u}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(u){return console.log(u),null}},"getCanvasDetection")}};e(Xzt,"ChecksumClient");var uUe=Xzt;var Qzt=class Qzt{constructor(){this.config={}}};e(Qzt,"PageInteractorAPI");var Yft=Qzt;var Zzt=class Zzt extends Yft{constructor(u){super();this.config=u;this.getTextDetection=e(async u=>{let p=await this.api.getCanvasDetection(u);if(!p)throw new Error("No data returned from canvas detection");return p},"getTextDetection");this.config=u,this.api=new uUe({apiKey:u.apiKey,apiURL:u.apiURL})}};e(Zzt,"RuntimePageInteractorAPI");var cUe=Zzt;var S1r=require("path");var eWt=class eWt{constructor(o){this.options=o;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=e(async o=>{let u=lL(o);if(this.trackedFramesGuid.includes(u))return this.frameNavigationPromises[u]=new Promise(async p=>{await this.loadScript(o),p()}),this.frameNavigationPromises[u]},"onFrameNavigated");this.loadScript=e(async(o,{retriesLeft:u=3,retryWaitMS:p=2e3,useWrapper:v=!0}={})=>{var P,I;if(v&&this.scriptLoadWrapper)return this.scriptLoadWrapper(()=>this.loadScript(o,{retriesLeft:u,retryWaitMS:p,useWrapper:!1}),o);if(!this.addScriptTagOptions){console.warn("[InjectedScriptManager] addScriptTagOptions not set, skipping loadScript");return}if(this.isFrameClosed(o))return;let b=!1;try{b=this.scriptLoadCheck?await((P=this.scriptLoadCheck)==null?void 0:P.call(this,o)):!1}catch{}if(b||this.isFrameClosed(o))return;try{await o.addScriptTag(this.addScriptTagOptions)}catch(B){if(u>0)return console.warn(`[InjectedScriptManager] Failed to add script to frame ${lL(o)}, trying again in ${p/1e3} seconds, ${u-1} retries left.`,B.message),await C3(p),this.loadScript(o,{retriesLeft:u-1,retryWaitMS:p,useWrapper:v});throw B}let S=lL(o),T=Date.now().toString(36)+Math.random().toString(36).substr(2);if(this.navigatingFrames[S]=T,this.options.scriptInitWait&&(console.log(`Waiting ${this.options.scriptInitWait}[ms] before onScriptLoad...`),await C3(this.options.scriptInitWait),console.log("Done waiting before onScriptLoad")),!this.isFrameClosed(o)){if(this.navigatingFrames[S]&&this.navigatingFrames[S]!==T)return console.log("Page navigated again, waiting on new promise..."),this.frameNavigationPromises[S];try{await((I=this.scriptLoadCallback)==null?void 0:I.call(this,o))}catch(B){console.error("[WebDriver] onScriptLoad error",B)}}},"loadScript");this.addScriptTagOptions=this.makeFrameInjectedScriptOptions()}setScriptLoadCallback(o){return this.scriptLoadCallback=o,this}setScriptLoadCheck(o){return this.scriptLoadCheck=o,this}setScriptLoadWrapper(o){return this.scriptLoadWrapper=o,this}async addTrackedFrame(o,u=!0){let p="mainFrame"in o?o.mainFrame():o,v=lL(p);if(this.trackedFramesGuid.includes(v)||this.trackedFramesGuid.push(v),u)return this.onFrameNavigated(p)}getNavigationPromise(o){if(!o){console.warn("[InjectedScriptManager] getNavigationPromise called with undefined argument");return}let u=typeof o=="string"?o:"mainFrame"in o?lL(o.mainFrame()):lL(o);return this.frameNavigationPromises[u]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,S1r.join)(process.cwd(),this.options.scriptFile)}:void 0;case"url":return this.options.scriptURL?{url:this.options.scriptURL}:void 0;default:return}}isFrameClosed(o){return o.isDetached()||o.page().isClosed()}};e(eWt,"InjectedScriptManager");var lUe=eWt;var d7e=ox(require("path")),iWt=require("fs");var Can=__dirname,k1r=d7e.join(__dirname,".."),Tan=(0,iWt.existsSync)(k1r)?k1r:Can;A1r().config({path:d7e.resolve(Tan,".env")});var Qft=process.env.DEV_MODE==="true";function F1r(){let s=__dirname;for(;!(0,iWt.existsSync)(d7e.join(s,"package.json"));)s=d7e.join(s,"..");return s}e(F1r,"findRoot");var P1r=d7e.join(F1r(),"vtg-build","index.html"),q7={isDevMode:Qft,logLevel:process.env.LOG_LEVEL??"warnings",checksumScript:{source:Qft?"url":"file",url:process.env.SCRIPT_URL,path:F1r()+"/checksumlib.js"},vtg:{writeLogFile:process.env.WRITE_LOG_FILE==="true",localBuildPath:P1r,appURL:Qft?process.env.VTG_APP_URL:`file://${P1r}`,useFakeStory:process.env.USE_FAKE_STORY==="true",recordEvents:process.env.RECORD_EVENTS==="true",fakeStory:{goal:process.env.FAKE_STORY_GOAL??"Send email via outreach list",instructions:process.env.FAKE_STORY_INSTRUCTIONS??"Make sure to select a user from the list first"},fakeTestGeneration:{internalTestId:process.env.FAKE_STORY_INTERNAL_TEST_ID??`tempID${Date.now().toString().slice(-5)}`,generationBatchId:process.env.FAKE_GENERATION_BATCH_ID??`tempID${Date.now().toString().slice(-5)}`},remoteDebugging:process.env.REMOTE_DEBUGGING==="true",taskTimeMachine:{showTaskTimeMachine:process.env.SHOW_TASK_TIME_MACHINE==="true",taskTimeout:parseInt(process.env.TASK_TIME_MACHINE_TIMEOUT??"240000")},aiAssertions:{disabled:process.env.AI_ASSERTIONS_DISABLED==="true",allowRefactoring:process.env.ALLOW_AI_ASSERTIONS_REFACTORING==="true"},aiLocators:{disabled:process.env.AI_LOCATORS_DISABLED==="true",useFakeAILocators:process.env.USE_FAKE_AI_LOCATORS==="true"}},testRun:{timeMachine:{active:!0,headless:!0},monitoring:{segment:{writeKey:process.env.MONITORING_SEGMENT_WRITE_KEY??"MfFJgdVFaFaD3NrBrgX3A9Blwfxs0pSD"}}},buildTime:process.env.BUILD_TIME??"unknown"};Qft&&console.log("Build",q7.buildTime);var aWt=class aWt{constructor(){this.frames={};this.pages=[];this.channels={};this.events=[]}register(o,u,p){if(this.frames[o])return;this.frames[o]=u;let v=u.page();this.pages.includes(v)||(this.pages.push(v),v.exposeFunction("checksumSendMessage",async(b,S)=>{let T=this.frames[b];if(!T)throw new Error(`Frame ${b} not found`);try{await T.evaluate(({message:P})=>{window.postMessage(P,"*")},{message:S})}catch{}}),v.exposeFunction("checksumSendBroadcastMessage",async(b,S)=>{let T=this.channels[b]??[];if(p){let P=require("fs"),I=require("path");this.events.push(...S),this.events.length%10===0&&P.writeFileSync(I.join(process.cwd(),"rrweb-player","events.json"),JSON.stringify(this.events))}T.forEach(async P=>{if(!(P.originFrameGuid&&P.originFrameGuid!==lL(u)))try{P.handler?await P.handler(S):await u.evaluate(({message:I})=>{window.postMessage(I,"*")},{message:S})}catch{}})}),v.exposeFunction("checksumBringPageToFront",async b=>{let S=this.frames[b];S&&await S.page().bringToFront()}))}subscribeToChannel(o,u,{originFrame:p,handler:v}={}){var b;(b=this.channels)[o]??(b[o]=[]),this.channels[o].push({frame:u,originFrameGuid:p?lL(p):void 0,handler:v})}unsubscribeFromChannel(o,u){var p;(p=this.channels)[o]??(p[o]=[]),this.channels[o]=this.channels[o].filter(v=>v.frame!==u)}};e(aWt,"FramesMsgBroker");var pUe=aWt;var I1r=require("@playwright/test");var fUe=require("jsdom");var sWt=class sWt{constructor(o){this.activeDOMType="checksumIds";this.rawReducedHTMLDom=new fUe.JSDOM(o),this.process()}process(){this.expandedChecksumIdsReducedDom=new fUe.JSDOM(this.rawReducedHTMLDom.serialize()),this.reducedHTMLDom=new fUe.JSDOM(this.rawReducedHTMLDom.serialize()),this.rrwebIdsReducedDom=new fUe.JSDOM(this.rawReducedHTMLDom.serialize());let o=e(S=>{S.window.document.body.querySelectorAll("[checksumid]:not([checksuminteractable])").forEach(P=>{P.removeAttribute("checksumid")})},"removeChecksumIdAttributeFromNonInteractable"),u=e((S,T)=>T.window.document.body.querySelectorAll(`[${S}]`).forEach(P=>P.removeAttribute(S)),"removeAttributeFromAllElements"),p=e(S=>u("checksuminteractable",S),"removeChecksumInteractableAttribute"),v=e(S=>u("checksumid",S),"removeChecksumIdAttribute"),b=e(S=>u("rrwebid",S),"removeRrwebIdAttribute");o(this.reducedHTMLDom),p(this.expandedChecksumIdsReducedDom),p(this.reducedHTMLDom),p(this.rrwebIdsReducedDom),b(this.expandedChecksumIdsReducedDom),b(this.reducedHTMLDom),v(this.rrwebIdsReducedDom)}getDOMForType(o){switch(o){default:case"checksumIds":return this.reducedHTMLDom;case"expandedChecksumIds":return this.expandedChecksumIdsReducedDom;case"rrwebIds":return this.rrwebIdsReducedDom}}async enrich(o){return await o(this.rawReducedHTMLDom),this.process(),this}setActiveDomType(o){this.activeDOMType=o}getActiveDom(){return this.getDOMForType(this.activeDOMType)}getActiveDOMString(){return this.getActiveDom().serialize()}getRrwebIdsReducedDomString(){return this.rrwebIdsReducedDom.serialize()}getDOMStringForType(o){return this.getDOMForType(o).serialize()}get raw(){return this.rawReducedHTMLDom}};e(sWt,"ReducedHTMLDOM");var dUe=sWt;var N1r=ox(require("path"));var uWt=class uWt{constructor(o="all"){this.listeners=[];this.logLevel=o}log(...o){try{let p=new Error().stack.split(`
|
|
1406
1406
|
`)[4].trim().match(/\(([^)]+)\)/);if(!(p&&p[1]))throw new Error;let v=p[1].split(":"),b=v.slice(0,-2).join(":"),S=v[v.length-2],P=`${N1r.default.basename(b)}:${S}`;console.log("\x1B[34m",P,"\x1B[0m",...o),setTimeout(()=>this.listeners.forEach(I=>I.onLog(...o)),0)}catch{console.log(...o)}}addListener(o){this.listeners.push(o)}info(...o){this.logLevel==="all"&&this.log(...o)}warning(...o){(this.logLevel==="all"||this.logLevel==="warnings")&&this.log(...o)}error(...o){this.log(...o)}setLogLevel(o){this.logLevel=o}};e(uWt,"Logger");var oWt=uWt,ECe=new oWt,wan=Object.assign((...s)=>ECe.info(...s),{info:e((...s)=>ECe.info(...s),"info"),warning:e((...s)=>ECe.warning(...s),"warning"),error:e((...s)=>ECe.error(...s),"error"),setLogLevel:e(s=>ECe.setLogLevel(s),"setLogLevel"),addLogListener:e(s=>ECe.addListener(s),"addLogListener")}),bm=wan;var cWt=class cWt{constructor(o,u,p={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4}){this.frameMsgBroker=o;this.injectedScriptManager=u;this.options=p;this.taskQueue=[];this.isRunning=!1;this.currentTimestamp=0;this.currentBeforeTimestamp=!1;this.timeMachineTaskIndex=0;this.currentChecksumId="0";this.timeGoingBack=0;this.timeRunningTasks=0;this.tasksExecuted=0;this.reducedHTMLCache={};this.getReducedHTMLWithRetries=e(async(o,{retriesLeft:u=3,retryWaitMS:p=1e3}={})=>{try{let{reducedHTML:v,currentChecksumId:b}=await o.evaluate(async S=>{var T,P;return(P=(T=window==null?void 0:window.checksum)==null?void 0:T.testGenerator)==null?void 0:P.reduceHTML({},S)},{stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:this.currentChecksumId,fromTimeMachine:!0,invalidateCache:!0});return this.currentChecksumId=b,{reducedHTML:v}}catch(v){if(u>0)return await C3(p),this.getReducedHTMLWithRetries(o,{retriesLeft:u-1,retryWaitMS:p});throw v}},"getReducedHTMLWithRetries");this.rrwebEventHandler=e(async o=>{let u=JSON.stringify(o);await this.timeMachineFrame.evaluate(function(p){let v=JSON.parse(p);return window.checksum.timeMachine.handleEvents(v)},u),o=null},"rrwebEventHandler")}getPage(){return this.timeMachineFrame.page()}getFrame(){return this.timeMachineFrame}async prepare(o,u,p){this.recordingFrame=o,this.frameMsgBroker.register("live",o),u?this.timeMachineFrame=u:this.timeMachineFrame=await this.prepareBrowserContextAndFrame(),p&&p(this.timeMachineFrame),await this.injectedScriptManager.addTrackedFrame(this.timeMachineFrame),this.subscribeToRrwebEvents(),this.taskQueue=[],this.isRunning=!1,await this.start()}async start(){await this.timeMachineFrame.evaluate(async()=>{window.checksum.timeMachine.start({firstEventTimestamp:Date.now()})})}setBrowserContext(o){this.timeMachineBrowserContext=o}async executeTask(o,u=void 0,{name:p,beforeTimestamp:v=!1}={}){return new Promise((b,S)=>{let T=this.timeMachineTaskIndex++,P=e(async({shouldGoBack:I,shouldBatch:B}={shouldGoBack:!0,shouldBatch:this.options.timestampBatchingEnabled})=>{if(this.timeMachineFrame.isDetached()&&S(),I){let W=Date.now();await this.goBack(u,v),this.timeGoingBack+=Date.now()-W}let j=[e(async()=>{try{let W=Date.now(),z=await Hw(o(this.timeMachineFrame),this.options.taskTimeout,()=>`Task execution timeout - ${p}, took ${Date.now()-W}ms with timeout of ${this.options.taskTimeout}ms`);b(z)}catch(W){bm.error("Task execution error:",W.message),S(W)}},"safeRunTask")()];this.taskQueue.length>0&&B&&(j.push(...this.taskQueue.filter(W=>W.timestamp===u).map(({task:W})=>W({shouldGoBack:!1,shouldBatch:!1}))),this.taskQueue=this.taskQueue.filter(W=>W.timestamp!==u),j.length&&console.log(`Batching to task "${p}, index: ${T} ${j.length-1} more tasks`)),await Promise.all(j)},"taskWrapper");this.taskQueue.push({name:p,task:P,timestamp:v?u-1:u,queuedAt:Date.now(),index:T}),this.runTasks()})}executeReducedHTMLTask(o){if(this.reducedHTMLCache[o]){let u=new dUe(this.reducedHTMLCache[o]);return Promise.resolve(u.getRrwebIdsReducedDomString())}return this.executeTask(async u=>{let p="",v=await this.getReducedHTMLWithRetries(u);return p=v==null?void 0:v.reducedHTML,p&&(this.reducedHTMLCache[o]=p),new dUe(p).getRrwebIdsReducedDomString()},o,{name:"getReducedHTMLForTimestamp"})}goBack(o,u=!1){return this.currentBeforeTimestamp===u&&this.currentTimestamp===o?Promise.resolve():(this.currentTimestamp=o,this.currentBeforeTimestamp=u,this.timeMachineFrame.evaluate(({timestamp:p,beforeTimestamp:v})=>p===void 0?window.checksum.timeMachine.goLive():window.checksum.timeMachine.goBack(p,{beforeTimestamp:v}),{timestamp:o,beforeTimestamp:u}))}goLive(){return this.timeMachineFrame.evaluate(()=>window.checksum.timeMachine.goLive())}popTask(){return this.options.sortByTimestamp&&(this.taskQueue=this.taskQueue.sort((o,u)=>o.timestamp-u.timestamp)),this.taskQueue.shift()}async runTasks(){if(this.isRunning)return;this.isRunning=!0;let o=this.popTask(),u=Date.now();try{let p=Date.now()-o.queuedAt;bm.info(`Running task, timestamp: ${o.timestamp} \x1B[36m${o.name}\x1B[0m, index: ${o.index}, was pending for`,p),await o.task();let v=Date.now()-u;this.timeRunningTasks+=v,bm.info("Finished running task, took",v,"ms.","Queue length:",this.taskQueue.length),this.tasksExecuted++}catch(p){bm.error("Task execution error:",p)}finally{this.isRunning=!1,this.taskQueue.length>0?this.runTasks():bm.info("Accumulated time running tasks:",this.timeRunningTasks,"ms, from which time spent going back:",this.timeGoingBack)}}async makeBrowserContext(){let o=await I1r.chromium.launch({devtools:!1,headless:this.options.headless});return this.timeMachineBrowserContext=await o.newContext({bypassCSP:!0}),this.timeMachineBrowserContext}async makeFrame(){return(await this.timeMachineBrowserContext.newPage()).mainFrame()}async prepareBrowserContextAndFrame(){return this.timeMachineBrowserContext||await this.makeBrowserContext(),this.makeFrame()}subscribeToRrwebEvents(){let o="rrweb";this.frameMsgBroker.subscribeToChannel(o,this.timeMachineFrame,{originFrame:this.recordingFrame,handler:this.rrwebEventHandler}),this.timeMachineFrame.page().on("close",()=>this.frameMsgBroker.unsubscribeFromChannel(o,this.timeMachineFrame))}async toggleTimeMachineHandleEvents(o){try{await this.timeMachineFrame.evaluate(u=>window.checksum.timeMachine.setShouldHandleEvents(u),o)}catch{}}};e(cWt,"ChecksumTimeMachine");var che=cWt;var Aan=require("@playwright/test");var ROn=1e3*30;var O1r=require("fs");var L1r=!1;function _Ue(s){L1r=s}e(_Ue,"setLogToConsole");function MN(...s){L1r&&console.log(...s)}e(MN,"log");async function v0r(s,o,u,p=6e4){if(!(o in s))return s;let v=e(()=>s[o](...u),"executor");return p===null?v():Hw(v(),p,"Execution timeout")}e(v0r,"executePlaywrightMethodWithTimeout");function pWt(s,{role:o,environment:u}={},p=!1){var T,P;let v;if(u&&(v=(T=s.environments)==null?void 0:T.find(({name:I})=>u===I)),v||(v=(P=s.environments)==null?void 0:P.find(({default:I})=>I)),!v)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let b=v.users,S;if(b&&(o!==void 0&&(S=b.find(I=>I.role===o)),S||(S=b.find(I=>I.default))),!S)throw new Error(`User not found. Please make sure the users array for the "${v.name}" environment is properly defined in the checksum.config.ts file.`);if(u&&v.name!==u){if(p)throw new Error(`Could not find environment with name "${u}" in config file`);console.warn(`Could not find environment with name "${u}" in config file, trying to use default environment`)}if(o&&S.role!==o){if(p)throw new Error(`Could not find user with role "${o}" for environment "${u}" in config file`);console.warn(`Could not find user with role "${o}" for environment "${u}" in config file, trying to login with environment's default user`)}return{environment:v,user:S}}e(pWt,"resolveEnvironment");function Fan(s){let o=`${s??kVt()}/login.ts`;if(!(0,O1r.existsSync)(o))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${o}`),new Error("Could not find login.ts file");try{return require(o).default}catch(u){throw console.warn("Error loading login.ts file",u),u}}e(Fan,"requireLogin");async function Nan(s,o,{environment:u,user:p,config:v}){try{let b=e(()=>o(s,{environment:u,user:p,config:v}),"performLogin");"checksumAI"in s?await s.checksumAI(`Log in${p!=null&&p.role?` using ${p.role} role`:""}${u!=null&&u.name?` in ${u.name} environment`:""}`,b):await b()}catch(b){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
|
|
1407
1407
|
`,b),b}}e(Nan,"proceedWithLogin");function lWt(s){let{config:o,folder:u,throwIfAuthFailed:p}=s,v=Fan(u);return async(b,{role:S,environment:T}={})=>{let{environment:P,user:I}=pWt(o,{role:S,environment:T},s.throwIfEnvInfoInvalid);if(p&&!I)throw new Error("Could not find user credentials matching the provided role and/or environment");await Nan(b,v,{environment:P,user:I,config:o})}}e(lWt,"makeUnboundLogin");var CJe=require("fs"),a9r=ox(require("child_process")),e0e=require("path");var gL=require("fs"),_mt=ox(require("child_process")),JJ=require("path");var qvr=ox(jvr());var lmt=(u=>(u.Launched="Launched",u.Log="Log",u))(lmt||{});var BKt=class BKt{constructor(o,u){this.config=o;this.options=u;this.didIdentify=!1;this.isolatedMode=!1;this.internalId=process.env.CHECKSUM_TRACE_INTERNAL_ID??gqe(6)}async identify(o,u,p=!1){let v=this.identifier;this.identifier=o,this.didIdentify=!0,!(!this.analyticsBase||p)&&(v&&(this.analyticsBase.alias({userId:o,previousId:v}),await C3(10)),this.analyticsBase.identify({userId:o,anonymousId:v,traits:{...u,...this.getTraits()}}))}log(...o){this.trackEvent("Log",{lines:o})}setIsolatedMode(){this.isolatedMode=!0}trackEvent(o,u={}){if(!(!this.analyticsBase||this.isolatedMode))try{!this.didIdentify&&!this.identifier&&(this.identifier=Date.now().toString()),u.internalId=this.internalId,this.track(o,u),this.logToConsole(o,u)}catch(p){console.error(`Failed to track event: ${o} with payload:`,u,p)}}logToConsole(o,u){this.options.logToConsole&&console.log(`Event Tracked: ${o}`,u)}getTraits(){return{}}};e(BKt,"BaseAnalytics");var pmt=BKt;var jKt=class jKt extends pmt{constructor(o,u){super(o,u),o!=null&&o.writeKey&&(this.analyticsBase=new qvr.default({...o,flushAt:1,flushInterval:1e3}))}async flush(){this.analyticsBase&&await this.analytics.flush()}async close(){this.analyticsBase&&await this.analytics.closeAndFlush({timeout:1e4})}track(o,u){if(this.analyticsBase)try{let p=this.didIdentify?{userId:this.identifier}:{anonymousId:this.identifier};this.analytics.track({...p,event:o,properties:u})}catch(p){console.error(`Failed to track event: ${o} with payload:`,u,p)}}get analytics(){return this.analyticsBase}};e(jKt,"NodeAnalytics");var fmt=jKt;var iTe=(bt=>(bt.RuntimeError="Runtime Error",bt.TestRunMonitorError="Test Run Monitor Error",bt.ChecksumConfigError="Checksum Config Error",bt.InitializationError="Initialization Error",bt.UploadStart="Upload Start",bt.UploadComplete="Upload Complete",bt.UploadFailed="Upload Failed",bt.TestRunStarted="Test Run Started",bt.TestRunEnd="Test Run End",bt.TestRunFailed="Test Run Failed",bt.AllUploadsComplete="All Uploads Complete",bt.UploadsCompleteWithErrors="Upload Complete With Errors",bt.ReportComplete="Report Complete",bt.ReportUploadError="Report Upload Error",bt.RuntimeTimeout="Runtime Timeout",bt.CompletionStatus="Completion Status",bt.RuntimeComplete="Runtime Complete",bt.ChecksumConfig="Checksum Config",bt.PlaywrightConfig="Playwright Config",bt.FallbackStart="Fallback Start",bt.ActionExecutionFailure="Action Execution Failure",bt.AIFallbackStep="AI Fallback Step",bt.ActionFallbackExecution="Action Fallback Execution",bt.AssertionFallbackExecution="Assertion Fallback Execution",bt.AssertionFailure="Assertion Failure",bt.CompoundSelectionFailure="Compound Selection Failure",bt))(iTe||{});var w7e=class w7e extends fmt{constructor(u,p,v){super(p,v);this.traits=u}static getInstance(u={},p={},v={logToConsole:!0}){return w7e.instance||(w7e.instance=new w7e(u,p,v)),w7e.instance}setTestId(u){this.testId=u}event(u){this.trackEvent(u)}eventWithMessage(u,p){this.trackEvent(u,{message:p})}runtimeError(u){this.trackEvent("Runtime Error",u)}completionStatus(u){this.trackEvent("Completion Status",{stats:u})}reportComplete(u,p){this.trackEvent("Report Complete",{stats:u,reportUrl:p})}allUploadsComplete(){this.trackEvent("All Uploads Complete")}uploadsCompleteWithErrors(u){this.trackEvent("Upload Complete With Errors",{errors:u})}testsStart(){this.trackEvent("Test Run Started")}testsEnd(){this.trackEvent("Test Run End")}testsFailed(){this.trackEvent("Test Run Failed")}checksumConfig(u){this.trackEvent("Checksum Config",u)}playwrightConfig(u){this.trackEvent("Playwright Config",u)}uploadStart(u){this.trackEvent("Upload Start",{filename:u})}uploadComplete(u){this.trackEvent("Upload Complete",{filename:u})}uploadFailed(u,p){this.trackEvent("Upload Failed",{filename:u,error:p})}fallbackStart(u){u.shouldSendToAnalytics&&this.trackEvent("Fallback Start",{description:u.toString(),testId:this.testId})}actionFallbackExecution(u,p){p.shouldSendToAnalytics&&this.trackEvent("Action Fallback Execution",{success:u,...p.getAnalyticsPayload(),testId:this.testId})}actionExecutionFailure(u){this.trackEvent("Action Execution Failure",{...u,testId:this.testId})}aiFallbackStep(u,p){this.trackEvent("AI Fallback Step",{sessionId:u,...p,testId:this.testId})}compoundSelectionFailure(u,p){this.trackEvent("Compound Selection Failure",{error:u,compoundSelector:p,testId:this.testId})}assertionFailure(u,p,v){this.trackEvent("Assertion Failure",{thought:u,error:p,matcher:v,testId:this.testId})}assertionFallbackExecution(u,p){p.shouldSendToAnalytics&&this.trackEvent("Assertion Fallback Execution",{success:u,...p.getAnalyticsPayload(),testId:this.testId})}track(u,p){if(!this.getAllowedEvents().includes(u))throw new Error(`Invalid runtime event type: ${u}`);super.track(u,p)}getTraits(){return this.traits}getAllowedEvents(){return[...Object.values(iTe),...Object.values(lmt)]}};e(w7e,"RuntimeAnalytics");var dmt=w7e;var qKt=class qKt{constructor(o,u=!1){this.args=o;this.debugMode=u;this.checksumAppUrl="https://app.checksum.ai";this.childProcesses=[];this.printError=e(o=>{console.log("\x1B[31m%s\x1B[0m",o,"\x1B[0m")},"printError");this.processConfigArg(),["SIGINT","SIGTERM"].forEach(p=>{process.on(p,()=>{this.cleanup(),process.exit()})}),this.checksumRuntimeVersion=this.getChecksumRuntimeVersion()}getChecksumRuntimeVersion(){if(this.checksumRuntimeVersion)return this.checksumRuntimeVersion;try{return require("./package.json").version}catch{return"unknown"}}loadTracer(){let o=q7.testRun.monitoring.segment;this.trace=dmt.getInstance({version:this.checksumRuntimeVersion},o,{logToConsole:this.debugMode})}async execCmd(o,u={}){let p={...process.env,...u},v=await _mt.spawn(o,{env:p,shell:!0,stdio:"inherit"});return this.childProcesses.push(v),new Promise((S,T)=>{v.on("exit",P=>{P===0?S(!0):T(new Error(`Checksum failed execution with code: ${P} `)),this.childProcesses=this.childProcesses.filter(I=>I!==v)})})}async getCmdOutput(o){return new Promise(function(u,p){_mt.exec(o,(v,b,S)=>{if(v){p(`Error executing command: ${v.message}`);return}u(b.trim())})})}validateAuthExists(){this.checksumRoot||this.findChecksumRoot();let o=(0,JJ.join)(this.checksumRoot,".auth");(0,gL.existsSync)(o)||(0,gL.writeFileSync)(o,"{}")}loadChecksumData(){this.locateChecksumLibs(),this.setChecksumConfig()}async patchPlaywright(o=!1){MN("Patching playwright",o);let u=(0,JJ.join)(__dirname,"./scripts/patch.js");(0,gL.existsSync)(u)||(u=(0,JJ.join)(__dirname,"../../../scripts/src/patch_playwright.js"));let p=`node "${u}"${o?" off":""}`;try{await this.execCmd(p,{PROJECT_ROOT:this.projectRootDirectory,RUNTIME:"true"})}catch(v){console.log("Error patching playwright",v.message)}}getPlaywrightConfigFilePath(){return(0,JJ.join)(this.checksumRoot,"playwright.config.ts")}buildVolatileConfig(){if(!this.volatileChecksumConfig)return;let o=this.getVolatileConfigPath(),u=`
|
|
1408
1408
|
import { RunMode, getChecksumConfig } from "@checksum-ai/runtime";
|
|
@@ -1450,7 +1450,7 @@ test(defineChecksumTest("${o}", "${s}"), async ({ ${p.join(", ")} }) => { ${u} }
|
|
|
1450
1450
|
`).find(u=>u.includes(".checksum.spec.ts"));if(o)return{lineNumber:parseInt(o.split(":")[1]),columnNumber:parseInt(o.split(":")[2])}},"findCodeLocationFromStackTrace"),Ztr=class Ztr{constructor(){this.store={};this.activeVariablesSet=new Set;return new Proxy(this,this)}clearAll(){for(let o in this.store)this.store.hasOwnProperty(o)&&delete this.store[o];this.activeVariablesSet.clear()}getActiveVariables(){return Array.from(this.activeVariablesSet).map(o=>this.store[o])}setVariable(o,u){this.store[o]={name:o,value:u,type:u instanceof Function?"RandomValueGenerator":"FillValue"}}set(o,u,p){if(typeof u!="string")return!1;let v=tAn();return o.store[u]={name:u,value:p,type:p instanceof Function?"RandomValueGenerator":"FillValue",...v,line:""},!0}get(o,u){var p;if(u in o)return o[u];if(!(u in o.store))throw new Error(`Variable ${u} is not defined`);return o.activeVariablesSet.add(u),(p=o.store[u])==null?void 0:p.value}};e(Ztr,"VariableStore");var pgt=Ztr;var err=class err{constructor(o=new pgt){this._variableStore=o}get variableStore(){return this._variableStore}};e(err,"VTGVariableStoreService");var fgt=err;var _VtgEvaluatorService=class _VtgEvaluatorService{constructor(s,o){this.variableStoreService=s;this.vtgTestFileMode=o;this.listenerBody=e(async({vtg})=>{await vtg.eval(async(code,callback)=>{try{callback(null,await eval(`(async () => {
|
|
1451
1451
|
${code}
|
|
1452
1452
|
})()`))}catch(s){callback(s,null)}})},"listenerBody")}setPage(s){this.page=s}async execute(s,o={}){return this.vtgTestFileMode?this.executeInPlaywrightTest(s,o):this.executeOnLive(s,o)}get vtgContext(){return{page:this.page,vs:this.variableStoreService.variableStore,expect:Ite.expect,checksumAI:e((s,o)=>o(),"checksumAI")}}async executeOnLive(s,o={}){let u={...this.vtgContext,...o},p=this.wrapCodeInContext(s,u);return await(0,eval)(p)(u)}wrapCodeInContext(s,o){return`(async ({${Object.keys(o).join(", ")}}) => { ${s} })`}async executeInPlaywrightTest(s,o={}){let u=o?this.wrapCodeInContext(s,o)+"(context)":s;if(this.listener===void 0)throw new Error("Listener is not defined");return new Promise((p,v)=>{this.listener(u,o,(b,S)=>{b?v(b):p(S)})})}async listenForExecution(s){return new Promise(o=>{this.resolveEvaluator=o,this.listener=s})}stopListening(){this.resolveEvaluator()}getFunctionContentToInject(){return this.listenerBody.toString()}};e(_VtgEvaluatorService,"VtgEvaluatorService");var dgt=_VtgEvaluatorService;var rrr=class rrr extends zJ{constructor(u,p=!1){p||(p=!!u.find(v=>v==="--debug"));super(u,p);this.checksumScriptFilePath="node_modules/@checksum-ai/runtime/checksumlib.js";this.vtgMode="start";this.initTimeMachine=e(async()=>{await this.webDriver.tmFrame.evaluate(()=>window.checksum.visualTestGenerator.init(!1))},"initTimeMachine");this.initVtgMode(u),bm.setLogLevel(p?"all":q7.isDevMode?q7.logLevel:"errors")}async run(u){await this.init(u),this.buildServices(),this.buildServer();let p=await this.getInitialServicesData();p&&this.setServicesData(p),await this.start()}async init(u){await this.patchPlaywright(),this.loadChecksumData(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(u),this.webDriver.registerEventListener(this),this.taskTimeMachine=new che(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!q7.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:q7.vtg.taskTimeMachine.taskTimeout}),this.pageInteractor=new oUe(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:bm.info,logError:bm.error},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new cUe(this.config)),this.testAssetsManager=new rgt(this.projectRootDirectory,this.checksumRoot),(q7.vtg.writeLogFile||this.debugMode)&&this.addLogFile()}buildServices(){this.actionsManager=new N1t,this.apiService=new zmt(this.config),this.userStoryService=new F1t(this.apiService,this.config),this.variableStoreService=new fgt,this.evaluatorService=new dgt(this.variableStoreService,this.vtgTestFileMode),this.actionsService=new Umt(this.config,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService),this.assertionsService=new t1t(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new u1t(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new Jmt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new e1t(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService),this.aiThoughtsService=new lgt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new P1t(this.config,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService,this.vtgTestFileRunConfig),this.settingsService=new ugt(this.checksumRoot),this.actionsManager.setStorageService(this.storageService)}buildServer(){this.reactAppServer=new egt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService)}loadPlaywrightConfigForVTG(){try{let u=`${this.checksumRoot}/playwright.config.ts`;if((0,SJe.existsSync)(u)){let p=require(u).default;p&&(this.playwrightConfigForVTG=p)}}catch{console.warn("Could not find playwright config file, will run with defaults")}}async getInitialServicesData(){if(this.vtgMode==="cloud")return this.getInitialServicesDataFromCloud();if(this.vtgMode==="edit")return this.vtgTestFileMode?await this.getInitialServicesDataByInternalTestId():this.getInitialServicesDataFromEditLocationPath()}getInitialServicesDataFromEditLocationPath(){let u=this.storageService.getLocalSavedData(this.editLocationPath);return{actions:u.executedActions,story:u.story,testGenerationData:u.testGenerationData}}async getInitialServicesDataFromCloud(){let p=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:v,story:b,testGenerationData:S}=p,T=await fetch(v,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!T.ok)throw new Error(`HTTP error! Status: ${T.status}`);let P=await T.json();return{actions:this.addIdsToActionsAndAssertions(P),story:b,testGenerationData:S}}addIdsToActionsAndAssertions(u){return u.map((p,v)=>({...p,id:(0,trr.randomUUID)(),assertions:(p.assertions??[]).map(b=>({...b,id:(0,trr.randomUUID)()}))}))}async getInitialServicesDataByInternalTestId(){var b,S,T;if(((b=this.vtgTestFileRunConfig)==null?void 0:b.mode)!=="edit")return;let u=[];u=this.storageService.readJsonFile((S=this.vtgTestFileRunConfig)==null?void 0:S.actionsJsonFilePath),u=this.addIdsToActionsAndAssertions(u);let p=await this.apiService.post(`test-generation-by-internal-test-id/${(T=this.vtgTestFileRunConfig)==null?void 0:T.internalTestId}/info`);if(!p.ok)throw new Error(`Error fetching test generation data: ${p.statusText}`);let v=await p.json();return{actions:u,story:v.story,testGenerationData:v.testGenerationData}}setServicesData({actions:u,story:p,testGenerationData:v}){this.actionsManager.setActions(u),this.userStoryService.setStoryInfo(p,v),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=p.id}async start({createAssetsFolder:u=!0}={}){var b,S;(this.vtgMode==="start"||this.vtgTestFileMode)&&await this.userStoryService.fetchStory(this.storyId),u&&this.testAssetsManager.createTestGenerationAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(this.storyId);let{environment:p}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:p.baseURL,shutdown:!this.vtgTestFileMode}),await this.webDriver.addHARMockAPIRecordings(this.testAssetsManager.getHarFilePath()),await this.initTimeMachine(),this.pageInteractor.init(),this.assertionsService.setPage(this.webDriver.appMainFrame.page()),this.actionsService.setPage(this.webDriver.appMainFrame.page()),this.evaluatorService.setPage(this.webDriver.appMainFrame.page()),await this.taskTimeMachine.prepare(this.webDriver.appMainFrame,void 0,T=>this.webDriver.registerTimeMachineFrame(T)),await this.reactAppServer.start(),await this.reactAppServer.evaluateServerPort(this.webDriver.page);let v=(()=>{let T=this.config.environments.find(P=>P.name===p.name);return!T||!T.baseURL?"/":T.baseURL})();this.webDriver.appMainFrame?await this.webDriver.appMainFrame.goto(v,{waitUntil:"domcontentloaded",timeout:0}):bm.error("Iframe not found"),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction()),console.log("VTG is ready",(b=this.userStoryService.getStory())==null?void 0:b.goal),await this.webDriver.page.evaluate(({localSaveFolderPath:T,actions:P,appViewport:I,userStoryGoal:B})=>{window.vtg.initClient(T,P,I,this.checksumRuntimeVersion,B)},{localSaveFolderPath:this.editLocationPath,actions:this.actionsManager.actions,appViewport:this.webDriver.getApplicationViewport(),userStoryGoal:(S=this.userStoryService.getStory())==null?void 0:S.goal}),this.vtgTestFileMode||await new Promise(()=>{})}getTimeoutParams(){var v,b,S,T;let u=((b=(v=this.playwrightConfigForVTG)==null?void 0:v.use)==null?void 0:b.navigationTimeout)||3e4,p=((T=(S=this.playwrightConfigForVTG)==null?void 0:S.use)==null?void 0:T.actionTimeout)||5e3;return{navigationTimeout:u,actionTimeout:p}}getPlaywrightProxySettings(){var S,T;let u=(T=(S=this.playwrightConfigForVTG)==null?void 0:S.use)==null?void 0:T.proxy,{server:p,username:v,password:b}=u||{};if(v&&b&&p)return{username:v,password:b,server:p}}getPlaywrightViewportSettings(){var v,b;let{width:u=1280,height:p=720}=((b=(v=this.playwrightConfigForVTG)==null?void 0:v.use)==null?void 0:b.viewport)||{};return{width:u,height:p}}buildWebDriver(u){var b;let p=this.getPlaywrightProxySettings(),v=this.getPlaywrightViewportSettings();return new sgt({scriptSource:q7.checksumScript.source,scriptURL:q7.checksumScript.url,scriptFile:q7.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(b=this.config.environments.find(S=>S.default))==null?void 0:b.baseURL,useProxy:!!p,webProxy:p,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:q7.vtg.remoteDebugging},{devtools:!1,headless:!1},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:v},u)}async onWebDriverContextClose(){var u,p,v;this.evaluatorService.stopListening(),(u=this.vtgTestFileRunConfig)!=null&&u.evalFilePath&&(0,SJe.rmSync)((p=this.vtgTestFileRunConfig)==null?void 0:p.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,SJe.rmSync)((v=this.vtgTestFileRunConfig)==null?void 0:v.actionsJsonFilePath,{force:!0})}initVtgMode(u){var b;let p=u.indexOf("--edit"),v=u.indexOf("--cloud");if(u.indexOf("--test-file")!==-1){this.vtgTestFileMode=!0,this.vtgTestFileRunConfig=JSON.parse(process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG),this.vtgMode=this.vtgTestFileRunConfig.mode,this.storyId=((b=this.vtgTestFileRunConfig)==null?void 0:b.mode)==="start"?this.vtgTestFileRunConfig.storyId:void 0;return}p!==-1&&(this.vtgMode="edit",this.editLocationPath=u.at(p+1)),v!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=u.at(v+1)),this.vtgMode==="start"&&(this.storyId=u[0])}addLogFile(){let u=require("fs"),p=`${this.testAssetsManager.getLogsPath()}/vtg_${new Date().toISOString()}.log`;u.existsSync(this.testAssetsManager.getLogsPath())||u.mkdirSync(this.testAssetsManager.getLogsPath(),{recursive:!0}),bm.addLogListener({onLog:e((...v)=>{let b=v.map(S=>{if(typeof S=="object")try{return JSON.stringify(S,null,2)}catch{}return String(S)}).join(" ")+`
|
|
1453
|
-
`;try{u.appendFile(p,b,S=>{S&&console.error(S)})}catch{}},"onLog")})}async eval(u){return this.evaluatorService.listenForExecution(u)}};e(rrr,"VisualTestGenerator");var EJe=rrr;var nrr=class nrr extends zJ{constructor(u,p=!1){super(u,p);this.MAX_COMPLETION_WAIT=2*3600*1e3;this.TEST_RUN_MONITOR_PATH=(0,e0e.join)(__dirname,"test-run-monitor.js");this.didFail=!1;this.isolationMode=!1;this.trmMessagesBuffer="";this.completeIndicators={upload:!1,tests:!1,report:!1};this.uploadProgress=0}get replMode(){return this.getChecksumArg("repl")??!1}get vtgMode(){return this.getChecksumArg("vtg")??!1}get vtgEditMode(){return this.getChecksumArg("vtg-edit")??!1}async run(){var S;if(this.loadTracer(),this.loadChecksumData(),this.validateAuthExists(),!await this.getSession())return;this.trace.log(`Project root found at ${this.projectRootDirectory}`,`Checksum root found at ${this.checksumRoot}`);let u;try{u=await Hw(this.startTestRunMonitor(this.testSession),1e4,"test run monitor timeout")}catch{this.logAndTrace("Error starting test run monitor. Test results will not be available on checksum.","Test Run Monitor Error")}this.buildVolatileConfig();let p={CHECKSUM_ROOT_FOLDER:this.checksumRoot};u&&(p.CHECKSUM_UPLOAD_AGENT_PORT=u),this.config.options.hostReports&&(p.PW_TEST_HTML_REPORT_OPEN="never"),this.testSession&&this.testSession!=="isolated-session"&&(p.CHECKSUM_TEST_SUITE_ID=this.testSession),this.replMode&&(p.CHECKSUM_REPL="true"),(S=this.trace)!=null&&S.internalId&&(p.CHECKSUM_TRACE_INTERNAL_ID=this.trace.internalId),this.getChecksumArg("tm")&&(p.CHECKSUM_SHOW_TIME_MACHINE="true");let v=this.getNonChecksumArgs();if(this.vtgMode&&(p.CHECKSUM_VTG_TEST_FILE_MODE="true",this.vtgEditMode?p.CHECKSUM_VTG_TEST_FILE_EDIT_MODE="true":p.CHECKSUM_VTG_STORY_ID=v[v.length-1]),this.vtgMode){let T,P;if(this.vtgEditMode){T=v[v.length-1];let I=this.loadVtgTestFileMirror(T);this.createActionJsonFileForExistingChecksumSpec(I,T),this.createEvalFileForExistingChecksumSpec(I,T),P={mode:"edit",actionsJsonFilePath:this.getActionJsonFilePath(T),internalTestId:I.testMirrors[0].internalTestId,evalFilePath:this.getEvalFilePath(T),sourceFilePath:T}}else this.createEvalFileForNewChecksumSpec(),_gt.writeFileSync(this.getSavePathForNewChecksumSpec(),KYt({body:"",testFunctionParams:["page","vs"]})),P={mode:"start",sourceFilePath:this.getSavePathForNewChecksumSpec(),evalFilePath:this.getEvalFilePath(),storyId:v[v.length-1]};p.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG=JSON.stringify(P),v[v.length-1]=l7r(this.getEvalFilePath(this.vtgEditMode?T:void 0))}this.replMode&&v.push("--debug");let b=`npx playwright test --config "${this.getPlaywrightConfigFilePath()}" ${v.map(T=>`"${T}"`).join(" ")}`;
|
|
1453
|
+
`;try{u.appendFile(p,b,S=>{S&&console.error(S)})}catch{}},"onLog")})}async eval(u){return this.evaluatorService.listenForExecution(u)}};e(rrr,"VisualTestGenerator");var EJe=rrr;var nrr=class nrr extends zJ{constructor(u,p=!1){super(u,p);this.MAX_COMPLETION_WAIT=2*3600*1e3;this.TEST_RUN_MONITOR_PATH=(0,e0e.join)(__dirname,"test-run-monitor.js");this.didFail=!1;this.isolationMode=!1;this.trmMessagesBuffer="";this.completeIndicators={upload:!1,tests:!1,report:!1};this.uploadProgress=0}get replMode(){return this.getChecksumArg("repl")??!1}get vtgMode(){return this.getChecksumArg("vtg")??!1}get vtgEditMode(){return this.getChecksumArg("vtg-edit")??!1}async run(){var S;if(this.loadTracer(),this.loadChecksumData(),this.validateAuthExists(),!await this.getSession())return;this.trace.log(`Project root found at ${this.projectRootDirectory}`,`Checksum root found at ${this.checksumRoot}`);let u;try{u=await Hw(this.startTestRunMonitor(this.testSession),1e4,"test run monitor timeout")}catch{this.logAndTrace("Error starting test run monitor. Test results will not be available on checksum.","Test Run Monitor Error")}this.buildVolatileConfig();let p={CHECKSUM_ROOT_FOLDER:this.checksumRoot};u&&(p.CHECKSUM_UPLOAD_AGENT_PORT=u),this.config.options.hostReports&&(p.PW_TEST_HTML_REPORT_OPEN="never"),this.testSession&&this.testSession!=="isolated-session"&&(p.CHECKSUM_TEST_SUITE_ID=this.testSession),this.replMode&&(p.CHECKSUM_REPL="true"),(S=this.trace)!=null&&S.internalId&&(p.CHECKSUM_TRACE_INTERNAL_ID=this.trace.internalId),this.getChecksumArg("tm")&&(p.CHECKSUM_SHOW_TIME_MACHINE="true");let v=this.getNonChecksumArgs();if(this.vtgMode&&(p.CHECKSUM_VTG_TEST_FILE_MODE="true",this.vtgEditMode?p.CHECKSUM_VTG_TEST_FILE_EDIT_MODE="true":p.CHECKSUM_VTG_STORY_ID=v[v.length-1]),this.vtgMode){let T,P;if(this.vtgEditMode){T=v[v.length-1];let I=this.loadVtgTestFileMirror(T);this.createActionJsonFileForExistingChecksumSpec(I,T),this.createEvalFileForExistingChecksumSpec(I,T),P={mode:"edit",actionsJsonFilePath:this.getActionJsonFilePath(T),internalTestId:I.testMirrors[0].internalTestId,evalFilePath:this.getEvalFilePath(T),sourceFilePath:T}}else this.createEvalFileForNewChecksumSpec(),_gt.writeFileSync(this.getSavePathForNewChecksumSpec(),KYt({body:"",testFunctionParams:["page","vs"]})),P={mode:"start",sourceFilePath:this.getSavePathForNewChecksumSpec(),evalFilePath:this.getEvalFilePath(),storyId:v[v.length-1]};p.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG=JSON.stringify(P),v[v.length-1]=l7r(this.getEvalFilePath(this.vtgEditMode?T:void 0))}this.replMode&&v.push("--debug");let b=`npx playwright test --config "${this.getPlaywrightConfigFilePath()}" ${v.map(T=>`"${T}"`).join(" ")}`;await this.patchPlaywright();try{console.log(`Tests running with @checksum-ai/runtime version ${this.checksumRuntimeVersion}`),this.replMode?(console.log("Running in REPL mode"),this.execCmd(b,p),await this.execCmd(`node ${__dirname}/repl.js`,p)):(this.trace.testsStart(),await this.execCmd(b,p),this.trace.testsEnd()),console.log("Tests execution finished")}catch{this.didFail=!0,console.log("Error during test execution: Failed passing test"),this.trace.testsFailed()}finally{this.isolationMode||console.log("Waiting for test files to upload to Checksum..."),this.sendReportUploadRequest(),await this.patchPlaywright(!0),this.completeIndicators.tests=!0,await this.handleCompleteMessage()}}createEvalFileForExistingChecksumSpec(u,p){let v=new gTe(u.sourceFile);v.transformSourceFile([a7r(p),jmt(u.sourceFile,u.testMirrors.map(b=>b.testBody),Bmt(YYt),["page","vs","vtg"])]),v.write(this.getEvalFilePath(p))}loadVtgTestFileMirror(u){if(!u||!u.startsWith("/"))throw new Error("Currently vtg mode can only run with absolute path to file");let p=new Che(u);if(p.loadTestsFromFile(),p.testMirrors.length===0||p.testMirrors.length>1)throw new Error("Currently vtg mode can only run with a single test inside the test file");return p}createActionJsonFileForExistingChecksumSpec(u,p){let v=u.testMirrors[0].translateStatementsToActions(),b=this.getActionJsonFilePath(p);_gt.writeFileSync(b,JSON.stringify(v,null,2))}getSavePathForNewChecksumSpec(){return(0,e0e.join)(this.checksumRoot,"tests","test-TEMP.checksum.spec.ts")}createEvalFileForNewChecksumSpec(){let u=this.getEvalFilePath();_gt.writeFileSync(u,KYt({body:YYt,testFunctionParams:["page","vs","vtg"],importMode:"require",useLocalChecksumImport:!!process.env.DEV_MODE}))}getTempFolder(){let u=(0,e0e.join)(this.checksumRoot,"drafts","temp");return(0,CJe.existsSync)(u)||(0,CJe.mkdirSync)(u,{recursive:!0}),u}getActionJsonFilePath(u){let p=this.getFileName(u).replace(".spec.ts",".json");return(0,e0e.join)(this.getTempFolder(),p)}getFileName(u){return u.split("/").pop()}getEvalFilePath(u){let p=u?this.getFileName(u).replace(/(\.eval)?(\.checksum\.spec\.ts)$/,(v,b,S)=>b?S:".eval"+S):"test-TEMP.eval.checksum.spec.ts";return(0,e0e.join)(this.getTempFolder(),p)}getPlaywrightReportPath(){var v;let u=e(b=>(MN("Using report folder",b),(0,e0e.join)(b,"index.html")),"makeFilePath");if(process.env.PLAYWRIGHT_HTML_OUTPUT_DIR)return u(process.env.PLAYWRIGHT_HTML_OUTPUT_DIR);let p=(v=this.playwrightConfig)==null?void 0:v.reporter;if(p instanceof Array){let S=p.filter(T=>T instanceof Array&&T[0]==="html").find(T=>{var P;return(P=T[1])==null?void 0:P.outputFolder});if(S)return u((0,e0e.join)(this.checksumRoot,S[1].outputFolder))}return u((0,e0e.join)(this.projectRootDirectory,"playwright-report"))}sendReportUploadRequest(){let u=this.getPlaywrightReportPath();if(!(0,CJe.existsSync)(u)){this.logAndTrace(`Could not find report file at ${u}`,"Runtime Error"),this.completeIndicators.report=!0,this.testRunMonitorProcess.stdin.write("cli:report=false");return}MN("Sending report upload request",u),this.testRunMonitorProcess.stdin.write(`cli:report=${u}`)}startTestRunMonitor(u){return new Promise(p=>{console.log("Starting test run monitor"),this.testRunMonitorProcess=a9r.spawn("node",[this.TEST_RUN_MONITOR_PATH,JSON.stringify({sessionId:u,apiURL:this.config.apiURL,apiKey:this.config.apiKey}),...this.isolationMode?["isolated"]:[]]),this.testRunMonitorProcess.stdout.on("data",v=>{let b=this.parseTRMMessages(v.toString().trim());if(b.length){this.logTRMMessage(b);for(let S of b){if(S.startsWith("trace")&&this.handleTestRunMonitorTrace(S.substring("trace".length+1)),!S.startsWith("monitor"))continue;let T=S.substring("monitor".length+1),P=T.indexOf("=");if(P===-1){this.handleTestRunMonitorMessage(T,"");continue}let[I,B]=[T.substring(0,P),T.substring(P+1)];if(!Object.values(TVt).includes(I)){console.warn(`Unknown test run monitor message: ${I}`);continue}I==="port"?p(B):this.handleTestRunMonitorMessage(I,B)}}}),this.testRunMonitorProcess.on("exit",(v,b)=>{this.logAndTrace(`test run monitor process exited with code ${v} and signal ${b}`,"Test Run Monitor Error")}),this.testRunMonitorProcess.stderr.on("data",v=>{this.logAndTrace(`TRM Error: ${v.toString().substring(0,300)}`,"Test Run Monitor Error")}),this.testRunMonitorProcess.on("error",v=>{this.logAndTrace(`Error starting test run monitor: ${v.message}`,"Test Run Monitor Error")})})}parseTRMMessages(u){let p=this.trmMessagesBuffer+u,v,b,S=e(()=>{v=p.indexOf("{trm}"),b=p.indexOf("{/trm}")},"findIndexes");S();let T=[];for(;v!==-1&&b!==-1&&b>v;){if(T.push(p.substring(v+"{trm}".length,b)),p=p.slice(b+"{/trm}".length).trim(),p.length&&!p.startsWith("{trm}"))return console.warn("Buffered data does not start with start delimiter",p),this.trmMessagesBuffer="",T;this.trmMessagesBuffer=p,S()}return T}async handleTestRunMonitorTrace(u){let p=u.indexOf("="),[v,b]=p>-1?[u.substring(0,p),u.substring(p+1)]:[u,""];if(!Object.values(iTe).includes(v)){MN("Unknown trace event",v);return}try{let S=b?JSON.parse(b):{};switch(v){case"Upload Start":this.trace.uploadStart(S.filename);break;case"Upload Complete":this.trace.uploadComplete(S.filename);break;case"Upload Failed":this.trace.uploadFailed(S.filename,S.error);break}}catch(S){MN(`Error parsing trace payload, ${S.message}`)}}async handleTestRunMonitorMessage(u,p){switch(u){case"uploads-complete-with-errors":console.log("Error uploading test files to Checksum");try{let b=JSON.parse(p);this.trace.uploadsCompleteWithErrors(b)}catch{}this.sendProcessingError().then(()=>{this.completeIndicators.upload=!0});break;case"uploads-complete":this.isolationMode||console.log("Test files uploaded successfully"),this.trace.allUploadsComplete(),this.sendUploadsComplete().then(()=>{this.completeIndicators.upload=!0});break;case"report-complete":{if(this.isolationMode){this.completeIndicators.report=!0;break}let b=p.slice(0,p.indexOf(":"))==="true",S=p.slice(p.indexOf(":")+1),T={};try{S&&S.length>0?T=JSON.parse(S):MN("No stats received from test run monitor")}catch(P){this.logAndTrace(`Error parsing stats - ${P.message}`,"Runtime Error")}if(await this.sendTestRunEnd(T),this.completeIndicators.report=!0,b){let P=`${this.checksumAppUrl}/#/test-runs/${this.testSession}`,I=`Checksum report URL: ${P}`,B="*".repeat(I.length);console.log(`${B}
|
|
1454
1454
|
${I}
|
|
1455
1455
|
${B}`),this.trace.reportComplete(T,P)}else this.trace.event("Report Upload Error"),console.log("An error occurred while uploading the test report to Checksum");break}case"upload-progress":{if(this.isolationMode)break;let b=parseInt(p);(b<this.uploadProgress||b>=this.uploadProgress+10||b===100&&this.uploadProgress!==100)&&(this.uploadProgress=b,console.log(`[ Uploads progress: ${this.uploadProgress}% ]`))}break;case"log":console.log(p);break;case"trace":let v=p;if(!Object.values(iTe).includes(v))return;this.trace.event(v);break;case"playwrightConfig":try{this.playwrightConfig||(this.playwrightConfig=JSON.parse(p),this.trace.playwrightConfig(this.playwrightConfig))}catch(b){this.logAndTrace(`Error parsing playwright config - ${b.message}`,"Runtime Error")}break;default:this.logAndTrace(`Unhandled test run monitor message: ${u}=${p}`,"Runtime Error")}}async handleCompleteMessage(){let u=Date.now(),p=12;for(;;){if(Date.now()-u>this.MAX_COMPLETION_WAIT){console.log("Warning: Checksum wasn't able to upload all test assets or expected a file the couldn't be found. This might cause issues when viewing the report/trace."),this.trace.event("Runtime Timeout"),this.shutdown(1);return}if(Object.keys(this.completeIndicators).find(v=>!this.completeIndicators[v]))MN(this.completeIndicators),--p===0&&(this.trace.completionStatus(this.completeIndicators),p=12),await C3(5e3);else{this.trace.event("Runtime Complete"),console.log("Checksum test run complete"),await this.shutdown(this.didFail?1:0);return}}}async shutdown(u=0){await this.cleanup(),process.exit(u)}async cleanup(){var u,p;await super.cleanup(),(u=this.testRunMonitorProcess)==null||u.stdin.write("cli:shutdown"),(p=this.testRunMonitorProcess)==null||p.kill()}async getSession(){let u,p;try{if(!this.config.options.hostReports)return this.setIsolatedMode(),!0;if(p=this.config.apiKey,!p||p==="<API key>")return this.logAndTrace("No API key found in checksum config - please set it in the config file - checksum.config.ts","Checksum Config Error",!0),this.shutdown(1),!1;let v=await this.getEnvInfo(),b=JSON.stringify({...v,isHidden:!!this.config.options.hideReports}),S=await fetch(`${this.config.apiURL}/client-api/test-runs`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:p},body:b}),{uuid:T,appName:P}=await S.json();return this.testSession=T,v.commit=v.name,v.name=P,await this.trace.identify(this.testSession,{...v,company:P,apiKey:p}),!0}catch(v){return this.logAndTrace(`Error connecting to Checksum, the report will not be hosted - ${v.message}`,"Initialization Error"),this.setIsolatedMode(),!0}}setIsolatedMode(){this.isolationMode=!0,this.testSession="isolated-session",this.trace.setIsolatedMode()}async sendTestRunEnd(u){if(!this.isolationMode)try{let p="{}";try{p=JSON.stringify({...u,endedAt:Date.now()})}catch(v){this.logAndTrace(`Error stringifying stats ${v.message}`,"Runtime Error")}await this.updateTestRun(`${this.config.apiURL}/client-api/test-runs/${this.testSession}`,"PATCH",p)}catch(p){return this.logAndTrace(`Error sending test run end ${p.message}`,"Runtime Error"),null}}async sendUploadsComplete(){if(!this.isolationMode)try{await this.updateTestRun(`${this.config.apiURL}/client-api/test-runs/${this.testSession}/uploads-completed`,"PATCH")}catch(u){this.logAndTrace(`Error sending test run uploads complete - ${u.message}`,"Runtime Error")}}async sendProcessingError(){if(!this.isolationMode)try{await this.updateTestRun(`${this.config.apiURL}/client-api/test-runs/${this.testSession}/process-error`,"PATCH")}catch(u){this.logAndTrace(`Error sending test run processing error - ${u.message}`,"Runtime Error")}}async updateTestRun(u,p,v=void 0){let b=await fetch(u,{method:p,headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:v});return MN("Received update test run response from url:",u),await this.logApiResponse(b),b}async logApiResponse(u){try{if(!u.ok){let{status:v,statusText:b}=u,S=await u.text();this.trace.runtimeError({status:v,statusText:b,errorText:S});return}u.headers.get("Content-Type").includes("application/json")?u.json().then(v=>{MN("API Response:",v)}):u.text().then(v=>{MN("API Response:",v)})}catch(p){this.trace.eventWithMessage("Runtime Error",`Error logging API response - ${p.message}`)}}logTRMMessage(u){(Array.isArray(u)?u:[u]).forEach(p=>{MN("\x1B[33m","[trm]","\x1B[0m",p)})}};e(nrr,"TestsRunner");var mgt=nrr;var irr=class irr extends zJ{constructor(o,u=!1){super(o,u)}async run(o){switch(o){default:console.log(`
|
|
1456
1456
|
Checksum CLI
|
package/index.js
CHANGED
|
@@ -1414,9 +1414,9 @@ AFTER:
|
|
|
1414
1414
|
${x}`}};e(Sft,"StackTraceAnalysis");var Dft=Sft;var jJt=class jJt extends Z1e{constructor(){super(...arguments);this.API_BASE_ROUTE="/client-api/runtime/ai-fallback";this.CLIENT_MAX_ITERATIONS=10;this.thoughts=[];this.withChecksumAI=!1;this.executedSteps=[];this.stepsPayload=[];this.currentChecksumId="0";this.hasPreviousActionFailed=!1;this.canResolveAssertion=!0;this.finish=!1;this.actionsCounter=1;this.mockServer=!1;this.actionEventCodeToMethodName={click:"click",double_click:"dblclick",drag_and_drop:"dragTo",input:"fill",click_and_type:"fill",clear_and_type:"fill",hover:"hover",keystroke:"keyboard.press",navigation:"goto",check:"check",uncheck:"uncheck",selectoption:"selectOption",upload_files:"upload_files",get_more_items:"get_more_items",wait:"wait",switch_tab:"switch_tab",custom_code:"custom_code",logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss",login:"login"}}init(u){let{goal:p,apiKey:y,testId:x,apiURL:S,thoughts:C}=u;return this.goal=p,this.apiKey=y,this.testId=x,this.testSuiteId=process.env.CHECKSUM_TEST_SUITE_ID??"",this.thoughts=C,this.withChecksumAI=!1,this.testFile=u.testFile,S&&(this.API_BASE_DOMAIN=S.replace(/\/$/,"")),this}getRecoveryAttemptTitle(u){switch(u.type){case"action":return`Checksum auto-heal: trying to achieve action "${this.getFailedThought()}"...`;case"assertion":return`Checksum auto-heal: trying to verify assertion "${this.getFailedThought()}"...`}}async resolve(u){this.fallbackData=u,this.withChecksumAI=u.withChecksumAI;let p=this.getFailedThought();if(p!=="_fail_")try{if(await this.initSession(),!await this.iterate()){this.log("[AIFallback] AIFallback failed");return}return this.addAutoHealErrorToReport(u,p),{steps:this.executedSteps.map(x=>{switch(x.type){case"action":return this.translateExecutedActionToFallbackAction(x);case"assertion":return x}})}}catch(y){if(this.errorMessage=y.message,this.withChecksumAI&&y.message==="fetch failed")throw y;this.log("[AIFallback] Error",y);return}}addAutoHealErrorToReport(u,p){this.withChecksumAI||this.checksumPage.addErrorMessage(u.error,`"${p}" auto-healed:
|
|
1415
1415
|
${this.executedSteps.map(y=>{switch(y.type){case"action":return y.thought;case"assertion":return y.feedback}}).join(`,
|
|
1416
1416
|
`)}`)}async getReductionComponents(u){var p,y;return u.interruptionEvent==="didRequestMoreItemsEvent"?{reducedHTML:(y=(p=u.payload)==null?void 0:p.promptData)==null?void 0:y.reducedHTML,reducedDomHTMLElement:this.lastReducedDOM,flashingHTML:[],elementsForNodeInterpretation:[],currentChecksumId:this.currentChecksumId}:this.pageInteractor.getCurrentReducedHTML({stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:this.currentChecksumId})}getStackTrace(){return new Dft(this.fallbackData.error,this.testFile).analyze()}async getPageScreenshot(){try{return(await this.page.screenshot({fullPage:!0})).toString("base64")}catch{return}}async iterate(){var p,y;this.hasPreviousActionFailed=!1;let u=this.CLIENT_MAX_ITERATIONS;do{if(this.didCancel)return!1;let x=await this.getPreviousActionOverview(),{reducedHTML:S,flashingHTML:C,elementsForNodeInterpretation:P,currentChecksumId:F}=await this.getReductionComponents(x),B=await this.getPageScreenshot();this.lastReducedDOM=new zfr.JSDOM(S),this.currentChecksumId=F;let J=await this.getNextAction({reducedHTML:S,flashingHTML:C,elementsForNodeInterpretation:P,previousActionOverview:x,screenshot:B});if(this.didCancel)return!1;if(["failed","fail"].includes(J.thought)||["failed","fail"].includes((p=J.action)==null?void 0:p.type))return this.log("[AIFallback] Received failed signal, will quit"),this.errorMessage="Received failed signal",!1;if((J.changedVariables??[]).forEach(({name:z,value:Y})=>{this.checksumPage.variableStore.setVariable(z,Y)}),this.fallbackData.type==="assertion"){let z=J.thought;this.log(`[AIFallback] for assertion returned with value: ${J.action.value}, feedback: ${z}`);let Y=["irrelevant","pass","soft_reject"].includes(J.action.value);this.checksumPage.step(`AI: ${z}`,async()=>{}),this.executedSteps.push({type:"assertion",feedback:z,response:J.action.value});let le={feedback:z,response:J.action.value};return this.stepsPayload.push(le),this.trace.aiFallbackStep(this.sessionId,le),Y}if(J.thought==="finish"||((y=J.action)==null?void 0:y.type)==="finish")return this.log("[AIFallback] Received finish step"),!0;let W=await this.pageInteractor.translateActionResponseToAgentPotentialAction(J);try{try{await this.checksumPage.step(`AI: ${W.thought}`,async()=>{await this.pageInteractor.performAction(W)})}catch(z){throw this.fallbackData.error=z,new Error("Action failed")}this.hasPreviousActionFailed=!1,this.executedSteps.push({type:"action",...W}),this.addActionStepPayload(J,W),await f6(1e3)}catch(z){this.log("[AIFallback] Error while executing selector",z.message),this.hasPreviousActionFailed=!0;continue}if(--u<=0){this.errorMessage="maximum repetition reached",this.log(`[AIFallback] ${this.errorMessage}`);break}}while(!0);return!1}addActionStepPayload(u,p){let{thought:y,action:{checksumid:x,type:S}}=u,{selector:C,locator:P,fillValue:F,getMoreItemsId:B}=p,J={thought:y,checksumid:x,type:S,selector:C,locator:P,fillValue:F,getMoreItemsId:B};this.stepsPayload.push(J),this.trace.aiFallbackStep(this.sessionId,J)}async getNextAction({reducedHTML:u,flashingHTML:p,elementsForNodeInterpretation:y,previousActionOverview:x,screenshot:S,codeTrace:C}){let{apiKey:P}=this;if(this.mockServer)return this.finish?{thought:"finish"}:(--this.actionsCounter===0&&(this.finish=!0),{thought:"mock-thought",action:{type:"click",checksumid:"10"}});let F={reduction:{reducedHTML:u,flashingHTML:p,elementsForNodeInterpretation:y},currentURL:this.page.url(),previousActionOverview:x,resolvesSmartAssertion:this.withChecksumAI,variables:this.variables,screenshot:S};try{let J=await(await fetch(`${this.getAPIBaseURL()}/iterate`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify({appName:P,sessionId:this.sessionId,iterationData:F})})).json();return this.log("[AIFallback] Received next action",J),J}catch(B){throw this.log("[AIFallback] Error calling iterate",B),B}}async getPreviousActionOverview(){let u=await this.pageInteractor.handleFileChooserEvent();return{success:!this.hasPreviousActionFailed,...this.hasPreviousActionFailed?{failureEvent:"generalExecutionFailureError"}:{},...this.getPreviousWaitActionOverview(),...u,...await this.getPreviousGetMoreItemsActionOverview()}}getExecutedActions(){return this.executedSteps.filter(u=>u.type==="action")}async getPreviousGetMoreItemsActionOverview(){let u=this.getExecutedActions(),p=u[u.length-1];if((p==null?void 0:p.eventCode)!=="get_more_items"||!this.lastReducedDOM)return{};try{return await this.pageInteractor.addMoreItemsToDom(this.lastReducedDOM.window.document.body,p.getMoreItemsId),{interruptionEvent:"didRequestMoreItemsEvent",payload:{promptData:{reducedHTML:this.lastReducedDOM.serialize()},getMoreItemsId:p.getMoreItemsId}}}catch{return{}}}getPreviousWaitActionOverview(){var y;let u=this.getExecutedActions();if(((y=u[u.length-1])==null?void 0:y.eventCode)!=="wait")return{};let p=0;return u.slice().reverse().every(x=>x.eventCode==="wait"?(p++,!0):!1,0),{payload:{waitCount:p}}}async initSession(){let{apiKey:u,goal:p,thoughts:y}=this;if(this.log("[AIFallback] Calling init session...",{appName:u,goal:p,thoughts:y}),!u){let C="Missing Checksum API key, will not run AI fallback";throw lJt(C),new Error(C)}if(this.mockServer){this.sessionId="mock-session-id";return}let x=this.getStackTrace();if(!x)throw new Error("Failed to get code trace");let S={type:this.fallbackData.type,resolveSmartAssertion:this.withChecksumAI,storyTitle:p,testSuiteId:this.testSuiteId,testId:this.testId,thoughtsAndActions:{previous:y.slice(0,Math.max(y.length-1,0)).map(C=>({thought:C})),failing:{thought:y[y.length-1]},next:[]},codeTrace:x};try{let C=await fetch(`${this.getAPIBaseURL()}/init`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify({appName:u,data:S})});this.sessionId=await C.text(),this.log("[AIFallback] Session ID",this.sessionId)}catch(C){throw this.withChecksumAI&&C.message==="fetch failed"&&(this.checksumPage.step(Q1e,async()=>{throw new Error(Q1e)}),lJt(Q1e)),this.log("[AIFallback] Error calling init session",C),C}}translateExecutedActionToFallbackAction(u){return{type:"action",esraMetadata:u.esraMetadata,generatedLocator:u.locator,selector:u.selector,parentFramesSelectors:u.parentFramesSelectors,method:this.getMethodForPotentialAction(u),thought:u.thought}}getMethodForPotentialAction(u){return{name:this.actionEventCodeToMethodName[u.eventCode],args:e(()=>{switch(u.eventCode){case"click":case"double_click":return[{position:u.clickOffset}];case"drag_and_drop":return[this.pageInteractor.makeLocator(u.dropTarget.selector,u.dropTarget.parentFramesSelectors)];case"input":case"click_and_type":case"clear_and_type":case"selectoption":case"keystroke":case"navigation":return[this.pageInteractor.getActionFillValue(u,!1)];case"upload_files":return u.files;default:return}},"makeArgs")()}}getAPIBaseURL(){return this.API_BASE_DOMAIN+this.API_BASE_ROUTE}getAnalyticsPayload(){return{fallbackType:"ai",error:this.errorMessage,thought:this.getFailedThought(),sessionId:this.sessionId,steps:this.stepsPayload.map(u=>JSON.stringify(u))}}getFailedThought(){return this.thoughts[this.thoughts.length-1]}toString(){return`Checksum AI ("${this.getFailedThought()}")`}};e(jJt,"AIFallback");var nhe=jJt;var Eq=require("fs");var Ehr=Xv(kWt());var rhr=!1,FWt=class FWt{constructor(o,u,p,y){this.page=o;this.checksumPage=u;this.executeLocatorAction=p;this.base=y;this.LOCATORS_TIMEOUT=rhr?9999999:5e3;this.HANDLES_TIMEOUT=rhr?9999999:5e3;this.HANDLES_INTERVAL=300;this.locatorsChain=[];this.base||(this.base=this.page)}setBase(o){this.base=o}init(...o){return this.sanitizeArgs(...o),new Proxy(this,{get:e((u,p)=>p==="setBase"?function(...y){this.setBase(y[0])}.bind(this):this.handleLocatorChain(u,p),"get")})}getLocatorSelector(o){if(o)return o._selector}sanitizeArgs(...o){if(o.length===1&&typeof o[0]=="object"){if(!o[0].anchors||typeof o[0].anchors!="function")throw new Error("Invalid compound selector format. Object must contain anchors property with a method value");this.anchorLocatorMethod=o[0].anchors,this.targetLocatorMethod=o[0].target;return}if(typeof o[0]!="function")throw new Error("Invalid compound selector format. First argument must be an object or a function");if(this.anchorLocatorMethod=o[0],o.length===2){if(typeof o[1]!="function")throw new Error("Invalid compound selector format. Second argument must be a function");this.targetLocatorMethod=o[1]}}async resolveLocator(){if(this.resolvedLocator)return this.resolvedLocator;Db("Waiting for locators..");let o=this.getLocatorsFromMethods();try{await Promise.all(o.map(async C=>m5(C.first().waitFor({bypassChecksum:!0}),this.LOCATORS_TIMEOUT,"Waiting for compound selector locators timeout")))}catch(C){throw new Error(`Error while waiting for locators - ${C.message}`)}let u=await m5(this.getElementHandles(o),this.HANDLES_TIMEOUT);Db(`Resolved to ${PWt(u)} elements from ${o.length} locators`);let p=this.getLocatorSelector(this.getLocatorsFromMethods(!1,!0,this.page)[0]),y=await this.checksumPage.evaluateWithChecksum(async({handles:C,targetSelector:P})=>window.checksum.testGenerator.getCompoundSelector().select(C,P),{handles:u,targetSelector:p});if(!y||y.length===0)throw new Error("Could not generate selectors from handles");Db(`Resolved compound selector to ${y.length} selectors`);let x=this.getBase(),S=x.locator(y[0]);return y.slice(1,50).forEach(C=>{S=S.or(x.locator(C))}),this.locatorsChain.length&&this.locatorsChain.forEach(({name:C,args:P})=>{S=S[C](...P)}),Db(`Compound locator selector: ${this.getLocatorSelector(S)}`),this.resolvedLocator=S,S}handleLocatorChain(o,u){if(typeof u=="symbol")return;if(u==="constructor")return e(function(...S){return this[u](...S)},"Locator");if(u==="toString")return()=>this.toString();let p=e(()=>new Proxy(o,{get:e((x,S)=>x.handleLocatorChain(x,S),"get")}),"createLocatorProxy");return u==="valueOf"?e(function(){return p()},"Locator"):Object.values([...Object.values(Q5e),...Object.values(Z5e)]).includes(u)?e(function(...S){return o.locatorsChain.push({name:u,args:S}),p()},"Locator"):e(async function(...S){return this.handleAction(u,S)},"Locator").bind(this)}async handleAction(o,u){try{if(typeof o=="symbol")return;if(!this.anchorLocatorMethod)throw new Error("Compound selection is missing anchor locators");let p=await this.resolveLocator();return await this.executeLocatorAction(p,o,u)}catch(p){throw Db(`Failed to execute compound selection action: ${p}`),this.checksumPage.analytics.compoundSelectionFailure(p.toString(),this.toString()),p}}async getElementHandles(o){Db("Resolving compound selector elements");let u,p,y,x,S,C=e(()=>{S=2},"resetSameHandlesCount");do u=p,p=[],await Promise.all(o.map(async P=>{let F=await P.elementHandles({bypassChecksum:!0});if(F.length===0)throw new Error(`No elements found for locator: ${this.getLocatorSelector(P)}`);p.push(F)})),y=PWt(p),x=u?PWt(u):0,Db(`Handles itteration, previous: ${u?x:"-"}, current: ${y}`),x!==y&&C(),await f6(this.HANDLES_INTERVAL);while(!u||x!==y||--S>0);return p}getLocatorsFromMethods(o=!0,u=!0,p=this.getBase()){return(o?this.anchorLocatorMethod(p):[]).concat(u&&this.targetLocatorMethod?[this.targetLocatorMethod(p)]:[]).map(y=>typeof y=="string"?p.getByText(y):y)}getBase(){return this.base}toString(){var o;return`CompoundSelection(${this.resolvedLocator?this.getLocatorSelector(this.resolvedLocator):`${this.anchorLocatorMethod.toString()}, ${(o=this.targetLocatorMethod)==null?void 0:o.toString()})`})`}};e(FWt,"CompoundSelectorLocator");var gdt=FWt,PWt=e(s=>s.reduce((o,u)=>o+u.length,0),"countHandleElements");var NWt=class NWt extends ehe{constructor(){super(...arguments);this.timeout=5*1e3}init(u){return super.init(u),this}async resolve(u){try{let{method:p,args:y}=u,{checksumId:x}=this.data,S;try{let j=await this.getMetadataForTestId();if(!(x in j)||!j[x].compoundSelector)throw new Error(`No compound selection metadata found for id ${x}`);S=j[x].compoundSelector}catch(j){super.log("Could not read compound selector metadata file, ",j)}let C=await this.generateCompoundSelector(S);if(!(C!=null&&C.length))throw new Error("No compound locators found");let P=C[0],F=this.pageInteractor.makeLocator(P.selector),B=S.targetSelection.featuresMetadata.tag,J=["check","uncheck"].includes(p)&&B!=="input"?"click":p;try{await this.checksumPage.wrapNoLocationSteps(async()=>this.execute(F,J,y));let j={selector:P.selector,generatedLocator:P.locator,esraMetadata:void 0};return this.sendLog(j),this.checksumPage.addErrorMessage(u.error,`${this.thought?`"${this.thought}" auto-healed`:"Auto-healed"} using alternative selector "${P.selector}"`),{steps:[{type:"action",...j}]}}catch(j){throw new Error(`Failed to execute compound selection fallback action: ${j.message}`)}}catch(p){this.errorMessage=p.message,this.log(p.message);return}}async generateCompoundSelector(u){let p=await this.evaluateWithChecksum(async y=>{var S;return await((S=window.checksum)==null?void 0:S.testGenerator.getCompoundSelector().selectFromMetadata(y))},u);return super.log("Resolved compound selector fallback to",p),p}getAnalyticsPayload(){return{fallbackType:"compound-selector",...this.logPayload??{checksumId:this.data.checksumId,error:this.errorMessage}}}toString(){return`Checksum compound selector fallback (${this.data.checksumId})`}};e(NWt,"CompoundSelectorFallback");var EUe=NWt;var ihr=Xv(nhr());var LWt=class LWt{constructor(o){this.toJSON=e(()=>this.data,"toJSON");this.data=o}getSimilar(o){let u=null,p=-1/0;for(let y of Object.keys(this.data)){let x=(0,ihr.levenshtein)([...o],[...y]);x>p&&(p=x,u=y)}return u?this.data[u]:null}};e(LWt,"SimilarityRecord");var OWt=LWt,mhe=class mhe extends OWt{constructor(o){super(mhe.preprocessRectangles(o))}getRectangleByTextAndSizeRanking(o,u){u=!u||!Number(u)?0:Number(u);let p=this.getSimilar(o);if(!p||p.length===0)return null;let y=Math.min(Math.max(u,0),p.length-1);return p[y]}};e(mhe,"RectangleIndex"),mhe.preprocessRectangles=e(o=>{let u=[...new Map([...o].map(y=>[JSON.stringify(y.vertices),y])).values()],p={};return u.forEach(y=>{p[y.text]||(p[y.text]=[]),p[y.text].push(y),p[y.text].sort((x,S)=>{let C=mhe.calculateArea(x.vertices),P=mhe.calculateArea(S.vertices);return C-P})}),p},"preprocessRectangles"),mhe.calculateArea=e(o=>{let u=Math.abs(o[1].x-o[0].x),p=Math.abs(o[3].y-o[0].y);return u*p},"calculateArea");var vdt=mhe;var phr=require("fs"),fhr=require("path");function cL(s){return s._guid}e(cL,"getPageOrFrameGuid");async function xdt(s,o,u){let p=s,y=p._mainFrame;try{p._mainFrame=o,await u(p)}finally{p._mainFrame=y}}e(xdt,"executeOnPageWithFrame");var ahr={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html"},RWt={click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",upload_files:"upload_files",wait:"wait",get_more_items:"get_more_items",reset:void 0,save:void 0,fail:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0,logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss"},shr=Object.fromEntries(Object.entries(RWt).map(s=>s.reverse())),MWt={goto:"navigation",click:"click",dblclick:"double_click",dragTo:"drag_and_drop",check:"check",uncheck:"uncheck",fill:"input",hover:"hover",selectOption:"selectoption",waitForTimeout:"wait","keyboard.press":"keystroke",setInputFiles:"upload_files",getPage:"switch_tab",reauthenticate:"logout_and_login",canvasClick:"canvas_click"},ohr=Object.fromEntries(Object.entries(MWt).map(s=>s.reverse()));var uhr={input:[1,2],selectoption:[1,2],keystroke:[1,2],wait:[1,2],navigation:[1,2],click:[0,1],double_click:[0,1],drag_and_drop:[1,2],upload_files:[1,2],canvas_click:[1,2],logout_and_login:[1],login:[1,2],click_and_type:[1,2],clear_and_type:[1,2],check:[0,1],uncheck:[0,1],hover:[0,1]},RCe={input:1,selectoption:1,keystroke:1,wait:-1,navigation:1,click:0,double_click:0,drag_and_drop:1,upload_files:1,canvas_click:-1,logout_and_login:-1,login:1,click_and_type:0,clear_and_type:0,check:0,uncheck:0,hover:0,native_accept:-1,native_dismiss:-1};var Gan=e(s=>s.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\${/g,"\\${"),"escapeStringForTemplateLiteral"),chr="variableStore",hhe=chr+".",lhr=e((s,{alwaysIncludeInitializationLine:o=!1,onlyValueExpression:u=!1}={})=>[o?`const ${chr} = {};`:"",...s.map(({name:y,value:x,valueExpression:S})=>{let C=typeof x=="string"&&!u?`\`${Gan(x)}\``:S;return`${hhe}${y} = ${C};`})].join(`
|
|
1417
|
-
`),"variablesToString");var Kan=!0,_TestGenerationPageInteractor=class _TestGenerationPageInteractor{constructor(s,o,u,p,y,x,S){this.evaluateWithChecksum=s;this.getFrame=o;this.getTimeMachine=u;this.logger=p;this.options=y;this.pageInteractorAPI=x;this.loginFunction=S;this.activeDialog=null;this.newPagesIds=[];this.listeners={dialog:null,filechooser:null,page:null};this.listenToContextPage=e(()=>{this.getPage().context().on("page",s=>{this.newPagesIds.push(s._guid)})},"listenToContextPage");this.listenToFileChooser=e(()=>{this.listeners.filechooser=async s=>{this.logger.log("File chooser event detected"),this.fileChooser=s},this.getPage().on("filechooser",this.listeners.filechooser)},"listenToFileChooser");this.waitForDialog=e((s=!0,o=1e4)=>new Promise(u=>{let y=0,x=e(()=>{if(this.activeDialog){let S=this.activeDialog;s&&(this.activeDialog=null),u(S)}else y>=o?u(null):(y+=1e3,setTimeout(x,1e3))},"checkDialog");x()}),"waitForDialog");this.performFileUploadAction=e(async(s,o)=>{if(!await s.evaluate(p=>p.tagName==="INPUT"&&p.getAttribute("type")==="file"))throw new Error("File upload action performed on non-file input element");let u=o.files.map(p=>(0,fhr.join)(this.options.testAssetsDir,p)).filter(p=>(0,phr.existsSync)(p)?!0:(this.logger.log(`Upload file not found: ${p}. Filtering out.`),!1));if(!u.length)throw new Error("No files to upload");await this.actionGuardReturn(s.setInputFiles(u),"Set input files timeout")},"performFileUploadAction");this.getSelectionDataForAction=e(async(s,o)=>s.checksumid?this.getSelectionDataForChecksumId(s.checksumid,o):s.position?await this.evaluateWithChecksum(async([u,p])=>window.checksum.testGenerator.getSelectorByPosition(u,p),[s.position.x,s.position.y]):s.selector?{selector:s.selector,locator:`locator("${s.selector}")`}:{selector:"",locator:""},"getSelectionDataForAction")}getPage(){return this.getFrame().page()}init(){this.listenToContextPage(),this.options.listenToFileChooser!==!1&&this.listenToFileChooser(),this.options.listenToDialog&&this.listenToDialog()}listenToDialog(){this.listeners.dialog=async s=>{this.activeDialog=s},this.getPage().on("dialog",this.listeners.dialog)}removeListener(s){try{switch(s){case"dialog":this.listeners.dialog&&(this.getPage().removeListener(s,this.listeners.dialog),this.listeners.dialog=null);break;case"filechooser":this.getPage().off(s,this.listeners.filechooser),this.listeners.filechooser=null;break;case"page":this.getPage().context().off(s,this.listeners.page),this.listeners.page=null;break}}catch(o){this.logger.logError(`Error removing listener: ${s}`,o)}}getOpenedFileChooser(){if(this.fileChooser){let s=this.fileChooser;return this.fileChooser=void 0,s}return null}async handleFileChooserEvent(s=[]){let o=this.getOpenedFileChooser();if(!o)return{};let u="fc_"+Math.random().toString(36).slice(2,4);return await this.evaluateWithChecksum(async([p,y])=>{window.checksum.testGenerator.addForceIncludeElement(y,p)},[u,o.element()]),{interruptionEvent:"fileUploadOpenedEvent",payload:{checksumid:u,customFiles:s}}}async addMoreItemsToDom(s,o){let u=s.querySelector(`[checksum-get-more-items='${o}']`);if(!u)throw new Error("Get more items root not found");let{items:p,hasMoreItems:y}=await this.getMoreItemsForTemplate(o);u.innerHTML=u.innerHTML+p,y||u.removeAttribute("checksum-get-more-items")}async getPageInfo(s){let o=cL(s);return{id:o,url:s.url(),title:await s.title(),new:this.newPagesIds.includes(o),active:o===cL(this.getPage())}}async getTabsInfo(){var p;let s=this.getPage(),o=await Promise.all(s.context().pages().map(y=>this.getPageInfo(y))),u=(p=this.getTimeMachine())==null?void 0:p.getPage();return u&&u!==s&&(o=o.filter(y=>y.id!==cL(u))),this.newPagesIds=[],o}async getSelectionDataFromSelectorGenerator(s,o,u={}){if(u={useCompoundSelector:!0,useCSSExtraction:!0,useVariables:!0,useArbitrarySelector:!0,...u},!s||!aJt(Q0r(o.action.type))||!o.action.checksumid)return{};let p=await s.generateSelectionForAction(o,u);return p?{locator:`locator("${p.selector}")`,...p}:{}}async translateActionResponseToAgentPotentialAction(s,o=void 0,{pageId:u,makeStaticMetadataForESRA:p}={}){let y=structuredClone(s.actionHiddenOverride??s.action),{selector:x,selectorWithVars:S,locator:C,locatorWithVars:P,clickOffset:F,selectOptionValue:B,compoundSelector:J,alternateLocators:j,parentFramesSelectors:W}={...await this.getSelectionDataForAction(y,s.actionHiddenOverride),...await this.getSelectionDataFromSelectorGenerator(o,s)},z=await this.getESRAForSelector(x,W,p);if(!z&&x&&this.logger.logError("Error getting ESRA metadata"),(z==null?void 0:z.tag)==="select")switch(this.getActionEventCode(y.type)){case"input":y.type="selectoption";break;case"click":B&&(y.type="selectoption",y.value=B);break}let Y={eventCode:this.getActionEventCode(y.type),selector:x,selectorWithVars:S,parentFramesSelectors:W,locator:C,locatorWithVars:P,clickOffset:F,pageId:u,compoundSelector:J,alternateLocators:j,fillValue:y.value,fillValueName:y.valueName?`${hhe}${y.valueName}`:"",variables:s.variables,getMoreItemsId:y.getMoreItemsId,esraMetadata:z,thought:s.thought,userRole:y.userRole,canvas:y.canvas,id:y.id};switch(Y.eventCode){case"drag_and_drop":{let{selector:le,selectorWithVars:ye,locator:ve,locatorWithVars:Ie,parentFramesSelectors:Be}={...await this.getSelectionDataForAction({type:s.action.type,checksumid:s.action.dropTargetChecksumid}),...await this.getSelectionDataFromSelectorGenerator(o,{...s,action:{type:s.action.type,checksumid:s.action.dropTargetChecksumid}},{useCompoundSelector:!1})};Y.dropTarget={selector:le,locator:ve,parentFramesSelectors:Be,esraMetadata:await this.getESRAForSelector(le,Be,p)}}break;case"upload_files":Y.files=this.mapFileMIMETypeToFilename(y.files);break;case"switch_tab":{let le=this.getPage();Y.switchToTab={id:y.tabId,index:le.context().pages().findIndex(ye=>cL(ye)===y.tabId)};break}case"keystroke":Y.fillValue=y.value}return Y}async reauthenticate(s){let o=this.getPage();this.loginFunction&&(await Promise.all([o.context().clearCookies(),o.evaluate(()=>localStorage.clear())]),await this.loginFunction(o,{role:s}))}mapFileMIMETypeToFilename(s){return s.map(o=>{if(o.fileName)return o.fileName;switch(o.mimeType){case"image/png":return"image_200x200.png";case"image/jpeg":return"image_200x200.jpg";case"application/pdf":return"document.pdf";case"text/csv":return"data.csv";default:return"file.txt"}})}async performAction(s,{useLocator:o=!1,handleActionFailed:u,monitorFlashingHTML:p=!0,timeout:y,allowForceClick:x=!0}={}){try{if(s.executed){this.logger.log("[performAction] Action marked as executed, skipping...");return}let S=o?!!s.locator:!!s.selector;if(aJt(s.eventCode)&&!S)throw new Error("No selector provided for action. Try changing app rules preMapReducedHTMLSelectors to true");p&&(this.logger.log("starting flashing elements detection"),await this.evaluateWithChecksum(async()=>window.checksum.testGenerator.startFlashingElementsDetection())),this.logger.log(`Performing action: ${s.eventCode}. Selector: ${s.selector}, Position: ${s.clickOffset}, Parent frame: ${s.parentFramesSelectors}`);let C=e(()=>o?this.makeLocatorFromLocator(s.locator):this.makeLocator(s.selector,s.parentFramesSelectors),"getLocator"),P=e(async(F,B,J={})=>this.actionGuardReturn(F,B,{timeout:y,...J}),"performWithActionGuard");switch(s.eventCode){case"click":try{await P(C().click({position:s.clickOffset,timeout:y??this.options.actionTimeout}),"Click timeout")}catch(F){if(!x)throw F;this.logger.log("Error performing click, will attempt a force click",F.message),s.force=!0,await P(C().click({position:s.clickOffset,force:!0,timeout:y??this.options.actionTimeout}),"Force Click timeout")}break;case"double_click":try{await P(C().dblclick({position:s.clickOffset,timeout:y??this.options.actionTimeout}),"DoubleClick timeout")}catch(F){if(!x)throw F;this.logger.log("Error performing double click, will attempt a force double click",F),s.force=!0,await P(C().dblclick({position:s.clickOffset,timeout:y??this.options.actionTimeout,force:!0}),"Force DoubleClick timeout")}break;case"check":await P(C().check({timeout:y??this.options.actionTimeout}),"Check timeout");break;case"uncheck":await P(C().uncheck({timeout:y??this.options.actionTimeout}),"UnCheck timeout");break;case"drag_and_drop":await P(C().dragTo(o?this.makeLocatorFromLocator(s.dropTarget.locator):this.makeLocator(s.dropTarget.selector,s.dropTarget.parentFramesSelectors),{timeout:y??this.options.actionTimeout}),"DragAndDrop timeout");break;case"input":await P(C().fill(this.getActionFillValue(s),{timeout:y??this.options.actionTimeout}),"Fill timeout");break;case"click_and_type":await m5(C().click({position:s.clickOffset,timeout:y??this.options.actionTimeout}),1e4,"Click before type timeout"),await m5(C().pressSequentially(this.getActionFillValue(s),{timeout:y??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"clear_and_type":await m5(C().clear({timeout:y??this.options.actionTimeout}),1e4,"Clear before type timeout"),await m5(C().pressSequentially(this.getActionFillValue(s),{timeout:y??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"selectoption":await P(C().selectOption(this.getActionFillValue(s),{timeout:y??this.options.actionTimeout}),"SelectOption timeout");break;case"hover":await P(C().hover({timeout:y??this.options.actionTimeout}),"Hover timeout");break;case"navigation":await P(this.getFrame().goto(s.fillValue,{timeout:y??this.options.navigationTimeout}),"Navigation timeout",{isNavigation:!0});break;case"keystroke":{let F=this.getPage();await P(F.keyboard.press(s.fillValue),"Keystroke timeout");break}case"upload_files":await this.performFileUploadAction(C(),s);break;case"wait":await f6(this.options.waitActionDelay??1e3);break;case"custom_code":await xdt(this.getPage(),this.getFrame(),async F=>{let B=`async (page) => {${s.fillValue}}`;await(0,eval)(B)(F)});break;case"logout_and_login":await this.reauthenticate(s.userRole);break;case"canvas_click":await this.canvasClick(C(),s.canvas);break}}catch(S){throw this.logger.log(`Error performing action: ${s.eventCode}, will attempt a correction template`,S),await(u==null?void 0:u()),S}this.logger.log(`Successfully performed action ${s.eventCode} with description "${s.thought}"`)}async getTextDetection(s){return new vdt(await this.pageInteractorAPI.getTextDetection(s))}async canvasClick(s,o){try{if(!await s.evaluate(x=>x.tagName.toLowerCase()==="canvas"))throw new Error("Click attempted on a non-canvas element");let y=(await this.getTextDetection(await s.screenshot())).getRectangleByTextAndSizeRanking(o.canvasText,o.rectSizeIndex);if(!y)throw new Error(`Canvas click target not found for ${o.canvasText}`);this.logger.log(`Canvas click target: ${y}`),await this.actionGuardReturn(s.click({position:y.center}),"Canvas click could not be performed")}catch(u){throw this.logger.logError("Canvas click:",u.message),new Error("Canvas click action failed")}}getActionFillValue(s,o=!0){let u=s.fillValue;if(!u){let p=s.selector.match(/(?<=value.*)('|").*/);p&&(u=p[0].slice(1,-1))}return typeof u!="string"&&(u="X"),o&&(s.fillValue=u),u}actionGuardReturn(s,o,{isNavigation:u=!1,timeout:p}={}){return m5(s,p??(u?this.options.navigationTimeout:this.options.actionTimeout),o)}makeLocator(s,o=[]){return pJt(this.getFrame(),s,o)}makeLocatorFromLocator(locator){return eval("this.getFrame()."+locator)}getCurrentURL(){return this.getFrame().url()}async getSelectionDataForChecksumId(s,o){if(o!=null&&o.selector)return{...o,selector:o.selector,locator:o.locator,clickOffset:o.position};if(!s)return this.logger.log(`[getSelectionDataForChecksumId] checksumid not provided (${s})`),{...o,selector:s,locator:`locator("${s}")`};let u=await this.evaluateWithChecksum(async p=>{let{selector:y,locator:x,clickOffset:S,parentFramesSelectors:C,invalid:P,rrwebId:F}=await window.checksum.testGenerator.getSelectorForChecksumId(p),B=await window.checksum.testGenerator.getElementForChecksumId(p),J=B instanceof HTMLOptionElement&&B.value?B.value:void 0;return{selector:y,locator:x,clickOffset:S,selectOptionValue:J,parentFramesSelectors:C,invalid:P,rrwebId:F}},s);if(Kan&&u.invalid&&u.rrwebId){this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${s}. Trying to use time machine...`);try{let p=await this.getSelectionDataForRRwebIdAtReduceHTMLTime(u.rrwebId);u={...u,...p}}catch{this.logger.log(`[getSelectionDataForChecksumId] error using time machine to get selector for checksumid: ${s}`)}this.logger.log(`[getSelectionDataForChecksumId] got selector: ${u.selector} for checksumid: ${s} from time machine`)}return u!=null&&u.selector||this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${s}. If checksumid is correct, try to change app rules preMapReducedHTMLSelectors to true`),u}async getSelectionDataForRRwebIdAtReduceHTMLTime(s){if(!this.rrwebEventAtLastReducedHTML)return;let o=this.getTimeMachine();if(o)return o.executeTask(u=>u.evaluate(async({rrwebId:p})=>await window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(p,{ignoredIframesSelectors:[".replayer-wrapper > iframe"],fromTimeMachine:!0}),{rrwebId:s}),this.rrwebEventAtLastReducedHTML.timestamp,{name:"getSelectionDataForRRwebIdAtReduceHTMLTime"})}async getESRAForSelector(s,o,u){let p=await this.evaluateWithChecksum(async({selector:y,parentFramesSelectors:x})=>window.checksum.testGenerator.getSelectionDataForSelector(y,x),{selector:s,parentFramesSelectors:o});return p!=null&&p.esraMetadata&&u&&(p.esraMetadata.staticMetadata=await u(p.esraMetadata,s)),p==null?void 0:p.esraMetadata}async getMoreItemsForTemplate(s){return await this.evaluateWithChecksum(async o=>window.checksum.testGenerator.getMoreItemsForTemplate(o,{}),s)??{items:"",hasMoreItems:!1}}async getCurrentReducedHTML({retriesLeft:s=3,retryWaitMS:o=2e3,initialChecksumId:u="0",extractESRAForInterpretationRequiredElements:p=!1,stopFlashingElementsDetection:y=!1,assignChecksumIdsToAllElements:x}={}){let S=new Date;this.logger.log("[getCurrentReducedHTML] Fetching reduced HTML...");try{let{reducedHTML:C,currentChecksumId:P,flashingHTML:F,elementsForNodeInterpretation:B,lastRRwebEvent:J}=await this.evaluateWithChecksum(async W=>window.checksum.testGenerator.reduceHTML({},W),{initialChecksumId:u,extractESRAForInterpretationRequiredElements:p,stopFlashingElementsDetection:y,assignChecksumIdsToAllElements:x}),j=new Date;return this.logger.log(`[getCurrentReducedHTML] Fetched reduced HTML in ${j.getTime()-S.getTime()}ms`),this.rrwebEventAtLastReducedHTML=J,{reducedHTML:C,flashingHTML:F,elementsForNodeInterpretation:B,currentChecksumId:P}}catch(C){if(s>0)return this.logger.logError(`[getCurrentReducedHTML] Error: ${C.message}`),this.logger.logError(`Failed do obtain reduced HTML, trying again in ${o/1e3} seconds, ${s-1} to go.`),await f6(o),this.getCurrentReducedHTML({retriesLeft:s-1,retryWaitMS:o});throw C}}getActionEventCode(s){return RWt[s]}};e(_TestGenerationPageInteractor,"TestGenerationPageInteractor");var MCe=_TestGenerationPageInteractor;var _AlternateSelectorFallback=class _AlternateSelectorFallback extends ehe{constructor(){super(...arguments);this.timeout=5*1e3}init(o){return super.init(o),this}async resolve(params){var o;try{let{method,args}=params,{checksumId}=this.data,alternateLocators=[];try{let u=await this.getMetadataForTestId();if(!(checksumId in u)||!u[checksumId].alternateLocators)throw new Error(`No alternate selection metadata found for id ${checksumId}`);alternateLocators=u[checksumId].alternateLocators.locators}catch(u){throw super.log(`Could not read alternate selector metadata file, ${u.message}`),u}try{this.log("Resolving alternate selectors locators");let elementsMap=new Map;await Promise.all(alternateLocators.map(async locatorExpression=>{let locator=eval(sse(locatorExpression,"this.page"));try{await m5(locator.first().waitFor({bypassChecksum:!0}),5e3),(await m5(locator.elementHandles({bypassChecksum:!0}),1e3)).forEach(p=>{elementsMap.has(p)?elementsMap.set(p,elementsMap.get(p)+1):elementsMap.set(p,1)})}catch(u){return}}));let majorityElementHandle=(o=Array.from(elementsMap.entries()))==null?void 0:o.reduce((u,p)=>u[1]>p[1]?u:p)[0];if(!majorityElementHandle)throw this.errorMessage="No alternate element found",new Error(this.errorMessage);let totalElements=Array.from(elementsMap.values()).reduce((u,p)=>u+p,0),elementSelector=await this.evaluateWithChecksum(async({element:u})=>window.playwright.selector(u),{element:majorityElementHandle});this.log(`Resolved alternate selector: ${elementSelector}' With majority vote of ${elementsMap.get(majorityElementHandle)} out of ${totalElements} elements`),await this.checksumPage.wrapNoLocationSteps(async()=>this.execute(this.page.locator(elementSelector),method,args));let fallbackResult={selector:elementSelector,generatedLocator:`locator("${elementSelector}")`,esraMetadata:void 0};return this.sendLog(fallbackResult),this.logPayload=this.logPayload.concat({mejorityVote:`${elementsMap.get(majorityElementHandle)}/${totalElements}`}),this.checksumPage.addErrorMessage(params.error,`${this.thought?`"${this.thought}" auto-healed`:"Auto-healed"} using alternative selector "${elementSelector}"`),{steps:[{type:"action",...fallbackResult}]}}catch(u){throw new Error(`Failed to execute compound selection fallback action: ${u.message}`)}}catch(u){this.errorMessage=u.message,this.log(this.errorMessage);return}}getAnalyticsPayload(){return{fallbackType:"alternative-selector",...this.logPayload??{checksumId:this.data.checksumId,error:this.errorMessage}}}toString(){return`Checksum alternative selector (${this.data.checksumId})`}};e(_AlternateSelectorFallback,"AlternateSelectorFallback");var wUe=_AlternateSelectorFallback;var UWt=class UWt{constructor(o){this.options=o}async handleError(o,u,p){let y=`Error in ${u} action during ${o} execution: ${p.message}`;throw new Error(y)}async guardedExecute(){try{return await(this.options.timeout!=null?m5(this.execute(),this.options.timeout,"Execution timeout"):this.execute())}catch(o){return this.handleError(this.options.method,this.constructor.name,o)}}};e(UWt,"Action");var Ddt=UWt,VWt=class VWt extends Ddt{async execute(){return this.options.method in this.options.locator?this.options.locator[this.options.method](...this.options.args):this.options.locator}};e(VWt,"PlaywrightAction");var BWt=VWt,JWt=class JWt extends Ddt{constructor(u,p){super(u);this.pageInteractor=p}};e(JWt,"APIAction");var jWt=JWt,zWt=class zWt extends jWt{constructor(o,u){super(o,u.pageInteractor)}async execute(){try{let{locator:o,args:u}=this.options,[p,y]=u,x=await o.screenshot({timeout:3e4}),C=(await this.pageInteractor.getTextDetection(x)).getRectangleByTextAndSizeRanking(p,y);if(!C)throw new Error("No matching text found");await o.click({position:C.center})}catch(o){throw new Error(`Error in canvas click action: ${o.message}`)}}};e(zWt,"CanvasClickAction");var qWt=zWt,WWt=class WWt{static async createAction(o,u){let p={canvasClick:qWt};return e(()=>o.method in p?new p[o.method]({...o,timeout:15e3},u):new BWt(o),"action")().guardedExecute()}};e(WWt,"ActionFactory");var Sdt=WWt;var $Wt=class $Wt{constructor(o){this.options=o;this.health=e(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(o=>(console.log(o),null)),"health");this.getCanvasDetection=e(async o=>{try{let u=o.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:u}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(u){return console.log(u),null}},"getCanvasDetection")}};e($Wt,"ChecksumClient");var BCe=$Wt;var HWt=class HWt{constructor(){this.config={}}};e(HWt,"PageInteractorAPI");var Edt=HWt;var GWt=class GWt extends Edt{constructor(u){super();this.config=u;this.getTextDetection=e(async u=>{let p=await this.api.getCanvasDetection(u);if(!p)throw new Error("No data returned from canvas detection");return p},"getTextDetection");this.config=u,this.api=new BCe({apiKey:u.apiKey,apiURL:u.apiURL})}};e(GWt,"RuntimePageInteractorAPI");var jCe=GWt;var dhr=require("path");var KWt=class KWt{constructor(o){this.options=o;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=e(async o=>{let u=cL(o);if(this.trackedFramesGuid.includes(u))return this.frameNavigationPromises[u]=new Promise(async p=>{await this.loadScript(o),p()}),this.frameNavigationPromises[u]},"onFrameNavigated");this.loadScript=e(async(o,{retriesLeft:u=3,retryWaitMS:p=2e3,useWrapper:y=!0}={})=>{var P,F;if(y&&this.scriptLoadWrapper)return this.scriptLoadWrapper(()=>this.loadScript(o,{retriesLeft:u,retryWaitMS:p,useWrapper:!1}),o);if(!this.addScriptTagOptions){console.warn("[InjectedScriptManager] addScriptTagOptions not set, skipping loadScript");return}if(this.isFrameClosed(o))return;let x=!1;try{x=this.scriptLoadCheck?await((P=this.scriptLoadCheck)==null?void 0:P.call(this,o)):!1}catch{}if(x||this.isFrameClosed(o))return;try{await o.addScriptTag(this.addScriptTagOptions)}catch(B){if(u>0)return console.warn(`[InjectedScriptManager] Failed to add script to frame ${cL(o)}, trying again in ${p/1e3} seconds, ${u-1} retries left.`,B.message),await f6(p),this.loadScript(o,{retriesLeft:u-1,retryWaitMS:p,useWrapper:y});throw B}let S=cL(o),C=Date.now().toString(36)+Math.random().toString(36).substr(2);if(this.navigatingFrames[S]=C,this.options.scriptInitWait&&(console.log(`Waiting ${this.options.scriptInitWait}[ms] before onScriptLoad...`),await f6(this.options.scriptInitWait),console.log("Done waiting before onScriptLoad")),!this.isFrameClosed(o)){if(this.navigatingFrames[S]&&this.navigatingFrames[S]!==C)return console.log("Page navigated again, waiting on new promise..."),this.frameNavigationPromises[S];try{await((F=this.scriptLoadCallback)==null?void 0:F.call(this,o))}catch(B){console.error("[WebDriver] onScriptLoad error",B)}}},"loadScript");this.addScriptTagOptions=this.makeFrameInjectedScriptOptions()}setScriptLoadCallback(o){return this.scriptLoadCallback=o,this}setScriptLoadCheck(o){return this.scriptLoadCheck=o,this}setScriptLoadWrapper(o){return this.scriptLoadWrapper=o,this}async addTrackedFrame(o,u=!0){let p="mainFrame"in o?o.mainFrame():o,y=cL(p);if(this.trackedFramesGuid.includes(y)||this.trackedFramesGuid.push(y),u)return this.onFrameNavigated(p)}getNavigationPromise(o){if(!o){console.warn("[InjectedScriptManager] getNavigationPromise called with undefined argument");return}let u=typeof o=="string"?o:"mainFrame"in o?cL(o.mainFrame()):cL(o);return this.frameNavigationPromises[u]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,dhr.join)(process.cwd(),this.options.scriptFile)}:void 0;case"url":return this.options.scriptURL?{url:this.options.scriptURL}:void 0;default:return}}isFrameClosed(o){return o.isDetached()||o.page().isClosed()}};e(KWt,"InjectedScriptManager");var qCe=KWt;var v7e=Xv(require("path")),ZWt=require("fs");var psn=__dirname,vhr=v7e.join(__dirname,".."),fsn=(0,ZWt.existsSync)(vhr)?vhr:psn;yhr().config({path:v7e.resolve(fsn,".env")});var Tdt=process.env.DEV_MODE==="true";function bhr(){let s=__dirname;for(;!(0,ZWt.existsSync)(v7e.join(s,"package.json"));)s=v7e.join(s,"..");return s}e(bhr,"findRoot");var xhr=v7e.join(bhr(),"vtg-build","index.html"),Qv={isDevMode:Tdt,logLevel:process.env.LOG_LEVEL??"warnings",checksumScript:{source:Tdt?"url":"file",url:process.env.SCRIPT_URL,path:bhr()+"/checksumlib.js"},vtg:{writeLogFile:process.env.WRITE_LOG_FILE==="true",localBuildPath:xhr,appURL:Tdt?process.env.VTG_APP_URL:`file://${xhr}`,useFakeStory:process.env.USE_FAKE_STORY==="true",recordEvents:process.env.RECORD_EVENTS==="true",fakeStory:{goal:process.env.FAKE_STORY_GOAL??"Send email via outreach list",instructions:process.env.FAKE_STORY_INSTRUCTIONS??"Make sure to select a user from the list first"},fakeTestGeneration:{internalTestId:process.env.FAKE_STORY_INTERNAL_TEST_ID??`tempID${Date.now().toString().slice(-5)}`,generationBatchId:process.env.FAKE_GENERATION_BATCH_ID??`tempID${Date.now().toString().slice(-5)}`},remoteDebugging:process.env.REMOTE_DEBUGGING==="true",taskTimeMachine:{showTaskTimeMachine:process.env.SHOW_TASK_TIME_MACHINE==="true",taskTimeout:parseInt(process.env.TASK_TIME_MACHINE_TIMEOUT??"240000")},aiAssertions:{disabled:process.env.AI_ASSERTIONS_DISABLED==="true",allowRefactoring:process.env.ALLOW_AI_ASSERTIONS_REFACTORING==="true"},aiLocators:{disabled:process.env.AI_LOCATORS_DISABLED==="true",useFakeAILocators:process.env.USE_FAKE_AI_LOCATORS==="true"}},testRun:{timeMachine:{active:!0,headless:!0},monitoring:{segment:{writeKey:process.env.MONITORING_SEGMENT_WRITE_KEY??"MfFJgdVFaFaD3NrBrgX3A9Blwfxs0pSD"}}},buildTime:process.env.BUILD_TIME??"unknown"};Tdt&&console.log("Build",Qv.buildTime);var e$t=class e$t{constructor(){this.frames={};this.pages=[];this.channels={};this.events=[]}register(o,u,p){if(this.frames[o])return;this.frames[o]=u;let y=u.page();this.pages.includes(y)||(this.pages.push(y),y.exposeFunction("checksumSendMessage",async(x,S)=>{let C=this.frames[x];if(!C)throw new Error(`Frame ${x} not found`);try{await C.evaluate(({message:P})=>{window.postMessage(P,"*")},{message:S})}catch{}}),y.exposeFunction("checksumSendBroadcastMessage",async(x,S)=>{let C=this.channels[x]??[];if(p){let P=require("fs"),F=require("path");this.events.push(...S),this.events.length%10===0&&P.writeFileSync(F.join(process.cwd(),"rrweb-player","events.json"),JSON.stringify(this.events))}C.forEach(async P=>{if(!(P.originFrameGuid&&P.originFrameGuid!==cL(u)))try{P.handler?await P.handler(S):await u.evaluate(({message:F})=>{window.postMessage(F,"*")},{message:S})}catch{}})}),y.exposeFunction("checksumBringPageToFront",async x=>{let S=this.frames[x];S&&await S.page().bringToFront()}))}subscribeToChannel(o,u,{originFrame:p,handler:y}={}){var x;(x=this.channels)[o]??(x[o]=[]),this.channels[o].push({frame:u,originFrameGuid:p?cL(p):void 0,handler:y})}unsubscribeFromChannel(o,u){var p;(p=this.channels)[o]??(p[o]=[]),this.channels[o]=this.channels[o].filter(y=>y.frame!==u)}};e(e$t,"FramesMsgBroker");var UCe=e$t;var Shr=require("@playwright/test");var AUe=require("jsdom");var t$t=class t$t{constructor(o){this.activeDOMType="checksumIds";this.rawReducedHTMLDom=new AUe.JSDOM(o),this.process()}process(){this.expandedChecksumIdsReducedDom=new AUe.JSDOM(this.rawReducedHTMLDom.serialize()),this.reducedHTMLDom=new AUe.JSDOM(this.rawReducedHTMLDom.serialize()),this.rrwebIdsReducedDom=new AUe.JSDOM(this.rawReducedHTMLDom.serialize());let o=e(S=>{S.window.document.body.querySelectorAll("[checksumid]:not([checksuminteractable])").forEach(P=>{P.removeAttribute("checksumid")})},"removeChecksumIdAttributeFromNonInteractable"),u=e((S,C)=>C.window.document.body.querySelectorAll(`[${S}]`).forEach(P=>P.removeAttribute(S)),"removeAttributeFromAllElements"),p=e(S=>u("checksuminteractable",S),"removeChecksumInteractableAttribute"),y=e(S=>u("checksumid",S),"removeChecksumIdAttribute"),x=e(S=>u("rrwebid",S),"removeRrwebIdAttribute");o(this.reducedHTMLDom),p(this.expandedChecksumIdsReducedDom),p(this.reducedHTMLDom),p(this.rrwebIdsReducedDom),x(this.expandedChecksumIdsReducedDom),x(this.reducedHTMLDom),y(this.rrwebIdsReducedDom)}getDOMForType(o){switch(o){default:case"checksumIds":return this.reducedHTMLDom;case"expandedChecksumIds":return this.expandedChecksumIdsReducedDom;case"rrwebIds":return this.rrwebIdsReducedDom}}async enrich(o){return await o(this.rawReducedHTMLDom),this.process(),this}setActiveDomType(o){this.activeDOMType=o}getActiveDom(){return this.getDOMForType(this.activeDOMType)}getActiveDOMString(){return this.getActiveDom().serialize()}getRrwebIdsReducedDomString(){return this.rrwebIdsReducedDom.serialize()}getDOMStringForType(o){return this.getDOMForType(o).serialize()}get raw(){return this.rawReducedHTMLDom}};e(t$t,"ReducedHTMLDOM");var kUe=t$t;var Dhr=Xv(require("path"));var n$t=class n$t{constructor(o="all"){this.listeners=[];this.logLevel=o}log(...o){try{let p=new Error().stack.split(`
|
|
1417
|
+
`),"variablesToString");var Kan=!0,_TestGenerationPageInteractor=class _TestGenerationPageInteractor{constructor(s,o,u,p,y,x,S){this.evaluateWithChecksum=s;this.getFrame=o;this.getTimeMachine=u;this.logger=p;this.options=y;this.pageInteractorAPI=x;this.loginFunction=S;this.activeDialog=null;this.newPagesIds=[];this.listeners={dialog:null,filechooser:null,page:null};this.listenToContextPage=e(()=>{this.getPage().context().on("page",s=>{this.newPagesIds.push(s._guid)})},"listenToContextPage");this.listenToFileChooser=e(()=>{this.listeners.filechooser=async s=>{this.logger.log("File chooser event detected"),this.fileChooser=s},this.getPage().on("filechooser",this.listeners.filechooser)},"listenToFileChooser");this.waitForDialog=e((s=!0,o=1e4)=>new Promise(u=>{let y=0,x=e(()=>{if(this.activeDialog){let S=this.activeDialog;s&&(this.activeDialog=null),u(S)}else y>=o?u(null):(y+=1e3,setTimeout(x,1e3))},"checkDialog");x()}),"waitForDialog");this.performFileUploadAction=e(async(s,o)=>{if(!await s.evaluate(p=>p.tagName==="INPUT"&&p.getAttribute("type")==="file"))throw new Error("File upload action performed on non-file input element");let u=o.files.map(p=>(0,fhr.join)(this.options.testAssetsDir,p)).filter(p=>(0,phr.existsSync)(p)?!0:(this.logger.log(`Upload file not found: ${p}. Filtering out.`),!1));if(!u.length)throw new Error("No files to upload");await this.actionGuardReturn(s.setInputFiles(u),"Set input files timeout")},"performFileUploadAction");this.getSelectionDataForAction=e(async(s,o)=>s.checksumid?this.getSelectionDataForChecksumId(s.checksumid,o):s.position?await this.evaluateWithChecksum(async([u,p])=>window.checksum.testGenerator.getSelectorByPosition(u,p),[s.position.x,s.position.y]):s.selector?{selector:s.selector,locator:`locator("${s.selector}")`}:{selector:"",locator:""},"getSelectionDataForAction")}getPage(){return this.getFrame().page()}init(){this.listenToContextPage(),this.options.listenToFileChooser!==!1&&this.listenToFileChooser(),this.options.listenToDialog&&this.listenToDialog()}listenToDialog(){this.listeners.dialog=async s=>{this.activeDialog=s},this.getPage().on("dialog",this.listeners.dialog)}removeListener(s){try{switch(s){case"dialog":this.listeners.dialog&&(this.getPage().removeListener(s,this.listeners.dialog),this.listeners.dialog=null);break;case"filechooser":this.getPage().off(s,this.listeners.filechooser),this.listeners.filechooser=null;break;case"page":this.getPage().context().off(s,this.listeners.page),this.listeners.page=null;break}}catch(o){this.logger.logError(`Error removing listener: ${s}`,o)}}getOpenedFileChooser(){if(this.fileChooser){let s=this.fileChooser;return this.fileChooser=void 0,s}return null}async handleFileChooserEvent(s=[]){let o=this.getOpenedFileChooser();if(!o)return{};let u="fc_"+Math.random().toString(36).slice(2,4);return await this.evaluateWithChecksum(async([p,y])=>{window.checksum.testGenerator.addForceIncludeElement(y,p)},[u,o.element()]),{interruptionEvent:"fileUploadOpenedEvent",payload:{checksumid:u,customFiles:s}}}async addMoreItemsToDom(s,o){let u=s.querySelector(`[checksum-get-more-items='${o}']`);if(!u)throw new Error("Get more items root not found");let{items:p,hasMoreItems:y}=await this.getMoreItemsForTemplate(o);u.innerHTML=u.innerHTML+p,y||u.removeAttribute("checksum-get-more-items")}async getPageInfo(s){let o=cL(s);return{id:o,url:s.url(),title:await s.title(),new:this.newPagesIds.includes(o),active:o===cL(this.getPage())}}async getTabsInfo(){var p;let s=this.getPage(),o=await Promise.all(s.context().pages().map(y=>this.getPageInfo(y))),u=(p=this.getTimeMachine())==null?void 0:p.getPage();return u&&u!==s&&(o=o.filter(y=>y.id!==cL(u))),this.newPagesIds=[],o}async getSelectionDataFromSelectorGenerator(s,o,u={}){if(u={useCompoundSelector:!0,useCSSExtraction:!0,useVariables:!0,useArbitrarySelector:!0,...u},!s||!aJt(Q0r(o.action.type))||!o.action.checksumid)return{};let p=await s.generateSelectionForAction(o,u);return p?{locator:`locator("${p.selector}")`,...p}:{}}async translateActionResponseToAgentPotentialAction(s,o=void 0,{pageId:u,makeStaticMetadataForESRA:p}={}){let y=structuredClone(s.actionHiddenOverride??s.action),{selector:x,selectorWithVars:S,locator:C,locatorWithVars:P,clickOffset:F,selectOptionValue:B,compoundSelector:J,alternateLocators:j,parentFramesSelectors:W}={...await this.getSelectionDataForAction(y,s.actionHiddenOverride),...await this.getSelectionDataFromSelectorGenerator(o,s)},z=await this.getESRAForSelector(x,W,p);if(!z&&x&&this.logger.logError("Error getting ESRA metadata"),(z==null?void 0:z.tag)==="select")switch(this.getActionEventCode(y.type)){case"input":y.type="selectoption";break;case"click":B&&(y.type="selectoption",y.value=B);break}let Y={eventCode:this.getActionEventCode(y.type),selector:x,selectorWithVars:S,parentFramesSelectors:W,locator:C,locatorWithVars:P,clickOffset:F,pageId:u,compoundSelector:J,alternateLocators:j,fillValue:y.value,fillValueName:y.valueName?`${hhe}${y.valueName}`:"",variables:s.variables,getMoreItemsId:y.getMoreItemsId,esraMetadata:z,thought:s.thought,userRole:y.userRole,canvas:y.canvas,id:y.id};switch(Y.eventCode){case"drag_and_drop":{let{selector:le,selectorWithVars:ye,locator:ve,locatorWithVars:Ie,parentFramesSelectors:Be}={...await this.getSelectionDataForAction({type:s.action.type,checksumid:s.action.dropTargetChecksumid}),...await this.getSelectionDataFromSelectorGenerator(o,{...s,action:{type:s.action.type,checksumid:s.action.dropTargetChecksumid}},{useCompoundSelector:!1})};Y.dropTarget={selector:le,locator:ve,parentFramesSelectors:Be,esraMetadata:await this.getESRAForSelector(le,Be,p)}}break;case"upload_files":Y.files=this.mapFileMIMETypeToFilename(y.files);break;case"switch_tab":{let le=this.getPage();Y.switchToTab={id:y.tabId,index:le.context().pages().findIndex(ye=>cL(ye)===y.tabId)};break}case"keystroke":Y.fillValue=y.value}return Y}async reauthenticate(s,o){let u=this.getPage();this.loginFunction&&(await Promise.all([u.context().clearCookies(),u.evaluate(()=>localStorage.clear())]),await this.loginFunction(o??u,{role:s}))}mapFileMIMETypeToFilename(s){return s.map(o=>{if(o.fileName)return o.fileName;switch(o.mimeType){case"image/png":return"image_200x200.png";case"image/jpeg":return"image_200x200.jpg";case"application/pdf":return"document.pdf";case"text/csv":return"data.csv";default:return"file.txt"}})}async performAction(s,{useLocator:o=!1,handleActionFailed:u,monitorFlashingHTML:p=!0,timeout:y,allowForceClick:x=!0}={}){try{if(s.executed){this.logger.log("[performAction] Action marked as executed, skipping...");return}let S=o?!!s.locator:!!s.selector;if(aJt(s.eventCode)&&!S)throw new Error("No selector provided for action. Try changing app rules preMapReducedHTMLSelectors to true");p&&(this.logger.log("starting flashing elements detection"),await this.evaluateWithChecksum(async()=>window.checksum.testGenerator.startFlashingElementsDetection())),this.logger.log(`Performing action: ${s.eventCode}. Selector: ${s.selector}, Position: ${s.clickOffset}, Parent frame: ${s.parentFramesSelectors}`);let C=e(()=>o?this.makeLocatorFromLocator(s.locator):this.makeLocator(s.selector,s.parentFramesSelectors),"getLocator"),P=e(async(F,B,J={})=>this.actionGuardReturn(F,B,{timeout:y,...J}),"performWithActionGuard");switch(s.eventCode){case"click":try{await P(C().click({position:s.clickOffset,timeout:y??this.options.actionTimeout}),"Click timeout")}catch(F){if(!x)throw F;this.logger.log("Error performing click, will attempt a force click",F.message),s.force=!0,await P(C().click({position:s.clickOffset,force:!0,timeout:y??this.options.actionTimeout}),"Force Click timeout")}break;case"double_click":try{await P(C().dblclick({position:s.clickOffset,timeout:y??this.options.actionTimeout}),"DoubleClick timeout")}catch(F){if(!x)throw F;this.logger.log("Error performing double click, will attempt a force double click",F),s.force=!0,await P(C().dblclick({position:s.clickOffset,timeout:y??this.options.actionTimeout,force:!0}),"Force DoubleClick timeout")}break;case"check":await P(C().check({timeout:y??this.options.actionTimeout}),"Check timeout");break;case"uncheck":await P(C().uncheck({timeout:y??this.options.actionTimeout}),"UnCheck timeout");break;case"drag_and_drop":await P(C().dragTo(o?this.makeLocatorFromLocator(s.dropTarget.locator):this.makeLocator(s.dropTarget.selector,s.dropTarget.parentFramesSelectors),{timeout:y??this.options.actionTimeout}),"DragAndDrop timeout");break;case"input":await P(C().fill(this.getActionFillValue(s),{timeout:y??this.options.actionTimeout}),"Fill timeout");break;case"click_and_type":await m5(C().click({position:s.clickOffset,timeout:y??this.options.actionTimeout}),1e4,"Click before type timeout"),await m5(C().pressSequentially(this.getActionFillValue(s),{timeout:y??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"clear_and_type":await m5(C().clear({timeout:y??this.options.actionTimeout}),1e4,"Clear before type timeout"),await m5(C().pressSequentially(this.getActionFillValue(s),{timeout:y??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"selectoption":await P(C().selectOption(this.getActionFillValue(s),{timeout:y??this.options.actionTimeout}),"SelectOption timeout");break;case"hover":await P(C().hover({timeout:y??this.options.actionTimeout}),"Hover timeout");break;case"navigation":await P(this.getFrame().goto(s.fillValue,{timeout:y??this.options.navigationTimeout}),"Navigation timeout",{isNavigation:!0});break;case"keystroke":{let F=this.getPage();await P(F.keyboard.press(s.fillValue),"Keystroke timeout");break}case"upload_files":await this.performFileUploadAction(C(),s);break;case"wait":await f6(this.options.waitActionDelay??1e3);break;case"custom_code":await xdt(this.getPage(),this.getFrame(),async F=>{let B=`async (page) => {${s.fillValue}}`;await(0,eval)(B)(F)});break;case"logout_and_login":await this.reauthenticate(s.userRole);break;case"canvas_click":await this.canvasClick(C(),s.canvas);break}}catch(S){throw this.logger.log(`Error performing action: ${s.eventCode}, will attempt a correction template`,S),await(u==null?void 0:u()),S}this.logger.log(`Successfully performed action ${s.eventCode} with description "${s.thought}"`)}async getTextDetection(s){return new vdt(await this.pageInteractorAPI.getTextDetection(s))}async canvasClick(s,o){try{if(!await s.evaluate(x=>x.tagName.toLowerCase()==="canvas"))throw new Error("Click attempted on a non-canvas element");let y=(await this.getTextDetection(await s.screenshot())).getRectangleByTextAndSizeRanking(o.canvasText,o.rectSizeIndex);if(!y)throw new Error(`Canvas click target not found for ${o.canvasText}`);this.logger.log(`Canvas click target: ${y}`),await this.actionGuardReturn(s.click({position:y.center}),"Canvas click could not be performed")}catch(u){throw this.logger.logError("Canvas click:",u.message),new Error("Canvas click action failed")}}getActionFillValue(s,o=!0){let u=s.fillValue;if(!u){let p=s.selector.match(/(?<=value.*)('|").*/);p&&(u=p[0].slice(1,-1))}return typeof u!="string"&&(u="X"),o&&(s.fillValue=u),u}actionGuardReturn(s,o,{isNavigation:u=!1,timeout:p}={}){return m5(s,p??(u?this.options.navigationTimeout:this.options.actionTimeout),o)}makeLocator(s,o=[]){return pJt(this.getFrame(),s,o)}makeLocatorFromLocator(locator){return eval("this.getFrame()."+locator)}getCurrentURL(){return this.getFrame().url()}async getSelectionDataForChecksumId(s,o){if(o!=null&&o.selector)return{...o,selector:o.selector,locator:o.locator,clickOffset:o.position};if(!s)return this.logger.log(`[getSelectionDataForChecksumId] checksumid not provided (${s})`),{...o,selector:s,locator:`locator("${s}")`};let u=await this.evaluateWithChecksum(async p=>{let{selector:y,locator:x,clickOffset:S,parentFramesSelectors:C,invalid:P,rrwebId:F}=await window.checksum.testGenerator.getSelectorForChecksumId(p),B=await window.checksum.testGenerator.getElementForChecksumId(p),J=B instanceof HTMLOptionElement&&B.value?B.value:void 0;return{selector:y,locator:x,clickOffset:S,selectOptionValue:J,parentFramesSelectors:C,invalid:P,rrwebId:F}},s);if(Kan&&u.invalid&&u.rrwebId){this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${s}. Trying to use time machine...`);try{let p=await this.getSelectionDataForRRwebIdAtReduceHTMLTime(u.rrwebId);u={...u,...p}}catch{this.logger.log(`[getSelectionDataForChecksumId] error using time machine to get selector for checksumid: ${s}`)}this.logger.log(`[getSelectionDataForChecksumId] got selector: ${u.selector} for checksumid: ${s} from time machine`)}return u!=null&&u.selector||this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${s}. If checksumid is correct, try to change app rules preMapReducedHTMLSelectors to true`),u}async getSelectionDataForRRwebIdAtReduceHTMLTime(s){if(!this.rrwebEventAtLastReducedHTML)return;let o=this.getTimeMachine();if(o)return o.executeTask(u=>u.evaluate(async({rrwebId:p})=>await window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(p,{ignoredIframesSelectors:[".replayer-wrapper > iframe"],fromTimeMachine:!0}),{rrwebId:s}),this.rrwebEventAtLastReducedHTML.timestamp,{name:"getSelectionDataForRRwebIdAtReduceHTMLTime"})}async getESRAForSelector(s,o,u){let p=await this.evaluateWithChecksum(async({selector:y,parentFramesSelectors:x})=>window.checksum.testGenerator.getSelectionDataForSelector(y,x),{selector:s,parentFramesSelectors:o});return p!=null&&p.esraMetadata&&u&&(p.esraMetadata.staticMetadata=await u(p.esraMetadata,s)),p==null?void 0:p.esraMetadata}async getMoreItemsForTemplate(s){return await this.evaluateWithChecksum(async o=>window.checksum.testGenerator.getMoreItemsForTemplate(o,{}),s)??{items:"",hasMoreItems:!1}}async getCurrentReducedHTML({retriesLeft:s=3,retryWaitMS:o=2e3,initialChecksumId:u="0",extractESRAForInterpretationRequiredElements:p=!1,stopFlashingElementsDetection:y=!1,assignChecksumIdsToAllElements:x}={}){let S=new Date;this.logger.log("[getCurrentReducedHTML] Fetching reduced HTML...");try{let{reducedHTML:C,currentChecksumId:P,flashingHTML:F,elementsForNodeInterpretation:B,lastRRwebEvent:J}=await this.evaluateWithChecksum(async W=>window.checksum.testGenerator.reduceHTML({},W),{initialChecksumId:u,extractESRAForInterpretationRequiredElements:p,stopFlashingElementsDetection:y,assignChecksumIdsToAllElements:x}),j=new Date;return this.logger.log(`[getCurrentReducedHTML] Fetched reduced HTML in ${j.getTime()-S.getTime()}ms`),this.rrwebEventAtLastReducedHTML=J,{reducedHTML:C,flashingHTML:F,elementsForNodeInterpretation:B,currentChecksumId:P}}catch(C){if(s>0)return this.logger.logError(`[getCurrentReducedHTML] Error: ${C.message}`),this.logger.logError(`Failed do obtain reduced HTML, trying again in ${o/1e3} seconds, ${s-1} to go.`),await f6(o),this.getCurrentReducedHTML({retriesLeft:s-1,retryWaitMS:o});throw C}}getActionEventCode(s){return RWt[s]}};e(_TestGenerationPageInteractor,"TestGenerationPageInteractor");var MCe=_TestGenerationPageInteractor;var _AlternateSelectorFallback=class _AlternateSelectorFallback extends ehe{constructor(){super(...arguments);this.timeout=5*1e3}init(o){return super.init(o),this}async resolve(params){var o;try{let{method,args}=params,{checksumId}=this.data,alternateLocators=[];try{let u=await this.getMetadataForTestId();if(!(checksumId in u)||!u[checksumId].alternateLocators)throw new Error(`No alternate selection metadata found for id ${checksumId}`);alternateLocators=u[checksumId].alternateLocators.locators}catch(u){throw super.log(`Could not read alternate selector metadata file, ${u.message}`),u}try{this.log("Resolving alternate selectors locators");let elementsMap=new Map;await Promise.all(alternateLocators.map(async locatorExpression=>{let locator=eval(sse(locatorExpression,"this.page"));try{await m5(locator.first().waitFor({bypassChecksum:!0}),5e3),(await m5(locator.elementHandles({bypassChecksum:!0}),1e3)).forEach(p=>{elementsMap.has(p)?elementsMap.set(p,elementsMap.get(p)+1):elementsMap.set(p,1)})}catch(u){return}}));let majorityElementHandle=(o=Array.from(elementsMap.entries()))==null?void 0:o.reduce((u,p)=>u[1]>p[1]?u:p)[0];if(!majorityElementHandle)throw this.errorMessage="No alternate element found",new Error(this.errorMessage);let totalElements=Array.from(elementsMap.values()).reduce((u,p)=>u+p,0),elementSelector=await this.evaluateWithChecksum(async({element:u})=>window.playwright.selector(u),{element:majorityElementHandle});this.log(`Resolved alternate selector: ${elementSelector}' With majority vote of ${elementsMap.get(majorityElementHandle)} out of ${totalElements} elements`),await this.checksumPage.wrapNoLocationSteps(async()=>this.execute(this.page.locator(elementSelector),method,args));let fallbackResult={selector:elementSelector,generatedLocator:`locator("${elementSelector}")`,esraMetadata:void 0};return this.sendLog(fallbackResult),this.logPayload=this.logPayload.concat({mejorityVote:`${elementsMap.get(majorityElementHandle)}/${totalElements}`}),this.checksumPage.addErrorMessage(params.error,`${this.thought?`"${this.thought}" auto-healed`:"Auto-healed"} using alternative selector "${elementSelector}"`),{steps:[{type:"action",...fallbackResult}]}}catch(u){throw new Error(`Failed to execute compound selection fallback action: ${u.message}`)}}catch(u){this.errorMessage=u.message,this.log(this.errorMessage);return}}getAnalyticsPayload(){return{fallbackType:"alternative-selector",...this.logPayload??{checksumId:this.data.checksumId,error:this.errorMessage}}}toString(){return`Checksum alternative selector (${this.data.checksumId})`}};e(_AlternateSelectorFallback,"AlternateSelectorFallback");var wUe=_AlternateSelectorFallback;var UWt=class UWt{constructor(o){this.options=o}async handleError(o,u,p){let y=`Error in ${u} action during ${o} execution: ${p.message}`;throw new Error(y)}async guardedExecute(){try{return await(this.options.timeout!=null?m5(this.execute(),this.options.timeout,"Execution timeout"):this.execute())}catch(o){return this.handleError(this.options.method,this.constructor.name,o)}}};e(UWt,"Action");var Ddt=UWt,VWt=class VWt extends Ddt{async execute(){return this.options.method in this.options.locator?this.options.locator[this.options.method](...this.options.args):this.options.locator}};e(VWt,"PlaywrightAction");var BWt=VWt,JWt=class JWt extends Ddt{constructor(u,p){super(u);this.pageInteractor=p}};e(JWt,"APIAction");var jWt=JWt,zWt=class zWt extends jWt{constructor(o,u){super(o,u.pageInteractor)}async execute(){try{let{locator:o,args:u}=this.options,[p,y]=u,x=await o.screenshot({timeout:3e4}),C=(await this.pageInteractor.getTextDetection(x)).getRectangleByTextAndSizeRanking(p,y);if(!C)throw new Error("No matching text found");await o.click({position:C.center})}catch(o){throw new Error(`Error in canvas click action: ${o.message}`)}}};e(zWt,"CanvasClickAction");var qWt=zWt,WWt=class WWt{static async createAction(o,u){let p={canvasClick:qWt};return e(()=>o.method in p?new p[o.method]({...o,timeout:15e3},u):new BWt(o),"action")().guardedExecute()}};e(WWt,"ActionFactory");var Sdt=WWt;var $Wt=class $Wt{constructor(o){this.options=o;this.health=e(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(o=>(console.log(o),null)),"health");this.getCanvasDetection=e(async o=>{try{let u=o.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:u}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(u){return console.log(u),null}},"getCanvasDetection")}};e($Wt,"ChecksumClient");var BCe=$Wt;var HWt=class HWt{constructor(){this.config={}}};e(HWt,"PageInteractorAPI");var Edt=HWt;var GWt=class GWt extends Edt{constructor(u){super();this.config=u;this.getTextDetection=e(async u=>{let p=await this.api.getCanvasDetection(u);if(!p)throw new Error("No data returned from canvas detection");return p},"getTextDetection");this.config=u,this.api=new BCe({apiKey:u.apiKey,apiURL:u.apiURL})}};e(GWt,"RuntimePageInteractorAPI");var jCe=GWt;var dhr=require("path");var KWt=class KWt{constructor(o){this.options=o;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=e(async o=>{let u=cL(o);if(this.trackedFramesGuid.includes(u))return this.frameNavigationPromises[u]=new Promise(async p=>{await this.loadScript(o),p()}),this.frameNavigationPromises[u]},"onFrameNavigated");this.loadScript=e(async(o,{retriesLeft:u=3,retryWaitMS:p=2e3,useWrapper:y=!0}={})=>{var P,F;if(y&&this.scriptLoadWrapper)return this.scriptLoadWrapper(()=>this.loadScript(o,{retriesLeft:u,retryWaitMS:p,useWrapper:!1}),o);if(!this.addScriptTagOptions){console.warn("[InjectedScriptManager] addScriptTagOptions not set, skipping loadScript");return}if(this.isFrameClosed(o))return;let x=!1;try{x=this.scriptLoadCheck?await((P=this.scriptLoadCheck)==null?void 0:P.call(this,o)):!1}catch{}if(x||this.isFrameClosed(o))return;try{await o.addScriptTag(this.addScriptTagOptions)}catch(B){if(u>0)return console.warn(`[InjectedScriptManager] Failed to add script to frame ${cL(o)}, trying again in ${p/1e3} seconds, ${u-1} retries left.`,B.message),await f6(p),this.loadScript(o,{retriesLeft:u-1,retryWaitMS:p,useWrapper:y});throw B}let S=cL(o),C=Date.now().toString(36)+Math.random().toString(36).substr(2);if(this.navigatingFrames[S]=C,this.options.scriptInitWait&&(console.log(`Waiting ${this.options.scriptInitWait}[ms] before onScriptLoad...`),await f6(this.options.scriptInitWait),console.log("Done waiting before onScriptLoad")),!this.isFrameClosed(o)){if(this.navigatingFrames[S]&&this.navigatingFrames[S]!==C)return console.log("Page navigated again, waiting on new promise..."),this.frameNavigationPromises[S];try{await((F=this.scriptLoadCallback)==null?void 0:F.call(this,o))}catch(B){console.error("[WebDriver] onScriptLoad error",B)}}},"loadScript");this.addScriptTagOptions=this.makeFrameInjectedScriptOptions()}setScriptLoadCallback(o){return this.scriptLoadCallback=o,this}setScriptLoadCheck(o){return this.scriptLoadCheck=o,this}setScriptLoadWrapper(o){return this.scriptLoadWrapper=o,this}async addTrackedFrame(o,u=!0){let p="mainFrame"in o?o.mainFrame():o,y=cL(p);if(this.trackedFramesGuid.includes(y)||this.trackedFramesGuid.push(y),u)return this.onFrameNavigated(p)}getNavigationPromise(o){if(!o){console.warn("[InjectedScriptManager] getNavigationPromise called with undefined argument");return}let u=typeof o=="string"?o:"mainFrame"in o?cL(o.mainFrame()):cL(o);return this.frameNavigationPromises[u]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,dhr.join)(process.cwd(),this.options.scriptFile)}:void 0;case"url":return this.options.scriptURL?{url:this.options.scriptURL}:void 0;default:return}}isFrameClosed(o){return o.isDetached()||o.page().isClosed()}};e(KWt,"InjectedScriptManager");var qCe=KWt;var v7e=Xv(require("path")),ZWt=require("fs");var psn=__dirname,vhr=v7e.join(__dirname,".."),fsn=(0,ZWt.existsSync)(vhr)?vhr:psn;yhr().config({path:v7e.resolve(fsn,".env")});var Tdt=process.env.DEV_MODE==="true";function bhr(){let s=__dirname;for(;!(0,ZWt.existsSync)(v7e.join(s,"package.json"));)s=v7e.join(s,"..");return s}e(bhr,"findRoot");var xhr=v7e.join(bhr(),"vtg-build","index.html"),Qv={isDevMode:Tdt,logLevel:process.env.LOG_LEVEL??"warnings",checksumScript:{source:Tdt?"url":"file",url:process.env.SCRIPT_URL,path:bhr()+"/checksumlib.js"},vtg:{writeLogFile:process.env.WRITE_LOG_FILE==="true",localBuildPath:xhr,appURL:Tdt?process.env.VTG_APP_URL:`file://${xhr}`,useFakeStory:process.env.USE_FAKE_STORY==="true",recordEvents:process.env.RECORD_EVENTS==="true",fakeStory:{goal:process.env.FAKE_STORY_GOAL??"Send email via outreach list",instructions:process.env.FAKE_STORY_INSTRUCTIONS??"Make sure to select a user from the list first"},fakeTestGeneration:{internalTestId:process.env.FAKE_STORY_INTERNAL_TEST_ID??`tempID${Date.now().toString().slice(-5)}`,generationBatchId:process.env.FAKE_GENERATION_BATCH_ID??`tempID${Date.now().toString().slice(-5)}`},remoteDebugging:process.env.REMOTE_DEBUGGING==="true",taskTimeMachine:{showTaskTimeMachine:process.env.SHOW_TASK_TIME_MACHINE==="true",taskTimeout:parseInt(process.env.TASK_TIME_MACHINE_TIMEOUT??"240000")},aiAssertions:{disabled:process.env.AI_ASSERTIONS_DISABLED==="true",allowRefactoring:process.env.ALLOW_AI_ASSERTIONS_REFACTORING==="true"},aiLocators:{disabled:process.env.AI_LOCATORS_DISABLED==="true",useFakeAILocators:process.env.USE_FAKE_AI_LOCATORS==="true"}},testRun:{timeMachine:{active:!0,headless:!0},monitoring:{segment:{writeKey:process.env.MONITORING_SEGMENT_WRITE_KEY??"MfFJgdVFaFaD3NrBrgX3A9Blwfxs0pSD"}}},buildTime:process.env.BUILD_TIME??"unknown"};Tdt&&console.log("Build",Qv.buildTime);var e$t=class e$t{constructor(){this.frames={};this.pages=[];this.channels={};this.events=[]}register(o,u,p){if(this.frames[o])return;this.frames[o]=u;let y=u.page();this.pages.includes(y)||(this.pages.push(y),y.exposeFunction("checksumSendMessage",async(x,S)=>{let C=this.frames[x];if(!C)throw new Error(`Frame ${x} not found`);try{await C.evaluate(({message:P})=>{window.postMessage(P,"*")},{message:S})}catch{}}),y.exposeFunction("checksumSendBroadcastMessage",async(x,S)=>{let C=this.channels[x]??[];if(p){let P=require("fs"),F=require("path");this.events.push(...S),this.events.length%10===0&&P.writeFileSync(F.join(process.cwd(),"rrweb-player","events.json"),JSON.stringify(this.events))}C.forEach(async P=>{if(!(P.originFrameGuid&&P.originFrameGuid!==cL(u)))try{P.handler?await P.handler(S):await u.evaluate(({message:F})=>{window.postMessage(F,"*")},{message:S})}catch{}})}),y.exposeFunction("checksumBringPageToFront",async x=>{let S=this.frames[x];S&&await S.page().bringToFront()}))}subscribeToChannel(o,u,{originFrame:p,handler:y}={}){var x;(x=this.channels)[o]??(x[o]=[]),this.channels[o].push({frame:u,originFrameGuid:p?cL(p):void 0,handler:y})}unsubscribeFromChannel(o,u){var p;(p=this.channels)[o]??(p[o]=[]),this.channels[o]=this.channels[o].filter(y=>y.frame!==u)}};e(e$t,"FramesMsgBroker");var UCe=e$t;var Shr=require("@playwright/test");var AUe=require("jsdom");var t$t=class t$t{constructor(o){this.activeDOMType="checksumIds";this.rawReducedHTMLDom=new AUe.JSDOM(o),this.process()}process(){this.expandedChecksumIdsReducedDom=new AUe.JSDOM(this.rawReducedHTMLDom.serialize()),this.reducedHTMLDom=new AUe.JSDOM(this.rawReducedHTMLDom.serialize()),this.rrwebIdsReducedDom=new AUe.JSDOM(this.rawReducedHTMLDom.serialize());let o=e(S=>{S.window.document.body.querySelectorAll("[checksumid]:not([checksuminteractable])").forEach(P=>{P.removeAttribute("checksumid")})},"removeChecksumIdAttributeFromNonInteractable"),u=e((S,C)=>C.window.document.body.querySelectorAll(`[${S}]`).forEach(P=>P.removeAttribute(S)),"removeAttributeFromAllElements"),p=e(S=>u("checksuminteractable",S),"removeChecksumInteractableAttribute"),y=e(S=>u("checksumid",S),"removeChecksumIdAttribute"),x=e(S=>u("rrwebid",S),"removeRrwebIdAttribute");o(this.reducedHTMLDom),p(this.expandedChecksumIdsReducedDom),p(this.reducedHTMLDom),p(this.rrwebIdsReducedDom),x(this.expandedChecksumIdsReducedDom),x(this.reducedHTMLDom),y(this.rrwebIdsReducedDom)}getDOMForType(o){switch(o){default:case"checksumIds":return this.reducedHTMLDom;case"expandedChecksumIds":return this.expandedChecksumIdsReducedDom;case"rrwebIds":return this.rrwebIdsReducedDom}}async enrich(o){return await o(this.rawReducedHTMLDom),this.process(),this}setActiveDomType(o){this.activeDOMType=o}getActiveDom(){return this.getDOMForType(this.activeDOMType)}getActiveDOMString(){return this.getActiveDom().serialize()}getRrwebIdsReducedDomString(){return this.rrwebIdsReducedDom.serialize()}getDOMStringForType(o){return this.getDOMForType(o).serialize()}get raw(){return this.rawReducedHTMLDom}};e(t$t,"ReducedHTMLDOM");var kUe=t$t;var Dhr=Xv(require("path"));var n$t=class n$t{constructor(o="all"){this.listeners=[];this.logLevel=o}log(...o){try{let p=new Error().stack.split(`
|
|
1418
1418
|
`)[4].trim().match(/\(([^)]+)\)/);if(!(p&&p[1]))throw new Error;let y=p[1].split(":"),x=y.slice(0,-2).join(":"),S=y[y.length-2],P=`${Dhr.default.basename(x)}:${S}`;console.log("\x1B[34m",P,"\x1B[0m",...o),setTimeout(()=>this.listeners.forEach(F=>F.onLog(...o)),0)}catch{console.log(...o)}}addListener(o){this.listeners.push(o)}info(...o){this.logLevel==="all"&&this.log(...o)}warning(...o){(this.logLevel==="all"||this.logLevel==="warnings")&&this.log(...o)}error(...o){this.log(...o)}setLogLevel(o){this.logLevel=o}};e(n$t,"Logger");var r$t=n$t,VCe=new r$t,dsn=Object.assign((...s)=>VCe.info(...s),{info:e((...s)=>VCe.info(...s),"info"),warning:e((...s)=>VCe.warning(...s),"warning"),error:e((...s)=>VCe.error(...s),"error"),setLogLevel:e(s=>VCe.setLogLevel(s),"setLogLevel"),addLogListener:e(s=>VCe.addListener(s),"addLogListener")}),bm=dsn;var i$t=class i$t{constructor(o,u,p={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4}){this.frameMsgBroker=o;this.injectedScriptManager=u;this.options=p;this.taskQueue=[];this.isRunning=!1;this.currentTimestamp=0;this.currentBeforeTimestamp=!1;this.timeMachineTaskIndex=0;this.currentChecksumId="0";this.timeGoingBack=0;this.timeRunningTasks=0;this.tasksExecuted=0;this.reducedHTMLCache={};this.getReducedHTMLWithRetries=e(async(o,{retriesLeft:u=3,retryWaitMS:p=1e3}={})=>{try{let{reducedHTML:y,currentChecksumId:x}=await o.evaluate(async S=>{var C,P;return(P=(C=window==null?void 0:window.checksum)==null?void 0:C.testGenerator)==null?void 0:P.reduceHTML({},S)},{stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:this.currentChecksumId,fromTimeMachine:!0,invalidateCache:!0});return this.currentChecksumId=x,{reducedHTML:y}}catch(y){if(u>0)return await f6(p),this.getReducedHTMLWithRetries(o,{retriesLeft:u-1,retryWaitMS:p});throw y}},"getReducedHTMLWithRetries");this.rrwebEventHandler=e(async o=>{let u=JSON.stringify(o);await this.timeMachineFrame.evaluate(function(p){let y=JSON.parse(p);return window.checksum.timeMachine.handleEvents(y)},u),o=null},"rrwebEventHandler")}getPage(){return this.timeMachineFrame.page()}getFrame(){return this.timeMachineFrame}async prepare(o,u,p){this.recordingFrame=o,this.frameMsgBroker.register("live",o),u?this.timeMachineFrame=u:this.timeMachineFrame=await this.prepareBrowserContextAndFrame(),p&&p(this.timeMachineFrame),await this.injectedScriptManager.addTrackedFrame(this.timeMachineFrame),this.subscribeToRrwebEvents(),this.taskQueue=[],this.isRunning=!1,await this.start()}async start(){await this.timeMachineFrame.evaluate(async()=>{window.checksum.timeMachine.start({firstEventTimestamp:Date.now()})})}setBrowserContext(o){this.timeMachineBrowserContext=o}async executeTask(o,u=void 0,{name:p,beforeTimestamp:y=!1}={}){return new Promise((x,S)=>{let C=this.timeMachineTaskIndex++,P=e(async({shouldGoBack:F,shouldBatch:B}={shouldGoBack:!0,shouldBatch:this.options.timestampBatchingEnabled})=>{if(this.timeMachineFrame.isDetached()&&S(),F){let W=Date.now();await this.goBack(u,y),this.timeGoingBack+=Date.now()-W}let j=[e(async()=>{try{let W=Date.now(),z=await m5(o(this.timeMachineFrame),this.options.taskTimeout,()=>`Task execution timeout - ${p}, took ${Date.now()-W}ms with timeout of ${this.options.taskTimeout}ms`);x(z)}catch(W){bm.error("Task execution error:",W.message),S(W)}},"safeRunTask")()];this.taskQueue.length>0&&B&&(j.push(...this.taskQueue.filter(W=>W.timestamp===u).map(({task:W})=>W({shouldGoBack:!1,shouldBatch:!1}))),this.taskQueue=this.taskQueue.filter(W=>W.timestamp!==u),j.length&&console.log(`Batching to task "${p}, index: ${C} ${j.length-1} more tasks`)),await Promise.all(j)},"taskWrapper");this.taskQueue.push({name:p,task:P,timestamp:y?u-1:u,queuedAt:Date.now(),index:C}),this.runTasks()})}executeReducedHTMLTask(o){if(this.reducedHTMLCache[o]){let u=new kUe(this.reducedHTMLCache[o]);return Promise.resolve(u.getRrwebIdsReducedDomString())}return this.executeTask(async u=>{let p="",y=await this.getReducedHTMLWithRetries(u);return p=y==null?void 0:y.reducedHTML,p&&(this.reducedHTMLCache[o]=p),new kUe(p).getRrwebIdsReducedDomString()},o,{name:"getReducedHTMLForTimestamp"})}goBack(o,u=!1){return this.currentBeforeTimestamp===u&&this.currentTimestamp===o?Promise.resolve():(this.currentTimestamp=o,this.currentBeforeTimestamp=u,this.timeMachineFrame.evaluate(({timestamp:p,beforeTimestamp:y})=>p===void 0?window.checksum.timeMachine.goLive():window.checksum.timeMachine.goBack(p,{beforeTimestamp:y}),{timestamp:o,beforeTimestamp:u}))}goLive(){return this.timeMachineFrame.evaluate(()=>window.checksum.timeMachine.goLive())}popTask(){return this.options.sortByTimestamp&&(this.taskQueue=this.taskQueue.sort((o,u)=>o.timestamp-u.timestamp)),this.taskQueue.shift()}async runTasks(){if(this.isRunning)return;this.isRunning=!0;let o=this.popTask(),u=Date.now();try{let p=Date.now()-o.queuedAt;bm.info(`Running task, timestamp: ${o.timestamp} \x1B[36m${o.name}\x1B[0m, index: ${o.index}, was pending for`,p),await o.task();let y=Date.now()-u;this.timeRunningTasks+=y,bm.info("Finished running task, took",y,"ms.","Queue length:",this.taskQueue.length),this.tasksExecuted++}catch(p){bm.error("Task execution error:",p)}finally{this.isRunning=!1,this.taskQueue.length>0?this.runTasks():bm.info("Accumulated time running tasks:",this.timeRunningTasks,"ms, from which time spent going back:",this.timeGoingBack)}}async makeBrowserContext(){let o=await Shr.chromium.launch({devtools:!1,headless:this.options.headless});return this.timeMachineBrowserContext=await o.newContext({bypassCSP:!0}),this.timeMachineBrowserContext}async makeFrame(){return(await this.timeMachineBrowserContext.newPage()).mainFrame()}async prepareBrowserContextAndFrame(){return this.timeMachineBrowserContext||await this.makeBrowserContext(),this.makeFrame()}subscribeToRrwebEvents(){let o="rrweb";this.frameMsgBroker.subscribeToChannel(o,this.timeMachineFrame,{originFrame:this.recordingFrame,handler:this.rrwebEventHandler}),this.timeMachineFrame.page().on("close",()=>this.frameMsgBroker.unsubscribeFromChannel(o,this.timeMachineFrame))}async toggleTimeMachineHandleEvents(o){try{await this.timeMachineFrame.evaluate(u=>window.checksum.timeMachine.setShouldHandleEvents(u),o)}catch{}}};e(i$t,"ChecksumTimeMachine");var Jpe=i$t;var a$t=require("@playwright/test");var s$t=class s$t extends Jpe{setTimeMachineBrowserContext(o){this.timeMachineBrowserContext=o}getTimeMachineBrowserContext(){return this.timeMachineBrowserContext}async makeBrowserContext(){a$t.chromium._checksumInternal=!0;let o=await a$t.chromium.launch({devtools:!1,headless:this.options.headless});return o._checksumInternal=!0,this.timeMachineBrowserContext=await o.newContext({bypassCSP:!0}),this.timeMachineBrowserContext._checksumInternal=!0,this.timeMachineBrowserContext.tracing.stop(),this.timeMachineBrowserContext.tracing.stop=async()=>{},this.timeMachineBrowserContext.tracing.stopChunk=async()=>{},this.timeMachineBrowserContext}async makeFrame(){let o=await this.timeMachineBrowserContext.newPage();o._checksumInternal=!0;let u=o.mainFrame();return u._checksumInternal=!0,u}};e(s$t,"RuntimeTimeMachine");var wdt=s$t;var o$t=1e3*30;var x7e=class x7e{constructor(o,u="normal",p,y,x,S,C,P,F,B,J,j,W){this.page=o;this.runMode=u;this.analytics=p;this.codeMirror=y;this.monitorBridge=x;this.testInfo=S;this.checksumTestId=C;this.test=P;this.options=F;this.isReplMode=B;this.config=J;this.pageInteractorAPI=j;this.locatorStack=[];this.hasRuntimeStartedTrace=!1;this.unzippedHarData=[];this.fallbacks=[];this.hasHealed=!1;this.thoughtsCounter=0;this.highLevelThoughts=[];this.pages={};this.framesMsgBroker=new UCe;this.scriptLoadWrapper=e(async(o,u)=>{var p;return u!==((p=this.timeMachine)==null?void 0:p.getFrame())&&this.navigationPromise&&await this.navigationPromise,this.wrapInternalSteps(o,u.page())},"scriptLoadWrapper");this.scriptLoadCheck=e(async o=>o.evaluate(()=>!!window.checksum),"scriptLoadCheck");this.scriptLoadCallback=e(async o=>{var u,p;await o.evaluate(async({appSpecificRules:y,esraTimeout:x,sessionRecorder:S,showFrontendLogs:C,showTMSeeker:P})=>{var F;(F=window.checksum)==null||F.testGenerator.init(y,{esraTimeout:x,showFrontendLogs:C,skipElementHighlighting:!0},{assertionGenerator:!1,sessionRecorder:S});try{P&&window.checksum.timeMachine.openSeekbar()}catch{}},{appSpecificRules:this.appSpecificRules,esraTimeout:o$t,sessionRecorder:o!==((u=this.timeMachine)==null?void 0:u.getFrame()),showFrontendLogs:Qv.isDevMode,showTMSeeker:o===((p=this.timeMachine)==null?void 0:p.getFrame())&&process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"}),Db(`[init] init script loaded for ${o.page().url()}`)},"scriptLoadCallback");var le,ye;fft(F.printLogs),(J.useVtg||process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG)&&(this.options={...this.options,useChecksumAI:{actions:!1,assertions:!1},useMockData:!1,useChecksumSelectors:!1,autoHealPRs:!1}),this.analytics.setTestId(this.checksumTestId);let z=kpe({config:this.config,throwIfAuthFailed:!0});this.injectedScriptManager=new qCe({scriptFile:Qv.checksumScript.path,scriptSource:Qv.checksumScript.source,scriptURL:Qv.checksumScript.url,isScriptFileAbsolute:!0}),this.injectedScriptManager.setScriptLoadWrapper(this.scriptLoadWrapper).setScriptLoadCallback(this.scriptLoadCallback).setScriptLoadCheck(this.scriptLoadCheck);let Y=this.getPlaywrightProjectConfig();this.pageInteractor=new MCe(this.evaluateWithChecksum.bind(this),()=>this.page.mainFrame(),()=>this.timeMachine,{log:Db,logError:Db},{navigationTimeout:(le=Y.use)==null?void 0:le.navigationTimeout,actionTimeout:(ye=Y.use)==null?void 0:ye.actionTimeout,testAssetsDir:oJt(Ape()),waitActionDelay:1e3},this.pageInteractorAPI,z),this.setPageProxy(),this.registerPageEvents(),this.checkForActiveTracing(),this.resetFallbacks(),this.checksumClient=new BCe({apiURL:this.config.apiURL,apiKey:this.config.apiKey}),W&&(this.highLevelThoughts=W.highLevelThoughts??[],this.pages=W.pages??{},this.timeMachineBrowserContext=W.timeMachineBrowserContext,this.variableStore=W.variableStore),Qv.testRun.timeMachine.active&&(this.timeMachine=new wdt(this.framesMsgBroker,this.injectedScriptManager,{headless:process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"?!1:Qv.testRun.timeMachine.headless}),this.timeMachineBrowserContext&&this.timeMachine.setTimeMachineBrowserContext(this.timeMachineBrowserContext)),this.pages[this.getPageGuid(o)]=this.proxy}static async init(o,u,p,y,x,S,C,P,F,B=!1){C||(C=Tpe(5),console.warn(`Checksum test id was not defined for test "${S.title}" and was auto-generated. Please replace - "${S.title}" with -
|
|
1419
|
-
test(defineChecksumTest("${S.title}", "${C}"), async ({ page }) => {...`)),y.addTestInfo(C,S.testId),F.options.useChecksumAI!==void 0&&typeof F.options.useChecksumAI=="boolean"&&(F.options.useChecksumAI={actions:F.options.useChecksumAI,assertions:!1});let J=new jCe(F),j=new x7e(o,F.runMode,u,p,y,S,C,P,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:F.runMode!=="normal",useMockData:!1,printLogs:!1,...F.options},B,F,J,{variableStore:x});return P._checksum.expect.setPage(j),P._checksum.checksumAI.page=j,x.clearAll(),await j.asyncInit(),j.proxy}async asyncInit(o=!1){await this.loadAppSpecificRules(),await this.wrapInternalSteps(async()=>{await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")})}),this.timeMachine&&(await this.timeMachine.prepare(this.page.mainFrame()),this.timeMachineBrowserContext=this.timeMachine.getTimeMachineBrowserContext()),this.pageInteractor.init(),o||await this.prepareForTestArtifacts()}async getPage(o){let u=this.page.context().pages()[o];if(!u)throw new Error(`Page with index ${o} not found`);return this.makePage(u)}async makePage(o){let u=this.getPageGuid(o);if(this.pages[u])return this.pages[u];let p=new x7e(o,this.runMode,this.analytics,this.codeMirror,this.monitorBridge,this.testInfo,this.checksumTestId,this.test,this.options,this.isReplMode,this.config,this.pageInteractorAPI,{highLevelThoughts:this.highLevelThoughts,pages:this.pages,timeMachineBrowserContext:this.timeMachineBrowserContext,variableStore:this.variableStore});return await p.asyncInit(!0),p.proxy}getTimeMachinePage(){return this.timeMachine.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}async reauthenticate(o){try{await this.pageInteractor.reauthenticate(o)}catch(u){throw new Error(`Failed to reauthenticate: ${u}`)}}async waitForDialog(o){try{return this.pageInteractor.waitForDialog(!0,o)}catch(u){throw new Error(`Failed to handle native dialog: ${u}`)}}getPageGuid(o){return o._guid}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var p;let u=(p=this.getPlaywrightProjectConfig().use)==null?void 0:p.trace;this.traceMode=typeof u=="string"?u:u==null?void 0:u.mode}registerPageEvents(){this.injectedScriptManager.addTrackedFrame(this.page),this.page.on("framenavigated",async o=>{this.injectedScriptManager.onFrameNavigated(o)})}setPageProxy(){this.proxy=new Proxy(this,{get:e(function(u,p){return u.getPageMethod(p)},"get")})}getPageMethod(o){return typeof this[o]=="function"?o==="constructor"?this[o]:this[o].bind(this):!Object.values(Q5e).includes(o)||!this.testInfo?this.page[o]:(this.locatorStack.length===0&&(this.pageInitialCallInTestFile=this.getFirstStackTraceFromTestFile()),this.pushToLocatorStack([{type:o,base:this.page,line:this.pageInitialCallInTestFile.line}]),e(function(p,y){try{return this.executeLocator(p,y)}catch(x){throw this.popLocatorChain(),x}},"Page").bind(this))}checksumSelector(o){return this.checksumStepId=o,this.options.useChecksumSelectors&&this.setSelectorFallback(o),this.proxy}checksumAI(o,u,p){let y=this.addNewThought(o,"action",!!u);return this.locatorStack=[],u?this.test.step(o,async()=>{var x;try{return p!=null&&p.withDialog&&this.pageInteractor.listenToDialog(),await u()}catch(S){if(y.children=[],!this.options.useChecksumAI.actions||p!=null&&p.withDialog)throw S;this.setAIFallback(o);try{return await this.initiateFallbackSequence({type:"action",error:S,method:void 0,args:[],testInfo:this.testInfo},{fallbackTypes:[nhe]})}catch{this.analytics.actionExecutionFailure({thought:o})}return await this.initiateFallbackSequence({type:"action",error:S,method:void 0,args:[]},{fallbackTypes:[nhe]})}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(x=this.currentThought)==null?void 0:x.parent}}):(this.options.useChecksumAI.actions&&this.setAIFallback(o),this.proxy)}resolveAssetsFolder(o){return o.map(u=>zpe.join(oJt(Ape()),u))}compoundSelection(...o){var u;try{let p=this.locatorStack.length?(u=this.getCurrentLocatorInChain())==null?void 0:u.base:void 0,y=new gdt(this.page,this,this.executeLocatorAction.bind(this),p??this.page);return this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),y.init(...o)}catch{throw new Error("Failed generating compound selector")}}getRuntimeOptions(){return this.options}async onTestComplete(o){await this.sendTestArtifacts(),this.cleanupMockData()}async wrapInternalSteps(o,u=this.page){try{return u.mainFrame()._checksumInternal=!0,u._checksumInternal=!0,await o()}finally{u.mainFrame()._checksumInternal=!1,u._checksumInternal=!1}}async conditionallyWrapInternalSteps(o,u){return o?this.wrapInternalSteps(u):u()}async wrapNoLocationSteps(o){try{return this.testInfo._checksumNoLocation=!0,await o()}finally{this.testInfo._checksumNoLocation=!1}}async step(o,u,p=!0,{obtainStep:y=void 0,box:x=!1}={}){try{return this.testInfo._checksumInternal=p===!0,await this.test.step(o,u||(()=>{}),{obtainStep:y,box:x})}finally{this.testInfo._checksumInternal=!1}}addErrorMessage(o,u){this.testInfo.addError(o,u)}async evaluateWithChecksum(o,u,p=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(p,()=>this.page.evaluate(o,u))}addNewThought(o,u,p=!1){let y={id:void 0,thought:o,type:u,children:p?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(y);else if(this.currentThought.children)this.currentThought.children.push(y),y.parent=this.currentThought;else{let x=this.currentThought.parent;x?(x.children.push(y),y.parent=x):this.highLevelThoughts.push(y)}return y.parent?y.id=`${y.parent.id}.${y.parent.children.length}`:y.id=`${++this.thoughtsCounter}`,this.currentThought=y,y}buildThoughtsChainForFallback(o=this.highLevelThoughts){let u=[];return o.forEach(p=>{u.push(p.thought),p.children&&u.push(...this.buildThoughtsChainForFallback(p.children))}),u}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.page)}pushToLocatorStack(o){this.locatorStack.push(o)}getCurrentLocatorChain(){return this.locatorStack.length||this.locatorStack.push([]),this.locatorStack[this.locatorStack.length-1]}popLocatorChain(){return this.locatorStack.pop()}getCurrentLocatorInChain(){let o=this.getCurrentLocatorChain();return o==null?void 0:o[o.length-1]}getLocator(o,u){let p=this.getCurrentLocatorInChain();return p.base[p.type](o,u)}getFirstStackTraceFromTestFile(){let o=this.getTestFileStackTrace()[0];if(!o)throw new Error(`Could not find test file location from stack trace ${x7e.getStackTrace()}`);let p=[/\((.*):(\d+):(\d+)\)$/,/.*at (.*):(\d+):(\d+)$/].map(C=>C.exec(o)).find(C=>C!==null);if(!p)throw new Error(`Could not find test file location from stack trace ${o}`);let[,y,x,S]=p;return{file:y,line:parseInt(x),column:parseInt(S)}}getTestFileStackTrace(){return x7e.getStackTrace().filter(u=>u.includes(this.testInfo.file))}static getStackTrace(){return new Error().stack.split(`
|
|
1419
|
+
test(defineChecksumTest("${S.title}", "${C}"), async ({ page }) => {...`)),y.addTestInfo(C,S.testId),F.options.useChecksumAI!==void 0&&typeof F.options.useChecksumAI=="boolean"&&(F.options.useChecksumAI={actions:F.options.useChecksumAI,assertions:!1});let J=new jCe(F),j=new x7e(o,F.runMode,u,p,y,S,C,P,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:F.runMode!=="normal",useMockData:!1,printLogs:!1,...F.options},B,F,J,{variableStore:x});return P._checksum.expect.setPage(j),P._checksum.checksumAI.page=j,x.clearAll(),await j.asyncInit(),j.proxy}async asyncInit(o=!1){await this.loadAppSpecificRules(),await this.wrapInternalSteps(async()=>{await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")})}),this.timeMachine&&(await this.timeMachine.prepare(this.page.mainFrame()),this.timeMachineBrowserContext=this.timeMachine.getTimeMachineBrowserContext()),this.pageInteractor.init(),o||await this.prepareForTestArtifacts()}async getPage(o){let u=this.page.context().pages()[o];if(!u)throw new Error(`Page with index ${o} not found`);return this.makePage(u)}async makePage(o){let u=this.getPageGuid(o);if(this.pages[u])return this.pages[u];let p=new x7e(o,this.runMode,this.analytics,this.codeMirror,this.monitorBridge,this.testInfo,this.checksumTestId,this.test,this.options,this.isReplMode,this.config,this.pageInteractorAPI,{highLevelThoughts:this.highLevelThoughts,pages:this.pages,timeMachineBrowserContext:this.timeMachineBrowserContext,variableStore:this.variableStore});return await p.asyncInit(!0),p.proxy}getTimeMachinePage(){return this.timeMachine.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}async reauthenticate(o){try{await this.pageInteractor.reauthenticate(o,this.proxy)}catch(u){throw new Error(`Failed to reauthenticate: ${u}`)}}async waitForDialog(o){try{return this.pageInteractor.waitForDialog(!0,o)}catch(u){throw new Error(`Failed to handle native dialog: ${u}`)}}getPageGuid(o){return o._guid}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var p;let u=(p=this.getPlaywrightProjectConfig().use)==null?void 0:p.trace;this.traceMode=typeof u=="string"?u:u==null?void 0:u.mode}registerPageEvents(){this.injectedScriptManager.addTrackedFrame(this.page),this.page.on("framenavigated",async o=>{this.injectedScriptManager.onFrameNavigated(o)})}setPageProxy(){this.proxy=new Proxy(this,{get:e(function(u,p){return u.getPageMethod(p)},"get")})}getPageMethod(o){return typeof this[o]=="function"?o==="constructor"?this[o]:this[o].bind(this):!Object.values(Q5e).includes(o)||!this.testInfo?this.page[o]:(this.locatorStack.length===0&&(this.pageInitialCallInTestFile=this.getFirstStackTraceFromTestFile()),this.pushToLocatorStack([{type:o,base:this.page,line:this.pageInitialCallInTestFile.line}]),e(function(p,y){try{return this.executeLocator(p,y)}catch(x){throw this.popLocatorChain(),x}},"Page").bind(this))}checksumSelector(o){return this.checksumStepId=o,this.options.useChecksumSelectors&&this.setSelectorFallback(o),this.proxy}checksumAI(o,u,p){let y=this.addNewThought(o,"action",!!u);return this.locatorStack=[],u?this.test.step(o,async()=>{var x;try{return p!=null&&p.withDialog&&this.pageInteractor.listenToDialog(),await u()}catch(S){if(y.children=[],!this.options.useChecksumAI.actions||p!=null&&p.withDialog)throw S;this.setAIFallback(o);try{return await this.initiateFallbackSequence({type:"action",error:S,method:void 0,args:[],testInfo:this.testInfo},{fallbackTypes:[nhe]})}catch{this.analytics.actionExecutionFailure({thought:o})}return await this.initiateFallbackSequence({type:"action",error:S,method:void 0,args:[]},{fallbackTypes:[nhe]})}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(x=this.currentThought)==null?void 0:x.parent}}):(this.options.useChecksumAI.actions&&this.setAIFallback(o),this.proxy)}resolveAssetsFolder(o){return o.map(u=>zpe.join(oJt(Ape()),u))}compoundSelection(...o){var u;try{let p=this.locatorStack.length?(u=this.getCurrentLocatorInChain())==null?void 0:u.base:void 0,y=new gdt(this.page,this,this.executeLocatorAction.bind(this),p??this.page);return this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),y.init(...o)}catch{throw new Error("Failed generating compound selector")}}getRuntimeOptions(){return this.options}async onTestComplete(o){await this.sendTestArtifacts(),this.cleanupMockData()}async wrapInternalSteps(o,u=this.page){try{return u.mainFrame()._checksumInternal=!0,u._checksumInternal=!0,await o()}finally{u.mainFrame()._checksumInternal=!1,u._checksumInternal=!1}}async conditionallyWrapInternalSteps(o,u){return o?this.wrapInternalSteps(u):u()}async wrapNoLocationSteps(o){try{return this.testInfo._checksumNoLocation=!0,await o()}finally{this.testInfo._checksumNoLocation=!1}}async step(o,u,p=!0,{obtainStep:y=void 0,box:x=!1}={}){try{return this.testInfo._checksumInternal=p===!0,await this.test.step(o,u||(()=>{}),{obtainStep:y,box:x})}finally{this.testInfo._checksumInternal=!1}}addErrorMessage(o,u){this.testInfo.addError(o,u)}async evaluateWithChecksum(o,u,p=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(p,()=>this.page.evaluate(o,u))}addNewThought(o,u,p=!1){let y={id:void 0,thought:o,type:u,children:p?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(y);else if(this.currentThought.children)this.currentThought.children.push(y),y.parent=this.currentThought;else{let x=this.currentThought.parent;x?(x.children.push(y),y.parent=x):this.highLevelThoughts.push(y)}return y.parent?y.id=`${y.parent.id}.${y.parent.children.length}`:y.id=`${++this.thoughtsCounter}`,this.currentThought=y,y}buildThoughtsChainForFallback(o=this.highLevelThoughts){let u=[];return o.forEach(p=>{u.push(p.thought),p.children&&u.push(...this.buildThoughtsChainForFallback(p.children))}),u}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.page)}pushToLocatorStack(o){this.locatorStack.push(o)}getCurrentLocatorChain(){return this.locatorStack.length||this.locatorStack.push([]),this.locatorStack[this.locatorStack.length-1]}popLocatorChain(){return this.locatorStack.pop()}getCurrentLocatorInChain(){let o=this.getCurrentLocatorChain();return o==null?void 0:o[o.length-1]}getLocator(o,u){let p=this.getCurrentLocatorInChain();return p.base[p.type](o,u)}getFirstStackTraceFromTestFile(){let o=this.getTestFileStackTrace()[0];if(!o)throw new Error(`Could not find test file location from stack trace ${x7e.getStackTrace()}`);let p=[/\((.*):(\d+):(\d+)\)$/,/.*at (.*):(\d+):(\d+)$/].map(C=>C.exec(o)).find(C=>C!==null);if(!p)throw new Error(`Could not find test file location from stack trace ${o}`);let[,y,x,S]=p;return{file:y,line:parseInt(x),column:parseInt(S)}}getTestFileStackTrace(){return x7e.getStackTrace().filter(u=>u.includes(this.testInfo.file))}static getStackTrace(){return new Error().stack.split(`
|
|
1420
1420
|
`)}executeLocator(o,u){try{Db(`
|
|
1421
1421
|
Executing locator ${this.getCurrentLocatorInChain().type} with ${typeof o=="string"?`selector ${o}`:"locator"}`);try{o&&typeof o=="object"&&"has"in o&&this.popLocatorChain()}catch{}let p=this.getLocator(o,u);return new Proxy(p,{get:e((y,x)=>this.getLocatorMethod(p,y,x),"get")})}catch(p){Db("Failed to locate",p)}}getLocatorMethod(o,u,p){return p==="then"?this.handleThen(o,u,p):p==="catch"?this.handleCatch(o,u):p==="finally"?this.handleFinally(o,u):p==="constructor"?e(function(...x){return this.popLocatorChain(),u.constructor(...x)},"Locator"):p in u&&typeof u[p]!="function"||p===Symbol.toPrimitive||p in Object?(this.popLocatorChain(),u[p]):p==="compoundSelection"?function(...y){let x=this.compoundSelection(...y);return x.setBase(o),x}.bind(this):[...Object.values(Q5e),...Object.values(Z5e)].includes(p)?["or","and"].includes(p)?(Db("'Or' and 'And' locator are not supported, will execute normally"),this.popLocatorChain(),u[p]):(this.getCurrentLocatorChain().push({type:p,base:o}),e(function(...x){return this.executeLocator(x[0],x[1])},"Locator").bind(this)):p==="page"?()=>(this.popLocatorChain(),this.proxy):e(async function(...x){let S=await this.executeLocatorAction(o,p,x);return this.popLocatorChain(),S},"Locator").bind(this)}async executeLocatorAction(o,u,p){if(p&&Array.from(p).some(P=>(P==null?void 0:P.bypassChecksum)===!0))return o[u](...p);let y=o._selector,x=this.consumeChecksumStepId();Db("Executing",u,y);let S=u==="_expect"?"assertion":"action";S==="action"&&this.lastLocatorActionType==="action"&&(Db("Adding minimal wait between consecutive actions..."),await new Promise(P=>setTimeout(P,100))),this.lastLocatorActionType=S,Db("Running initial locator...");let C;try{this.navigationPromise&&await this.navigationPromise,await this.wrapInternalSteps(async()=>{try{Db("[executeLocatorAction] waitForFunction"),await this.page.waitForFunction(()=>!!window.checksum,{timeout:5e3})}catch{Db("[executeLocatorAction] checksum libs not loaded")}});let P=await Sdt.createAction({locator:o,method:u,args:p,timeout:this.getLocatorActionTimeout(S,u,p)},{api:this.checksumClient,pageInteractor:this.pageInteractor});if(S==="action"){if(P!==!1)return this.resetFallbacks(),P}else if(S==="assertion")return P;C=new Error("Locator action error")}catch(P){Db("Failed initial execution. Exception:",P.message),C=P}switch(S){case"action":try{return await this.initiateFallbackSequence({type:"action",locator:o,method:u,args:p,error:C})}catch(P){this.currentThought||this.analytics.actionExecutionFailure({locator:o,selector:o._selector,method:u,checksumId:x,error:P.toString()})}case"assertion":throw C}}consumeChecksumStepId(){let o=this.checksumStepId;return this.checksumStepId=void 0,o}setExpectConfiguration(o=void 0){this.expectConfiguration=o}getLocatorActionTimeout(o,u,p=[]){if(this.isReplMode)return null;if(o==="assertion"){let S=this.getAssertionTimeout(p);return Db(`Assertion timeout set to ${S}`),S}let y=["fill","dragTo"].includes(u)?1:0;return(p[y]??{}).timeout??3e4}getAssertionTimeout(o=[]){var y,x,S,C,P;let u=(y=o[1])==null?void 0:y.timeout;if(u!==void 0)return u;if(((x=this.expectConfiguration)==null?void 0:x.timeout)!==void 0)return(S=this.expectConfiguration)==null?void 0:S.timeout;let p=(P=(C=this.testInfo._projectInternal)==null?void 0:C.expect)==null?void 0:P.timeout;return p!==void 0?p:3e4}handleThen(o,u,p){return(y,x)=>Promise.resolve(o).then(S=>{let C=y?y(S):S;return C instanceof Promise?C:this.getLocatorMethod(C,u,p)},S=>{if(x)return x(S);throw S})}handleCatch(o,u){return p=>Promise.resolve(o).catch(y=>{if(p)return p(y);throw y})}handleFinally(o,u){return p=>Promise.resolve(o).finally(p)}setSelectorFallback(o){let u={checksumId:o,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:o$t};this.pushFallback(this.constructFallback(Rqe).init(u)),this.pushFallback(this.constructFallback(wUe).init(u))}setCompoundSelectorFallback(o){this.pushFallback(this.constructFallback(EUe).init({checksumId:o,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:o$t}))}setAIFallback(o){return this.pushFallback(this.constructFallback(nhe).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback()})),this.proxy}pushFallback(o){this.fallbacks.push(o),this.sortFallbacks()}async runFallback(o,u){this.analytics.fallbackStart(o);let p=o.resolve(u),y=await m5(p,o.timeout);if(!y)throw new Error("Fallback failed");if(this.hasHealed=!0,y.steps.length===1){let x=y.steps[0];x.thought&&(this.currentThought.thought=x.thought)}else this.currentThought.children=y.steps.map((x,S)=>({id:`${this.currentThought.id}.${S+1}`,thought:x.thought,type:x.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(o,u,p){return o?await this.step(u,p):await p()}async initiateFallbackSequence(o,{fallbackTypes:u=void 0}={}){Db(`[initiateFallbackSequence] with type: ${o.type}...`);let p=this.fallbacks.find(x=>x instanceof nhe);if(p){let x=p.getFailedThought(),S=this.variableStore.getActiveVariables();this.fallbacks.forEach(C=>{C.setThought(x),C.setVariables(S)})}let y=this.fallbacks;u&&(y=y.filter(x=>u.reduce((S,C)=>S||x instanceof C,!1))),y=y.filter(x=>x.canResolve(o));try{for(let x of y){let S=x==null?void 0:x.toString();S&&console.log(`Using ${S}`);let C;try{await this.runConditionallyWithinStep(o.type!=="assertion"||!o.withChecksumAI,x.getRecoveryAttemptTitle(o),async()=>{await this.runFallback(x,o)}),C=!0}catch(P){if(C=!1,o.withChecksumAI&&P.message==="fetch failed")throw new Error(Q1e);S&&console.log(`Failed to use ${S}`),x.cancel();continue}finally{this.analytics[`${o.type}FallbackExecution`](C,x)}return!0}throw o.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(Mqe).init()]}async shutdown(){if(this.analytics)return Db("Flushing events..."),this.analytics.close()}sortFallbacks(){let o=[Mqe,EUe,Rqe,wUe,nhe];this.fallbacks.sort((u,p)=>o.indexOf(u.constructor)-o.indexOf(p.constructor))}constructFallback(o){return new o(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,this.analytics,{generateSelectionData:this.runMode!=="normal"})}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let u=await this.getTraceFilePath();u&&this.monitorBridge.addAsset({type:"trace",path:u,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let u=rfr(eCe(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:u,testId:this.checksumTestId})}}async sendTestArtifacts(){this.runMode!=="normal"&&(await this.codeMirror.write()).forEach(o=>this.monitorBridge.addAsset(o))}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?nfr(eCe(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let o=uJt(eCe(this.testInfo.file)),u=zpe.join(o,`${this.checksumTestId}.har.zip`);if(!(0,Eq.existsSync)(u))throw new Error("Could not find har file or zip file");let p=zpe.join(o,"tmp");(0,Eq.existsSync)(p)||(0,Eq.mkdirSync)(p);let y=(0,Eq.readFileSync)(u),x=await(0,Ehr.loadAsync)(y);for(let C of Object.keys(x.files)){let P=await x.file(C).async("string"),F=zpe.join(p,C);(0,Eq.writeFileSync)(F,P),this.unzippedHarData.push(F)}let S=zpe.join(p,"test.har");if(!(0,Eq.existsSync)(S))throw this.cleanupMockData(),new Error(`Could not find har file ${S} after unzipping ${u}`);return S}cleanupMockData(){this.unzippedHarData.forEach(o=>{(0,Eq.rmSync)(o)}),this.unzippedHarData.length>0&&(0,Eq.rmSync)(zpe.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let o={GET:0,POST:0,PUT:0,DELETE:0};try{let u=await this.prepareMockData();await this.page.routeFromHAR(u,{url:"*/**",notFound:"fallback",update:!1});let p=this.page._routes[0].handler;await this.page.route("**/*",y=>{let x=y.request().headers(),S=y.request().method();x["Checksum-Id"]=(++o[S]).toString(),y.request()._applyFallbackOverrides({headers:x}),p(y)})}catch(u){Db("Error setting up mock data",u.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let o=zpe.join(tCe(Ape()),"settings.asr");if(!(0,Eq.existsSync)(o)){Db("Could not find ASR file");return}let{ungzip:u}=oft();try{let p=await u((0,Eq.readFileSync)(o));this.appSpecificRules=JSON.parse(p)||{}}catch(p){Db("Could not read ASR file",p.message)}}};e(x7e,"ChecksumPage");var Adt=x7e;var b7e=Xv(Fpe()),Chr=Xv(require("path")),Wpe=require("fs");var PUe=class PUe{constructor(o,u){this.runMode=o;this.assertionCodeGenerator=u;this.lines=[];this.linesOffsetFromOriginalFile=0;let p={getPageRegexMatchingUrl:e(()=>null,"getPageRegexMatchingUrl"),resolvePageIdFromUrl:e(()=>null,"resolvePageIdFromUrl")}}static init(o,u){return new PUe(o,u)}static initWithContent(o,u){let p=new PUe("normal",u);return p.lines=[o],p}async load(o,u){if(this.filename)return;this.filename=o,this.testId=u;let p=this.getProcessedFilename(this.filename);(0,Wpe.existsSync)(p)&&(0,Wpe.unlinkSync)(p),this.lines=["",...(0,Wpe.readFileSync)(this.filename,"utf-8").split(`
|
|
1422
1422
|
`)];try{this.esraMetadataMap=await uft(eCe(p),u)}catch{console.log("[CodeMirror] Failed loading ESRA metadata for test file, creating new ESRA map"),this.esraMetadataMap={}}}addTestToCode(o,u){let p=b7e.createSourceFile("",this.lines.join(""),b7e.ScriptTarget.ES2015),y=this.findTitleInParentNode(this.getSourceFileChildren(p),p,o.description);if(y){let C=p.text.substring(0,y.pos)+u.generateSingleTestCode(o)+p.text.substring(y.end);return u.styleCode(C)}let x=this.getLastDescribeNode(this.getSourceFileChildren(p),p);if(x){let C=p.text.substring(0,p.text.substring(0,x.end).lastIndexOf("}")-1)+u.generateSingleTestCode(o)+"});";return u.styleCode(C)}let S=p.text+`
|