@checksum-ai/runtime 4.8.0 → 4.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env +1 -1
- package/cli.js +1 -1
- package/index.d.ts +1 -0
- package/index.js +1 -1
- package/package.json +1 -1
package/.env
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
CHECKSUM_RUNTIME_BUILD_TIME=2026-07-
|
|
1
|
+
CHECKSUM_RUNTIME_BUILD_TIME=2026-07-13T23:42:01.981Z
|
package/cli.js
CHANGED
|
@@ -767,7 +767,7 @@ ${l}`;return{success:!0,pages:c,message:d}}async switchPageHandler(s){if(!s.page
|
|
|
767
767
|
${n}`)}get createChecksumStep(){return n=>this.checksumPage.createChecksumStep(n)}get step(){return this.checksumPage.step.bind(this.checksumPage)}get runConditionallyWithinStep(){return(n,s,c)=>this.checksumPage.runConditionallyWithinStep(n,s,c)}async getScreenshotForElement(n){var s;try{let c=await this.getSelectionDataForChecksumId(n);if(!c)throw new Error(`Locator not found for checksumId: ${n}`);let l=((s=this.arConfig.modelConfig)==null?void 0:s.provider)==="anthropic"?"jpeg":"png";return(await this.page.locator(c.selector).screenshot({type:l})).toString("base64")}catch{throw new Error(`Failed to get screenshot for element: ${n}`)}}get analytics(){return this._analytics}get pageInteractor(){return this._pageInteractor}};t(MJ,"AutoRecoveryRuntimeIteratorUtils"),MJ.currentChecksumId="0";var QRe=MJ;async function Oar(i,n){let s;try{s=await i.json()}catch{s=void 0}return KEn({ok:i.ok,status:i.status,body:s},n)}t(Oar,"assertOkJson");function KEn(i,n){let s=i.body&&typeof i.body=="object"?i.body:void 0;if(!i.ok){let l=XEn(s==null?void 0:s.message);throw eCn(new Error(`${n.resource} failed (HTTP ${i.status})`+(l?`: ${l}`:".")),i.status)}if(!s)throw new Error(`${n.resource} (HTTP ${i.status}) returned a non-object body; expected JSON.`);let c=(n.requiredFields??[]).filter(l=>!s[l]);if(c.length>0)throw new Error(`${n.resource} (HTTP ${i.status}) response is missing required field${c.length>1?"s":""}: ${c.join(", ")}.`);return s}t(KEn,"assertJsonBody");function XEn(i){return typeof i=="string"?i:Array.isArray(i)?i.filter(n=>typeof n=="string").join("; "):""}t(XEn,"extractMessage");function eCn(i,n){return Object.assign(i,{status:n})}t(eCn,"withStatus");var URe=t(i=>{if(i.error!=null)return"ERROR";let n=i.status_code;if(typeof n=="number"&&n>=500)return"ERROR";let s=i.exit_code;return typeof s=="number"&&s!==0?"ERROR":"INFO"},"severityFor");var T_t=require("fs");var Mar="\x1B[31m",tCn="\x1B[33m",rCn="\x1B[32m",nCn="\x1B[36m",iCn="\x1B[2m",sCn="\x1B[1m",Tme="\x1B[0m",oCn=t(()=>{let i=process.env.WIDE_EVENT_PRETTY;return i==="true"||i==="1"?!0:i==="false"||i==="0"?!1:process.stdout.isTTY?!0:process.env.APP_ENV==="local"},"shouldPretty"),aCn=new Set(["severity","message","kind","timestamp","_startedAtMs"]),cCn=t(i=>{let n=new WeakSet;return JSON.stringify(i,(s,c)=>{if(typeof c=="bigint")return c.toString();if(typeof c=="object"&&c!==null){if(n.has(c))return"[Circular]";n.add(c)}return c})},"safeStringify"),lCn=t(i=>i==="ERROR"||i==="CRITICAL"?Mar:i==="WARNING"?tCn:rCn,"colorForSeverity"),uCn=t(i=>{let n=String(i.severity??"INFO"),s=`${lCn(n)}${n.padEnd(5)}${Tme}`,c=i.kind?`${nCn}${i.kind}${Tme}`:"",l=String(i.message??""),d=i.error&&typeof i.error=="object"?(()=>{let B=i.error;return` ${Mar}${B.type??"Error"}: ${B.message??""}${Tme}`})():"",h=["outcome","test_suite_run_id","status"],b=Object.entries(i).filter(([B,H])=>!aCn.has(B)&&H!=null&&B!=="error"&&typeof H!="object"),T=t(B=>{let H=h.indexOf(B);return H===-1?h.length:H},"rank"),k=b.sort(([B],[H])=>T(B)-T(H)).slice(0,8).map(([B,H])=>`${iCn}${B}=${Tme}${H}`).join(" ");return[s,sCn+c+Tme,l,k,d].filter(B=>B&&B.trim()!=="").join(" ")},"formatPretty"),fCn=t(i=>{let n=i.trace_id;if(typeof n!="string"||n==="")return i;let s=process.env.GCP_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT;return s?{...i,"logging.googleapis.com/trace":`projects/${s}/traces/${n}`}:i},"withGcpTraceField"),Pte=t(i=>{let n=oCn()?uCn(i):cCn(fCn(i));(0,T_t.writeSync)(1,n+`
|
|
768
768
|
`)},"emitEvent");var jRe=t(i=>{(0,T_t.writeSync)(2,i.endsWith(`
|
|
769
769
|
`)?i:`${i}
|
|
770
|
-
`)},"writeStderrLine");var dCn=t(i=>{let n=i.kind??"event",s=i.outcome?` ${i.outcome}`:"",c=typeof i.duration_ms=="number"?` ${i.duration_ms}ms`:"";return`${n}${s}${c}`.trim()},"defaultMessage"),pCn=t((i,n,s)=>{let c=Date.now(),l={timestamp:new Date().toISOString(),kind:i,...n},d=!1,h={set(b){return Object.assign(l,b),h},emit(b){d||(d=!0,b&&Object.assign(l,b),l.duration_ms===void 0&&(l.duration_ms=Date.now()-c),s(l))}};return h},"startHandle"),_Cn=t((i={})=>{let n=i.decide??(()=>!0),s=i.deriveMessage??dCn,c=i.label??"[wide-event]",l=i.sink??(b=>Pte(b)),d=t(b=>{if(!n(b))return;let T={severity:URe(b),message:b.message??s(b),...b};try{l(T)}catch(k){try{jRe(`${c} emit failed: ${String(k)}`)}catch{}}},"emit");return{emit:d,emitWideEvent:t((b,T={})=>{d({timestamp:new Date().toISOString(),kind:b,...T})},"emitWideEvent"),wideEvent:t((b,T={})=>pCn(b,T,d),"wideEvent"),configureSink:t(b=>{l=b},"configureSink")}},"createWideEvents"),Lar=t(i=>i==="true"||i==="1","truthy"),$Re=t(()=>Lar(process.env.CHECKSUM_WIDE_EVENTS)||Lar(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),x_t=_Cn({decide:t(()=>$Re(),"decide")}),mCn=x_t.configureSink,S6=t((i,n={})=>x_t.wideEvent(i,n),"wideEvent"),JRe=t((i,n={})=>{x_t.emitWideEvent(i,n)},"emitWideEvent"),MQ=t(i=>i instanceof Error?{type:i.name,message:i.message}:{type:"UnknownError",message:String(i)},"toErrorField");var I6=class I6 extends fR{getInitializationData(){if(!this.initializationData)throw new Error("ARFallback initialization data is not initialized");return this.initializationData}getAgent(){if(!this.agent)throw new Error("ARFallback agent is not initialized");return this.agent}getUtils(){if(!this.utils)throw new Error("ARFallback utils is not initialized");return this.utils}constructor(n,s,c,l,d,h,b){super(n,s,c,l,d,h,b),this.runtimePageContext=h}init(n){var s;return this.initializationData=n,(s=n.fallbackConfig).arMode??(s.arMode="
|
|
770
|
+
`)},"writeStderrLine");var dCn=t(i=>{let n=i.kind??"event",s=i.outcome?` ${i.outcome}`:"",c=typeof i.duration_ms=="number"?` ${i.duration_ms}ms`:"";return`${n}${s}${c}`.trim()},"defaultMessage"),pCn=t((i,n,s)=>{let c=Date.now(),l={timestamp:new Date().toISOString(),kind:i,...n},d=!1,h={set(b){return Object.assign(l,b),h},emit(b){d||(d=!0,b&&Object.assign(l,b),l.duration_ms===void 0&&(l.duration_ms=Date.now()-c),s(l))}};return h},"startHandle"),_Cn=t((i={})=>{let n=i.decide??(()=>!0),s=i.deriveMessage??dCn,c=i.label??"[wide-event]",l=i.sink??(b=>Pte(b)),d=t(b=>{if(!n(b))return;let T={severity:URe(b),message:b.message??s(b),...b};try{l(T)}catch(k){try{jRe(`${c} emit failed: ${String(k)}`)}catch{}}},"emit");return{emit:d,emitWideEvent:t((b,T={})=>{d({timestamp:new Date().toISOString(),kind:b,...T})},"emitWideEvent"),wideEvent:t((b,T={})=>pCn(b,T,d),"wideEvent"),configureSink:t(b=>{l=b},"configureSink")}},"createWideEvents"),Lar=t(i=>i==="true"||i==="1","truthy"),$Re=t(()=>Lar(process.env.CHECKSUM_WIDE_EVENTS)||Lar(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),x_t=_Cn({decide:t(()=>$Re(),"decide")}),mCn=x_t.configureSink,S6=t((i,n={})=>x_t.wideEvent(i,n),"wideEvent"),JRe=t((i,n={})=>{x_t.emitWideEvent(i,n)},"emitWideEvent"),MQ=t(i=>i instanceof Error?{type:i.name,message:i.message}:{type:"UnknownError",message:String(i)},"toErrorField");var I6=class I6 extends fR{getInitializationData(){if(!this.initializationData)throw new Error("ARFallback initialization data is not initialized");return this.initializationData}getAgent(){if(!this.agent)throw new Error("ARFallback agent is not initialized");return this.agent}getUtils(){if(!this.utils)throw new Error("ARFallback utils is not initialized");return this.utils}constructor(n,s,c,l,d,h,b){super(n,s,c,l,d,h,b),this.runtimePageContext=h}init(n){var s;return this.initializationData=n,(s=n.fallbackConfig).arMode??(s.arMode="one_shot"),this}canResolve(n){return!0}get failingThought(){return this.getInitializationData().thoughts.failing}getRecoveryAttemptTitle(){switch(this.getInitializationData().type){case"action":return`Checksum Auto-Recovery: trying to achieve action "${this.failingThought}"...`;case"assertion":return`Checksum Auto-Recovery: trying to verify assertion "${this.failingThought}"...`;default:return`Checksum Auto-Recovery: trying to achieve action "${this.failingThought}"...`}}static async registerSession(n){let s=n.config.apiURL,c=n.config.apiKey,l=await fetch(`${s}${I6.API_BASE_ROUTE}/register-auto-recovery-session`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:c},body:JSON.stringify({appName:n.testIdentification.testFileName,fallbackData:n})});return Oar(l,{resource:"register-auto-recovery-session",requiredFields:["arConfig","sessionId"]})}async prepareSession(n){let s=this.getInitializationData(),c=await I6.registerSession(s);this.utils=new QRe({page:this.page,evaluateWithChecksum:this.evaluateWithChecksum,checksumPage:this.checksumPage,pageInteractor:this.pageInteractor,arConfig:c.arConfig,sessionId:c.sessionId,runtimeFallbackData:s,fallbackData:n,variableStore:this.variables??[],runtimePage:this.runtimePageContext,...this.context!==void 0?{context:this.context}:{}});try{this.agent=await ORe.build(this.getUtils())}catch(l){let d=l instanceof Error?l.message:String(l);throw new Error(`Failed to prepare ARFallback: ${d}`)}}async resolve(n){var h;let s=null,c=new Promise((b,T)=>{s=setTimeout(()=>{s=null;let k=this.getUtils();k.analytics.ARError({error:`Auto-recovery timed out after ${I6.TIMEOUT_MS/1e3} seconds`});let B="Auto-Recovery attempt finished unsuccessfully";k.createChecksumStep({title:B,withError:!0}),k.addAutoRecoveryErrorToReport(B,!1),T(new Error(B))},I6.TIMEOUT_MS)}),l=Date.now();await this.prepareSession(n);let d=S6("auto_recovery_session",{recovery:this.getUtils().analytics.metadata});this.getUtils().analytics.ARStart();try{let b=await Promise.race([this.getAgent().init(),c]);return s!==null&&(clearTimeout(s),s=null),this.getUtils().analytics.ARFinish({duration:Date.now()-l}),d.emit({outcome:"success",result:b.result,steps_count:((h=b.stepsThoughts)==null?void 0:h.length)??0,final_thought:b.finalThought}),{fbResult:b.result,thought:b.finalThought,stepsThoughts:b.stepsThoughts,steps:[]}}catch(b){throw s!==null&&clearTimeout(s),this.getUtils().analytics.ARFinish({duration:Date.now()-l}),d.emit({outcome:"error",error:MQ(b)}),b}}};t(I6,"ARFallback"),I6.API_BASE_ROUTE="/auto-recovery",I6.TIMEOUT_MS=12e4;var T6=I6;var Qar=t(i=>{let n=i.info();return n.annotations.some(s=>s.type==="bug")||n.tags.some(s=>s==="@bug")},"isKnownBugTest");var w_t=1e3*30;function gCn(i,n){Reflect.set(i,"fallbackResult",n)}t(gCn,"setFallbackResult");var LJ=class LJ extends H2e{constructor(s,c="normal",l,d,h,b,T,k,B,H,j,X,se){var Qe,gt,Ot,$t;super(s,l,j,()=>this.pageInteractor,void 0);this.page=s;this.runMode=c;this.testRunAnalytics=d;this.monitorBridge=h;this.testInfo=b;this.checksumTestId=T;this.test=k;this.options=B;this.isReplMode=H;this.config=j;this.pageInteractorAPI=X;this.appSpecificRules={};this.hasRuntimeStartedTrace=!1;this.unzippedHarData=[];this.fallbacks=[];this.hasUsedAutoRecovery=!1;this.hasSuccessfulAutoRecovery=!1;this.arSummaries=[];this.arStepIds=[];this.arResults=[];this.thoughtsCounter=0;this.highLevelThoughts=[];this.framesMsgBroker=new bIe;this.previousSteps=[];this.scriptLoadWrapper=t(async(s,c)=>(!this.isTimeMachineFrame(c)&&this.navigationPromise&&await this.navigationPromise,this.wrapInternalSteps(s,c.page())),"scriptLoadWrapper");this.scriptLoadCheck=t(async s=>s.evaluate(()=>!!window.checksum),"scriptLoadCheck");this.scriptLoadCallback=t(async s=>{await s.evaluate(async({appSpecificRules:c,esraTimeout:l,sessionRecorder:d,showFrontendLogs:h,showTMSeeker:b,filesObserver:T,nativeDialogObserver:k,assertionsObserver:B,actionsObserver:H,recordOptions:j})=>{var X,se;(X=window.checksum)==null||X.testGenerator.init(c,{esraTimeout:l,showFrontendLogs:h,skipElementHighlighting:!0,...j!==void 0?{recordOptions:j}:{}},{assertionGenerator:!1,sessionRecorder:d,filesObserver:T,nativeDialogObserver:k,assertionsObserver:B,actionsObserver:H});try{b&&((se=window.checksum)==null||se.timeMachine.openSeekbar())}catch{}},{appSpecificRules:this.appSpecificRules,esraTimeout:w_t,sessionRecorder:!this.isTimeMachineFrame(s)&&!!this.timeMachine,showFrontendLogs:tc.isDevMode,showTMSeeker:this.isTimeMachineFrame(s)&&process.env.CHECKSUM_SHOW_TIME_MACHINE==="true",filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1,actionsObserver:!1}),Tc(`[init] init script loaded for ${s.page().url()}`)},"scriptLoadCallback");zRe(B.printLogs??!1);let _e=(Qe=this.config.options)==null?void 0:Qe.useChecksumAI;Qar(k)&&typeof _e=="object"&&_e.skipTestsWithKnownBugs&&(console.log("Auto recovery will not run for this test as it is marked as a known bug"),_e.actions=!1,_e.assertions=!1,_e.visualComparison=!1);let Xe=this.injectedScriptManager;if(!Xe)throw new Error("Injected script manager not initialized");Xe.setScriptLoadWrapper(this.scriptLoadWrapper).setScriptLoadCallback(this.scriptLoadCallback).setScriptLoadCheck(this.scriptLoadCheck);let qe=Jar({config:this.config,throwIfAuthFailed:!0}),lt=this.getPlaywrightProjectConfig();if(this.pageInteractor=new Tue({evaluateWithChecksum:this.evaluateWithChecksum.bind(this),getFrame:t(()=>this.page.mainFrame(),"getFrame"),getTimeMachine:t(()=>this.timeMachine,"getTimeMachine"),logger:{log:Tc,logError:Tc},options:{navigationTimeout:(gt=lt.use)==null?void 0:gt.navigationTimeout,actionTimeout:(Ot=lt.use)==null?void 0:Ot.actionTimeout,testAssetsDir:Cue(ow()),waitActionDelay:1e3},pageInteractorAPI:this.pageInteractorAPI,loginFunction:qe}),this.checkForActiveTracing(),this.resetFallbacks(),se&&(this.highLevelThoughts=se.highLevelThoughts??[],se.timeMachineBrowserContext!==void 0&&(this.timeMachineBrowserContext=se.timeMachineBrowserContext),se.variableStore!==void 0&&(this.variableStore=se.variableStore)),tc.testRun.timeMachine.active&&!this.options.disableTimeMachine){let wt=this.shouldRecordRRwebEvents()?{recordRRwebEventsToFile:!0,recordRRwebEventsToFilePath:dOt(this.checksumTestId,this.testInfo.retry)}:{};this.timeMachine=new O2e(this.framesMsgBroker,Xe,{...wt,maxRRwebBytes:tc.testRun.timeMachine.maxRRwebBytes,headless:process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"?!1:tc.testRun.timeMachine.headless,webProxy:($t=b.project.use)==null?void 0:$t.proxy,recordOnly:process.env.CHECKSUM_RUNTIME_TIME_MACHINE_REPLAY!=="true"}),this.timeMachineBrowserContext&&this.timeMachine.setTimeMachineBrowserContext(this.timeMachineBrowserContext)}}previousThoughtsAndTimestamps(){return this.previousSteps}static async init(s,c,l,d,h,b,T,k,B,H=!1){let j=!1;T||(T=rOt(5),j=!0,console.warn(`Checksum test id was not defined for test "${b.title}" and was auto-generated. Please replace - "${b.title}" with -
|
|
771
771
|
test(defineChecksumTest("${b.title}", "${T}"), async ({ page }) => {...`)),d.addTestInfo(T,b.testId,j),B.options!==void 0&&B.options.useChecksumAI!==void 0&&typeof B.options.useChecksumAI=="boolean"&&(B.options.useChecksumAI={actions:B.options.useChecksumAI,assertions:!1,visualComparison:!1});let X=new _Te(B),se=new LJ(s,B.runMode,c,l,d,b,T,k,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:B.runMode!=="normal",useMockData:!1,printLogs:!1,...B.options},H,B,X,{variableStore:h});return c.pages().length===0&&(k._checksum.expect.setPage(se),k._checksum.checksumAI.page=se,h.clearAll(),se.testRunAnalytics.testRunStart()),await se.asyncInit(),se.proxy}async asyncInit(s=!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(),s||await this.prepareForTestArtifacts()}async makePage(s){let c=new LJ(s,this.runMode,this._context,this.testRunAnalytics,this.monitorBridge,this.testInfo,this.checksumTestId,this.test,this.options,this.isReplMode,this.config,this.pageInteractorAPI,{highLevelThoughts:this.highLevelThoughts,...this.timeMachineBrowserContext!==void 0?{timeMachineBrowserContext:this.timeMachineBrowserContext}:{},...this.variableStore!==void 0?{variableStore:this.variableStore}:{}});return await c.asyncInit(!0),c.proxy}getTimeMachinePage(){var s;return(s=this.timeMachine)==null?void 0:s.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}isTimeMachineFrame(s){var c;return(c=this.timeMachine)!=null&&c.hasReplayFrame()?s===this.timeMachine.getFrame():!1}shouldRecordRRwebEvents(){var s;return S8t({recordRRwebEventsToFile:tc.testRun.timeMachine.recordRRwebEventsToFile,hostReports:(s=this.config.options)==null?void 0:s.hostReports,disableRrwebRecording:this.options.disableRrwebRecording,disableTimeMachine:this.options.disableTimeMachine})}recordInteraction(){let s=this.getPageGuid(this.page);LJ.recentlyInteracted.set(s,Date.now())}async goto(s,c){return this.recordInteraction(),this.page.goto(s,c)}async reload(s){return this.recordInteraction(),this.page.reload(s)}async goBack(s){return this.recordInteraction(),this.page.goBack(s)}async goForward(s){return this.recordInteraction(),this.page.goForward(s)}async click(s,c){return this.recordInteraction(),this.page.click(s,c)}async dblclick(s,c){return this.recordInteraction(),this.page.dblclick(s,c)}async fill(s,c,l){return this.recordInteraction(),this.page.fill(s,c,l)}async press(s,c,l){return this.recordInteraction(),this.page.press(s,c,l)}async check(s,c){return this.recordInteraction(),this.page.check(s,c)}async uncheck(s,c){return this.recordInteraction(),this.page.uncheck(s,c)}async selectOption(s,c,l){return this.recordInteraction(),this.page.selectOption(s,c,l)}async hover(s,c){return this.recordInteraction(),this.page.hover(s,c)}async type(s,c,l){return this.recordInteraction(),this.page.type(s,c,l)}async setInputFiles(s,c,l){return this.recordInteraction(),this.page.setInputFiles(s,c,l)}async tap(s,c){return this.recordInteraction(),this.page.tap(s,c)}async dragAndDrop(s,c,l){return this.recordInteraction(),this.page.dragAndDrop(s,c,l)}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var l;let c=(l=this.getPlaywrightProjectConfig().use)==null?void 0:l.trace;this.traceMode=typeof c=="string"?c:c==null?void 0:c.mode}registerPageEvents(){super.registerPageEvents();let s=this.injectedScriptManager;s&&(s.addTrackedFrame(this.page),this.page.on("framenavigated",async c=>{s.onFrameNavigated(c)}))}checksumSelector(s){return this.checksumStepId=s,this.options.useChecksumSelectors&&this.setSelectorFallback(s),this.proxy}checksumAI(s,c,l){let d=this.addNewThought(s,"action",!!c);this.previousSteps.push({thought:d.thought,timestamp:Date.now()});let h=this.getPageGuid(this.page);return Tue.setLastAction(h,s),c&&typeof c=="function"?this.test.step(s,async b=>{var T;try{return l!=null&&l.withDialog&&this.pageInteractor.listenToDialog(),await c()}catch(k){if(d.children=[],!this.options.useChecksumAI.actions||l!=null&&l.withDialog||l!=null&&l.skipAutoRecovery)throw k;this.setAIFallback(s,"action");try{return await this.initiateFallbackSequence({type:"action",error:k,method:"",args:[],testInfo:this.testInfo,step:b},{fallbackTypes:[RO,T6]})}catch(B){throw this.testRunAnalytics.testRunError({failedThought:s,error:(B==null?void 0:B.message)||"Unknown error"}),B}}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(T=this.currentThought)==null?void 0:T.parent}}):(this.options.useChecksumAI.actions&&!(l!=null&&l.skipAutoRecovery)&&this.setAIFallback(s,"action"),this.proxy)}resolveAssetsFolder(s){return s.map(c=>ND.join(Cue(ow()),c))}getRuntimeOptions(){return this.options}addPwAnnotation(s){this.testInfo.annotations.push({type:s.type,description:`
|
|
772
772
|
${s.description}`})}async onTestComplete(s){this.testRunAnalytics.testRunEnd({success:s,autoRecoveryTriggered:this.hasUsedAutoRecovery,summaries:this.arSummaries}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoveryMetadata",data:{autoRecoveryTriggered:this.hasUsedAutoRecovery,autoRecovered:this.hasSuccessfulAutoRecovery&&s}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(s,c=this.page){try{return c.mainFrame()._checksumInternal=!0,c._checksumInternal=!0,await s()}finally{c.mainFrame()._checksumInternal=!1,c._checksumInternal=!1}}async conditionallyWrapInternalSteps(s,c){return s?this.wrapInternalSteps(c):c()}async wrapNoLocationSteps(s){try{return this.testInfo._checksumNoLocation=!0,await s()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(s,c,l=[]){for(let d of s){(d._stepId===c||d.stepId===c)&&l.push(d);let h=[d.steps,d._testInfoSteps,d._steps].filter(Boolean);for(let b of h)this.findAllStepsRecursively(b,c,l)}return l}makeChecksumStepFunction(s){return c=>{if(!s)return;let l=c._stepId||c.stepId;this.findAllStepsRecursively(c._testInfo._steps,l).forEach(h=>{h.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(s){let c,l={box:!0,noLocation:!0,obtainStep:t(d=>{c=d},"obtainStep")};if(await this.step(s.title,this.makeChecksumStepFunction(s.withError),!1,l),c!=null&&c.stepId&&this.arStepIds.push(c.stepId),!c)throw new Error("Checksum step was not created");return c}async step(s,c,l=!0,{obtainStep:d=void 0,box:h=!1,noLocation:b=void 0}={}){let T=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=l===!0,b!==void 0&&(this.testInfo._checksumNoLocation=b),await this.test.step(s,c??(()=>{}),{obtainStep:d,box:h})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=T}}addErrorMessage(s,c){this.testInfo.addError(s,c)}async evaluateWithChecksum(s,c,l=!0){this.navigationPromise&&await this.navigationPromise;let d=this.page.evaluate.bind(this.page);return this.conditionallyWrapInternalSteps(l,()=>d(s,c))}getChecksumTestId(){return this.checksumTestId}addNewThought(s,c,l=!1){var b;let d={thought:s,type:c,...l?{children:[]}:{}};if(!this.currentThought)this.highLevelThoughts.push(d);else if(this.currentThought.children)this.currentThought.children.push(d),d.parent=this.currentThought;else{let T=this.currentThought.parent;T?(T.children=T.children??[],T.children.push(d),d.parent=T):this.highLevelThoughts.push(d)}let h=d.parent;return h?d.id=`${h.id}.${((b=h.children)==null?void 0:b.length)??0}`:d.id=`${++this.thoughtsCounter}`,this.currentThought=d,d}buildThoughtsChainForFallback(s=this.highLevelThoughts){let c=[];return s.forEach(l=>{c.push(l.thought),l.children&&c.push(...this.buildThoughtsChainForFallback(l.children))}),c}compoundSelection(...s){let c=super.compoundSelection(...s);return c.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),c}setSelectorFallback(s){let c={checksumId:s,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:w_t};this.pushFallback(this.constructFallback(Ufe).init(c)),this.pushFallback(this.constructFallback(Lfe).init(c))}setCompoundSelectorFallback(s){this.pushFallback(this.constructFallback(Qfe).init({checksumId:s,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:w_t}))}setAIFallback(s,c){var b;let l=((b=this.options.useChecksumAI)==null?void 0:b.arVersion)===1,d=t(()=>{var X,se,_e,Xe,qe,lt;let T=this.buildThoughtsChainForFallback(),k={title:this.testInfo.title},B={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},H={previous:T.slice(0,-1),failing:s,next:T.slice(1)},j={storyInfo:k,testIdentification:B,fallbackConfig:{arMode:(X=this.options.useChecksumAI)==null?void 0:X.arMode,overrideOptions:{...(se=this.options.useChecksumAI)==null?void 0:se.overrideOptions,...(_e=this.options.useChecksumAI)!=null&&_e.modelName&&!((qe=(Xe=this.options.useChecksumAI)==null?void 0:Xe.overrideOptions)!=null&&qe.modelName)?{modelName:this.options.useChecksumAI.modelName}:{}},markRecovered:(lt=this.options.useChecksumAI)==null?void 0:lt.markRecovered},thoughts:H,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:c};return this.constructFallback(T6).init(j)},"createArFallback"),h=t(()=>{let T=typeof this.options.useChecksumAI=="object"?this.options.useChecksumAI:void 0,k=T==null?void 0:T.arMode,B=T==null?void 0:T.overrideOptions;return this.constructFallback(RO).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),...k!==void 0?{arMode:k}:{},...B!==void 0?{overrideOptions:B}:{},fallbackType:c})},"createAIFallback");return l?this.pushFallback(h()):this.pushFallback(d()),this.proxy}pushFallback(s){this.fallbacks.push(s),this.sortFallbacks()}handleAIFallback(s,c,l,d){let h=s.fallbackAnalyticsPayload.iterationSteps,b=h.length>0?d/h.length:0,T=l.fbResult??"failed";this.testRunAnalytics.testRunFallbackExecution({result:T,failedThought:s.getFailedThought(),summary:l.summary??"",stepsPayload:s.fallbackAnalyticsPayload,type:s.fallbackType??c.type,duration:d,avgDuration:b,success:["finish","soft_assertion"].includes(T)}),this.arResults.push({failedThought:s.getFailedThought(),result:T,...l.thought!==void 0?{thought:l.thought}:{}})}handleAutoRecovery(s,c,l,d){let h=l.stepsThoughts??[],b=h.length>0?d/h.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:s.failingThought,type:c.type,finalThought:l.thought??"",result:l.fbResult??"failed",duration:d,avgStepDuration:b,stepsThoughts:h,version:"v1"})}async runFallback(s,c){let l=Date.now(),d=s.resolve(c),h=await Hp(d,s.timeout),b=Date.now()-l;if(!h)throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:"Recovery Failed",withError:!0}),new Error("Fallback failed");s instanceof RO&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(s,c,h,b)),s instanceof T6&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(s,c,h,b));let T=h.thought?`: ${h.thought}`:"";if(h.fbResult==="failed")throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:`Recovery Failed${T}`,withError:!0}),new Error("Fallback failed");if(h.fbResult==="hard_assertion")throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:`Recovery Failed${T}`,withError:!0}),new cfe(h.fbResult);this.hasUsedAutoRecovery&&(this.hasSuccessfulAutoRecovery=!0),s instanceof RO&&h.summary&&this.arSummaries.push(h.summary),s instanceof T6&&h.thought&&this.arSummaries.push(h.thought),this.createChecksumStep({title:`Recovery Complete${T}`});let k=this.currentThought;if(k&&h.steps.length===1){let B=h.steps[0];B!=null&&B.thought&&(k.thought=B.thought)}else k&&(k.children=h.steps.map((B,H)=>({id:`${k.id}.${H+1}`,thought:B.thought??"",type:B.type,parent:k})))}async runConditionallyWithinStep(s,c,l){return s?await this.step(c,l):await l()}async onExecutionError(s){try{return await this.initiateFallbackSequence({...s,type:"action"})}catch(c){if(!this.currentThought){let{locator:l,method:d}=s;this.testRunAnalytics.testRunActionExecutionFailure({locator:(l==null?void 0:l.toString())??"",selector:(l==null?void 0:l._selector)??"",method:d,checksumStepId:this.checksumStepId??"",error:c instanceof Error?c.toString():String(c)})}throw c}}async initiateFallbackSequence(s,{fallbackTypes:c=void 0}={}){var b;Tc(`[initiateFallbackSequence] with type: ${s.type}...`);let l=this.fallbacks.find(T=>T instanceof RO);if(l){let T=l.getFailedThought(),k=((b=this.variableStore)==null?void 0:b.getActiveVariables())??[];this.fallbacks.forEach(B=>{B.setThought(T),B.setVariables(k)})}let d=this.fallbacks.find(T=>T instanceof T6);if(d){let T=d.failingThought;this.fallbacks.forEach(k=>{var B;k instanceof T6&&k.setVariables(((B=this.variableStore)==null?void 0:B.getActiveVariables())??[]),k.setThought(T)})}let h=this.fallbacks;c&&(h=h.filter(T=>c.reduce((k,B)=>k||T instanceof B,!1))),h=h.filter(T=>T.canResolve(s));try{for(let T of h){let k=T==null?void 0:T.toString();k&&console.log(`Using ${k}`);try{await this.runConditionallyWithinStep(s.type!=="assertion"||!s.withChecksumAI,T.getRecoveryAttemptTitle(s),async()=>await this.runFallback(T,s))}catch(B){if(s.withChecksumAI&&B.message==="fetch failed")throw new Error(UZ);B instanceof cfe&&B.fallbackResult==="hard_assertion"&&gCn(s.error,"hard_assertion"),k&&console.log(`Failed to use ${k}`),T.cancel();continue}return!0}throw s.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(jfe).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()&&this.timeMachine){let s=this.timeMachine;try{await s.flushRRwebEventsToFile();let c=s.getRRwebFilePath();c&&this.monitorBridge.addAsset({type:"rrweb-recording",path:c,testId:this.checksumTestId,fileName:ND.basename(c)})}catch(c){Tc("Error shutting down RRweb events recording",c)}if(this.testRunAnalytics)return Tc("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let s=[jfe,Qfe,Ufe,Lfe,RO];this.fallbacks.sort((c,l)=>s.indexOf(c.constructor)-s.indexOf(l.constructor))}constructFallback(s){return new s(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"},this,this._context)}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let c=await this.getTraceFilePath();c&&this.monitorBridge.addAsset({type:"trace",path:c,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let c=fOt(gIe(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:c,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?pOt(gIe(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let s=tWe(gIe(this.testInfo.file)),c=ND.join(s,`${this.checksumTestId}.har.zip`);if(!(0,PE.existsSync)(c))throw new Error("Could not find har file or zip file");let l=ND.join(s,"tmp");(0,PE.existsSync)(l)||(0,PE.mkdirSync)(l);let d=(0,PE.readFileSync)(c),h=await(0,$ar.loadAsync)(d);for(let T of Object.keys(h.files)){let k=h.file(T);if(!k)continue;let B=await k.async("string"),H=ND.join(l,T);(0,PE.writeFileSync)(H,B),this.unzippedHarData.push(H)}let b=ND.join(l,"test.har");if(!(0,PE.existsSync)(b))throw this.cleanupMockData(),new Error(`Could not find har file ${b} after unzipping ${c}`);return b}cleanupMockData(){this.unzippedHarData.forEach(c=>{(0,PE.rmSync)(c)});let s=this.unzippedHarData[0];s&&(0,PE.rmSync)(ND.dirname(s),{recursive:!0,force:!0})}async prepareAPIMock(){let s={GET:0,POST:0,PUT:0,DELETE:0};try{let c=await this.prepareMockData();await this.page.routeFromHAR(c,{url:"*/**",notFound:"fallback",update:!1});let l=this.page._routes[0].handler;await this.page.route("**/*",d=>{let h=d.request().headers(),b=d.request().method(),T=(s[b]??0)+1;s[b]=T,h["Checksum-Id"]=T.toString(),d.request()._applyFallbackOverrides({headers:h}),l(d)})}catch(c){Tc("Error setting up mock data",c.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let s=ND.join(KU(ow()),"settings.asr");if(!(0,PE.existsSync)(s)){Tc("Could not find ASR file");return}let{ungzip:c}=await Promise.resolve().then(()=>Na(Xze()));try{let l=await c((0,PE.readFileSync)(s));this.appSpecificRules=JSON.parse(l.toString())||{}}catch(l){Tc("Could not read ASR file",l.message)}}addAutoRecoveryStepId(s){this.arStepIds.push(s)}};t(LJ,"RuntimePage"),LJ.recentlyInteracted=new Map;var Uar=LJ;var zar=require("fs"),War=require("module"),Har=require("path"),Var=require("vm"),qar=require("sucrase");function WRe(i){let n=(0,zar.readFileSync)(i,"utf8"),{code:s}=(0,qar.transform)(n,{transforms:["typescript","imports"],filePath:i}),c={},l={exports:c};(0,Var.runInThisContext)(`(function (exports, require, module, __filename, __dirname) {
|
|
773
773
|
${s}
|
package/index.d.ts
CHANGED
package/index.js
CHANGED
|
@@ -767,7 +767,7 @@ ${u}`;return{success:!0,pages:c,message:_}}async switchPageHandler(s){if(!s.page
|
|
|
767
767
|
${n}`)}get createChecksumStep(){return n=>this.checksumPage.createChecksumStep(n)}get step(){return this.checksumPage.step.bind(this.checksumPage)}get runConditionallyWithinStep(){return(n,s,c)=>this.checksumPage.runConditionallyWithinStep(n,s,c)}async getScreenshotForElement(n){var s;try{let c=await this.getSelectionDataForChecksumId(n);if(!c)throw new Error(`Locator not found for checksumId: ${n}`);let u=((s=this.arConfig.modelConfig)==null?void 0:s.provider)==="anthropic"?"jpeg":"png";return(await this.page.locator(c.selector).screenshot({type:u})).toString("base64")}catch{throw new Error(`Failed to get screenshot for element: ${n}`)}}get analytics(){return this._analytics}get pageInteractor(){return this._pageInteractor}};t(l$,"AutoRecoveryRuntimeIteratorUtils"),l$.currentChecksumId="0";var CPe=l$;async function Oir(i,n){let s;try{s=await i.json()}catch{s=void 0}return M0n({ok:i.ok,status:i.status,body:s},n)}t(Oir,"assertOkJson");function M0n(i,n){let s=i.body&&typeof i.body=="object"?i.body:void 0;if(!i.ok){let u=L0n(s==null?void 0:s.message);throw Q0n(new Error(`${n.resource} failed (HTTP ${i.status})`+(u?`: ${u}`:".")),i.status)}if(!s)throw new Error(`${n.resource} (HTTP ${i.status}) returned a non-object body; expected JSON.`);let c=(n.requiredFields??[]).filter(u=>!s[u]);if(c.length>0)throw new Error(`${n.resource} (HTTP ${i.status}) response is missing required field${c.length>1?"s":""}: ${c.join(", ")}.`);return s}t(M0n,"assertJsonBody");function L0n(i){return typeof i=="string"?i:Array.isArray(i)?i.filter(n=>typeof n=="string").join("; "):""}t(L0n,"extractMessage");function Q0n(i,n){return Object.assign(i,{status:n})}t(Q0n,"withStatus");var Mir=t(i=>{if(i.error!=null)return"ERROR";let n=i.status_code;if(typeof n=="number"&&n>=500)return"ERROR";let s=i.exit_code;return typeof s=="number"&&s!==0?"ERROR":"INFO"},"severityFor");var Rdt=require("fs");var Lir="\x1B[31m",U0n="\x1B[33m",j0n="\x1B[32m",J0n="\x1B[36m",$0n="\x1B[2m",z0n="\x1B[1m",Epe="\x1B[0m",W0n=t(()=>{let i=process.env.WIDE_EVENT_PRETTY;return i==="true"||i==="1"?!0:i==="false"||i==="0"?!1:process.stdout.isTTY?!0:process.env.APP_ENV==="local"},"shouldPretty"),H0n=new Set(["severity","message","kind","timestamp","_startedAtMs"]),V0n=t(i=>{let n=new WeakSet;return JSON.stringify(i,(s,c)=>{if(typeof c=="bigint")return c.toString();if(typeof c=="object"&&c!==null){if(n.has(c))return"[Circular]";n.add(c)}return c})},"safeStringify"),q0n=t(i=>i==="ERROR"||i==="CRITICAL"?Lir:i==="WARNING"?U0n:j0n,"colorForSeverity"),G0n=t(i=>{let n=String(i.severity??"INFO"),s=`${q0n(n)}${n.padEnd(5)}${Epe}`,c=i.kind?`${J0n}${i.kind}${Epe}`:"",u=String(i.message??""),_=i.error&&typeof i.error=="object"?(()=>{let O=i.error;return` ${Lir}${O.type??"Error"}: ${O.message??""}${Epe}`})():"",g=["outcome","test_suite_run_id","status"],b=Object.entries(i).filter(([O,G])=>!H0n.has(O)&&G!=null&&O!=="error"&&typeof G!="object"),w=t(O=>{let G=g.indexOf(O);return G===-1?g.length:G},"rank"),D=b.sort(([O],[G])=>w(O)-w(G)).slice(0,8).map(([O,G])=>`${$0n}${O}=${Epe}${G}`).join(" ");return[s,z0n+c+Epe,u,D,_].filter(O=>O&&O.trim()!=="").join(" ")},"formatPretty"),Y0n=t(i=>{let n=i.trace_id;if(typeof n!="string"||n==="")return i;let s=process.env.GCP_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT;return s?{...i,"logging.googleapis.com/trace":`projects/${s}/traces/${n}`}:i},"withGcpTraceField"),Qir=t(i=>{let n=W0n()?G0n(i):V0n(Y0n(i));(0,Rdt.writeSync)(1,n+`
|
|
768
768
|
`)},"emitEvent");var Uir=t(i=>{(0,Rdt.writeSync)(2,i.endsWith(`
|
|
769
769
|
`)?i:`${i}
|
|
770
|
-
`)},"writeStderrLine");var Z0n=t(i=>{let n=i.kind??"event",s=i.outcome?` ${i.outcome}`:"",c=typeof i.duration_ms=="number"?` ${i.duration_ms}ms`:"";return`${n}${s}${c}`.trim()},"defaultMessage"),K0n=t((i,n,s)=>{let c=Date.now(),u={timestamp:new Date().toISOString(),kind:i,...n},_=!1,g={set(b){return Object.assign(u,b),g},emit(b){_||(_=!0,b&&Object.assign(u,b),u.duration_ms===void 0&&(u.duration_ms=Date.now()-c),s(u))}};return g},"startHandle"),X0n=t((i={})=>{let n=i.decide??(()=>!0),s=i.deriveMessage??Z0n,c=i.label??"[wide-event]",u=i.sink??(b=>Qir(b)),_=t(b=>{if(!n(b))return;let w={severity:Mir(b),message:b.message??s(b),...b};try{u(w)}catch(D){try{Uir(`${c} emit failed: ${String(D)}`)}catch{}}},"emit");return{emit:_,emitWideEvent:t((b,w={})=>{_({timestamp:new Date().toISOString(),kind:b,...w})},"emitWideEvent"),wideEvent:t((b,w={})=>K0n(b,w,_),"wideEvent"),configureSink:t(b=>{u=b},"configureSink")}},"createWideEvents"),jir=t(i=>i==="true"||i==="1","truthy"),Jir=t(()=>jir(process.env.CHECKSUM_WIDE_EVENTS)||jir(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),$ir=X0n({decide:t(()=>Jir(),"decide")}),evn=$ir.configureSink,Odt=t((i,n={})=>$ir.wideEvent(i,n),"wideEvent");var Mdt=t(i=>i instanceof Error?{type:i.name,message:i.message}:{type:"UnknownError",message:String(i)},"toErrorField");var K6=class K6 extends JP{getInitializationData(){if(!this.initializationData)throw new Error("ARFallback initialization data is not initialized");return this.initializationData}getAgent(){if(!this.agent)throw new Error("ARFallback agent is not initialized");return this.agent}getUtils(){if(!this.utils)throw new Error("ARFallback utils is not initialized");return this.utils}constructor(n,s,c,u,_,g,b){super(n,s,c,u,_,g,b),this.runtimePageContext=g}init(n){var s;return this.initializationData=n,(s=n.fallbackConfig).arMode??(s.arMode="
|
|
770
|
+
`)},"writeStderrLine");var Z0n=t(i=>{let n=i.kind??"event",s=i.outcome?` ${i.outcome}`:"",c=typeof i.duration_ms=="number"?` ${i.duration_ms}ms`:"";return`${n}${s}${c}`.trim()},"defaultMessage"),K0n=t((i,n,s)=>{let c=Date.now(),u={timestamp:new Date().toISOString(),kind:i,...n},_=!1,g={set(b){return Object.assign(u,b),g},emit(b){_||(_=!0,b&&Object.assign(u,b),u.duration_ms===void 0&&(u.duration_ms=Date.now()-c),s(u))}};return g},"startHandle"),X0n=t((i={})=>{let n=i.decide??(()=>!0),s=i.deriveMessage??Z0n,c=i.label??"[wide-event]",u=i.sink??(b=>Qir(b)),_=t(b=>{if(!n(b))return;let w={severity:Mir(b),message:b.message??s(b),...b};try{u(w)}catch(D){try{Uir(`${c} emit failed: ${String(D)}`)}catch{}}},"emit");return{emit:_,emitWideEvent:t((b,w={})=>{_({timestamp:new Date().toISOString(),kind:b,...w})},"emitWideEvent"),wideEvent:t((b,w={})=>K0n(b,w,_),"wideEvent"),configureSink:t(b=>{u=b},"configureSink")}},"createWideEvents"),jir=t(i=>i==="true"||i==="1","truthy"),Jir=t(()=>jir(process.env.CHECKSUM_WIDE_EVENTS)||jir(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),$ir=X0n({decide:t(()=>Jir(),"decide")}),evn=$ir.configureSink,Odt=t((i,n={})=>$ir.wideEvent(i,n),"wideEvent");var Mdt=t(i=>i instanceof Error?{type:i.name,message:i.message}:{type:"UnknownError",message:String(i)},"toErrorField");var K6=class K6 extends JP{getInitializationData(){if(!this.initializationData)throw new Error("ARFallback initialization data is not initialized");return this.initializationData}getAgent(){if(!this.agent)throw new Error("ARFallback agent is not initialized");return this.agent}getUtils(){if(!this.utils)throw new Error("ARFallback utils is not initialized");return this.utils}constructor(n,s,c,u,_,g,b){super(n,s,c,u,_,g,b),this.runtimePageContext=g}init(n){var s;return this.initializationData=n,(s=n.fallbackConfig).arMode??(s.arMode="one_shot"),this}canResolve(n){return!0}get failingThought(){return this.getInitializationData().thoughts.failing}getRecoveryAttemptTitle(){switch(this.getInitializationData().type){case"action":return`Checksum Auto-Recovery: trying to achieve action "${this.failingThought}"...`;case"assertion":return`Checksum Auto-Recovery: trying to verify assertion "${this.failingThought}"...`;default:return`Checksum Auto-Recovery: trying to achieve action "${this.failingThought}"...`}}static async registerSession(n){let s=n.config.apiURL,c=n.config.apiKey,u=await fetch(`${s}${K6.API_BASE_ROUTE}/register-auto-recovery-session`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:c},body:JSON.stringify({appName:n.testIdentification.testFileName,fallbackData:n})});return Oir(u,{resource:"register-auto-recovery-session",requiredFields:["arConfig","sessionId"]})}async prepareSession(n){let s=this.getInitializationData(),c=await K6.registerSession(s);this.utils=new CPe({page:this.page,evaluateWithChecksum:this.evaluateWithChecksum,checksumPage:this.checksumPage,pageInteractor:this.pageInteractor,arConfig:c.arConfig,sessionId:c.sessionId,runtimeFallbackData:s,fallbackData:n,variableStore:this.variables??[],runtimePage:this.runtimePageContext,...this.context!==void 0?{context:this.context}:{}});try{this.agent=await vPe.build(this.getUtils())}catch(u){let _=u instanceof Error?u.message:String(u);throw new Error(`Failed to prepare ARFallback: ${_}`)}}async resolve(n){var g;let s=null,c=new Promise((b,w)=>{s=setTimeout(()=>{s=null;let D=this.getUtils();D.analytics.ARError({error:`Auto-recovery timed out after ${K6.TIMEOUT_MS/1e3} seconds`});let O="Auto-Recovery attempt finished unsuccessfully";D.createChecksumStep({title:O,withError:!0}),D.addAutoRecoveryErrorToReport(O,!1),w(new Error(O))},K6.TIMEOUT_MS)}),u=Date.now();await this.prepareSession(n);let _=Odt("auto_recovery_session",{recovery:this.getUtils().analytics.metadata});this.getUtils().analytics.ARStart();try{let b=await Promise.race([this.getAgent().init(),c]);return s!==null&&(clearTimeout(s),s=null),this.getUtils().analytics.ARFinish({duration:Date.now()-u}),_.emit({outcome:"success",result:b.result,steps_count:((g=b.stepsThoughts)==null?void 0:g.length)??0,final_thought:b.finalThought}),{fbResult:b.result,thought:b.finalThought,stepsThoughts:b.stepsThoughts,steps:[]}}catch(b){throw s!==null&&clearTimeout(s),this.getUtils().analytics.ARFinish({duration:Date.now()-u}),_.emit({outcome:"error",error:Mdt(b)}),b}}};t(K6,"ARFallback"),K6.API_BASE_ROUTE="/auto-recovery",K6.TIMEOUT_MS=12e4;var X6=K6;var zir=t(i=>{let n=i.info();return n.annotations.some(s=>s.type==="bug")||n.tags.some(s=>s==="@bug")},"isKnownBugTest");var Ldt=1e3*30;function tvn(i,n){Reflect.set(i,"fallbackResult",n)}t(tvn,"setFallbackResult");var u$=class u$ extends kke{constructor(s,c="normal",u,_,g,b,w,D,O,G,z,le,ye){var Ft,nr,Or,mr;super(s,u,z,()=>this.pageInteractor,void 0);this.page=s;this.runMode=c;this.testRunAnalytics=_;this.monitorBridge=g;this.testInfo=b;this.checksumTestId=w;this.test=D;this.options=O;this.isReplMode=G;this.config=z;this.pageInteractorAPI=le;this.appSpecificRules={};this.hasRuntimeStartedTrace=!1;this.unzippedHarData=[];this.fallbacks=[];this.hasUsedAutoRecovery=!1;this.hasSuccessfulAutoRecovery=!1;this.arSummaries=[];this.arStepIds=[];this.arResults=[];this.thoughtsCounter=0;this.highLevelThoughts=[];this.framesMsgBroker=new iSe;this.previousSteps=[];this.scriptLoadWrapper=t(async(s,c)=>(!this.isTimeMachineFrame(c)&&this.navigationPromise&&await this.navigationPromise,this.wrapInternalSteps(s,c.page())),"scriptLoadWrapper");this.scriptLoadCheck=t(async s=>s.evaluate(()=>!!window.checksum),"scriptLoadCheck");this.scriptLoadCallback=t(async s=>{await s.evaluate(async({appSpecificRules:c,esraTimeout:u,sessionRecorder:_,showFrontendLogs:g,showTMSeeker:b,filesObserver:w,nativeDialogObserver:D,assertionsObserver:O,actionsObserver:G,recordOptions:z})=>{var le,ye;(le=window.checksum)==null||le.testGenerator.init(c,{esraTimeout:u,showFrontendLogs:g,skipElementHighlighting:!0,...z!==void 0?{recordOptions:z}:{}},{assertionGenerator:!1,sessionRecorder:_,filesObserver:w,nativeDialogObserver:D,assertionsObserver:O,actionsObserver:G});try{b&&((ye=window.checksum)==null||ye.timeMachine.openSeekbar())}catch{}},{appSpecificRules:this.appSpecificRules,esraTimeout:Ldt,sessionRecorder:!this.isTimeMachineFrame(s)&&!!this.timeMachine,showFrontendLogs:hu.isDevMode,showTMSeeker:this.isTimeMachineFrame(s)&&process.env.CHECKSUM_SHOW_TIME_MACHINE==="true",filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1,actionsObserver:!1}),Cu(`[init] init script loaded for ${s.page().url()}`)},"scriptLoadCallback");Hir(O.printLogs??!1);let Te=(Ft=this.config.options)==null?void 0:Ft.useChecksumAI;zir(D)&&typeof Te=="object"&&Te.skipTestsWithKnownBugs&&(console.log("Auto recovery will not run for this test as it is marked as a known bug"),Te.actions=!1,Te.assertions=!1,Te.visualComparison=!1);let Tt=this.injectedScriptManager;if(!Tt)throw new Error("Injected script manager not initialized");Tt.setScriptLoadWrapper(this.scriptLoadWrapper).setScriptLoadCallback(this.scriptLoadCallback).setScriptLoadCheck(this.scriptLoadCheck);let vt=f$({config:this.config,throwIfAuthFailed:!0}),jt=this.getPlaywrightProjectConfig();if(this.pageInteractor=new Cle({evaluateWithChecksum:this.evaluateWithChecksum.bind(this),getFrame:t(()=>this.page.mainFrame(),"getFrame"),getTimeMachine:t(()=>this.timeMachine,"getTimeMachine"),logger:{log:Cu,logError:Cu},options:{navigationTimeout:(nr=jt.use)==null?void 0:nr.navigationTimeout,actionTimeout:(Or=jt.use)==null?void 0:Or.actionTimeout,testAssetsDir:vle(Qx()),waitActionDelay:1e3},pageInteractorAPI:this.pageInteractorAPI,loginFunction:vt}),this.checkForActiveTracing(),this.resetFallbacks(),ye&&(this.highLevelThoughts=ye.highLevelThoughts??[],ye.timeMachineBrowserContext!==void 0&&(this.timeMachineBrowserContext=ye.timeMachineBrowserContext),ye.variableStore!==void 0&&(this.variableStore=ye.variableStore)),hu.testRun.timeMachine.active&&!this.options.disableTimeMachine){let tr=this.shouldRecordRRwebEvents()?{recordRRwebEventsToFile:!0,recordRRwebEventsToFilePath:gFt(this.checksumTestId,this.testInfo.retry)}:{};this.timeMachine=new Ake(this.framesMsgBroker,Tt,{...tr,maxRRwebBytes:hu.testRun.timeMachine.maxRRwebBytes,headless:process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"?!1:hu.testRun.timeMachine.headless,webProxy:(mr=b.project.use)==null?void 0:mr.proxy,recordOnly:process.env.CHECKSUM_RUNTIME_TIME_MACHINE_REPLAY!=="true"}),this.timeMachineBrowserContext&&this.timeMachine.setTimeMachineBrowserContext(this.timeMachineBrowserContext)}}previousThoughtsAndTimestamps(){return this.previousSteps}static async init(s,c,u,_,g,b,w,D,O,G=!1){let z=!1;w||(w=aFt(5),z=!0,console.warn(`Checksum test id was not defined for test "${b.title}" and was auto-generated. Please replace - "${b.title}" with -
|
|
771
771
|
test(defineChecksumTest("${b.title}", "${w}"), async ({ page }) => {...`)),_.addTestInfo(w,b.testId,z),O.options!==void 0&&O.options.useChecksumAI!==void 0&&typeof O.options.useChecksumAI=="boolean"&&(O.options.useChecksumAI={actions:O.options.useChecksumAI,assertions:!1,visualComparison:!1});let le=new ZSe(O),ye=new u$(s,O.runMode,c,u,_,b,w,D,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:O.runMode!=="normal",useMockData:!1,printLogs:!1,...O.options},G,O,le,{variableStore:g});return c.pages().length===0&&(D._checksum.expect.setPage(ye),D._checksum.checksumAI.page=ye,g.clearAll(),ye.testRunAnalytics.testRunStart()),await ye.asyncInit(),ye.proxy}async asyncInit(s=!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(),s||await this.prepareForTestArtifacts()}async makePage(s){let c=new u$(s,this.runMode,this._context,this.testRunAnalytics,this.monitorBridge,this.testInfo,this.checksumTestId,this.test,this.options,this.isReplMode,this.config,this.pageInteractorAPI,{highLevelThoughts:this.highLevelThoughts,...this.timeMachineBrowserContext!==void 0?{timeMachineBrowserContext:this.timeMachineBrowserContext}:{},...this.variableStore!==void 0?{variableStore:this.variableStore}:{}});return await c.asyncInit(!0),c.proxy}getTimeMachinePage(){var s;return(s=this.timeMachine)==null?void 0:s.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}isTimeMachineFrame(s){var c;return(c=this.timeMachine)!=null&&c.hasReplayFrame()?s===this.timeMachine.getFrame():!1}shouldRecordRRwebEvents(){var s;return xMt({recordRRwebEventsToFile:hu.testRun.timeMachine.recordRRwebEventsToFile,hostReports:(s=this.config.options)==null?void 0:s.hostReports,disableRrwebRecording:this.options.disableRrwebRecording,disableTimeMachine:this.options.disableTimeMachine})}recordInteraction(){let s=this.getPageGuid(this.page);u$.recentlyInteracted.set(s,Date.now())}async goto(s,c){return this.recordInteraction(),this.page.goto(s,c)}async reload(s){return this.recordInteraction(),this.page.reload(s)}async goBack(s){return this.recordInteraction(),this.page.goBack(s)}async goForward(s){return this.recordInteraction(),this.page.goForward(s)}async click(s,c){return this.recordInteraction(),this.page.click(s,c)}async dblclick(s,c){return this.recordInteraction(),this.page.dblclick(s,c)}async fill(s,c,u){return this.recordInteraction(),this.page.fill(s,c,u)}async press(s,c,u){return this.recordInteraction(),this.page.press(s,c,u)}async check(s,c){return this.recordInteraction(),this.page.check(s,c)}async uncheck(s,c){return this.recordInteraction(),this.page.uncheck(s,c)}async selectOption(s,c,u){return this.recordInteraction(),this.page.selectOption(s,c,u)}async hover(s,c){return this.recordInteraction(),this.page.hover(s,c)}async type(s,c,u){return this.recordInteraction(),this.page.type(s,c,u)}async setInputFiles(s,c,u){return this.recordInteraction(),this.page.setInputFiles(s,c,u)}async tap(s,c){return this.recordInteraction(),this.page.tap(s,c)}async dragAndDrop(s,c,u){return this.recordInteraction(),this.page.dragAndDrop(s,c,u)}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var u;let c=(u=this.getPlaywrightProjectConfig().use)==null?void 0:u.trace;this.traceMode=typeof c=="string"?c:c==null?void 0:c.mode}registerPageEvents(){super.registerPageEvents();let s=this.injectedScriptManager;s&&(s.addTrackedFrame(this.page),this.page.on("framenavigated",async c=>{s.onFrameNavigated(c)}))}checksumSelector(s){return this.checksumStepId=s,this.options.useChecksumSelectors&&this.setSelectorFallback(s),this.proxy}checksumAI(s,c,u){let _=this.addNewThought(s,"action",!!c);this.previousSteps.push({thought:_.thought,timestamp:Date.now()});let g=this.getPageGuid(this.page);return Cle.setLastAction(g,s),c&&typeof c=="function"?this.test.step(s,async b=>{var w;try{return u!=null&&u.withDialog&&this.pageInteractor.listenToDialog(),await c()}catch(D){if(_.children=[],!this.options.useChecksumAI.actions||u!=null&&u.withDialog||u!=null&&u.skipAutoRecovery)throw D;this.setAIFallback(s,"action");try{return await this.initiateFallbackSequence({type:"action",error:D,method:"",args:[],testInfo:this.testInfo,step:b},{fallbackTypes:[a6,X6]})}catch(O){throw this.testRunAnalytics.testRunError({failedThought:s,error:(O==null?void 0:O.message)||"Unknown error"}),O}}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(w=this.currentThought)==null?void 0:w.parent}}):(this.options.useChecksumAI.actions&&!(u!=null&&u.skipAutoRecovery)&&this.setAIFallback(s,"action"),this.proxy)}resolveAssetsFolder(s){return s.map(c=>lD.join(vle(Qx()),c))}getRuntimeOptions(){return this.options}addPwAnnotation(s){this.testInfo.annotations.push({type:s.type,description:`
|
|
772
772
|
${s.description}`})}async onTestComplete(s){this.testRunAnalytics.testRunEnd({success:s,autoRecoveryTriggered:this.hasUsedAutoRecovery,summaries:this.arSummaries}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoveryMetadata",data:{autoRecoveryTriggered:this.hasUsedAutoRecovery,autoRecovered:this.hasSuccessfulAutoRecovery&&s}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(s,c=this.page){try{return c.mainFrame()._checksumInternal=!0,c._checksumInternal=!0,await s()}finally{c.mainFrame()._checksumInternal=!1,c._checksumInternal=!1}}async conditionallyWrapInternalSteps(s,c){return s?this.wrapInternalSteps(c):c()}async wrapNoLocationSteps(s){try{return this.testInfo._checksumNoLocation=!0,await s()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(s,c,u=[]){for(let _ of s){(_._stepId===c||_.stepId===c)&&u.push(_);let g=[_.steps,_._testInfoSteps,_._steps].filter(Boolean);for(let b of g)this.findAllStepsRecursively(b,c,u)}return u}makeChecksumStepFunction(s){return c=>{if(!s)return;let u=c._stepId||c.stepId;this.findAllStepsRecursively(c._testInfo._steps,u).forEach(g=>{g.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(s){let c,u={box:!0,noLocation:!0,obtainStep:t(_=>{c=_},"obtainStep")};if(await this.step(s.title,this.makeChecksumStepFunction(s.withError),!1,u),c!=null&&c.stepId&&this.arStepIds.push(c.stepId),!c)throw new Error("Checksum step was not created");return c}async step(s,c,u=!0,{obtainStep:_=void 0,box:g=!1,noLocation:b=void 0}={}){let w=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=u===!0,b!==void 0&&(this.testInfo._checksumNoLocation=b),await this.test.step(s,c??(()=>{}),{obtainStep:_,box:g})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=w}}addErrorMessage(s,c){this.testInfo.addError(s,c)}async evaluateWithChecksum(s,c,u=!0){this.navigationPromise&&await this.navigationPromise;let _=this.page.evaluate.bind(this.page);return this.conditionallyWrapInternalSteps(u,()=>_(s,c))}getChecksumTestId(){return this.checksumTestId}addNewThought(s,c,u=!1){var b;let _={thought:s,type:c,...u?{children:[]}:{}};if(!this.currentThought)this.highLevelThoughts.push(_);else if(this.currentThought.children)this.currentThought.children.push(_),_.parent=this.currentThought;else{let w=this.currentThought.parent;w?(w.children=w.children??[],w.children.push(_),_.parent=w):this.highLevelThoughts.push(_)}let g=_.parent;return g?_.id=`${g.id}.${((b=g.children)==null?void 0:b.length)??0}`:_.id=`${++this.thoughtsCounter}`,this.currentThought=_,_}buildThoughtsChainForFallback(s=this.highLevelThoughts){let c=[];return s.forEach(u=>{c.push(u.thought),u.children&&c.push(...this.buildThoughtsChainForFallback(u.children))}),c}compoundSelection(...s){let c=super.compoundSelection(...s);return c.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),c}setSelectorFallback(s){let c={checksumId:s,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:Ldt};this.pushFallback(this.constructFallback(Oue).init(c)),this.pushFallback(this.constructFallback(Fue).init(c))}setCompoundSelectorFallback(s){this.pushFallback(this.constructFallback(Rue).init({checksumId:s,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:Ldt}))}setAIFallback(s,c){var b;let u=((b=this.options.useChecksumAI)==null?void 0:b.arVersion)===1,_=t(()=>{var le,ye,Te,Tt,vt,jt;let w=this.buildThoughtsChainForFallback(),D={title:this.testInfo.title},O={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},G={previous:w.slice(0,-1),failing:s,next:w.slice(1)},z={storyInfo:D,testIdentification:O,fallbackConfig:{arMode:(le=this.options.useChecksumAI)==null?void 0:le.arMode,overrideOptions:{...(ye=this.options.useChecksumAI)==null?void 0:ye.overrideOptions,...(Te=this.options.useChecksumAI)!=null&&Te.modelName&&!((vt=(Tt=this.options.useChecksumAI)==null?void 0:Tt.overrideOptions)!=null&&vt.modelName)?{modelName:this.options.useChecksumAI.modelName}:{}},markRecovered:(jt=this.options.useChecksumAI)==null?void 0:jt.markRecovered},thoughts:G,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:c};return this.constructFallback(X6).init(z)},"createArFallback"),g=t(()=>{let w=typeof this.options.useChecksumAI=="object"?this.options.useChecksumAI:void 0,D=w==null?void 0:w.arMode,O=w==null?void 0:w.overrideOptions;return this.constructFallback(a6).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),...D!==void 0?{arMode:D}:{},...O!==void 0?{overrideOptions:O}:{},fallbackType:c})},"createAIFallback");return u?this.pushFallback(g()):this.pushFallback(_()),this.proxy}pushFallback(s){this.fallbacks.push(s),this.sortFallbacks()}handleAIFallback(s,c,u,_){let g=s.fallbackAnalyticsPayload.iterationSteps,b=g.length>0?_/g.length:0,w=u.fbResult??"failed";this.testRunAnalytics.testRunFallbackExecution({result:w,failedThought:s.getFailedThought(),summary:u.summary??"",stepsPayload:s.fallbackAnalyticsPayload,type:s.fallbackType??c.type,duration:_,avgDuration:b,success:["finish","soft_assertion"].includes(w)}),this.arResults.push({failedThought:s.getFailedThought(),result:w,...u.thought!==void 0?{thought:u.thought}:{}})}handleAutoRecovery(s,c,u,_){let g=u.stepsThoughts??[],b=g.length>0?_/g.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:s.failingThought,type:c.type,finalThought:u.thought??"",result:u.fbResult??"failed",duration:_,avgStepDuration:b,stepsThoughts:g,version:"v1"})}async runFallback(s,c){let u=Date.now(),_=s.resolve(c),g=await Zm(_,s.timeout),b=Date.now()-u;if(!g)throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:"Recovery Failed",withError:!0}),new Error("Fallback failed");s instanceof a6&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(s,c,g,b)),s instanceof X6&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(s,c,g,b));let w=g.thought?`: ${g.thought}`:"";if(g.fbResult==="failed")throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:`Recovery Failed${w}`,withError:!0}),new Error("Fallback failed");if(g.fbResult==="hard_assertion")throw this.hasSuccessfulAutoRecovery=!1,this.createChecksumStep({title:`Recovery Failed${w}`,withError:!0}),new sue(g.fbResult);this.hasUsedAutoRecovery&&(this.hasSuccessfulAutoRecovery=!0),s instanceof a6&&g.summary&&this.arSummaries.push(g.summary),s instanceof X6&&g.thought&&this.arSummaries.push(g.thought),this.createChecksumStep({title:`Recovery Complete${w}`});let D=this.currentThought;if(D&&g.steps.length===1){let O=g.steps[0];O!=null&&O.thought&&(D.thought=O.thought)}else D&&(D.children=g.steps.map((O,G)=>({id:`${D.id}.${G+1}`,thought:O.thought??"",type:O.type,parent:D})))}async runConditionallyWithinStep(s,c,u){return s?await this.step(c,u):await u()}async onExecutionError(s){try{return await this.initiateFallbackSequence({...s,type:"action"})}catch(c){if(!this.currentThought){let{locator:u,method:_}=s;this.testRunAnalytics.testRunActionExecutionFailure({locator:(u==null?void 0:u.toString())??"",selector:(u==null?void 0:u._selector)??"",method:_,checksumStepId:this.checksumStepId??"",error:c instanceof Error?c.toString():String(c)})}throw c}}async initiateFallbackSequence(s,{fallbackTypes:c=void 0}={}){var b;Cu(`[initiateFallbackSequence] with type: ${s.type}...`);let u=this.fallbacks.find(w=>w instanceof a6);if(u){let w=u.getFailedThought(),D=((b=this.variableStore)==null?void 0:b.getActiveVariables())??[];this.fallbacks.forEach(O=>{O.setThought(w),O.setVariables(D)})}let _=this.fallbacks.find(w=>w instanceof X6);if(_){let w=_.failingThought;this.fallbacks.forEach(D=>{var O;D instanceof X6&&D.setVariables(((O=this.variableStore)==null?void 0:O.getActiveVariables())??[]),D.setThought(w)})}let g=this.fallbacks;c&&(g=g.filter(w=>c.reduce((D,O)=>D||w instanceof O,!1))),g=g.filter(w=>w.canResolve(s));try{for(let w of g){let D=w==null?void 0:w.toString();D&&console.log(`Using ${D}`);try{await this.runConditionallyWithinStep(s.type!=="assertion"||!s.withChecksumAI,w.getRecoveryAttemptTitle(s),async()=>await this.runFallback(w,s))}catch(O){if(s.withChecksumAI&&O.message==="fetch failed")throw new Error(zL);O instanceof sue&&O.fallbackResult==="hard_assertion"&&tvn(s.error,"hard_assertion"),D&&console.log(`Failed to use ${D}`),w.cancel();continue}return!0}throw s.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(Mue).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()&&this.timeMachine){let s=this.timeMachine;try{await s.flushRRwebEventsToFile();let c=s.getRRwebFilePath();c&&this.monitorBridge.addAsset({type:"rrweb-recording",path:c,testId:this.checksumTestId,fileName:lD.basename(c)})}catch(c){Cu("Error shutting down RRweb events recording",c)}if(this.testRunAnalytics)return Cu("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let s=[Mue,Rue,Oue,Fue,a6];this.fallbacks.sort((c,u)=>s.indexOf(c.constructor)-s.indexOf(u.constructor))}constructFallback(s){return new s(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"},this,this._context)}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let c=await this.getTraceFilePath();c&&this.monitorBridge.addAsset({type:"trace",path:c,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let c=hFt(eSe(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:c,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?yFt(eSe(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let s=u$e(eSe(this.testInfo.file)),c=lD.join(s,`${this.checksumTestId}.har.zip`);if(!(0,pE.existsSync)(c))throw new Error("Could not find har file or zip file");let u=lD.join(s,"tmp");(0,pE.existsSync)(u)||(0,pE.mkdirSync)(u);let _=(0,pE.readFileSync)(c),g=await(0,Wir.loadAsync)(_);for(let w of Object.keys(g.files)){let D=g.file(w);if(!D)continue;let O=await D.async("string"),G=lD.join(u,w);(0,pE.writeFileSync)(G,O),this.unzippedHarData.push(G)}let b=lD.join(u,"test.har");if(!(0,pE.existsSync)(b))throw this.cleanupMockData(),new Error(`Could not find har file ${b} after unzipping ${c}`);return b}cleanupMockData(){this.unzippedHarData.forEach(c=>{(0,pE.rmSync)(c)});let s=this.unzippedHarData[0];s&&(0,pE.rmSync)(lD.dirname(s),{recursive:!0,force:!0})}async prepareAPIMock(){let s={GET:0,POST:0,PUT:0,DELETE:0};try{let c=await this.prepareMockData();await this.page.routeFromHAR(c,{url:"*/**",notFound:"fallback",update:!1});let u=this.page._routes[0].handler;await this.page.route("**/*",_=>{let g=_.request().headers(),b=_.request().method(),w=(s[b]??0)+1;s[b]=w,g["Checksum-Id"]=w.toString(),_.request()._applyFallbackOverrides({headers:g}),u(_)})}catch(c){Cu("Error setting up mock data",c.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let s=lD.join(EU(Qx()),"settings.asr");if(!(0,pE.existsSync)(s)){Cu("Could not find ASR file");return}let{ungzip:c}=await Promise.resolve().then(()=>_c(c$e()));try{let u=await c((0,pE.readFileSync)(s));this.appSpecificRules=JSON.parse(u.toString())||{}}catch(u){Cu("Could not read ASR file",u.message)}}addAutoRecoveryStepId(s){this.arStepIds.push(s)}};t(u$,"RuntimePage"),u$.recentlyInteracted=new Map;var SPe=u$;var Vir=require("fs"),qir=require("module"),Gir=require("path"),Yir=require("vm"),Zir=require("sucrase");function Kir(i){let n=(0,Vir.readFileSync)(i,"utf8"),{code:s}=(0,Zir.transform)(n,{transforms:["typescript","imports"],filePath:i}),c={},u={exports:c};(0,Yir.runInThisContext)(`(function (exports, require, module, __filename, __dirname) {
|
|
773
773
|
${s}
|
package/package.json
CHANGED