@checksum-ai/runtime 2.0.5-alpha.5 → 2.0.5-alpha.6

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 CHANGED
@@ -1 +1 @@
1
- CHECKSUM_RUNTIME_BUILD_TIME=2025-12-09T13:16:09.222Z
1
+ CHECKSUM_RUNTIME_BUILD_TIME=2025-12-09T13:33:14.297Z
package/index.js CHANGED
@@ -1807,7 +1807,7 @@ Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/
1807
1807
  `)}function Atr(i,t){if(pXa(i))return i.anyOf.map(r=>Atr(r,t)).join(" | ");switch(i.type){case"string":return i.enum?i.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return i.enum?i.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return i.enum?i.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",lbi(i,t+2),"}"].join(`
1808
1808
  `);case"array":return i.items?`${Atr(i.items,t)}[]`:"any[]";default:return""}}var pbi=Dr(()=>{e(pXa,"isAnyOfProp");e(cbi,"formatFunctionDefinitions");e(lbi,"formatObjectProperties");e(Atr,"formatType")});function fbi(i,t){let r;if(Cie(i)){let a=sbi({name:i.name,parameters:i.schema,description:i.description});a.function.parameters?r={type:a.type,function:{name:a.function.name,description:a.function.description,parameters:a.function.parameters,...(t==null?void 0:t.strict)!==void 0?{strict:t.strict}:{}}}:r={type:"function",function:DXt(i,t)}}else r=i;return(t==null?void 0:t.strict)!==void 0&&(r.function.strict=t.strict),r}var dbi=Dr(()=>{mOe();zmn();e(fbi,"_convertToOpenAITool")});function fXa(i){return i.role!=="system"&&i.role!=="developer"&&i.role!=="assistant"&&i.role!=="user"&&i.role!=="function"&&i.role!=="tool"&&console.warn(`Unknown message role: ${i.role}`),i.role}function _bi(i){let t=i._getType();switch(t){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!kce.isInstance(i))throw new Error("Invalid generic chat message");return fXa(i)}default:throw new Error(`Unknown message type: ${t}`)}}function dXa(i,t,r){let a=i.tool_calls;switch(i.role){case"assistant":{let o=[],c=[];for(let v of a??[])try{o.push($yt(v,{returnId:!0}))}catch(C){c.push(FXt(v,C.message))}let f={function_call:i.function_call,tool_calls:a};r!==void 0&&(f.__raw_response=t);let _={model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};return i.audio&&(f.audio=i.audio),new PI({content:i.content||"",tool_calls:o,invalid_tool_calls:c,additional_kwargs:f,response_metadata:_,id:t.id})}default:return new kce(i.content||"",i.role??"unknown")}}function mXa(i,t,r,a){var v,C;let o=i.role??r,c=i.content??"",f;i.function_call?f={function_call:i.function_call}:i.tool_calls?f={tool_calls:i.tool_calls}:f={},a&&(f.__raw_response=t),i.audio&&(f.audio={...i.audio,index:t.choices[0].index});let _={usage:{...t.usage}};if(o==="user")return new cbe({content:c,response_metadata:_});if(o==="assistant"){let w=[];if(Array.isArray(i.tool_calls))for(let T of i.tool_calls)w.push({name:(v=T.function)==null?void 0:v.name,args:(C=T.function)==null?void 0:C.arguments,id:T.id,index:T.index,type:"tool_call_chunk"});return new kA({content:c,tool_call_chunks:w,additional_kwargs:f,id:t.id,response_metadata:_})}else return o==="system"?new Ice({content:c,response_metadata:_}):o==="developer"?new Ice({content:c,response_metadata:_,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new ube({content:c,additional_kwargs:f,name:i.name,response_metadata:_}):o==="tool"?new t7e({content:c,additional_kwargs:f,tool_call_id:i.tool_call_id,response_metadata:_}):new obe({content:c,role:o,response_metadata:_})}function Jmn(i,t){return i.flatMap(r=>{var c;let a=_bi(r);a==="system"&&(t!=null&&t.startsWith("o1"))&&(a="developer");let o={role:a,content:r.content};if(r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call,o.content=null),yz(r)&&((c=r.tool_calls)!=null&&c.length)?(o.tool_calls=r.tool_calls.map(PXt),o.content=null):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let f={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[o,f]}return o})}function mbi(i,t){return PJe(i)?(t==null?void 0:t.strict)!==void 0?{...i,function:{...i.function,strict:t.strict}}:i:fbi(i,t)}function Etr(i){return typeof(i==null?void 0:i.parse)=="function"}function _Xa(i){return i!==void 0&&typeof i.schema=="object"}var Wmn,dBe,Ctr=Dr(()=>{_tr();Cxe();bhe();Lz();Lyt();Myt();jyt();Uyt();NXt();__e();zmn();Uxe();fBe();pbi();dbi();e(fXa,"extractGenericMessageCustomRole");e(_bi,"messageToOpenAIRole");e(dXa,"openAIResponseToChatMessage");e(mXa,"_convertDeltaToMessageChunk");e(Jmn,"_convertMessagesToOpenAIParams");e(mbi,"_convertChatOpenAIToolTypeToOpenAITool");Wmn=class Wmn extends xhe{static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning_effort"]}get lc_secrets(){return{openAIApiKey:"OPENAI_API_KEY",apiKey:"OPENAI_API_KEY",azureOpenAIApiKey:"AZURE_OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{modelName:"model",openAIApiKey:"openai_api_key",apiKey:"openai_api_key",azureOpenAIApiVersion:"azure_openai_api_version",azureOpenAIApiKey:"azure_openai_api_key",azureOpenAIApiInstanceName:"azure_openai_api_instance_name",azureOpenAIApiDeploymentName:"azure_openai_api_deployment_name"}}constructor(t,r){var a,o,c,f,_,v,C,w,T;if(super(t??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"frequencyPenalty",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"presencePenalty",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"logitBias",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"gpt-3.5-turbo"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"gpt-3.5-turbo"}),Object.defineProperty(this,"modelKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topLogprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"openAIApiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureOpenAIApiVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureOpenAIApiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureADTokenProvider",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureOpenAIApiInstanceName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureOpenAIApiDeploymentName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureOpenAIBasePath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"azureOpenAIEndpoint",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"organization",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"__includeRawResponse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"clientConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"supportsStrictToolCalling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"audio",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modalities",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reasoningEffort",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.openAIApiKey=(t==null?void 0:t.apiKey)??(t==null?void 0:t.openAIApiKey)??((a=t==null?void 0:t.configuration)==null?void 0:a.apiKey)??nA("OPENAI_API_KEY"),this.apiKey=this.openAIApiKey,this.azureOpenAIApiKey=(t==null?void 0:t.azureOpenAIApiKey)??nA("AZURE_OPENAI_API_KEY"),this.azureADTokenProvider=(t==null?void 0:t.azureADTokenProvider)??void 0,!this.azureOpenAIApiKey&&!this.apiKey&&!this.azureADTokenProvider)throw new Error("OpenAI or Azure OpenAI API key or Token Provider not found");if(this.azureOpenAIApiInstanceName=(t==null?void 0:t.azureOpenAIApiInstanceName)??nA("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=(t==null?void 0:t.azureOpenAIApiDeploymentName)??nA("AZURE_OPENAI_API_DEPLOYMENT_NAME"),this.azureOpenAIApiVersion=(t==null?void 0:t.azureOpenAIApiVersion)??nA("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=(t==null?void 0:t.azureOpenAIBasePath)??nA("AZURE_OPENAI_BASE_PATH"),this.organization=((o=t==null?void 0:t.configuration)==null?void 0:o.organization)??nA("OPENAI_ORGANIZATION"),this.azureOpenAIEndpoint=(t==null?void 0:t.azureOpenAIEndpoint)??nA("AZURE_OPENAI_ENDPOINT"),this.modelName=(t==null?void 0:t.model)??(t==null?void 0:t.modelName)??this.model,this.model=this.modelName,this.modelKwargs=(t==null?void 0:t.modelKwargs)??{},this.timeout=t==null?void 0:t.timeout,this.temperature=(t==null?void 0:t.temperature)??this.temperature,this.topP=(t==null?void 0:t.topP)??this.topP,this.frequencyPenalty=(t==null?void 0:t.frequencyPenalty)??this.frequencyPenalty,this.presencePenalty=(t==null?void 0:t.presencePenalty)??this.presencePenalty,this.maxTokens=t==null?void 0:t.maxTokens,this.logprobs=t==null?void 0:t.logprobs,this.topLogprobs=t==null?void 0:t.topLogprobs,this.n=(t==null?void 0:t.n)??this.n,this.logitBias=t==null?void 0:t.logitBias,this.stop=(t==null?void 0:t.stopSequences)??(t==null?void 0:t.stop),this.stopSequences=this==null?void 0:this.stop,this.user=t==null?void 0:t.user,this.__includeRawResponse=t==null?void 0:t.__includeRawResponse,this.audio=t==null?void 0:t.audio,this.modalities=t==null?void 0:t.modalities,this.reasoningEffort=t==null?void 0:t.reasoningEffort,this.azureOpenAIApiKey||this.azureADTokenProvider){if(!this.azureOpenAIApiInstanceName&&!this.azureOpenAIBasePath&&!this.azureOpenAIEndpoint)throw new Error("Azure OpenAI API instance name not found");if(!this.azureOpenAIApiDeploymentName&&this.azureOpenAIBasePath){let k=this.azureOpenAIBasePath.split("/openai/deployments/");if(k.length===2){let[,R]=k;this.azureOpenAIApiDeploymentName=R}}if(!this.azureOpenAIApiDeploymentName)throw new Error("Azure OpenAI API deployment name not found");if(!this.azureOpenAIApiVersion)throw new Error("Azure OpenAI API version not found");this.apiKey=this.apiKey??"",this.streamUsage=!1}this.streaming=(t==null?void 0:t.streaming)??!1,this.streamUsage=(t==null?void 0:t.streamUsage)??this.streamUsage,this.clientConfig={apiKey:this.apiKey,organization:this.organization,baseURL:(r==null?void 0:r.basePath)??((c=t==null?void 0:t.configuration)==null?void 0:c.basePath),dangerouslyAllowBrowser:!0,defaultHeaders:((f=r==null?void 0:r.baseOptions)==null?void 0:f.headers)??((v=(_=t==null?void 0:t.configuration)==null?void 0:_.baseOptions)==null?void 0:v.headers),defaultQuery:((C=r==null?void 0:r.baseOptions)==null?void 0:C.params)??((T=(w=t==null?void 0:t.configuration)==null?void 0:w.baseOptions)==null?void 0:T.params),...r,...t==null?void 0:t.configuration},(t==null?void 0:t.supportsStrictToolCalling)!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling)}getLsParams(t){let r=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:r.temperature??void 0,ls_max_tokens:r.max_tokens??void 0,ls_stop:t.stop}}bindTools(t,r){let a;return(r==null?void 0:r.strict)!==void 0?a=r.strict:this.supportsStrictToolCalling!==void 0&&(a=this.supportsStrictToolCalling),this.bind({tools:t.map(o=>mbi(o,{strict:a})),...r})}createResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&Etr(t.json_schema.schema)?abi(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}invocationParams(t,r){var _;let a;(t==null?void 0:t.strict)!==void 0?a=t.strict:this.supportsStrictToolCalling!==void 0&&(a=this.supportsStrictToolCalling);let o={};(t==null?void 0:t.stream_options)!==void 0?o={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||r!=null&&r.streaming)&&(o={stream_options:{include_usage:!0}});let c={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,max_tokens:this.maxTokens===-1?void 0:this.maxTokens,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:(t==null?void 0:t.stop)??this.stopSequences,user:this.user,stream:this.streaming,functions:t==null?void 0:t.functions,function_call:t==null?void 0:t.function_call,tools:(_=t==null?void 0:t.tools)!=null&&_.length?t.tools.map(v=>mbi(v,{strict:a})):void 0,tool_choice:ubi(t==null?void 0:t.tool_choice),response_format:this.createResponseFormat(t==null?void 0:t.response_format),seed:t==null?void 0:t.seed,...o,parallel_tool_calls:t==null?void 0:t.parallel_tool_calls,...this.audio||t!=null&&t.audio?{audio:this.audio||(t==null?void 0:t.audio)}:{},...this.modalities||t!=null&&t.modalities?{modalities:this.modalities||(t==null?void 0:t.modalities)}:{},...this.modelKwargs};(t==null?void 0:t.prediction)!==void 0&&(c.prediction=t.prediction);let f=(t==null?void 0:t.reasoning_effort)??this.reasoningEffort;return f!==void 0&&(c.reasoning_effort=f),c}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}async*_streamResponseChunks(t,r,a){var C,w,T,k,R,B,U,W,X,ne;let o=Jmn(t,this.model),c={...this.invocationParams(r,{streaming:!0}),messages:o,stream:!0},f,_=await this.completionWithRetry(c,r),v;for await(let ce of _){let fe=(C=ce==null?void 0:ce.choices)==null?void 0:C[0];if(ce.usage&&(v=ce.usage),!fe)continue;let{delta:be}=fe;if(!be)continue;let De=mXa(be,ce,f,this.__includeRawResponse);f=be.role??f;let Fe={prompt:r.promptIndex??0,completion:fe.index??0};if(typeof De.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let ke={...Fe};fe.finish_reason!=null&&(ke.finish_reason=fe.finish_reason,ke.system_fingerprint=ce.system_fingerprint,ke.model_name=ce.model),this.logprobs&&(ke.logprobs=fe.logprobs);let Oe=new p3({message:De,text:De.content,generationInfo:ke});yield Oe,await(a==null?void 0:a.handleLLMNewToken(Oe.text??"",Fe,void 0,void 0,void 0,{chunk:Oe}))}if(v){let ce={...((w=v.prompt_tokens_details)==null?void 0:w.audio_tokens)!==null&&{audio:(T=v.prompt_tokens_details)==null?void 0:T.audio_tokens},...((k=v.prompt_tokens_details)==null?void 0:k.cached_tokens)!==null&&{cache_read:(R=v.prompt_tokens_details)==null?void 0:R.cached_tokens}},fe={...((B=v.completion_tokens_details)==null?void 0:B.audio_tokens)!==null&&{audio:(U=v.completion_tokens_details)==null?void 0:U.audio_tokens},...((W=v.completion_tokens_details)==null?void 0:W.reasoning_tokens)!==null&&{reasoning:(X=v.completion_tokens_details)==null?void 0:X.reasoning_tokens}};yield new p3({message:new kA({content:"",response_metadata:{usage:{...v}},usage_metadata:{input_tokens:v.prompt_tokens,output_tokens:v.completion_tokens,total_tokens:v.total_tokens,...Object.keys(ce).length>0&&{input_token_details:ce},...Object.keys(fe).length>0&&{output_token_details:fe}}}),text:""})}if((ne=r.signal)!=null&&ne.aborted)throw new Error("AbortError")}identifyingParams(){return this._identifyingParams()}async _generate(t,r,a){var _,v;let o={},c=this.invocationParams(r),f=Jmn(t,this.model);if(c.stream){let C=this._streamResponseChunks(t,r,a),w={};for await(let W of C){W.message.response_metadata={...W.generationInfo,...W.message.response_metadata};let X=((_=W.generationInfo)==null?void 0:_.completion)??0;w[X]===void 0?w[X]=W:w[X]=w[X].concat(W)}let T=Object.entries(w).sort(([W],[X])=>parseInt(W,10)-parseInt(X,10)).map(([W,X])=>X),{functions:k,function_call:R}=this.invocationParams(r),B=await this.getEstimatedTokenCountFromPrompt(t,k,R),U=await this.getNumTokensFromGenerations(T);return o.input_tokens=B,o.output_tokens=U,o.total_tokens=B+U,{generations:T,llmOutput:{estimatedTokenUsage:{promptTokens:o.input_tokens,completionTokens:o.output_tokens,totalTokens:o.total_tokens}}}}else{let C;r.response_format&&r.response_format.type==="json_schema"?C=await this.betaParsedCompletionWithRetry({...c,stream:!1,messages:f},{signal:r==null?void 0:r.signal,...r==null?void 0:r.options}):C=await this.completionWithRetry({...c,stream:!1,messages:f},{signal:r==null?void 0:r.signal,...r==null?void 0:r.options});let{completion_tokens:w,prompt_tokens:T,total_tokens:k,prompt_tokens_details:R,completion_tokens_details:B}=(C==null?void 0:C.usage)??{};w&&(o.output_tokens=(o.output_tokens??0)+w),T&&(o.input_tokens=(o.input_tokens??0)+T),k&&(o.total_tokens=(o.total_tokens??0)+k),((R==null?void 0:R.audio_tokens)!==null||(R==null?void 0:R.cached_tokens)!==null)&&(o.input_token_details={...(R==null?void 0:R.audio_tokens)!==null&&{audio:R==null?void 0:R.audio_tokens},...(R==null?void 0:R.cached_tokens)!==null&&{cache_read:R==null?void 0:R.cached_tokens}}),((B==null?void 0:B.audio_tokens)!==null||(B==null?void 0:B.reasoning_tokens)!==null)&&(o.output_token_details={...(B==null?void 0:B.audio_tokens)!==null&&{audio:B==null?void 0:B.audio_tokens},...(B==null?void 0:B.reasoning_tokens)!==null&&{reasoning:B==null?void 0:B.reasoning_tokens}});let U=[];for(let W of(C==null?void 0:C.choices)??[]){let ne={text:((v=W.message)==null?void 0:v.content)??"",message:dXa(W.message??{role:"assistant"},C,this.__includeRawResponse)};ne.generationInfo={...W.finish_reason?{finish_reason:W.finish_reason}:{},...W.logprobs?{logprobs:W.logprobs}:{}},yz(ne.message)&&(ne.message.usage_metadata=o),ne.message=new PI(Object.fromEntries(Object.entries(ne.message).filter(([ce])=>!ce.startsWith("lc_")))),U.push(ne)}return{generations:U,llmOutput:{tokenUsage:{promptTokens:o.input_tokens,completionTokens:o.output_tokens,totalTokens:o.total_tokens}}}}}async getEstimatedTokenCountFromPrompt(t,r,a){let o=(await this.getNumTokensFromMessages(t)).totalCount;if(r&&a!=="auto"){let c=cbi(r);o+=await this.getNumTokens(c),o+=9}return r&&t.find(c=>c._getType()==="system")&&(o-=4),a==="none"?o+=1:typeof a=="object"&&(o+=await this.getNumTokens(a.name)+4),o}async getNumTokensFromGenerations(t){return(await Promise.all(t.map(async a=>{var o;return(o=a.message.additional_kwargs)!=null&&o.function_call?(await this.getNumTokensFromMessages([a.message])).countPerMessage[0]:await this.getNumTokens(a.message.content)}))).reduce((a,o)=>a+o,0)}async getNumTokensFromMessages(t){let r=0,a=0,o=0;this.model==="gpt-3.5-turbo-0301"?(a=4,o=-1):(a=3,o=1);let c=await Promise.all(t.map(async f=>{var k,R,B,U,W,X;let _=await this.getNumTokens(f.content),v=await this.getNumTokens(_bi(f)),C=f.name!==void 0?o+await this.getNumTokens(f.name):0,w=_+a+v+C,T=f;if(T._getType()==="function"&&(w-=2),(k=T.additional_kwargs)!=null&&k.function_call&&(w+=3),(R=T==null?void 0:T.additional_kwargs.function_call)!=null&&R.name&&(w+=await this.getNumTokens((B=T.additional_kwargs.function_call)==null?void 0:B.name)),(U=T.additional_kwargs.function_call)!=null&&U.arguments)try{w+=await this.getNumTokens(JSON.stringify(JSON.parse((W=T.additional_kwargs.function_call)==null?void 0:W.arguments)))}catch(ne){console.error("Error parsing function arguments",ne,JSON.stringify(T.additional_kwargs.function_call)),w+=await this.getNumTokens((X=T.additional_kwargs.function_call)==null?void 0:X.arguments)}return r+=w,w}));return r+=3,{totalCount:r,countPerMessage:c}}async completionWithRetry(t,r){let a=this._getClientOptions(r);return this.caller.call(async()=>{try{return await this.client.chat.completions.create(t,a)}catch(o){throw pBe(o)}})}async betaParsedCompletionWithRetry(t,r){let a=this._getClientOptions(r);return this.caller.call(async()=>{try{return await this.client.beta.chat.completions.parse(t,a)}catch(o){throw pBe(o)}})}_getClientOptions(t){if(!this.client){let a={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,baseURL:this.clientConfig.baseURL,azureOpenAIEndpoint:this.azureOpenAIEndpoint},o=g3e(a),c={...this.clientConfig,baseURL:o,timeout:this.timeout,maxRetries:0};c.baseURL||delete c.baseURL,this.client=new IA(c)}let r={...this.clientConfig,...t};return this.azureOpenAIApiKey&&(r.headers={"api-key":this.azureOpenAIApiKey,...r.headers},r.query={"api-version":this.azureOpenAIApiVersion,...r.query}),r}_llmType(){return"openai"}_combineLLMOutput(...t){return t.reduce((r,a)=>(a&&a.tokenUsage&&(r.tokenUsage.completionTokens+=a.tokenUsage.completionTokens??0,r.tokenUsage.promptTokens+=a.tokenUsage.promptTokens??0,r.tokenUsage.totalTokens+=a.tokenUsage.totalTokens??0),r),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}withStructuredOutput(t,r){let a,o,c,f;_Xa(t)?(a=t.schema,o=t.name,c=t.method,f=t.includeRaw):(a=t,o=r==null?void 0:r.name,c=r==null?void 0:r.method,f=r==null?void 0:r.includeRaw);let _,v;if((r==null?void 0:r.strict)!==void 0&&c==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");if(c==="jsonMode")_=this.bind({response_format:{type:"json_object"}}),Etr(a)?v=hOe.fromZodSchema(a):v=new gOe;else if(c==="jsonSchema")_=this.bind({response_format:{type:"json_schema",json_schema:{name:o??"extract",description:a.description,schema:a,strict:r==null?void 0:r.strict}}}),Etr(a)?v=hOe.fromZodSchema(a):v=new gOe;else{let k=o??"extract";if(Etr(a)){let R=DR(a);_=this.bind({tools:[{type:"function",function:{name:k,description:R.description,parameters:R}}],tool_choice:{type:"function",function:{name:k}},...(r==null?void 0:r.strict)!==void 0?{strict:r.strict}:{}}),v=new Ele({returnSingle:!0,keyName:k,zodSchema:a})}else{let R;typeof a.name=="string"&&typeof a.parameters=="object"&&a.parameters!=null?(R=a,k=a.name):(k=a.title??k,R={name:k,description:a.description??"",parameters:a}),_=this.bind({tools:[{type:"function",function:R}],tool_choice:{type:"function",function:{name:k}},...(r==null?void 0:r.strict)!==void 0?{strict:r.strict}:{}}),v=new Ele({returnSingle:!0,keyName:k})}}if(!f)return _.pipe(v);let C=mO.assign({parsed:e((k,R)=>v.invoke(k.raw,R),"parsed")}),w=mO.assign({parsed:e(()=>null,"parsed")}),T=C.withFallbacks({fallbacks:[w]});return xz.from([{raw:_},T])}};e(Wmn,"ChatOpenAI");dBe=Wmn;e(Etr,"isZodSchema");e(_Xa,"isStructuredOutputMethodParams")});var hbi=Dr(()=>{Ctr();Uxe()});var gbi=Dr(()=>{bhe();Lz();WXt();Uxe();fBe()});var Hmn=Dr(()=>{Myt();bhe();Lz();WXt();YXt();Uxe();gbi();fBe()});var ybi=Dr(()=>{Hmn();Uxe()});var Gmn=Dr(()=>{Lz();lun();YXt();Uxe();fBe()});var vbi=Dr(()=>{Gmn();Uxe();fBe()});var bbi=Dr(()=>{});var Ymn,Kmn,xbi=Dr(()=>{Lz();_tr();tQr();Ymn=class Ymn extends Kmt{static lc_name(){return"DallEAPIWrapper"}constructor(t){(t==null?void 0:t.responseFormat)!==void 0&&["url","b64_json"].includes(t.responseFormat)&&(t.dallEResponseFormat=t.responseFormat,t.responseFormat="content"),super(t),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"dall-e-3"}),Object.defineProperty(this,"style",{enumerable:!0,configurable:!0,writable:!0,value:"vivid"}),Object.defineProperty(this,"quality",{enumerable:!0,configurable:!0,writable:!0,value:"standard"}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:"1024x1024"}),Object.defineProperty(this,"dallEResponseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"url"}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let r=(t==null?void 0:t.apiKey)??(t==null?void 0:t.openAIApiKey)??nA("OPENAI_API_KEY"),a=(t==null?void 0:t.organization)??nA("OPENAI_ORGANIZATION"),o={apiKey:r,organization:a,dangerouslyAllowBrowser:!0,baseUrl:t==null?void 0:t.baseUrl};this.client=new IA(o),this.model=(t==null?void 0:t.model)??(t==null?void 0:t.modelName)??this.model,this.style=(t==null?void 0:t.style)??this.style,this.quality=(t==null?void 0:t.quality)??this.quality,this.n=(t==null?void 0:t.n)??this.n,this.size=(t==null?void 0:t.size)??this.size,this.dallEResponseFormat=(t==null?void 0:t.dallEResponseFormat)??this.dallEResponseFormat,this.user=t==null?void 0:t.user}processMultipleGeneratedUrls(t){return this.dallEResponseFormat==="url"?t.flatMap(r=>r.data.flatMap(o=>o.url?{type:"image_url",image_url:o.url}:[]).filter(o=>o!==void 0&&o.type==="image_url"&&typeof o.image_url=="string"&&o.image_url!==void 0)):t.flatMap(r=>r.data.flatMap(o=>o.b64_json?{type:"image_url",image_url:{url:o.b64_json}}:[]).filter(o=>o!==void 0&&o.type==="image_url"&&typeof o.image_url=="object"&&"url"in o.image_url&&typeof o.image_url.url=="string"&&o.image_url.url!==void 0))}async _call(t){let r={model:this.model,prompt:t,n:1,size:this.size,response_format:this.dallEResponseFormat,style:this.style,quality:this.quality,user:this.user};if(this.n>1){let c=await Promise.all(Array.from({length:this.n}).map(()=>this.client.images.generate(r)));return this.processMultipleGeneratedUrls(c)}let a=await this.client.images.generate(r),o="";return this.dallEResponseFormat==="url"?[o]=a.data.map(c=>c.url).filter(c=>c!=="undefined"):[o]=a.data.map(c=>c.b64_json).filter(c=>c!=="undefined"),o}};e(Ymn,"DallEAPIWrapper");Kmn=Ymn;Object.defineProperty(Kmn,"toolName",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"})});var Abi=Dr(()=>{xbi()});var Ebi=Dr(()=>{Ctr()});var Cbi=Dr(()=>{Ctr();hbi();Hmn();ybi();vbi();Gmn();bbi();fBe();Uxe();Abi();Ebi()});var Xmn=Dr(()=>{Cbi()});var e_n,Zmn,wbi=Dr(()=>{Xmn();Lz();e_n=class e_n extends dBe{static lc_name(){return"ChatFireworks"}_llmType(){return"fireworks"}get lc_secrets(){return{fireworksApiKey:"FIREWORKS_API_KEY",apiKey:"FIREWORKS_API_KEY"}}constructor(t){let r=(t==null?void 0:t.apiKey)||(t==null?void 0:t.fireworksApiKey)||nA("FIREWORKS_API_KEY");if(!r)throw new Error('Fireworks API key not found. Please set the FIREWORKS_API_KEY environment variable or provide the key into "fireworksApiKey"');super({...t,model:(t==null?void 0:t.model)||(t==null?void 0:t.modelName)||"accounts/fireworks/models/llama-v3p1-8b-instruct",apiKey:r,configuration:{baseURL:"https://api.fireworks.ai/inference/v1"},streamUsage:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"fireworksApiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.fireworksApiKey=r,this.apiKey=r}getLsParams(t){let r=super.getLsParams(t);return r.ls_provider="fireworks",r}toJSON(){let t=super.toJSON();return"kwargs"in t&&typeof t.kwargs=="object"&&t.kwargs!=null&&(delete t.kwargs.openai_api_key,delete t.kwargs.configuration),t}async completionWithRetry(t,r){return delete t.frequency_penalty,delete t.presence_penalty,delete t.logit_bias,delete t.functions,t.stream===!0?super.completionWithRetry(t,r):super.completionWithRetry(t,r)}};e(e_n,"ChatFireworks");Zmn=e_n});var Sbi={};rQ(Sbi,{ChatFireworks:()=>Zmn});var Dbi=Dr(()=>{wbi()});var r_n,t_n,Tbi=Dr(()=>{Xmn();Lz();r_n=class r_n extends dBe{static lc_name(){return"ChatTogetherAI"}_llmType(){return"togetherAI"}get lc_secrets(){return{togetherAIApiKey:"TOGETHER_AI_API_KEY",apiKey:"TOGETHER_AI_API_KEY"}}constructor(t){let r=(t==null?void 0:t.apiKey)||(t==null?void 0:t.togetherAIApiKey)||nA("TOGETHER_AI_API_KEY");if(!r)throw new Error('TogetherAI API key not found. Please set the TOGETHER_AI_API_KEY environment variable or provide the key into "togetherAIApiKey"');super({...t,model:(t==null?void 0:t.model)||"mistralai/Mixtral-8x7B-Instruct-v0.1",apiKey:r,configuration:{baseURL:"https://api.together.xyz/v1/"}}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}getLsParams(t){let r=super.getLsParams(t);return r.ls_provider="together",r}toJSON(){let t=super.toJSON();return"kwargs"in t&&typeof t.kwargs=="object"&&t.kwargs!=null&&(delete t.kwargs.openai_api_key,delete t.kwargs.configuration),t}async completionWithRetry(t,r){return delete t.frequency_penalty,delete t.presence_penalty,delete t.logit_bias,delete t.functions,t.stream===!0?super.completionWithRetry(t,r):super.completionWithRetry(t,r)}};e(r_n,"ChatTogetherAI");t_n=r_n});var kbi={};rQ(kbi,{ChatTogetherAI:()=>t_n});var Ibi=Dr(()=>{Tbi()});var Mbi=hr((QLo,Lbi)=>{"use strict";Lbi.exports=e(function(t){if(!Array.isArray(t))throw new TypeError("arr-union expects the first argument to be an array.");for(var r=arguments.length,a=0;++a<r;){var o=arguments[a];if(o){Array.isArray(o)||(o=[o]);for(var c=0;c<o.length;c++){var f=o[c];t.indexOf(f)>=0||t.push(f)}}}return t},"union")});var Ubi=hr((VLo,jbi)=>{"use strict";function vXa(i){var t={},r=e(function(a,o){o=o||bXa(a),(process.env.UNLAZY==="true"||process.env.UNLAZY===!0||process.env.TRAVIS)&&(t[o]=i(a)),Object.defineProperty(r,o,{enumerable:!0,configurable:!0,get:c});function c(){return t.hasOwnProperty(o)?t[o]:t[o]=i(a)}return e(c,"getter"),c},"proxy");return r}e(vXa,"lazyCache");function bXa(i){return i.length===1?i.toLowerCase():(i=i.replace(/^[\W_]+|[\W_]+$/g,"").toLowerCase(),i.replace(/[\W_]+(\w|$)/g,function(t,r){return r.toUpperCase()}))}e(bXa,"camelcase");jbi.exports=vXa});var Qbi=hr((JLo,qbi)=>{"use strict";qbi.exports=e(function(t,r,a){for(var o in t)if(r.call(a,t[o],o,t)===!1)break},"forIn")});var Vbi=hr((HLo,$bi)=>{"use strict";var xXa=Qbi(),AXa=Object.prototype.hasOwnProperty;$bi.exports=e(function(t,r,a){xXa(t,function(o,c){if(AXa.call(t,c))return r.call(a,t[c],c,t)})},"forOwn")});var Wbi=hr((KLo,Jbi)=>{"use strict";var zbi=Ubi()(require),EXa=require;require=zbi;require("is-plain-object","isObject");require("shallow-clone","clone");require("kind-of","typeOf");Vbi();require=EXa;Jbi.exports=zbi});var Gbi=hr((YLo,Hbi)=>{"use strict";var Itr=Wbi();function l_n(i,t){switch(Itr.typeOf(i)){case"object":return CXa(i,t);case"array":return wXa(i,t);default:return Itr.clone(i)}}e(l_n,"cloneDeep");function CXa(i,t){if(Itr.isObject(i)){var r={};return Itr.forOwn(i,function(a,o){this[o]=l_n(a,t)},r),r}else return t?t(i):i}e(CXa,"cloneObjectDeep");function wXa(i,t){for(var r=i.length,a=[],o=-1;++o<r;)a[o]=l_n(i[o],t);return a}e(wXa,"cloneArrayDeep");Hbi.exports=l_n});var Xbi=hr((ZLo,Ybi)=>{Ybi.exports=function(i){return i!=null&&(Kbi(i)||SXa(i)||!!i._isBuffer)};function Kbi(i){return!!i.constructor&&typeof i.constructor.isBuffer=="function"&&i.constructor.isBuffer(i)}e(Kbi,"isBuffer");function SXa(i){return typeof i.readFloatLE=="function"&&typeof i.slice=="function"&&Kbi(i.slice(0,0))}e(SXa,"isSlowBuffer")});var exi=hr((tMo,Zbi)=>{var DXa=Xbi(),TXa=Object.prototype.toString;Zbi.exports=e(function(t){if(typeof t>"u")return"undefined";if(t===null)return"null";if(t===!0||t===!1||t instanceof Boolean)return"boolean";if(typeof t=="string"||t instanceof String)return"string";if(typeof t=="number"||t instanceof Number)return"number";if(typeof t=="function"||t instanceof Function)return"function";if(typeof Array.isArray<"u"&&Array.isArray(t))return"array";if(t instanceof RegExp)return"regexp";if(t instanceof Date)return"date";var r=TXa.call(t);return r==="[object RegExp]"?"regexp":r==="[object Date]"?"date":r==="[object Arguments]"?"arguments":r==="[object Error]"?"error":DXa(t)?"buffer":r==="[object Set]"?"set":r==="[object WeakSet]"?"weakset":r==="[object Map]"?"map":r==="[object WeakMap]"?"weakmap":r==="[object Symbol]"?"symbol":r==="[object Int8Array]"?"int8array":r==="[object Uint8Array]"?"uint8array":r==="[object Uint8ClampedArray]"?"uint8clampedarray":r==="[object Int16Array]"?"int16array":r==="[object Uint16Array]"?"uint16array":r==="[object Int32Array]"?"int32array":r==="[object Uint32Array]"?"uint32array":r==="[object Float32Array]"?"float32array":r==="[object Float64Array]"?"float64array":"object"},"kindOf")});var axi=hr((nMo,ixi)=>{"use strict";var kXa=Mbi(),rxi=Gbi(),txi=exi();ixi.exports=e(function(t,r){!Ptr(t)&&!Array.isArray(t)&&(t={});for(var a=rxi(t),o=arguments.length,c=0;++c<o;){var f=arguments[c];(Ptr(f)||Array.isArray(f))&&nxi(a,f)}return a},"mergeDeep");function nxi(i,t){for(var r in t)if(!(!PXa(r)||!IXa(t,r))){var a=t[r],o=i[r];Ptr(o)&&Ptr(a)?i[r]=nxi(o,a):Array.isArray(o)?i[r]=kXa([],o,a):i[r]=rxi(a)}return i}e(nxi,"merge");function IXa(i,t){return Object.prototype.hasOwnProperty.call(i,t)}e(IXa,"hasOwn");function Ptr(i){return txi(i)==="object"||txi(i)==="function"}e(Ptr,"isObject");function PXa(i){return i!=="__proto__"&&i!=="constructor"&&i!=="prototype"}e(PXa,"isValidKey")});var oxi=hr(f_n=>{"use strict";Object.defineProperty(f_n,"__esModule",{value:!0});function FXa(i){return i&&typeof i=="object"&&"default"in i?i.default:i}e(FXa,"_interopDefault");var sxi=FXa(yWe()),NXa=axi(),d_n=class d_n{constructor(t){this._debugBase=sxi(`puppeteer-extra-plugin:base:${this.name}`),this._childClassMembers=[],this._opts=NXa(this.defaults,t||{}),this._debugBase("Initialized.")}get name(){throw new Error('Plugin must override "name"')}get defaults(){return{}}get requirements(){return new Set([])}get dependencies(){return new Set([])}get data(){return[]}get opts(){return this._opts}get debug(){return sxi(`puppeteer-extra-plugin:${this.name}`)}async beforeLaunch(t){}async afterLaunch(t,r={options:{}}){}async beforeConnect(t){}async afterConnect(t,r={}){}async onBrowser(t,r){}async onTargetCreated(t){}async onPageCreated(t){}async onTargetChanged(t){}async onTargetDestroyed(t){}async onDisconnected(){}async onClose(){}async onPluginRegistered(){}getDataFromPlugins(t){return[]}_getMissingDependencies(t){let r=new Set(t.map(o=>o.name));return new Set(Array.from(this.dependencies.values()).filter(o=>!r.has(o)))}async _bindBrowserEvents(t,r={}){(this._hasChildClassMember("onTargetCreated")||this._hasChildClassMember("onPageCreated"))&&t.on("targetcreated",this._onTargetCreated.bind(this)),this._hasChildClassMember("onTargetChanged")&&this.onTargetChanged&&t.on("targetchanged",this.onTargetChanged.bind(this)),this._hasChildClassMember("onTargetDestroyed")&&this.onTargetDestroyed&&t.on("targetdestroyed",this.onTargetDestroyed.bind(this)),this._hasChildClassMember("onDisconnected")&&this.onDisconnected&&t.on("disconnected",this.onDisconnected.bind(this)),r.context==="launch"&&this._hasChildClassMember("onClose")&&this.onClose&&(process.on("exit",this.onClose.bind(this)),t.on("disconnected",this.onClose.bind(this)),r.options.handleSIGINT!==!1&&process.on("SIGINT",this.onClose.bind(this)),r.options.handleSIGTERM!==!1&&process.on("SIGTERM",this.onClose.bind(this)),r.options.handleSIGHUP!==!1&&process.on("SIGHUP",this.onClose.bind(this))),r.context==="launch"&&this.afterLaunch&&await this.afterLaunch(t,r),r.context==="connect"&&this.afterConnect&&await this.afterConnect(t,r),this.onBrowser&&await this.onBrowser(t,r)}async _onTargetCreated(t){if(this.onTargetCreated&&await this.onTargetCreated(t),t.type()==="page")try{let r=await t.page();if(!r)return;let a="isClosed"in r&&!r.isClosed();this.onPageCreated&&a&&await this.onPageCreated(r)}catch(r){console.error(r)}}_register(t){this._registerChildClassMembers(t),this.onPluginRegistered&&this.onPluginRegistered()}_registerChildClassMembers(t){this._childClassMembers=Object.getOwnPropertyNames(t)}_hasChildClassMember(t){return!!this._childClassMembers.includes(t)}get _isPuppeteerExtraPlugin(){return!0}};e(d_n,"PuppeteerExtraPlugin");var p_n=d_n;f_n.PuppeteerExtraPlugin=p_n});var WXa={};rQ(WXa,{AutoRecoveryMode:()=>cft,RunMode:()=>uft,checksumHotRequire:()=>hxi,getChecksumConfig:()=>LVt,getLogin:()=>Dbe,init:()=>zXa});module.exports=iz(WXa);var vme=(C=>(C.Locator="locator",C.GetByRole="getByRole",C.GetByText="getByText",C.GetByLabel="getByLabel",C.GetByPlaceholder="getByPlaceholder",C.GetByAltText="getByAltText",C.GetByTitle="getByTitle",C.GetByTestId="getByTestId",C.FrameLocator="frameLocator",C))(vme||{});var u$e=(f=>(f.First="first",f.Last="last",f.Nth="nth",f.Filter="filter",f.Or="or",f.And="and",f))(u$e||{});var G3r=(a=>(a.Alert="alert",a.Confirm="confirm",a.Prompt="prompt",a))(G3r||{});var tA=e(i=>new Promise(t=>setTimeout(t,i)),"awaitSleep"),lD=e(async(i,t=1e3,r)=>{if(t===null)return i;let a="guard-timed-out",o=e(async()=>(await tA(t+1e3),a),"guard"),c=await Promise.race([i,o()]);if(typeof c=="string"&&c===a)throw typeof r=="function"?new Error(r()):new Error(r??"guardReturnTimedOut");return c},"guardReturn");function zBt(i=5,t="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"){let r="";for(let a=i;a>0;--a)r+=t[Math.floor(Math.random()*t.length)];return r}e(zBt,"randomString");function oft(i){return!!i&&!["navigation","keystroke","wait","get_more_items","custom_code","native_accept","native_dismiss","login"].includes(i)}e(oft,"isActionOnElement");function _En(i){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}[i]}e(_En,"getActionEventCode");var aj=e((i,t="page")=>t+"."+JBt(i,t),"injectBaseToLocatorString"),JBt=e((i,t="page")=>i.replace(".and(locator(",`.and(${t}.locator(`).replace(".or(locator(",`.or(${t}.locator(`),"injectBaseToLogicalLocatorString");var hEn="checksum",uft=(a=>(a.Normal="normal",a.Heal="heal",a.Refactor="refactor",a))(uft||{});var cft=(a=>(a.Regular="regular",a.Fast="fast",a.ExtraFast="extra_fast",a))(cft||{});var y7=rf(require("path")),dve=require("fs");async function bEn(i,t){let a=e(()=>{let v=LUi(i,t);if((0,dve.existsSync)(v)||v.endsWith(".data")&&(v=v.replace(".data",".esra"),(0,dve.existsSync)(v)))return v;throw new Error(`Could not find metadata file for test ${t}`)},"getFilePath")(),{ungzip:o}=K3r(),c=await o((0,dve.readFileSync)(a)),f=JSON.parse(c),_=Object.keys(f);return _.length>0&&!f[_[0]].esraMetadata?_.reduce((v,C)=>({...v,[C]:{esraMetadata:f[C]}}),{}):f}e(bEn,"getMetadataForTestId");function WBt(i){return y7.join(y7.dirname(i),"..")}e(WBt,"getTestBaseDir");function LUi(i,t){return y7.join(MUi(i),`${t}.checksum.data`)}e(LUi,"getMetadataFilePath");function MUi(i){return y7.join(a9e(i),"esra")}e(MUi,"getMetadataFolderPath");function lft(i){return y7.join(a9e(i),"bin")}e(lft,"getBinFolderPath");function Y3r(i){return y7.join(a9e(i),"har")}e(Y3r,"getHARFolderPath");function xEn(i,t){return y7.join(Y3r(i),`${t}.har.zip`)}e(xEn,"getHARFilePath");function AEn(i,t=1){return y7.join(a9e(Fne()),"rrweb",`${i}.${t}.rrweb.jsonl`)}e(AEn,"getRRwebFilePath");function EEn(i,t){return y7.join(a9e(i),"trace",`${t}.playwright-trace.zip`)}e(EEn,"getTraceFilePath");function a9e(i){return y7.join(i,"test-data")}e(a9e,"getTestDataPath");var vEn=e(async i=>{try{await lD(i,5e3)}catch{}},"guardAwait");var X3r=e(i=>{console.log("\x1B[31m%s\x1B[0m",i)},"printError"),Z3r=e((i,t,r)=>{if(!t)return i;if(!r||!r.length)return i.locator(t);let a=i.frameLocator(r[0]);for(let o of r.slice(1))a=a.frameLocator(o);return a.locator(t)},"makeLocator");async function CEn(i,t,r){let o=e(async()=>i.evaluate(async({selector:f,parentFramesSelectors:_})=>await window.checksum.testGenerator.getSelectionDataForSelector(f,_),{selector:t,parentFramesSelectors:r}),"getSelectionDataForSelector"),c=await o();if(c||(await vEn(i.waitForLoadState("networkidle")),c=await o(),c)||(await vEn(Z3r(i,t,r).waitFor({state:"visible"})),c=await o(),c)||(await tA(5e3),c=await o(),c))return c}e(CEn,"selectionDataForSelector");function Fne(){return process.env.CHECKSUM_ROOT_FOLDER?process.env.CHECKSUM_ROOT_FOLDER:y7.join(__dirname,"..","..","..","checksum")}e(Fne,"checksumFolder");function wEn(i,t){try{let r=i.filter(a=>a.endsWith("checksum.config.ts")&&y7.dirname(a).endsWith("checksum"));return r.find(a=>a==="checksum/checksum.config.ts")?"checksum":r.length===1?y7.dirname(r[0]):t?y7.dirname(jUi(r,t)):y7.dirname(r.sort((a,o)=>o.length-a.length)[0])}catch{return"checksum"}}e(wEn,"findChecksumRootFolder");function jUi(i,t){let r=e(_=>_.split(y7.sep).filter(v=>v.length>0),"splitPath"),a=e((_,v)=>{let C=r(_),w=r(v),T=Math.min(C.length,w.length),k=Math.abs(C.length-w.length);for(let R=0;R<T;R++)if(C[R]!==w[R]){k+=2*(T-R);break}return k},"directoryDistance"),o=null,c=1/0,f=y7.dirname(t);return i.forEach(_=>{let v=a(f,_);v<c&&(c=v,o=_)}),o}e(jUi,"getClosestPath");function SEn(i,t=2){let r=[],a=[],o=e(f=>{if(r.includes(f))return;r.push(f);let _=(0,dve.readdirSync)(f);for(let v of _){let C=y7.join(f,v),w=(0,dve.statSync)(C);if(!(w.isSymbolicLink()||C.includes("node_modules"))){if(w.isDirectory())o(C);else if(v==="checksum.config.ts"){a.push(C);return}}}},"searchDirectory"),c=y7.dirname(i);try{for(let f=0;f<t&&(o(c),c=y7.join(c,".."),f===t-1&&f<9&&!a.length&&(t+=2),!(y7.resolve(c)==="/"||!c||y7.resolve(c)===y7.resolve(process.cwd())));f++);return a}catch{return a}}e(SEn,"findChecksumRootQualifyingPathsForTestFile");var TEn=rf(DEn());var tTr=class tTr{constructor(t){this.toJSON=e(()=>this.data,"toJSON");this.data=t}getSimilar(t){let r=null,a=-1/0;for(let o of Object.keys(this.data)){let c=(0,TEn.levenshtein)([...t],[...o]);c>a&&(a=c,r=o)}return r?this.data[r]:null}};e(tTr,"SimilarityRecord");var eTr=tTr,V6e=class V6e extends eTr{constructor(t){super(V6e.preprocessRectangles(t))}getRectangleByTextAndSizeRanking(t,r){r=!r||!Number(r)?0:Number(r);let a=this.getSimilar(t);if(!a||a.length===0)return null;let o=Math.min(Math.max(r,0),a.length-1);return a[o]}};e(V6e,"RectangleIndex"),V6e.preprocessRectangles=e(t=>{let r=[...new Map([...t].map(o=>[JSON.stringify(o.vertices),o])).values()],a={};return r.forEach(o=>{a[o.text]||(a[o.text]=[]),a[o.text].push(o),a[o.text].sort((c,f)=>{let _=V6e.calculateArea(c.vertices),v=V6e.calculateArea(f.vertices);return _-v})}),a},"preprocessRectangles"),V6e.calculateArea=e(t=>{let r=Math.abs(t[1].x-t[0].x),a=Math.abs(t[3].y-t[0].y);return r*a},"calculateArea");var KBt=V6e;var REn=require("fs"),LEn=require("path");function EI(i){return i._guid}e(EI,"getPageOrFrameGuid");async function kEn(i,t,r){let a=i,o=a._mainFrame;try{a._mainFrame=t,await r(a)}finally{a._mainFrame=o}}e(kEn,"executeOnPageWithFrame");var IEn={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html","rrweb-recording":"application/json"},nTr={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",hard_assertion:void 0,soft_assertion:void 0,recovery:void 0,scroll:void 0},PEn=Object.fromEntries(Object.entries(nTr).map(i=>i.reverse())),iTr={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"},FEn=Object.fromEntries(Object.entries(iTr).map(i=>i.reverse()));var NEn={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]},l$e={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 UUi=e(i=>i.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\${/g,"\\${"),"escapeStringForTemplateLiteral"),OEn="variableStore",z6e=OEn+".",BEn=e((i,{alwaysIncludeInitializationLine:t=!1,onlyValueExpression:r=!1}={})=>[t?`const ${OEn} = {};`:"",...i.map(({name:o,value:c,valueExpression:f})=>{let _=typeof c=="string"&&!r?`\`${UUi(c)}\``:f;return`${z6e}${o} = ${_};`})].join(`
1809
1809
  `),"variablesToString");var qUi=!0,_TestGenerationPageInteractor=class _TestGenerationPageInteractor{constructor(i,t,r,a,o,c,f){this.evaluateWithChecksum=i;this.getFrame=t;this.getTimeMachine=r;this.logger=a;this.options=o;this.pageInteractorAPI=c;this.loginFunction=f;this.activeDialog=null;this.newPagesIds=[];this.listeners={dialog:null,filechooser:null,page:null};this.listenToContextPage=e(()=>{this.getPage().context().on("page",i=>{this.newPagesIds.push(i._guid)})},"listenToContextPage");this.listenToFileChooser=e(()=>{this.listeners.filechooser=async i=>{this.logger.log("File chooser event detected"),this.fileChooser=i},this.getPage().on("filechooser",this.listeners.filechooser)},"listenToFileChooser");this.waitForDialog=e((i=!0,t=1e4)=>new Promise(r=>{let o=0,c=e(()=>{if(this.activeDialog){let f=this.activeDialog;i&&(this.activeDialog=null),r(f)}else o>=t?r(null):(o+=1e3,setTimeout(c,1e3))},"checkDialog");c()}),"waitForDialog");this.performFileUploadAction=e(async(i,t)=>{if(!await i.evaluate(a=>a.tagName==="INPUT"&&a.getAttribute("type")==="file"))throw new Error("File upload action performed on non-file input element");let r=t.files.map(a=>(0,LEn.join)(this.options.testAssetsDir,a)).filter(a=>(0,REn.existsSync)(a)?!0:(this.logger.log(`Upload file not found: ${a}. Filtering out.`),!1));if(!r.length)throw new Error("No files to upload");await this.actionGuardReturn(i.setInputFiles(r),"Set input files timeout")},"performFileUploadAction");this.getSelectionDataForAction=e(async(i,t)=>i.checksumid?this.getSelectionDataForChecksumId(i.checksumid,t):i.position?await this.evaluateWithChecksum(async([r,a])=>window.checksum.testGenerator.getSelectorByPosition(r,a),[i.position.x,i.position.y]):i.selector?{selector:i.selector,locator:`locator("${i.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 i=>{this.activeDialog=i},this.getPage().on("dialog",this.listeners.dialog)}removeListener(i){try{switch(i){case"dialog":this.listeners.dialog&&(this.getPage().removeListener(i,this.listeners.dialog),this.listeners.dialog=null);break;case"filechooser":this.getPage().off(i,this.listeners.filechooser),this.listeners.filechooser=null;break;case"page":this.getPage().context().off(i,this.listeners.page),this.listeners.page=null;break}}catch(t){this.logger.logError(`Error removing listener: ${i}`,t)}}getOpenedFileChooser(){if(this.fileChooser){let i=this.fileChooser;return this.fileChooser=void 0,i}return null}async handleFileChooserEvent(i=[]){let t=this.getOpenedFileChooser();if(!t)return{};let r="fc_"+Math.random().toString(36).slice(2,4);return await this.evaluateWithChecksum(async([a,o])=>{window.checksum.testGenerator.addForceIncludeElement(o,a)},[r,t.element()]),{interruptionEvent:"fileUploadOpenedEvent",payload:{checksumid:r,customFiles:i}}}async addMoreItemsToDom(i,t){let r=i.querySelector(`[checksum-get-more-items='${t}']`);if(!r)throw new Error("Get more items root not found");let{items:a,hasMoreItems:o}=await this.getMoreItemsForTemplate(t);r.innerHTML=r.innerHTML+a,o||r.removeAttribute("checksum-get-more-items")}async getPageInfo(i){let t=EI(i);return{id:t,url:i.url(),title:await i.title(),new:this.newPagesIds.includes(t),active:t===EI(this.getPage())}}async getTabsInfo(){var a;let i=this.getPage(),t=await Promise.all(i.context().pages().map(o=>this.getPageInfo(o))),r=(a=this.getTimeMachine())==null?void 0:a.getPage();return r&&r!==i&&(t=t.filter(o=>o.id!==EI(r))),this.newPagesIds=[],t}async getSelectionDataFromSelectorGenerator(i,t,r={}){if(r={useCompoundSelector:!0,useCSSExtraction:!0,useVariables:!0,useArbitrarySelector:!0,...r},!i||!oft(_En(t.action.type))||!t.action.checksumid)return{};let a=await i.generateSelectionForAction(t,r);return a?{locator:`locator("${a.selector}")`,...a}:{}}async translateActionResponseToAgentPotentialAction(i,t=void 0,{pageId:r}={}){let a=structuredClone(i.actionHiddenOverride??i.action),{selector:o,selectorWithVars:c,locator:f,locatorWithVars:_,clickOffset:v,selectOptionValue:C,compoundSelector:w,alternateLocators:T,parentFramesSelectors:k}={...await this.getSelectionDataForAction(a,i.actionHiddenOverride),...await this.getSelectionDataFromSelectorGenerator(t,i)},R=await this.getESRAForSelector(o,k);if(!R&&o&&this.logger.logError("Error getting ESRA metadata"),(R==null?void 0:R.tag)==="select")switch(this.getActionEventCode(a.type)){case"input":a.type="selectoption";break;case"click":C&&(a.type="selectoption",a.value=C);break}let B={eventCode:this.getActionEventCode(a.type),selector:o,selectorWithVars:c,parentFramesSelectors:k,locator:f,locatorWithVars:_,clickOffset:v,pageId:r,compoundSelector:w,alternateLocators:T,fillValue:a.value,fillValueName:a.valueName?`${z6e}${a.valueName}`:"",variables:i.variables,getMoreItemsId:a.getMoreItemsId,esraMetadata:R,thought:i.thought,userRole:a.userRole,canvas:a.canvas,id:a.id,codeContext:{frameTargetName:null}};switch(B.eventCode){case"drag_and_drop":{let{selector:U,selectorWithVars:W,locator:X,locatorWithVars:ne,parentFramesSelectors:ce}={...await this.getSelectionDataForAction({type:i.action.type,checksumid:i.action.dropTargetChecksumid}),...await this.getSelectionDataFromSelectorGenerator(t,{...i,action:{type:i.action.type,checksumid:i.action.dropTargetChecksumid}},{useCompoundSelector:!1})};B.dropTarget={selector:U,locator:X,parentFramesSelectors:ce,esraMetadata:await this.getESRAForSelector(U,ce)}}break;case"upload_files":B.files=this.mapFileMIMETypeToFilename(a.files);break;case"switch_tab":{let U=this.getPage();B.switchToTab={id:a.tabId,index:U.context().pages().findIndex(W=>EI(W)===a.tabId)};break}case"keystroke":B.fillValue=a.value}return B}async reauthenticate(i,t){let r=this.getPage();this.loginFunction&&(await Promise.all([r.context().clearCookies(),r.evaluate(()=>localStorage.clear())]),await this.loginFunction(t??r,{role:i}))}mapFileMIMETypeToFilename(i){return i.map(t=>{if(t.fileName)return t.fileName;switch(t.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(i,{useLocator:t=!1,handleActionFailed:r,monitorFlashingHTML:a=!0,timeout:o,allowForceClick:c=!0}={}){try{if(i.executed){this.logger.log("[performAction] Action marked as executed, skipping...");return}let f=t?!!i.locator:!!i.selector;if(oft(i.eventCode)&&!f)throw new Error("No selector provided for action. Try changing app rules preMapReducedHTMLSelectors to true");a&&(this.logger.log("starting flashing elements detection"),await this.evaluateWithChecksum(async()=>window.checksum.testGenerator.startFlashingElementsDetection())),this.logger.log(`Performing action: ${i.eventCode}. Selector: ${i.selector}, Position: ${i.clickOffset}, Parent frame: ${i.parentFramesSelectors}`);let _=e(()=>t?this.makeLocatorFromLocator(i.locator):this.makeLocator(i.selector,i.parentFramesSelectors),"getLocator"),v=e(async(C,w,T={})=>this.actionGuardReturn(C,w,{timeout:o,...T}),"performWithActionGuard");switch(i.eventCode){case"click":try{await v(_().click({position:i.clickOffset,timeout:o??this.options.actionTimeout}),"Click timeout")}catch(C){if(!c)throw C;this.logger.log("Error performing click, will attempt a force click",C.message),i.force=!0,await v(_().click({position:i.clickOffset,force:!0,timeout:o??this.options.actionTimeout}),"Force Click timeout")}break;case"double_click":try{await v(_().dblclick({position:i.clickOffset,timeout:o??this.options.actionTimeout}),"DoubleClick timeout")}catch(C){if(!c)throw C;this.logger.log("Error performing double click, will attempt a force double click",C),i.force=!0,await v(_().dblclick({position:i.clickOffset,timeout:o??this.options.actionTimeout,force:!0}),"Force DoubleClick timeout")}break;case"check":await v(_().check({timeout:o??this.options.actionTimeout}),"Check timeout");break;case"uncheck":await v(_().uncheck({timeout:o??this.options.actionTimeout}),"UnCheck timeout");break;case"drag_and_drop":await v(_().dragTo(t?this.makeLocatorFromLocator(i.dropTarget.locator):this.makeLocator(i.dropTarget.selector,i.dropTarget.parentFramesSelectors),{timeout:o??this.options.actionTimeout}),"DragAndDrop timeout");break;case"input":await v(_().fill(this.getActionFillValue(i),{timeout:o??this.options.actionTimeout}),"Fill timeout");break;case"click_and_type":await lD(_().click({position:i.clickOffset,timeout:o??this.options.actionTimeout}),1e4,"Click before type timeout"),await lD(_().pressSequentially(this.getActionFillValue(i),{timeout:o??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"clear_and_type":await lD(_().clear({timeout:o??this.options.actionTimeout}),1e4,"Clear before type timeout"),await lD(_().pressSequentially(this.getActionFillValue(i),{timeout:o??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"selectoption":await v(_().selectOption(this.getActionFillValue(i),{timeout:o??this.options.actionTimeout}),"SelectOption timeout");break;case"hover":await v(_().hover({timeout:o??this.options.actionTimeout}),"Hover timeout");break;case"navigation":await v(this.getFrame().goto(i.fillValue,{timeout:o??this.options.navigationTimeout}),"Navigation timeout",{isNavigation:!0});break;case"keystroke":{let C=this.getPage();await v(C.keyboard.press(i.fillValue),"Keystroke timeout");break}case"upload_files":await this.performFileUploadAction(_(),i);break;case"wait":await tA(this.options.waitActionDelay??1e3);break;case"custom_code":await kEn(this.getPage(),this.getFrame(),async C=>{let w=`async (page) => {${i.fillValue}}`;await(0,eval)(w)(C)});break;case"logout_and_login":await this.reauthenticate(i.userRole);break;case"canvas_click":await this.canvasClick(_(),i.canvas);break}}catch(f){throw this.logger.log(`Error performing action: ${i.eventCode}, will attempt a correction template`,f),await(r==null?void 0:r()),f}this.logger.log(`Successfully performed action ${i.eventCode} with description "${i.thought}"`)}async getTextDetection(i){return new KBt(await this.pageInteractorAPI.getTextDetection(i))}async canvasClick(i,t){try{if(!await i.evaluate(c=>c.tagName.toLowerCase()==="canvas"))throw new Error("Click attempted on a non-canvas element");let o=(await this.getTextDetection(await i.screenshot())).getRectangleByTextAndSizeRanking(t.canvasText,t.rectSizeIndex);if(!o)throw new Error(`Canvas click target not found for ${t.canvasText}`);this.logger.log(`Canvas click target: ${o}`),await this.actionGuardReturn(i.click({position:o.center}),"Canvas click could not be performed")}catch(r){throw this.logger.logError("Canvas click:",r.message),new Error("Canvas click action failed")}}getActionFillValue(i,t=!0){let r=i.fillValue;if(!r){let a=i.selector.match(/(?<=value.*)('|").*/);a&&(r=a[0].slice(1,-1))}return typeof r!="string"&&(r="X"),t&&(i.fillValue=r),r}actionGuardReturn(i,t,{isNavigation:r=!1,timeout:a}={}){return lD(i,a??(r?this.options.navigationTimeout:this.options.actionTimeout),t)}makeLocator(i,t=[]){return Z3r(this.getFrame(),i,t)}makeLocatorFromLocator(locator){return eval("this.getFrame()."+locator)}async takeScreenshot(i){let t=await this.getPage().screenshot({type:"jpeg",scale:"css",timeout:5e3,...i});return{base64:`data:image/jpeg;base64,${t.toString("base64")}`,buffer:t}}getCurrentURL(){return this.getFrame().url()}async getSelectionDataForChecksumId(i,t){if(t!=null&&t.selector)return{...t,selector:t.selector,locator:t.locator,clickOffset:t.position};if(!i)return this.logger.log(`[getSelectionDataForChecksumId] checksumid not provided (${i})`),{...t,selector:i,locator:`locator("${i}")`};let r=await this.evaluateWithChecksum(async a=>{let{selector:o,locator:c,clickOffset:f,parentFramesSelectors:_,invalid:v,rrwebId:C}=await window.checksum.testGenerator.getSelectorForChecksumId(a),w=await window.checksum.testGenerator.getElementForChecksumId(a),T=w instanceof HTMLOptionElement&&w.value?w.value:void 0;return{selector:o,locator:c,clickOffset:f,selectOptionValue:T,parentFramesSelectors:_,invalid:v,rrwebId:C}},i);if(qUi&&r.invalid&&r.rrwebId){this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${i}. Trying to use time machine...`);try{let a=await this.getSelectionDataForRRwebIdAtReduceHTMLTime(r.rrwebId);r={...r,...a}}catch{this.logger.log(`[getSelectionDataForChecksumId] error using time machine to get selector for checksumid: ${i}`)}this.logger.log(`[getSelectionDataForChecksumId] got selector: ${r.selector} for checksumid: ${i} from time machine`)}return r!=null&&r.selector||this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${i}. If checksumid is correct, try to change app rules preMapReducedHTMLSelectors to true`),r}async getSelectionDataForRRwebIdAtReduceHTMLTime(i){if(!this.rrwebEventAtLastReducedHTML)return;let t=this.getTimeMachine();if(t)return t.executeTask(r=>r.evaluate(async({rrwebId:a})=>await window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(a,{ignoredIframesSelectors:[".replayer-wrapper > iframe"],fromTimeMachine:!0}),{rrwebId:i}),this.rrwebEventAtLastReducedHTML.timestamp,{name:"getSelectionDataForRRwebIdAtReduceHTMLTime"})}async getESRAForSelector(i,t){let r=await this.evaluateWithChecksum(async({selector:a,parentFramesSelectors:o})=>window.checksum.testGenerator.getSelectionDataForSelector(a,o),{selector:i,parentFramesSelectors:t});return r==null?void 0:r.esraMetadata}async getMoreItemsForTemplate(i){return await this.evaluateWithChecksum(async t=>window.checksum.testGenerator.getMoreItemsForTemplate(t,{}),i)??{items:"",hasMoreItems:!1}}scrollElementIntoViewByChecksumId(i){return this.evaluateWithChecksum(async t=>window.checksum.testGenerator.scrollElementIntoViewByChecksumId(t),i)}scrollElementIntoViewByRrwebId(i){return this.evaluateWithChecksum(async t=>window.checksum.testGenerator.scrollElementIntoViewByRrwebId(t),i)}generateLocatorByRrwebId(i){return this.evaluateWithChecksum(async t=>window.checksum.testGenerator.generateLocatorByRrwebId(t),i)}getViewportHTML(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.extractViewportHTML())}scrollScrollableElement(i,t,r){return this.evaluateWithChecksum(async({rrwebId:a,direction:o,length:c})=>window.checksum.testGenerator.scrollScrollableElement(a,o,c),{rrwebId:i,direction:t,length:r})}async getCurrentReducedHTML({retriesLeft:i=3,retryWaitMS:t=2e3,initialChecksumId:r="0",extractESRAForInterpretationRequiredElements:a=!1,stopFlashingElementsDetection:o=!1,assignChecksumIdsToAllElements:c}={}){let f=new Date;this.logger.log("[getCurrentReducedHTML] Fetching reduced HTML...");try{let{reducedHTML:_,currentChecksumId:v,flashingHTML:C,elementsForNodeInterpretation:w,lastRRwebEvent:T,scrollableElements:k}=await this.evaluateWithChecksum(async B=>window.checksum.testGenerator.reduceHTML({},B),{initialChecksumId:r,extractESRAForInterpretationRequiredElements:a,stopFlashingElementsDetection:o,assignChecksumIdsToAllElements:c}),R=new Date;return this.logger.log(`[getCurrentReducedHTML] Fetched reduced HTML in ${R.getTime()-f.getTime()}ms`),this.rrwebEventAtLastReducedHTML=T,{reducedHTML:_,flashingHTML:C,elementsForNodeInterpretation:w,currentChecksumId:v,scrollableElements:k}}catch(_){if(i>0)return this.logger.logError(`[getCurrentReducedHTML] Error: ${_.message}`),this.logger.logError(`Failed do obtain reduced HTML, trying again in ${t/1e3} seconds, ${i-1} to go.`),await tA(t),this.getCurrentReducedHTML({retriesLeft:i-1,retryWaitMS:t});throw _}}getActionEventCode(i){return nTr[i]}};e(_TestGenerationPageInteractor,"TestGenerationPageInteractor");var J6e=_TestGenerationPageInteractor;nQ();var KUi=!1,lTr=class lTr{constructor(){this.frames={};this.pages=[];this.channels={};this.events=[];this.pendingMessages={};this.uuid=db();this.log=e(t=>{KUi&&console.log(`[FramesMsgBroker] ${this.uuid}:
1810
- ${t}`)},"log");this.exposeFunctionsPromises=new WeakMap}getFrameName(t){return Object.keys(this.frames).find(a=>this.frames[a]===t)}async safeExposeFunction(t,r,a){try{await t.exposeFunction(r,a),this.log(`[safeExposeFunction] ${r} exposed successfully`)}catch(o){this.log(`[safeExposeFunction] ${r}: ${o.message}`)}}async register(t,r,a){if(this.log(`[register] ${t} ${EI(r)}`),this.frames[t]){let f=r.page(),_=this.exposeFunctionsPromises.get(f);_&&await _;return}this.frames[t]=r;let o=r.page();if(this.pages.includes(o)){let f=this.exposeFunctionsPromises.get(o);f&&await f;return}this.pages.push(o);let c=(async()=>{await this.safeExposeFunction(o,"checksumSendMessage",async(f,_,v=!1)=>{var w;this.log(`[checksumSendMessage] from ${t} to ${f}`);let C=this.frames[f];if(!C){if(v){(w=this.pendingMessages)[f]??(w[f]=[]),this.pendingMessages[f].push(_);return}throw new Error(`Frame ${f} not found`)}try{await C.evaluate(({message:T})=>{window.postMessage(T,"*")},{message:_})}catch{}}),await this.safeExposeFunction(o,"checksumSendBroadcastMessage",async(f,_)=>{let v=this.channels[f]??[];if(this.log(`[checksumSendBroadcastMessage] on channel ${f} from ${t}`),this.log(`subscribers: ${v.map(C=>`(${C.originFrameGuid}) ${C.frame.url()}`).join(", ")}`),a){let C=require("fs"),w=require("path");this.events.push(..._),this.events.length%10===0&&C.writeFileSync(w.join(process.cwd(),"rrweb-player","events.json"),JSON.stringify(this.events))}v.forEach(async C=>{if(C.originFrameGuid&&C.originFrameGuid!==EI(r))return;let w=this.getFrameName(C.frame);this.log(`handling message from ${t} to subscriber ${w}`);try{C.handler?await C.handler(_):await r.evaluate(({message:T})=>{window.postMessage(T,"*")},{message:_})}catch{}})}),await this.safeExposeFunction(o,"checksumBringPageToFront",async f=>{let _=this.frames[f];_&&await _.page().bringToFront()})})();this.exposeFunctionsPromises.set(o,c),await c,this.pendingMessages[t]&&(this.pendingMessages[t].forEach(async f=>{try{await r.evaluate(({message:_})=>{window.postMessage(_,"*")},{message:f})}catch{}}),delete this.pendingMessages[t])}subscribeToChannel(t,r,{originFrame:a,handler:o}={}){var c;this.log(`[subscribeToChannel] ${t} frame ${EI(r)}`),(c=this.channels)[t]??(c[t]=[]),this.channels[t].push({frame:r,originFrameGuid:a?EI(a):void 0,handler:o})}unsubscribeFromChannel(t,r){var a;(a=this.channels)[t]??(a[t]=[]),this.channels[t]=this.channels[t].filter(o=>o.frame!==r)}};e(lTr,"FramesMsgBroker");var p$e=lTr;var Cz=require("fs"),oVn=rf(ekr()),bZ=rf(require("path"));var tkr=class tkr extends Error{constructor(t){super("Fallback Exception Wrapper"),this.fallbackResult=t}};e(tkr,"ExpectError");var Hft=tkr;var rkr=class rkr{constructor(){this.config={}}};e(rkr,"PageInteractorAPI");var JRt=rkr;var nkr=class nkr{constructor(t){this.options=t;this.health=e(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(t=>(console.log(t),null)),"health");this.getCanvasDetection=e(async t=>{try{let r=t.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:r}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(r){return console.log(r),null}},"getCanvasDetection")}};e(nkr,"ChecksumClient");var M$e=nkr;var ikr=class ikr extends JRt{constructor(r){super();this.config=r;this.getTextDetection=e(async r=>{let a=await this.api.getCanvasDetection(r);if(!a)throw new Error("No data returned from canvas detection");return a},"getTextDetection");this.config=r,this.api=new M$e({apiKey:r.apiKey,apiURL:r.apiURL})}};e(ikr,"RuntimePageInteractorAPI");var j$e=ikr;var kme=rf(require("path")),pkr=require("fs");var akr=require("path"),WRt=require("fs");function Izi(i,t,r=10){let a=i;for(let o=0;o<r;o++){let c=(0,akr.join)(a,"package.json");if((0,WRt.existsSync)(c))try{if(JSON.parse((0,WRt.readFileSync)(c,"utf8")).name===t)return a}catch{}a=(0,akr.join)(a,"..")}}e(Izi,"findRepositoryRoot");function c4n(i,t=10){return Izi(i,"checksum-customer-engineering-workspace",t)}e(c4n,"findCustomerEngineeringRoot");var fkr=rf(m4n());var jw=e((i,t)=>{if(i==null||i==="")return(t==null?void 0:t.default)??!1;let r=i.toLowerCase().trim();return r==="true"?!0:r==="false"?!1:(t==null?void 0:t.default)??!1},"parseBoolean");var Wzi=__dirname,_4n=kme.join(__dirname,".."),y4n=(0,pkr.existsSync)(_4n)?_4n:Wzi;(0,fkr.config)({path:kme.resolve(y4n,".env")});var ckr=jw(process.env.CHECKSUM_RUNTIME_DEV_MODE);function Hzi(){let i=__dirname;for(;!(0,pkr.existsSync)(kme.join(i,"package.json"));)i=kme.join(i,"..");return i}e(Hzi,"findRoot");var U$e=Hzi(),Gzi=c4n(U$e,10);(0,fkr.config)({path:[y4n,Gzi].filter(Boolean).map(i=>kme.resolve(i,".env")),override:!1});var GRt=jw(process.env.CHECKSUM_VTG_E2E_TEST_MODE),h4n=kme.join(U$e,"vtg-build","index.html"),lkr=GRt?!0:jw(process.env.CHECKSUM_RUNTIME_REPO_MODE),g4n=jw(process.env.CHECKSUM_VTG_SEPARATE_PROCESS),Kzi=lkr?kme.join(U$e,"package","pw-report-template.html"):kme.join(U$e,"pw-report-template.html"),Yzi=jw(process.env.CHECKSUM_DEBUG_ANALYTICS),Xzi=jw(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),V0={isDevMode:ckr,isRepoMode:lkr,CI:!!process.env.CI,checksumRootFolderBypass:GRt?"packages/runtime/test/e2e/checksum":lkr&&process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE?process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE:process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS,logLevel:process.env.CHECKSUM_RUNTIME_LOG_LEVEL??"warnings",checksumScript:{source:process.env.CHECKSUM_RUNTIME_SCRIPT_SOURCE??(ckr?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:U$e+"/checksumlib.js"},runtimeRoot:U$e,playwrightReporter:{htmlReportTemplatePath:Kzi},bypassProxyForLocalhost:jw(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),promptKillActivePlaywrightProcesses:jw(process.env.CHECKSUM_RUNTIME_PROMPT_KILL_ACTIVE_PLAYWRIGHT_PROCESSES,{default:!0}),useCLIDebug:jw(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),useRemoteDebugging:{enabled:jw(process.env.CHECKSUM_RUNTIME_USE_REMOTE_DEBUGGING),port:parseInt(process.env.CHECKSUM_AGENT_RUNTIME_REMOTE_DEBUGGING_PORT??"9500")},testRun:{timeMachine:{active:!0,headless:!jw(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:jw(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0})},monitoring:{defaultProvider:process.env.CHECKSUM_RUNTIME_MONITORING_DEFAULT_PROVIDER??"newrelic",debugAnalytics:Yzi,logToConsole:Xzi,newrelic:{appName:process.env.CHECKSUM_RUNTIME_MONITORING_NEWRELIC_APP_NAME??"checksum-runtime",licenseKey:"b4f3f644f40df19fe3d385c75428a450FFFFNRAL",logging:jw(process.env.NEW_RELIC_LOG_ENABLED,{default:!1})},segment:{writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},autoRecovery:{verboseConsoleLog:jw(process.env.CHECKSUM_RUNTIME_AUTO_RECOVERY_CONSOLE_LOG,{default:!1}),sessionTimeout:18e4},disableAutoRecovery:jw(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:jw(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),request:{userEmail:process.env.CHECKSUM_RUNTIME_REQUEST_USER_EMAIL,reason:process.env.CHECKSUM_RUNTIME_REQUEST_REASON},platform:{name:process.env.CHECKSUM_RUNTIME_PLATFORM_NAME,jobURL:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_URL,jobName:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_NAME},runType:process.env.CHECKSUM_RUNTIME_RUN_TYPE},vtg:{isSeparateProcess:g4n,isE2ETestMode:GRt,writeLogFile:jw(process.env.CHECKSUM_VTG_WRITE_LOG_FILE,{default:!0}),appSource:process.env.CHECKSUM_VTG_APP_SOURCE??(ckr?"served-app":"served-build-file"),localUrl:`file://${h4n}`,localBuildPath:h4n,appURL:process.env.CHECKSUM_VTG_APP_URL,writeRrwebEventsToFile:jw(process.env.CHECKSUM_VTG_RECORD_EVENTS_TO_FILE),useFakeStory:jw(process.env.CHECKSUM_VTG_USE_FAKE_STORY)||GRt,logAPIServer:{interval:jw(process.env.CHECKSUM_VTG_LOG_API_SERVER_INTERVAL),httpTransactions:jw(process.env.CHECKSUM_VTG_LOG_API_SERVER_HTTP_TRANSACTIONS,{default:!0})},customerEngRepoInternalUtilsRelativePath:process.env.CHECKSUM_VTG_CUSTOMER_ENG_REPO_INTERNAL_UTILS_RELATIVE_PATH??"tools/internal-utils.ts",fakeStory:{goal:process.env.CHECKSUM_VTG_FAKE_STORY_GOAL??"Send email via outreach list",instructions:process.env.CHECKSUM_VTG_FAKE_STORY_INSTRUCTIONS??"Make sure to select a user from the list first"},fakeTestGeneration:{internalTestId:process.env.CHECKSUM_VTG_FAKE_STORY_INTERNAL_TEST_ID??`tempID${Date.now().toString().slice(-5)}`,generationBatchId:process.env.CHECKSUM_VTG_FAKE_GENERATION_BATCH_ID??`tempID${Date.now().toString().slice(-5)}`},remoteDebugging:g4n?!0:jw(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING),appRemoteDebuggingPort:parseInt(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING_PORT??"9230"),vtgRemoteDebuggingPort:parseInt(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING_PORT??"9231"),taskTimeMachine:{showTaskTimeMachine:jw(process.env.CHECKSUM_VTG_SHOW_TASK_TIME_MACHINE),taskTimeout:parseInt(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_TIMEOUT??"240000"),debugPort:parseInt(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_DEBUG_PORT??"9232"),logPerformance:jw(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_LOG_PERFORMANCE,{default:!0})},aiAssertions:{disabled:jw(process.env.CHECKSUM_VTG_AI_ASSERTIONS_DISABLED),allowRefactoring:jw(process.env.CHECKSUM_VTG_ALLOW_AI_ASSERTIONS_REFACTORING),allowFiltering:jw(process.env.CHECKSUM_VTG_ALLOW_AI_ASSERTIONS_FILTERING),logPerformance:jw(process.env.CHECKSUM_VTG_AI_ASSERTIONS_LOG_PERFORMANCE,{default:!1})},aiLocators:{disabled:jw(process.env.CHECKSUM_VTG_AI_LOCATORS_DISABLED),useFakeAILocators:jw(process.env.CHECKSUM_VTG_USE_FAKE_AI_LOCATORS)}},benchmark:jw(process.env.BENCHMARK_MODE),buildTime:process.env.CHECKSUM_RUNTIME_BUILD_TIME??"unknown",llm:{models:{openai:{key:process.env.CHECKSUM_RUNTIME_OPENAI_API_KEY},anthropic:{key:process.env.CHECKSUM_RUNTIME_ANTHROPIC_API_KEY},gemini:{model:process.env.CHECKSUM_RUNTIME_GEMINI_MODEL},groq:{apiKey:process.env.CHECKSUM_RUNTIME_GROQ_API_KEY}}},gcp:{credentialsFile:process.env.CHECKSUM_RUNTIME_GCP_CREDENTIALS_FILE}};var dkr=rf(require("fs"));function Zzi(i){return i.replace(/(\s*)try\s*\{([\s\S]*?)\}[\s\n]*catch\s*\(.*?\)\s*\{[\s\S]*?\}[\s\n]*\1testInfo\.status\s*=\s*["']failed["'];?/g,(t,r,a)=>a.trimEnd())}e(Zzi,"removeTryCatchAndTestInfo");var mkr=class mkr{static toString(t,r){let a=v4n(t,r);return Object.entries(a).map(([o,c])=>`
1810
+ ${t}`)},"log");this.exposeFunctionsPromises=new WeakMap}getFrameName(t){return Object.keys(this.frames).find(a=>this.frames[a]===t)}async safeExposeFunction(t,r,a){try{await t.exposeFunction(r,a),this.log(`[safeExposeFunction] ${r} exposed successfully`)}catch(o){this.log(`[safeExposeFunction] ${r}: ${o.message}`)}}async register(t,r,a){if(this.log(`[register] ${t} ${EI(r)}`),this.frames[t]){let f=r.page(),_=this.exposeFunctionsPromises.get(f);_&&await _;return}this.frames[t]=r;let o=r.page();if(this.pages.includes(o)){let f=this.exposeFunctionsPromises.get(o);f&&await f;return}this.pages.push(o);let c=(async()=>{await this.safeExposeFunction(o,"checksumSendMessage",async(f,_,v=!1)=>{var w;this.log(`[checksumSendMessage] from ${t} to ${f}`);let C=this.frames[f];if(!C){if(v){(w=this.pendingMessages)[f]??(w[f]=[]),this.pendingMessages[f].push(_);return}throw new Error(`Frame ${f} not found`)}try{await C.evaluate(({message:T})=>{window.postMessage(T,"*")},{message:_})}catch{}}),await this.safeExposeFunction(o,"checksumSendBroadcastMessage",async(f,_)=>{let v=this.channels[f]??[];if(this.log(`[checksumSendBroadcastMessage] on channel ${f} from ${t}`),this.log(`subscribers: ${v.map(C=>`(${C.originFrameGuid}) ${C.frame.url()}`).join(", ")}`),a){let C=require("fs"),w=require("path");this.events.push(..._),this.events.length%10===0&&C.writeFileSync(w.join(process.cwd(),"rrweb-player","events.json"),JSON.stringify(this.events))}v.forEach(async C=>{if(C.originFrameGuid&&C.originFrameGuid!==EI(r))return;let w=this.getFrameName(C.frame);this.log(`handling message from ${t} to subscriber ${w}`);try{C.handler?await C.handler(_):await r.evaluate(({message:T})=>{window.postMessage(T,"*")},{message:_})}catch{}})}),await this.safeExposeFunction(o,"checksumBringPageToFront",async f=>{let _=this.frames[f];_&&await _.page().bringToFront()})})();this.exposeFunctionsPromises.set(o,c),await c,this.pendingMessages[t]&&(this.pendingMessages[t].forEach(async f=>{try{await r.evaluate(({message:_})=>{window.postMessage(_,"*")},{message:f})}catch{}}),delete this.pendingMessages[t])}subscribeToChannel(t,r,{originFrame:a,handler:o}={}){var c;this.log(`[subscribeToChannel] ${t} frame ${EI(r)}`),(c=this.channels)[t]??(c[t]=[]),this.channels[t].push({frame:r,originFrameGuid:a?EI(a):void 0,handler:o})}unsubscribeFromChannel(t,r){var a;(a=this.channels)[t]??(a[t]=[]),this.channels[t]=this.channels[t].filter(o=>o.frame!==r)}unregister(t){this.log(`[unregister] ${t}`);let r=this.frames[t];if(!r)return;delete this.frames[t],delete this.pendingMessages[t];let a=r.page();if(!Object.values(this.frames).some(c=>c.page()===a)){let c=this.pages.indexOf(a);c!==-1&&this.pages.splice(c,1)}for(let c of Object.keys(this.channels))this.channels[c]=this.channels[c].filter(f=>f.frame!==r),this.channels[c].length===0&&delete this.channels[c]}cleanup(){this.log("[cleanup] Cleaning up all resources"),this.frames={},this.pages=[],this.channels={},this.events=[],this.pendingMessages={}}};e(lTr,"FramesMsgBroker");var p$e=lTr;var Cz=require("fs"),oVn=rf(ekr()),bZ=rf(require("path"));var tkr=class tkr extends Error{constructor(t){super("Fallback Exception Wrapper"),this.fallbackResult=t}};e(tkr,"ExpectError");var Hft=tkr;var rkr=class rkr{constructor(){this.config={}}};e(rkr,"PageInteractorAPI");var JRt=rkr;var nkr=class nkr{constructor(t){this.options=t;this.health=e(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(t=>(console.log(t),null)),"health");this.getCanvasDetection=e(async t=>{try{let r=t.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:r}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(r){return console.log(r),null}},"getCanvasDetection")}};e(nkr,"ChecksumClient");var M$e=nkr;var ikr=class ikr extends JRt{constructor(r){super();this.config=r;this.getTextDetection=e(async r=>{let a=await this.api.getCanvasDetection(r);if(!a)throw new Error("No data returned from canvas detection");return a},"getTextDetection");this.config=r,this.api=new M$e({apiKey:r.apiKey,apiURL:r.apiURL})}};e(ikr,"RuntimePageInteractorAPI");var j$e=ikr;var kme=rf(require("path")),pkr=require("fs");var akr=require("path"),WRt=require("fs");function Izi(i,t,r=10){let a=i;for(let o=0;o<r;o++){let c=(0,akr.join)(a,"package.json");if((0,WRt.existsSync)(c))try{if(JSON.parse((0,WRt.readFileSync)(c,"utf8")).name===t)return a}catch{}a=(0,akr.join)(a,"..")}}e(Izi,"findRepositoryRoot");function c4n(i,t=10){return Izi(i,"checksum-customer-engineering-workspace",t)}e(c4n,"findCustomerEngineeringRoot");var fkr=rf(m4n());var jw=e((i,t)=>{if(i==null||i==="")return(t==null?void 0:t.default)??!1;let r=i.toLowerCase().trim();return r==="true"?!0:r==="false"?!1:(t==null?void 0:t.default)??!1},"parseBoolean");var Wzi=__dirname,_4n=kme.join(__dirname,".."),y4n=(0,pkr.existsSync)(_4n)?_4n:Wzi;(0,fkr.config)({path:kme.resolve(y4n,".env")});var ckr=jw(process.env.CHECKSUM_RUNTIME_DEV_MODE);function Hzi(){let i=__dirname;for(;!(0,pkr.existsSync)(kme.join(i,"package.json"));)i=kme.join(i,"..");return i}e(Hzi,"findRoot");var U$e=Hzi(),Gzi=c4n(U$e,10);(0,fkr.config)({path:[y4n,Gzi].filter(Boolean).map(i=>kme.resolve(i,".env")),override:!1});var GRt=jw(process.env.CHECKSUM_VTG_E2E_TEST_MODE),h4n=kme.join(U$e,"vtg-build","index.html"),lkr=GRt?!0:jw(process.env.CHECKSUM_RUNTIME_REPO_MODE),g4n=jw(process.env.CHECKSUM_VTG_SEPARATE_PROCESS),Kzi=lkr?kme.join(U$e,"package","pw-report-template.html"):kme.join(U$e,"pw-report-template.html"),Yzi=jw(process.env.CHECKSUM_DEBUG_ANALYTICS),Xzi=jw(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),V0={isDevMode:ckr,isRepoMode:lkr,CI:!!process.env.CI,checksumRootFolderBypass:GRt?"packages/runtime/test/e2e/checksum":lkr&&process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE?process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE:process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS,logLevel:process.env.CHECKSUM_RUNTIME_LOG_LEVEL??"warnings",checksumScript:{source:process.env.CHECKSUM_RUNTIME_SCRIPT_SOURCE??(ckr?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:U$e+"/checksumlib.js"},runtimeRoot:U$e,playwrightReporter:{htmlReportTemplatePath:Kzi},bypassProxyForLocalhost:jw(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),promptKillActivePlaywrightProcesses:jw(process.env.CHECKSUM_RUNTIME_PROMPT_KILL_ACTIVE_PLAYWRIGHT_PROCESSES,{default:!0}),useCLIDebug:jw(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),useRemoteDebugging:{enabled:jw(process.env.CHECKSUM_RUNTIME_USE_REMOTE_DEBUGGING),port:parseInt(process.env.CHECKSUM_AGENT_RUNTIME_REMOTE_DEBUGGING_PORT??"9500")},testRun:{timeMachine:{active:!0,headless:!jw(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:jw(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0})},monitoring:{defaultProvider:process.env.CHECKSUM_RUNTIME_MONITORING_DEFAULT_PROVIDER??"newrelic",debugAnalytics:Yzi,logToConsole:Xzi,newrelic:{appName:process.env.CHECKSUM_RUNTIME_MONITORING_NEWRELIC_APP_NAME??"checksum-runtime",licenseKey:"b4f3f644f40df19fe3d385c75428a450FFFFNRAL",logging:jw(process.env.NEW_RELIC_LOG_ENABLED,{default:!1})},segment:{writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},autoRecovery:{verboseConsoleLog:jw(process.env.CHECKSUM_RUNTIME_AUTO_RECOVERY_CONSOLE_LOG,{default:!1}),sessionTimeout:18e4},disableAutoRecovery:jw(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:jw(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),request:{userEmail:process.env.CHECKSUM_RUNTIME_REQUEST_USER_EMAIL,reason:process.env.CHECKSUM_RUNTIME_REQUEST_REASON},platform:{name:process.env.CHECKSUM_RUNTIME_PLATFORM_NAME,jobURL:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_URL,jobName:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_NAME},runType:process.env.CHECKSUM_RUNTIME_RUN_TYPE},vtg:{isSeparateProcess:g4n,isE2ETestMode:GRt,writeLogFile:jw(process.env.CHECKSUM_VTG_WRITE_LOG_FILE,{default:!0}),appSource:process.env.CHECKSUM_VTG_APP_SOURCE??(ckr?"served-app":"served-build-file"),localUrl:`file://${h4n}`,localBuildPath:h4n,appURL:process.env.CHECKSUM_VTG_APP_URL,writeRrwebEventsToFile:jw(process.env.CHECKSUM_VTG_RECORD_EVENTS_TO_FILE),useFakeStory:jw(process.env.CHECKSUM_VTG_USE_FAKE_STORY)||GRt,logAPIServer:{interval:jw(process.env.CHECKSUM_VTG_LOG_API_SERVER_INTERVAL),httpTransactions:jw(process.env.CHECKSUM_VTG_LOG_API_SERVER_HTTP_TRANSACTIONS,{default:!0})},customerEngRepoInternalUtilsRelativePath:process.env.CHECKSUM_VTG_CUSTOMER_ENG_REPO_INTERNAL_UTILS_RELATIVE_PATH??"tools/internal-utils.ts",fakeStory:{goal:process.env.CHECKSUM_VTG_FAKE_STORY_GOAL??"Send email via outreach list",instructions:process.env.CHECKSUM_VTG_FAKE_STORY_INSTRUCTIONS??"Make sure to select a user from the list first"},fakeTestGeneration:{internalTestId:process.env.CHECKSUM_VTG_FAKE_STORY_INTERNAL_TEST_ID??`tempID${Date.now().toString().slice(-5)}`,generationBatchId:process.env.CHECKSUM_VTG_FAKE_GENERATION_BATCH_ID??`tempID${Date.now().toString().slice(-5)}`},remoteDebugging:g4n?!0:jw(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING),appRemoteDebuggingPort:parseInt(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING_PORT??"9230"),vtgRemoteDebuggingPort:parseInt(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING_PORT??"9231"),taskTimeMachine:{showTaskTimeMachine:jw(process.env.CHECKSUM_VTG_SHOW_TASK_TIME_MACHINE),taskTimeout:parseInt(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_TIMEOUT??"240000"),debugPort:parseInt(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_DEBUG_PORT??"9232"),logPerformance:jw(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_LOG_PERFORMANCE,{default:!0})},aiAssertions:{disabled:jw(process.env.CHECKSUM_VTG_AI_ASSERTIONS_DISABLED),allowRefactoring:jw(process.env.CHECKSUM_VTG_ALLOW_AI_ASSERTIONS_REFACTORING),allowFiltering:jw(process.env.CHECKSUM_VTG_ALLOW_AI_ASSERTIONS_FILTERING),logPerformance:jw(process.env.CHECKSUM_VTG_AI_ASSERTIONS_LOG_PERFORMANCE,{default:!1})},aiLocators:{disabled:jw(process.env.CHECKSUM_VTG_AI_LOCATORS_DISABLED),useFakeAILocators:jw(process.env.CHECKSUM_VTG_USE_FAKE_AI_LOCATORS)}},benchmark:jw(process.env.BENCHMARK_MODE),buildTime:process.env.CHECKSUM_RUNTIME_BUILD_TIME??"unknown",llm:{models:{openai:{key:process.env.CHECKSUM_RUNTIME_OPENAI_API_KEY},anthropic:{key:process.env.CHECKSUM_RUNTIME_ANTHROPIC_API_KEY},gemini:{model:process.env.CHECKSUM_RUNTIME_GEMINI_MODEL},groq:{apiKey:process.env.CHECKSUM_RUNTIME_GROQ_API_KEY}}},gcp:{credentialsFile:process.env.CHECKSUM_RUNTIME_GCP_CREDENTIALS_FILE}};var dkr=rf(require("fs"));function Zzi(i){return i.replace(/(\s*)try\s*\{([\s\S]*?)\}[\s\n]*catch\s*\(.*?\)\s*\{[\s\S]*?\}[\s\n]*\1testInfo\.status\s*=\s*["']failed["'];?/g,(t,r,a)=>a.trimEnd())}e(Zzi,"removeTryCatchAndTestInfo");var mkr=class mkr{static toString(t,r){let a=v4n(t,r);return Object.entries(a).map(([o,c])=>`
1811
1811
  ${c}`).join("")}static toRecord(t,r){return v4n(t,r)}};e(mkr,"ErrorFormatter");var q$e=mkr;function v4n(i,t){let a=(i.stack||"No stack trace available").split(`
1812
1812
  `),o={};for(let f of a){let _=f.match(/\(([^)]+):(\d+):(\d+)\)/)||f.match(/at ((?:[a-zA-Z]:\\|\/)[^:]+):(\d+):(\d+)/);if(_){let v=_[1];if(!v.includes(t)||v.includes("node_modules")||v.includes("<anonymous>")||v.includes("internal")||v.includes("loader")||v.startsWith("eval"))continue;try{if(!o[v]&&dkr.default.existsSync(v)){let C=dkr.default.readFileSync(v,"utf-8");o[v]=Zzi(C)}}catch(C){o[v]=`Error reading file: ${C.message}`}}}let c={};for(let[f,_]of Object.entries(o)){let v=`
1813
1813
  --- File: ${f} ---
@@ -1822,7 +1822,7 @@ ${this.executedSteps.map(c=>{switch(c.type){case"action":return c.thought;case"a
1822
1822
  Executing locator ${this.getCurrentLocatorInChain().type} with ${typeof t=="string"?`selector ${t}`:"locator"}`);try{t&&typeof t=="object"&&"has"in t&&this.popLocatorChain()}catch{}let a=this.getLocator(t,r);return new Proxy(a,{get:e((o,c)=>this.getLocatorMethod(a,o,c),"get")})}catch(a){Dv("Failed to locate",a)}}getLocatorMethod(t,r,a){return a==="then"?this.handleThen(t,r,a):a==="catch"?this.handleCatch(t,r):a==="finally"?this.handleFinally(t,r):a==="constructor"?e(function(...c){return this.popLocatorChain(),r.constructor(...c)},"Locator"):a in r&&typeof r[a]!="function"||a===Symbol.toPrimitive||a in Object||a==="evaluate"?(this.popLocatorChain(),r[a]):a==="compoundSelection"?function(...o){let c=this.compoundSelection(...o);return c.setBase(t),c}.bind(this):[...Object.values(vme),...Object.values(u$e)].includes(a)?["or","and"].includes(a)?(Dv("'Or' and 'And' locator are not supported, will execute normally"),this.popLocatorChain(),r[a]):(this.getCurrentLocatorChain().push({type:a,base:t}),e(function(...c){return this.executeLocator(c[0],c[1])},"Locator").bind(this)):a==="page"?()=>(this.popLocatorChain(),this.proxy.page()):e(async function(...c){let f=await this.executeLocatorAction(t,a,c);return this.popLocatorChain(),f},"Locator").bind(this)}async executeLocatorAction(t,r,a){if(a&&Array.from(a).some(_=>(_==null?void 0:_.bypassChecksum)===!0))return t[r](...a);let o=t._selector;Dv("Executing",r,o);let c=r==="_expect"?"assertion":"action";c==="action"&&this.lastLocatorActionType==="action"&&(Dv("Adding minimal wait between consecutive actions..."),await new Promise(_=>setTimeout(_,100))),this.lastLocatorActionType=c,Dv("Running initial locator...");let f;try{return this.navigationPromise&&await this.navigationPromise,await this.wrapInternalSteps(async()=>{try{Dv("[executeLocatorAction] waitForFunction"),await this.frame.waitForFunction(()=>!!window.checksum,{timeout:5e3})}catch{Dv("[executeLocatorAction] checksum libs not loaded")}}),await Eqt.createAction({locator:t,method:r,args:a,timeout:this.getLocatorActionTimeout(c,r,a)},{api:this.checksumClient,pageInteractor:this.getPageInteractor()}).guardedExecute();f=new Error("Locator action error")}catch(_){Dv("Failed initial execution. Exception:",_.message),f=_}if(c==="action"&&this.onExecutionError)return this.onExecutionError({error:f,locator:t,method:r,args:a},this.frame);throw f}setExpectConfiguration(t=void 0){this.expectConfiguration=t}getLocatorActionTimeout(t,r,a=[]){var o;if(this.isReplMode)return null;try{if(t==="assertion"){let _=this.getAssertionTimeout(a);return Dv(`Assertion timeout set to ${_}`),_}let c=["fill","dragTo"].includes(r)?1:0,f=(o=a[c])==null?void 0:o.timeout;return isNaN(f)?3e4:f}catch{return 3e4}}getAssertionTimeout(t=[]){var o,c,f,_,v;let r=(o=t[1])==null?void 0:o.timeout;if(r!==void 0)return r;if(((c=this.expectConfiguration)==null?void 0:c.timeout)!==void 0)return(f=this.expectConfiguration)==null?void 0:f.timeout;let a=(v=(_=this.testInfo._projectInternal)==null?void 0:_.expect)==null?void 0:v.timeout;return a!==void 0?a:3e4}handleThen(t,r,a){return(o,c)=>Promise.resolve(t).then(f=>{let _=o?o(f):f;return _ instanceof Promise?_:this.getLocatorMethod(_,r,a)},f=>{if(c)return c(f);throw f})}handleCatch(t,r){return a=>Promise.resolve(t).catch(o=>{if(a)return a(o);throw o})}handleFinally(t,r){return a=>Promise.resolve(t).finally(a)}};e(Sqt,"ChecksumFrame");var wqt=Sqt;var Dqt=class Dqt{constructor(t,r,a,o,c){this.page=t;this.config=r;this.getPageInteractor=a;this.injectedScriptManager=o;this._frames={};this.isVTG=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG;var f,_;this.setPageProxy(),this.injectedScriptManager||(this.injectedScriptManager=new $ze({scriptFile:V0.checksumScript.path,scriptSource:V0.checksumScript.source,scriptURL:V0.checksumScript.url,isScriptFileAbsolute:!0,silenceLogs:!V0.isDevMode,scriptInitWait:(f=r==null?void 0:r.options)==null?void 0:f.browserScriptInitWait,scriptAddWait:(_=r==null?void 0:r.options)==null?void 0:_.browserScriptAddWait})),this.registerPageEvents(),this.page.frames().forEach(v=>this.registerFrame(v)),c&&(this.variableStore=c.variableStore)}static makePage(t,r,a){let o=Tqt();return new Dqt(t,o,()=>r,a).proxy}async registerFrame(t){var o;let r=this.getFrameGuid(t);if(t===this.page.mainFrame()&&(this.mainFrameGuid=r),this._frames[r])return;let a=wqt.init(t,this.proxy,this.injectedScriptManager,this.getPageInteractor,(o=this.onExecutionError)==null?void 0:o.bind(this),this.config);this._frames[r]=a}async onExecutionError(t){throw t.error}getFrameGuid(t){return t._guid}registerPageEvents(){this.page.on("frameattached",async t=>{this.registerFrame(t)})}setPageProxy(){this.proxy=new Proxy(this,{get:e(function(r,a){return r.getPageMethod(a)},"get")})}getPageMethod(t){if(typeof this[t]=="function")return t==="constructor"?this[t]:this[t].bind(this);switch(t){case"pageInteractor":return this.getPageInteractor();case"variableStore":return this.variableStore}return Object.values(vme).includes(t)?e(function(a,o){try{return this.mainFrame()[t](a,o)}catch(c){throw c}},"Page").bind(this):this.page[t]}mainFrame(){var t;return(t=this._frames)==null?void 0:t[this.mainFrameGuid]}frames(){return Object.values(this._frames)}getFrame(t){if(!this.page.frames().find(a=>this.getFrameGuid(a)===t))throw new Error(`Frame with guid ${t} not found`);return this._frames[t]}async waitForDialog(t){try{return this.getPageInteractor().waitForDialog(!0,t)}catch(r){throw new Error(`Failed to handle native dialog: ${r}`)}}async reauthenticate(t){try{await this.getPageInteractor().reauthenticate(t,this.proxy)}catch(r){throw new Error(`Failed to reauthenticate: ${r}`)}}resolveAssetsFolder(t){return t.map(r=>lBn.join(lft(Fne()),r))}compoundSelection(...t){try{return new Qze(this.mainFrame()).init(...t)}catch{throw new Error("Failed generating compound selector")}}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.page)}setExpectConfiguration(t=void 0){this.expectConfiguration=t,Object.values(this._frames).forEach(r=>r.setExpectConfiguration(t))}};e(Dqt,"ChecksumPage");var Vze=Dqt;tQr();kI();var hbe=class hbe{constructor(){this.toolsMap={}}get addTool(){return this._addTool||(this._addTool=this.buildAddToolFacade()),this._addTool}getToolNames(){return Object.keys(this.toolRecord.names)}get tools(){return this.toolsMap}buildAddToolFacade(){let t={},r=this.toolRecord.tools;for(let a of Object.keys(r))t[a]=o=>this._addSingleTool(a,o);return t}static describeTool(t,r){if(t instanceof Nh.ZodObject){let a={},o=t.shape;for(let c of Object.keys(o)){let f=o[c],_=r==null?void 0:r[c];typeof _=="string"?a[c]=f.describe(_):_&&typeof _=="object"?a[c]=hbe.describeTool(f,_):a[c]=f}return Nh.object(a).strict()}if(t instanceof Nh.ZodArray){let a=t.element;return r&&typeof r=="object"&&r.element?Nh.array(hbe.describeTool(a,r.element)):t}return t instanceof Nh.ZodOptional?hbe.describeTool(t.unwrap(),r).optional():t instanceof Nh.ZodNullable?hbe.describeTool(t.unwrap(),r).nullable():typeof r=="string"?t.describe(r):t}_addSingleTool(t,r){let a=r.name??String(t),c=this.toolRecord.tools[t]._create({...r,name:a,params:r.params,handler:r.handler}),f=this.toolRecord.tools[t],_=hbe.describeTool(f,r.params),C=Kqr(e(async w=>{let T=_.parse(w);return r.handler(T)},"validatedHandler"),{name:c.name,description:c.description,schema:_});return this.toolsMap[t]=C,C}_buildOne(t,r){return this._addSingleTool(t,{...r,name:String(t)})}static buildTool(t,r,a){let o=String(r),f=t.tools[r]._create({name:o,description:"",handler:a,params:{}}),_=t.tools[r],v=hbe.describeTool(_,{});return Kqr(e(async T=>{let k=v.parse(T);return a(k)},"validatedHandler"),{name:f.name,description:f.description,schema:v})}};e(hbe,"AbstractToolContainer");var u7e=hbe;kI();var W$t=class W$t{constructor(t,r){this.version=t;let a={};for(let c in r)a[c]=c;this.names=a;let o={};for(let c in r){let f=r[c];Object.defineProperty(f,"name",{value:c,configurable:!1,enumerable:!0,writable:!1}),f._create=(_=>v=>{let C=v.name??_;return{...v,name:C}})(c),o[c]=f}this.tools=o}static create(t,r){return new W$t(t,r)}};e(W$t,"ToolProtocol");var J$t=W$t;var xj=J$t.create("v1",{readFile:Nh.object({path:Nh.string()}),getState:Nh.object({thought:Nh.string()}),invokeCode:Nh.object({code:Nh.string().refine(i=>{let t=i.trim();return t.includes("page.getByChecksumId(")||t.includes("page.getByChecksumId(")||t.startsWith("const ")||t.startsWith("let ")||t.startsWith("var ")||t.includes("=")||t.includes("variableStore.")},{message:"Code should use page.getByChecksumId() for element targeting, or be explicit variable assignments/function calls"}),thought:Nh.string()}),wait:Nh.object({time:Nh.number().optional()}),scroll:Nh.object({checksumId:Nh.string(),thought:Nh.string()}),final_result:Nh.object({result:Nh.enum(["pass","fail"]),thought:Nh.string(),visualAnalysis:Nh.string().optional()}),getElementScreenshot:Nh.object({checksumId:Nh.string(),thought:Nh.string()}),analyze:Nh.object({previousImmediateSteps:Nh.string(),currentFailingStep:Nh.string(),nextImmediateSteps:Nh.string(),testStepToStopAt:Nh.string()}),think:Nh.object({thought:Nh.string()})});var gQr=rf(Vqn(),1);var jce=Object.create(null);jce.open="0";jce.close="1";jce.ping="2";jce.pong="3";jce.message="4";jce.upgrade="5";jce.noop="6";var Ymt=Object.create(null);Object.keys(jce).forEach(i=>{Ymt[jce[i]]=i});var Xmt={type:"error",data:"parser error"};var Zmt=e(({type:i,data:t},r,a)=>t instanceof ArrayBuffer||ArrayBuffer.isView(t)?a(r?t:"b"+zqn(t,!0).toString("base64")):a(jce[i]+(t||"")),"encodePacket"),zqn=e((i,t)=>Buffer.isBuffer(i)||i instanceof Uint8Array&&!t?i:i instanceof ArrayBuffer?Buffer.from(i):Buffer.from(i.buffer,i.byteOffset,i.byteLength),"toBuffer"),nQr;function Jqn(i,t){if(i.data instanceof ArrayBuffer||ArrayBuffer.isView(i.data))return t(zqn(i.data,!1));Zmt(i,!0,r=>{nQr||(nQr=new TextEncoder),t(nQr.encode(r))})}e(Jqn,"encodePacketToBinary");var e_t=e((i,t)=>{if(typeof i!="string")return{type:"message",data:Wqn(i,t)};let r=i.charAt(0);if(r==="b"){let a=Buffer.from(i.substring(1),"base64");return{type:"message",data:Wqn(a,t)}}return Ymt[r]?i.length>1?{type:Ymt[r],data:i.substring(1)}:{type:Ymt[r]}:Xmt},"decodePacket"),Wqn=e((i,t)=>{switch(t){case"arraybuffer":return i instanceof ArrayBuffer?i:Buffer.isBuffer(i)?i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength):i.buffer;case"nodebuffer":default:return Buffer.isBuffer(i)?i:Buffer.from(i)}},"mapBinary");var Hqn="",Gqn=e((i,t)=>{let r=i.length,a=new Array(r),o=0;i.forEach((c,f)=>{Zmt(c,!1,_=>{a[f]=_,++o===r&&t(a.join(Hqn))})})},"encodePayload"),Kqn=e((i,t)=>{let r=i.split(Hqn),a=[];for(let o=0;o<r.length;o++){let c=e_t(r[o],t);if(a.push(c),c.type==="error")break}return a},"decodePayload");function Yqn(){return new TransformStream({transform(i,t){Jqn(i,r=>{let a=r.length,o;if(a<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,a);else if(a<65536){o=new Uint8Array(3);let c=new DataView(o.buffer);c.setUint8(0,126),c.setUint16(1,a)}else{o=new Uint8Array(9);let c=new DataView(o.buffer);c.setUint8(0,127),c.setBigUint64(1,BigInt(a))}i.data&&typeof i.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(r)})}})}e(Yqn,"createPacketEncoderStream");var iQr;function H$t(i){return i.reduce((t,r)=>t+r.length,0)}e(H$t,"totalLength");function G$t(i,t){if(i[0].length===t)return i.shift();let r=new Uint8Array(t),a=0;for(let o=0;o<t;o++)r[o]=i[0][a++],a===i[0].length&&(i.shift(),a=0);return i.length&&a<i[0].length&&(i[0]=i[0].slice(a)),r}e(G$t,"concatChunks");function Xqn(i,t){iQr||(iQr=new TextDecoder);let r=[],a=0,o=-1,c=!1;return new TransformStream({transform(f,_){for(r.push(f);;){if(a===0){if(H$t(r)<1)break;let v=G$t(r,1);c=(v[0]&128)===128,o=v[0]&127,o<126?a=3:o===126?a=1:a=2}else if(a===1){if(H$t(r)<2)break;let v=G$t(r,2);o=new DataView(v.buffer,v.byteOffset,v.length).getUint16(0),a=3}else if(a===2){if(H$t(r)<8)break;let v=G$t(r,8),C=new DataView(v.buffer,v.byteOffset,v.length),w=C.getUint32(0);if(w>Math.pow(2,21)-1){_.enqueue(Xmt);break}o=w*Math.pow(2,32)+C.getUint32(4),a=3}else{if(H$t(r)<o)break;let v=G$t(r,o);_.enqueue(e_t(c?v:iQr.decode(v),t)),a=0}if(o===0||o>i){_.enqueue(Xmt);break}}}})}e(Xqn,"createPacketDecoderStream");var aQr=4;var mQn=rf(eFe(),1);var gbe=process.nextTick,Ez=global,eQn="nodebuffer";function tQn(){return new sQr}e(tQn,"createCookieJar");function gva(i){let t=i.split("; "),r=t[0].indexOf("=");if(r===-1)return;let a=t[0].substring(0,r).trim();if(!a.length)return;let o=t[0].substring(r+1).trim();o.charCodeAt(0)===34&&(o=o.slice(1,-1));let c={name:a,value:o};for(let f=1;f<t.length;f++){let _=t[f].split("=");if(_.length!==2)continue;let v=_[0].trim(),C=_[1].trim();switch(v){case"Expires":c.expires=new Date(C);break;case"Max-Age":let w=new Date;w.setUTCSeconds(w.getUTCSeconds()+parseInt(C,10)),c.expires=w;break;default:}}return c}e(gva,"parse");var oQr=class oQr{constructor(){this._cookies=new Map}parseCookies(t){t&&t.forEach(r=>{let a=gva(r);a&&this._cookies.set(a.name,a)})}get cookies(){let t=Date.now();return this._cookies.forEach((r,a)=>{var o;((o=r.expires)===null||o===void 0?void 0:o.getTime())<t&&this._cookies.delete(a)}),this._cookies.entries()}addCookies(t){let r=[];for(let[a,o]of this.cookies)r.push(`${a}=${o.value}`);r.length&&(t.setDisableHeaderCheck(!0),t.setRequestHeader("cookie",r.join("; ")))}appendCookies(t){for(let[r,a]of this.cookies)t.append("cookie",`${r}=${a.value}`)}};e(oQr,"CookieJar");var sQr=oQr;function K$t(i,...t){return t.reduce((r,a)=>(i.hasOwnProperty(a)&&(r[a]=i[a]),r),{})}e(K$t,"pick");var yva=Ez.setTimeout,vva=Ez.clearTimeout;function ybe(i,t){t.useNativeTimers?(i.setTimeoutFn=yva.bind(Ez),i.clearTimeoutFn=vva.bind(Ez)):(i.setTimeoutFn=Ez.setTimeout.bind(Ez),i.clearTimeoutFn=Ez.clearTimeout.bind(Ez))}e(ybe,"installTimerFunctions");var bva=1.33;function rQn(i){return typeof i=="string"?xva(i):Math.ceil((i.byteLength||i.size)*bva)}e(rQn,"byteLength");function xva(i){let t=0,r=0;for(let a=0,o=i.length;a<o;a++)t=i.charCodeAt(a),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(a++,r+=4);return r}e(xva,"utf8Length");function Y$t(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}e(Y$t,"randomString");function nQn(i){let t="";for(let r in i)i.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(i[r]));return t}e(nQn,"encode");function iQn(i){let t={},r=i.split("&");for(let a=0,o=r.length;a<o;a++){let c=r[a].split("=");t[decodeURIComponent(c[0])]=decodeURIComponent(c[1])}return t}e(iQn,"decode");var _Qn=rf(nFe(),1);var Vva=(0,_Qn.default)("engine.io-client:transport"),fQr=class fQr extends Error{constructor(t,r,a){super(t),this.description=r,this.context=a,this.type="TransportError"}};e(fQr,"TransportError");var rVt=fQr,dQr=class dQr extends mQn.Emitter{constructor(t){super(),this.writable=!1,ybe(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,r,a){return super.emitReserved("error",new rVt(t,r,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"?this.write(t):Vva("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){let r=e_t(t,this.socket.binaryType);this.onPacket(r)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,r={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(r)}_hostname(){let t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){let r=nQn(t);return r.length?"?"+r:""}};e(dQr,"Transport");var vbe=dQr;var hQn=rf(nFe(),1);var Uce=(0,hQn.default)("engine.io-client:polling"),mQr=class mQr extends vbe{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";let r=e(()=>{Uce("paused"),this.readyState="paused",t()},"pause");if(this._polling||!this.writable){let a=0;this._polling&&(Uce("we are currently polling - waiting to pause"),a++,this.once("pollComplete",function(){Uce("pre-pause polling complete"),--a||r()})),this.writable||(Uce("we are currently writing - waiting to pause"),a++,this.once("drain",function(){Uce("pre-pause writing complete"),--a||r()}))}else r()}_poll(){Uce("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){Uce("polling got data %s",t);let r=e(a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)},"callback");Kqn(t,this.socket.binaryType).forEach(r),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Uce('ignoring poll - transport state "%s"',this.readyState))}doClose(){let t=e(()=>{Uce("writing close packet"),this.write([{type:"close"}])},"close");this.readyState==="open"?(Uce("transport open - closing"),t()):(Uce("transport not open - deferring close"),this.once("open",t))}write(t){this.writable=!1,Gqn(t,r=>{this.doWrite(r,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let t=this.opts.secure?"https":"http",r=this.query||{};return this.opts.timestampRequests!==!1&&(r[this.opts.timestampParam]=Y$t()),!this.supportsBinary&&!r.sid&&(r.b64=1),this.createUri(t,r)}};e(mQr,"Polling");var r_t=mQr;var bQn=rf(eFe(),1);var gQn=!1;try{gQn=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var yQn=gQn;var xQn=rf(nFe(),1);var _Qr=(0,xQn.default)("engine.io-client:polling");function zva(){}e(zva,"empty");var hQr=class hQr extends r_t{constructor(t){if(super(t),typeof location<"u"){let r=location.protocol==="https:",a=location.port;a||(a=r?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||a!==t.port}}doWrite(t,r){let a=this.request({method:"POST",data:t});a.on("success",r),a.on("error",(o,c)=>{this.onError("xhr post error",o,c)})}doPoll(){_Qr("xhr poll");let t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(r,a)=>{this.onError("xhr poll error",r,a)}),this.pollXhr=t}};e(hQr,"BaseXHR");var nVt=hQr,RJe=class RJe extends bQn.Emitter{constructor(t,r,a){super(),this.createRequest=t,ybe(this,a),this._opts=a,this._method=a.method||"GET",this._uri=r,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var t;let r=K$t(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;let a=this._xhr=this.createRequest(r);try{_Qr("xhr open %s: %s",this._method,this._uri),a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let o in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(o)&&a.setRequestHeader(o,this._opts.extraHeaders[o])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var o;a.readyState===3&&((o=this._opts.cookieJar)===null||o===void 0||o.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},_Qr("xhr data %s",this._data),a.send(this._data)}catch(o){this.setTimeoutFn(()=>{this._onError(o)},0);return}typeof document<"u"&&(this._index=RJe.requestsCount++,RJe.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=zva,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete RJe.requests[this._index],this._xhr=null}}_onLoad(){let t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};e(RJe,"Request");var bbe=RJe;bbe.requestsCount=0;bbe.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",vQn);else if(typeof addEventListener=="function"){let i="onpagehide"in Ez?"pagehide":"unload";addEventListener(i,vQn,!1)}}function vQn(){for(let i in bbe.requests)bbe.requests.hasOwnProperty(i)&&bbe.requests[i].abort()}e(vQn,"unloadHandler");var zDs=function(){let i=Jva({xdomain:!1});return i&&i.responseType!==null}();function Jva(i){let t=i.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||yQn))return new XMLHttpRequest}catch{}if(!t)try{return new Ez[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}e(Jva,"newRequest");var Wva=gQr.default||gQr,yQr=class yQr extends nVt{request(t={}){var r;return Object.assign(t,{xd:this.xd,cookieJar:(r=this.socket)===null||r===void 0?void 0:r._cookieJar},this.opts),new bbe(a=>new Wva(a),this.uri(),t)}};e(yQr,"XHR");var LJe=yQr;var nxa=rf(wQn(),1),ixa=rf(FQr(),1),axa=rf(OQr(),1),HQr=rf(zQr(),1),sxa=rf(A$n(),1);var E$n=rf(nFe(),1);var uxa=(0,E$n.default)("engine.io-client:websocket"),cxa=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",GQr=class GQr extends vbe{get name(){return"websocket"}doOpen(){let t=this.uri(),r=this.opts.protocols,a=cxa?{}:K$t(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,r,a)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let r=0;r<t.length;r++){let a=t[r],o=r===t.length-1;Zmt(a,this.supportsBinary,c=>{try{this.doWrite(a,c)}catch{uxa("websocket closed before onclose event")}o&&gbe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let t=this.opts.secure?"wss":"ws",r=this.query||{};return this.opts.timestampRequests&&(r[this.opts.timestampParam]=Y$t()),this.supportsBinary||(r.b64=1),this.createUri(t,r)}};e(GQr,"BaseWS");var gVt=GQr,P3s=Ez.WebSocket||Ez.MozWebSocket;var KQr=class KQr extends gVt{createSocket(t,r,a){var o;if(!((o=this.socket)===null||o===void 0)&&o._cookieJar){a.headers=a.headers||{},a.headers.cookie=typeof a.headers.cookie=="string"?[a.headers.cookie]:a.headers.cookie||[];for(let[c,f]of this.socket._cookieJar.cookies)a.headers.cookie.push(`${c}=${f.value}`)}return new HQr.default(t,r,a)}doWrite(t,r){let a={};t.options&&(a.compress=t.options.compress),this.opts.perMessageDeflate&&(typeof r=="string"?Buffer.byteLength(r):r.length)<this.opts.perMessageDeflate.threshold&&(a.compress=!1),this.ws.send(r,a)}};e(KQr,"WS");var QJe=KQr;var C$n=rf(nFe(),1);var d_t=(0,C$n.default)("engine.io-client:webtransport"),YQr=class YQr extends vbe{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{d_t("transport closed gracefully"),this.onClose()}).catch(t=>{d_t("transport closed due to %s",t),this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{let r=Xqn(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=t.readable.pipeThrough(r).getReader(),o=Yqn();o.readable.pipeTo(t.writable),this._writer=o.writable.getWriter();let c=e(()=>{a.read().then(({done:_,value:v})=>{if(_){d_t("session is closed");return}d_t("received chunk: %o",v),this.onPacket(v),c()}).catch(_=>{d_t("an error occurred while reading: %s",_)})},"read");c();let f={type:"open"};this.query.sid&&(f.data=`{"sid":"${this.query.sid}"}`),this._writer.write(f).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let r=0;r<t.length;r++){let a=t[r],o=r===t.length-1;this._writer.write(a).then(()=>{o&&gbe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}};e(YQr,"WT");var $Je=YQr;var XQr={websocket:QJe,webtransport:$Je,polling:LJe};var lxa=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,pxa=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function VJe(i){if(i.length>8e3)throw"URI too long";let t=i,r=i.indexOf("["),a=i.indexOf("]");r!=-1&&a!=-1&&(i=i.substring(0,r)+i.substring(r,a).replace(/:/g,";")+i.substring(a,i.length));let o=lxa.exec(i||""),c={},f=14;for(;f--;)c[pxa[f]]=o[f]||"";return r!=-1&&a!=-1&&(c.source=t,c.host=c.host.substring(1,c.host.length-1).replace(/;/g,":"),c.authority=c.authority.replace("[","").replace("]","").replace(/;/g,":"),c.ipv6uri=!0),c.pathNames=fxa(c,c.path),c.queryKey=dxa(c,c.query),c}e(VJe,"parse");function fxa(i,t){let r=/\/{2,9}/g,a=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&a.splice(0,1),t.slice(-1)=="/"&&a.splice(a.length-1,1),a}e(fxa,"pathNames");function dxa(i,t){let r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,o,c){o&&(r[o]=c)}),r}e(dxa,"queryKey");var w$n=rf(eFe(),1);var S$n=rf(nFe(),1);var E7=(0,S$n.default)("engine.io-client:socket"),ZQr=typeof addEventListener=="function"&&typeof removeEventListener=="function",m_t=[];ZQr&&addEventListener("offline",()=>{E7("closing %d connection(s) because the network was lost",m_t.length),m_t.forEach(i=>i())},!1);var zJe=class zJe extends w$n.Emitter{constructor(t,r){if(super(),this.binaryType=eQn,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){let a=VJe(t);r.hostname=a.host,r.secure=a.protocol==="https"||a.protocol==="wss",r.port=a.port,a.query&&(r.query=a.query)}else r.host&&(r.hostname=VJe(r.host).host);ybe(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.transports.forEach(a=>{let o=a.prototype.name;this.transports.push(o),this._transportsByName[o]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=iQn(this.opts.query)),ZQr&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(E7("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},m_t.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=tQn()),this._open()}createTransport(t){E7('creating transport "%s"',t);let r=Object.assign({},this.opts.query);r.EIO=aQr,r.transport=t,this.id&&(r.sid=this.id);let a=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return E7("options: %j",a),new this._transportsByName[t](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let t=this.opts.rememberUpgrade&&zJe.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){E7("setting transport %s",t.name),this.transport&&(E7("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){E7("socket open"),this.readyState="open",zJe.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(E7('socket receive: type "%s", data "%s"',t.type,t.data),this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}else E7('packet received with socket readyState "%s"',this.readyState)}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let t=this._getWritablePackets();E7("flushing %d packets in socket",t.length),this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let r=1;for(let a=0;a<this.writeBuffer.length;a++){let o=this.writeBuffer[a].data;if(o&&(r+=rQn(o)),a>0&&r>this._maxPayload)return E7("only send %d out of %d packets",a,this.writeBuffer.length),this.writeBuffer.slice(0,a);r+=2}return E7("payload size is %d (max: %d)",r,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let t=Date.now()>this._pingTimeoutTime;return t&&(E7("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,gbe(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,a){return this._sendPacket("message",t,r,a),this}send(t,r,a){return this._sendPacket("message",t,r,a),this}_sendPacket(t,r,a,o){if(typeof r=="function"&&(o=r,r=void 0),typeof a=="function"&&(o=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;let c={type:t,data:r,options:a};this.emitReserved("packetCreate",c),this.writeBuffer.push(c),o&&this.once("flush",o),this.flush()}close(){let t=e(()=>{this._onClose("forced close"),E7("socket closing - telling transport to close"),this.transport.close()},"close"),r=e(()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},"cleanupAndClose"),a=e(()=>{this.once("upgrade",r),this.once("upgradeError",r)},"waitForUpgrade");return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():t()}):this.upgrading?a():t()),this}_onError(t){if(E7("socket error %j",t),zJe.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return E7("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(E7('socket close with reason: "%s"',t),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ZQr&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let a=m_t.indexOf(this._offlineEventListener);a!==-1&&(E7("removing listener for the 'offline' event"),m_t.splice(a,1))}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}};e(zJe,"SocketWithoutUpgrade");var uFe=zJe;uFe.protocol=aQr;var e$r=class e$r extends uFe{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){E7("starting upgrade probes");for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}}_probe(t){E7('probing transport "%s"',t);let r=this.createTransport(t),a=!1;uFe.priorWebsocketSuccess=!1;let o=e(()=>{a||(E7('probe transport "%s" opened',t),r.send([{type:"ping",data:"probe"}]),r.once("packet",T=>{if(!a)if(T.type==="pong"&&T.data==="probe"){if(E7('probe transport "%s" pong',t),this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;uFe.priorWebsocketSuccess=r.name==="websocket",E7('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{a||this.readyState!=="closed"&&(E7("changing transport and sending upgrade packet"),w(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{E7('probe transport "%s" failed',t);let k=new Error("probe error");k.transport=r.name,this.emitReserved("upgradeError",k)}}))},"onTransportOpen");function c(){a||(a=!0,w(),r.close(),r=null)}e(c,"freezeTransport");let f=e(T=>{let k=new Error("probe error: "+T);k.transport=r.name,c(),E7('probe transport "%s" failed because of error: %s',t,T),this.emitReserved("upgradeError",k)},"onerror");function _(){f("transport closed")}e(_,"onTransportClose");function v(){f("socket closed")}e(v,"onclose");function C(T){r&&T.name!==r.name&&(E7('"%s" works - aborting "%s"',T.name,r.name),c())}e(C,"onupgrade");let w=e(()=>{r.removeListener("open",o),r.removeListener("error",f),r.removeListener("close",_),this.off("close",v),this.off("upgrading",C)},"cleanup");r.once("open",o),r.once("error",f),r.once("close",_),this.once("close",v),this.once("upgrading",C),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{a||r.open()},200):r.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){let r=[];for(let a=0;a<t.length;a++)~this.transports.indexOf(t[a])&&r.push(t[a]);return r}};e(e$r,"SocketWithUpgrade");var yVt=e$r,t$r=class t$r extends yVt{constructor(t,r={}){let a=typeof t=="object"?t:r;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(o=>XQr[o]).filter(o=>!!o)),super(t,a)}};e(t$r,"Socket");var JJe=t$r;var sTs=JJe.protocol;var F$n=rf(__t(),1);var P$n=(0,F$n.default)("socket.io-client:url");function N$n(i,t="",r){let a=i;r=r||typeof location<"u"&&location,i==null&&(i=r.protocol+"//"+r.host),typeof i=="string"&&(i.charAt(0)==="/"&&(i.charAt(1)==="/"?i=r.protocol+i:i=r.host+i),/^(https?|wss?):\/\//.test(i)||(P$n("protocol-less url %s",i),typeof r<"u"?i=r.protocol+"//"+i:i="https://"+i),P$n("parse %s",i),a=VJe(i)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";let c=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+c+":"+a.port+t,a.href=a.protocol+"://"+c+(r&&r.port===a.port?"":":"+a.port),a}e(N$n,"url");var f$r={};rQ(f$r,{Decoder:()=>l$r,Encoder:()=>c$r,PacketType:()=>RE,protocol:()=>z$n});var $$n=rf(eFe(),1);var Fxa=typeof ArrayBuffer=="function",Nxa=e(i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer,"isView"),O$n=Object.prototype.toString,Oxa=typeof Blob=="function"||typeof Blob<"u"&&O$n.call(Blob)==="[object BlobConstructor]",Bxa=typeof File=="function"||typeof File<"u"&&O$n.call(File)==="[object FileConstructor]";function g_t(i){return Fxa&&(i instanceof ArrayBuffer||Nxa(i))||Oxa&&i instanceof Blob||Bxa&&i instanceof File}e(g_t,"isBinary");function h_t(i,t){if(!i||typeof i!="object")return!1;if(Array.isArray(i)){for(let r=0,a=i.length;r<a;r++)if(h_t(i[r]))return!0;return!1}if(g_t(i))return!0;if(i.toJSON&&typeof i.toJSON=="function"&&arguments.length===1)return h_t(i.toJSON(),!0);for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)&&h_t(i[r]))return!0;return!1}e(h_t,"hasBinary");function B$n(i){let t=[],r=i.data,a=i;return a.data=i$r(r,t),a.attachments=t.length,{packet:a,buffers:t}}e(B$n,"deconstructPacket");function i$r(i,t){if(!i)return i;if(g_t(i)){let r={_placeholder:!0,num:t.length};return t.push(i),r}else if(Array.isArray(i)){let r=new Array(i.length);for(let a=0;a<i.length;a++)r[a]=i$r(i[a],t);return r}else if(typeof i=="object"&&!(i instanceof Date)){let r={};for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&(r[a]=i$r(i[a],t));return r}return i}e(i$r,"_deconstructPacket");function R$n(i,t){return i.data=a$r(i.data,t),delete i.attachments,i}e(R$n,"reconstructPacket");function a$r(i,t){if(!i)return i;if(i&&i._placeholder===!0){if(typeof i.num=="number"&&i.num>=0&&i.num<t.length)return t[i.num];throw new Error("illegal attachments")}else if(Array.isArray(i))for(let r=0;r<i.length;r++)i[r]=a$r(i[r],t);else if(typeof i=="object")for(let r in i)Object.prototype.hasOwnProperty.call(i,r)&&(i[r]=a$r(i[r],t));return i}e(a$r,"_reconstructPacket");var V$n=rf(q$n(),1);var u$r=(0,V$n.default)("socket.io-parser"),Yxa=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],z$n=5,RE;(function(i){i[i.CONNECT=0]="CONNECT",i[i.DISCONNECT=1]="DISCONNECT",i[i.EVENT=2]="EVENT",i[i.ACK=3]="ACK",i[i.CONNECT_ERROR=4]="CONNECT_ERROR",i[i.BINARY_EVENT=5]="BINARY_EVENT",i[i.BINARY_ACK=6]="BINARY_ACK"})(RE||(RE={}));var d$r=class d$r{constructor(t){this.replacer=t}encode(t){return u$r("encoding packet %j",t),(t.type===RE.EVENT||t.type===RE.ACK)&&h_t(t)?this.encodeAsBinary({type:t.type===RE.EVENT?RE.BINARY_EVENT:RE.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let r=""+t.type;return(t.type===RE.BINARY_EVENT||t.type===RE.BINARY_ACK)&&(r+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(r+=t.nsp+","),t.id!=null&&(r+=t.id),t.data!=null&&(r+=JSON.stringify(t.data,this.replacer)),u$r("encoded %j as %s",t,r),r}encodeAsBinary(t){let r=B$n(t),a=this.encodeAsString(r.packet),o=r.buffers;return o.unshift(a),o}};e(d$r,"Encoder");var c$r=d$r;function Q$n(i){return Object.prototype.toString.call(i)==="[object Object]"}e(Q$n,"isObject");var wVt=class wVt extends $$n.Emitter{constructor(t){super(),this.reviver=t}add(t){let r;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");r=this.decodeString(t);let a=r.type===RE.BINARY_EVENT;a||r.type===RE.BINARY_ACK?(r.type=a?RE.EVENT:RE.ACK,this.reconstructor=new p$r(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(g_t(t)||t.base64)if(this.reconstructor)r=this.reconstructor.takeBinaryData(t),r&&(this.reconstructor=null,super.emitReserved("decoded",r));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let r=0,a={type:Number(t.charAt(0))};if(RE[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===RE.BINARY_EVENT||a.type===RE.BINARY_ACK){let c=r+1;for(;t.charAt(++r)!=="-"&&r!=t.length;);let f=t.substring(c,r);if(f!=Number(f)||t.charAt(r)!=="-")throw new Error("Illegal attachments");a.attachments=Number(f)}if(t.charAt(r+1)==="/"){let c=r+1;for(;++r&&!(t.charAt(r)===","||r===t.length););a.nsp=t.substring(c,r)}else a.nsp="/";let o=t.charAt(r+1);if(o!==""&&Number(o)==o){let c=r+1;for(;++r;){let f=t.charAt(r);if(f==null||Number(f)!=f){--r;break}if(r===t.length)break}a.id=Number(t.substring(c,r+1))}if(t.charAt(++r)){let c=this.tryParse(t.substr(r));if(wVt.isPayloadValid(a.type,c))a.data=c;else throw new Error("invalid payload")}return u$r("decoded %s as %j",t,a),a}tryParse(t){try{return JSON.parse(t,this.reviver)}catch{return!1}}static isPayloadValid(t,r){switch(t){case RE.CONNECT:return Q$n(r);case RE.DISCONNECT:return r===void 0;case RE.CONNECT_ERROR:return typeof r=="string"||Q$n(r);case RE.EVENT:case RE.BINARY_EVENT:return Array.isArray(r)&&(typeof r[0]=="number"||typeof r[0]=="string"&&Yxa.indexOf(r[0])===-1);case RE.ACK:case RE.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};e(wVt,"Decoder");var l$r=wVt,m$r=class m$r{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){let r=R$n(this.reconPack,this.buffers);return this.finishedReconstruction(),r}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};e(m$r,"BinaryReconstructor");var p$r=m$r;function vZ(i,t,r){return i.on(t,r),e(function(){i.off(t,r)},"subDestroy")}e(vZ,"on");var J$n=rf(eFe(),1),W$n=rf(__t(),1);var aO=(0,W$n.default)("socket.io-client:socket"),Xxa=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),_$r=class _$r extends J$n.Emitter{constructor(t,r,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=r,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let t=this.io;this.subs=[vZ(t,"open",this.onopen.bind(this)),vZ(t,"packet",this.onpacket.bind(this)),vZ(t,"error",this.onerror.bind(this)),vZ(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...r){var a,o,c;if(Xxa.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(r.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(r),this;let f={type:RE.EVENT,data:r};if(f.options={},f.options.compress=this.flags.compress!==!1,typeof r[r.length-1]=="function"){let w=this.ids++;aO("emitting packet with ack id %d",w);let T=r.pop();this._registerAckCallback(w,T),f.id=w}let _=(o=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||o===void 0?void 0:o.writable,v=this.connected&&!(!((c=this.io.engine)===null||c===void 0)&&c._hasPingExpired());return this.flags.volatile&&!_?aO("discard packet as the transport is not currently writable"):v?(this.notifyOutgoingListeners(f),this.packet(f)):this.sendBuffer.push(f),this.flags={},this}_registerAckCallback(t,r){var a;let o=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(o===void 0){this.acks[t]=r;return}let c=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let _=0;_<this.sendBuffer.length;_++)this.sendBuffer[_].id===t&&(aO("removing packet with ack id %d from the buffer",t),this.sendBuffer.splice(_,1));aO("event with ack id %d has timed out after %d ms",t,o),r.call(this,new Error("operation has timed out"))},o),f=e((..._)=>{this.io.clearTimeoutFn(c),r.apply(this,_)},"fn");f.withError=!0,this.acks[t]=f}emitWithAck(t,...r){return new Promise((a,o)=>{let c=e((f,_)=>f?o(f):a(_),"fn");c.withError=!0,r.push(c),this.emit(t,...r)})}_addToQueue(t){let r;typeof t[t.length-1]=="function"&&(r=t.pop());let a={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...c)=>a!==this._queue[0]?void 0:(o!==null?a.tryCount>this._opts.retries&&(aO("packet [%d] is discarded after %d tries",a.id,a.tryCount),this._queue.shift(),r&&r(o)):(aO("packet [%d] was successfully sent",a.id),this._queue.shift(),r&&r(null,...c)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(t=!1){if(aO("draining queue"),!this.connected||this._queue.length===0)return;let r=this._queue[0];if(r.pending&&!t){aO("packet [%d] has already been sent and is waiting for an ack",r.id);return}r.pending=!0,r.tryCount++,aO("sending packet [%d] (try n\xB0%d)",r.id,r.tryCount),this.flags=r.flags,this.emit.apply(this,r.args)}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){aO("transport is open - connecting"),typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:RE.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,r){aO("close (%s)",t),this.connected=!1,delete this.id,this.emitReserved("disconnect",t,r),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(a=>String(a.id)===t)){let a=this.acks[t];delete this.acks[t],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case RE.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case RE.EVENT:case RE.BINARY_EVENT:this.onevent(t);break;case RE.ACK:case RE.BINARY_ACK:this.onack(t);break;case RE.DISCONNECT:this.ondisconnect();break;case RE.CONNECT_ERROR:this.destroy();let a=new Error(t.data.message);a.data=t.data.data,this.emitReserved("connect_error",a);break}}onevent(t){let r=t.data||[];aO("emitting event %j",r),t.id!=null&&(aO("attaching ack callback to event"),r.push(this.ack(t.id))),this.connected?this.emitEvent(r):this.receiveBuffer.push(Object.freeze(r))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){let r=this._anyListeners.slice();for(let a of r)a.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){let r=this,a=!1;return function(...o){a||(a=!0,aO("sending ack %j",o),r.packet({type:RE.ACK,id:t,data:o}))}}onack(t){let r=this.acks[t.id];if(typeof r!="function"){aO("bad ack %s",t.id);return}delete this.acks[t.id],aO("calling ack %s with %j",t.id,t.data),r.withError&&t.data.unshift(null),r.apply(this,t.data)}onconnect(t,r){aO("socket connected with id %s",t),this.id=t,this.recovered=r&&this._pid===r,this._pid=r,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){aO("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(aO("performing disconnect (%s)",this.nsp),this.packet({type:RE.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){let r=this._anyListeners;for(let a=0;a<r.length;a++)if(t===r[a])return r.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){let r=this._anyOutgoingListeners;for(let a=0;a<r.length;a++)if(t===r[a])return r.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let r=this._anyOutgoingListeners.slice();for(let a of r)a.apply(this,t.data)}}};e(_$r,"Socket");var WJe=_$r;function cFe(i){i=i||{},this.ms=i.min||100,this.max=i.max||1e4,this.factor=i.factor||2,this.jitter=i.jitter>0&&i.jitter<=1?i.jitter:0,this.attempts=0}e(cFe,"Backoff");cFe.prototype.duration=function(){var i=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*i);i=Math.floor(t*10)&1?i+r:i-r}return Math.min(i,this.max)|0};cFe.prototype.reset=function(){this.attempts=0};cFe.prototype.setMin=function(i){this.ms=i};cFe.prototype.setMax=function(i){this.max=i};cFe.prototype.setJitter=function(i){this.jitter=i};var H$n=rf(eFe(),1),G$n=rf(__t(),1);var Aj=(0,G$n.default)("socket.io-client:manager"),h$r=class h$r extends H$n.Emitter{constructor(t,r){var a;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(r=t,t=void 0),r=r||{},r.path=r.path||"/socket.io",this.opts=r,ybe(this,r),this.reconnection(r.reconnection!==!1),this.reconnectionAttempts(r.reconnectionAttempts||1/0),this.reconnectionDelay(r.reconnectionDelay||1e3),this.reconnectionDelayMax(r.reconnectionDelayMax||5e3),this.randomizationFactor((a=r.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new cFe({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(r.timeout==null?2e4:r.timeout),this._readyState="closed",this.uri=t;let o=r.parser||f$r;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=r.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var r;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(r=this.backoff)===null||r===void 0||r.setMin(t),this)}randomizationFactor(t){var r;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(r=this.backoff)===null||r===void 0||r.setJitter(t),this)}reconnectionDelayMax(t){var r;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(r=this.backoff)===null||r===void 0||r.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(Aj("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Aj("opening %s",this.uri),this.engine=new JJe(this.uri,this.opts);let r=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;let o=vZ(r,"open",function(){a.onopen(),t&&t()}),c=e(_=>{Aj("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",_),t?t(_):this.maybeReconnectOnOpen()},"onError"),f=vZ(r,"error",c);if(this._timeout!==!1){let _=this._timeout;Aj("connect attempt will timeout after %d",_);let v=this.setTimeoutFn(()=>{Aj("connect attempt timed out after %d",_),o(),c(new Error("timeout")),r.close()},_);this.opts.autoUnref&&v.unref(),this.subs.push(()=>{this.clearTimeoutFn(v)})}return this.subs.push(o),this.subs.push(f),this}connect(t){return this.open(t)}onopen(){Aj("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let t=this.engine;this.subs.push(vZ(t,"ping",this.onping.bind(this)),vZ(t,"data",this.ondata.bind(this)),vZ(t,"error",this.onerror.bind(this)),vZ(t,"close",this.onclose.bind(this)),vZ(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(r){this.onclose("parse error",r)}}ondecoded(t){gbe(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){Aj("error",t),this.emitReserved("error",t)}socket(t,r){let a=this.nsps[t];return a?this._autoConnect&&!a.active&&a.connect():(a=new WJe(this,t,r),this.nsps[t]=a),a}_destroy(t){let r=Object.keys(this.nsps);for(let a of r)if(this.nsps[a].active){Aj("socket %s is still active, skipping close",a);return}this._close()}_packet(t){Aj("writing packet %j",t);let r=this.encoder.encode(t);for(let a=0;a<r.length;a++)this.engine.write(r[a],t.options)}cleanup(){Aj("cleanup"),this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){Aj("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,r){var a;Aj("closed due to %s",t),this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,r),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let t=this;if(this.backoff.attempts>=this._reconnectionAttempts)Aj("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let r=this.backoff.duration();Aj("will wait %dms before reconnect attempt",r),this._reconnecting=!0;let a=this.setTimeoutFn(()=>{t.skipReconnect||(Aj("attempting reconnect"),this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(Aj("reconnect attempt error"),t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):(Aj("reconnect success"),t.onreconnect())}))},r);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){let t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}};e(h$r,"Manager");var HJe=h$r;var Y$n=rf(__t(),1);var K$n=(0,Y$n.default)("socket.io-client"),y_t={};function v_t(i,t){typeof i=="object"&&(t=i,i=void 0),t=t||{};let r=N$n(i,t.path||"/socket.io"),a=r.source,o=r.id,c=r.path,f=y_t[o]&&c in y_t[o].nsps,_=t.forceNew||t["force new connection"]||t.multiplex===!1||f,v;return _?(K$n("ignoring socket cache for %s",a),v=new HJe(a,t)):(y_t[o]||(K$n("new io instance for %s",a),y_t[o]=new HJe(a,t)),v=y_t[o]),r.query&&!t.query&&(t.query=r.queryKey),v.socket(r.path,t)}e(v_t,"lookup");Object.assign(v_t,{Manager:HJe,Socket:WJe,io:v_t,connect:v_t});var SVt={URL:"http://localhost:3000",NAMESPACE:"auto-recovery",RECONNECTION_ATTEMPTS:5,RECONNECTION_DELAY:1e3},g$r=class g$r{constructor(t={}){this.socket=null;this.connectionState="disconnected";this.connectionPromise=null;this.resolution=null;this.options=t,this.url=t.url||SVt.URL,this.namespace=t.namespace||SVt.NAMESPACE,this.initializationPromise=this.createInitializationPromise()}createInitializationPromise(){return new Promise((t,r)=>{this.resolveInitialization=a=>t(a),this.rejectInitialization=a=>r(a)}).then(t=>(this.resolution=t,this.log("\u2705 Client initialization successful"),t),t=>{throw this.resolution=t,this.logError("\u274C Client initialization failed:",t),t}).finally(()=>{this.disconnect()})}defineHandlers(t){return t}async startSession(t,r,a){try{if(await this.connect(),this.emit(t,r,o=>{this.resolveInitialization(o)}),a&&a>0){let o=new Promise((c,f)=>{setTimeout(()=>{f(new Error(`Session initialization timed out after ${a}ms`))},a)});return Promise.race([this.initializationPromise,o])}return this.initializationPromise}catch(o){throw this.logError("\u274C Failed to start session:",o),this.rejectInitialization(o),o}}isConnected(){var t;return((t=this.socket)==null?void 0:t.connected)||!1}getConnectionState(){return this.connectionState}success(t){return{success:!0,data:t}}error(t){return{success:!1,error:t}}log(t,...r){this.options.verbose&&console.log(`[${this.namespace}] ${t}`,...r)}logError(t,...r){this.options.verbose&&console.error(`[${this.namespace}] ${t}`,...r)}async connect(){var t;if(this.connectionPromise)return this.connectionPromise;if(this.connectionState==="connected"&&((t=this.socket)!=null&&t.connected))return Promise.resolve();this.connectionState="connecting",this.connectionPromise=this.establishConnection();try{await this.connectionPromise,this.connectionState="connected"}catch(r){throw this.connectionState="disconnected",this.connectionPromise=null,r}return this.connectionPromise}establishConnection(){return new Promise((t,r)=>{let a=!1;try{let o=`${this.url}/${this.namespace}`;this.log(`\u{1F517} Connecting to socket at: ${o}`),this.socket=v_t(o,{autoConnect:!0,reconnection:!0,reconnectionAttempts:SVt.RECONNECTION_ATTEMPTS,reconnectionDelay:SVt.RECONNECTION_DELAY,...this.options.path&&{path:this.options.path}}),this.setupConnectionHandlers(t,r,a)}catch(o){this.logError("\u274C Failed to create socket connection:",o),a||r(o)}})}setupConnectionHandlers(t,r,a){if(!this.socket)return;let o={resolve:t,reject:r,connectionResolved:a};this.socket.on("connect",()=>this.handleConnect(o)),this.socket.on("reconnect",()=>this.handleReconnect()),this.socket.on("connect_error",c=>this.handleConnectError(c,o)),this.socket.on("disconnect",c=>this.handleDisconnect(c,o)),this.socket.io.on("reconnect_attempt",c=>this.handleReconnectAttempt(c)),this.socket.io.on("reconnect_error",c=>this.handleReconnectError(c)),this.socket.io.on("reconnect_failed",()=>this.handleReconnectFailed(o))}handleConnect(t){this.log("\u2705 Connected to socket"),this.connectionState="connected",this.setupEventHandlers(),t.connectionResolved||(t.connectionResolved=!0,t.resolve())}handleReconnect(){this.log("\u2705 Reconnected to socket"),this.connectionState="connected"}handleConnectError(t,r){var a;this.logError("\u274C Connection error:",t),this.connectionState="disconnected",!r.connectionResolved&&((a=this.socket)==null?void 0:a.disconnected)!==!1&&(r.connectionResolved=!0,r.reject(t))}handleDisconnect(t,r){this.log("\u{1F50C} Disconnected from socket:",t),this.connectionState="disconnected";let a=new Error(`Socket disconnected: ${t}`);this.resolution===null&&t==="io server disconnect"&&this.rejectInitialization(a),!r.connectionResolved&&(t==="io server disconnect"||t==="transport close")&&(r.connectionResolved=!0,r.reject(a)),this.resolution===null&&this.connectionState==="disconnected"&&this.rejectInitialization(a)}handleReconnectAttempt(t){this.log(`\u{1F504} Reconnection attempt #${t}`),this.connectionState="reconnecting"}handleReconnectError(t){this.logError("\u274C Reconnection attempt failed:",t)}handleReconnectFailed(t){this.logError("\u274C All reconnection attempts failed"),this.connectionState="disconnected",this.resolution===null&&this.rejectInitialization("All reconnection attempts failed"),t.connectionResolved||(t.connectionResolved=!0,t.reject(new Error("All reconnection attempts failed")))}setupEventHandlers(){if(!this.socket){this.logError("\u274C Cannot setup event handlers: socket is null");return}this.log("\u2705 Setting up event handlers"),this.socket.on("__call",this.handleGatewayCall.bind(this))}async handleGatewayCall(t,r){this.log(`\u{1F4E5} Gateway called method: ${t.key} with args:`,t.args);try{let a=this.validateGatewayCall(t);if(a){r(a);return}let o=this.handlers[t.key];if(!o){let f=`No handler registered for method: ${t.key}`;this.logError(`\u274C ${f}`),r(this.error(f));return}let c=await o(...t.args);r(this.success(c))}catch(a){this.logError("\u274C Error handling gateway call:",a),r(this.error(a.message||"Unknown error occurred"))}}validateGatewayCall(t){return t.key?Array.isArray(t.args)?null:(this.logError("\u274C Received call with invalid args"),this.error("Args must be an array")):(this.logError("\u274C Received call with undefined key"),this.error("Key is undefined"))}emit(t,r,a){if(!this.socket){this.logError("\u274C Cannot emit: socket is null");return}this.log(`\u{1F4E4} Emitting event: ${t}`),this.socket.emit(t,r,o=>{a(o)})}disconnect(){this.connectionState!=="shutting_down"&&(this.connectionState="shutting_down",this.log("\u{1F50C} Initiating disconnect"),this.socket&&(this.socket.disconnect(),this.socket=null),this.connectionPromise=null,this.connectionState="disconnected",this.log("\u2705 Disconnected successfully"))}};e(g$r,"AbstractClient");var DVt=g$r;var X$n,Z$n,eVn,tVn,rVn,nVn,kVt=class kVt extends(nVn=DVt,rVn=xj.names.getState,tVn=xj.names.invokeCode,eVn=xj.names.final_result,Z$n=xj.names.wait,X$n=xj.names.getElementScreenshot,nVn){constructor(r,a){super({verbose:V0.testRun.autoRecovery.verboseConsoleLog,url:a.config.apiURL,namespace:"auto-recovery",path:"/auto-recovery/socket.io"});this.utils=r;this.initData=a;this.stepsThoughts=[];this.handlers=this.defineHandlers({callLangChainTool:e(async(r,a)=>{if(!this[r])throw new Error(`Tool ${r} not found`);return a.thought&&this.stepsThoughts.push(a.thought),await this[r].invoke(a)},"callLangChainTool"),getStatus:e(async r=>({sessionId:r,status:"active",data:{message:"Status retrieved successfully"}}),"getStatus")});this[rVn]=u7e.buildTool(xj,xj.names.getState,async r=>this.getStateHandler(r));this[tVn]=u7e.buildTool(xj,xj.names.invokeCode,async r=>this.invokeCodeHandler(r));this[eVn]=u7e.buildTool(xj,xj.names.final_result,async r=>this.finalResultHandler(r));this[Z$n]=u7e.buildTool(xj,xj.names.wait,async r=>this.waitHandler(r));this[X$n]=u7e.buildTool(xj,xj.names.getElementScreenshot,async r=>this.getElementScreenshotHandler(r))}async init(){let r={...this.initData,version:xj.version};return await this.startSession("initialize",r).catch(a=>{this.utils.analytics.ARError({error:a.message});let o="Auto-Recovery attempt finished unsuccessfully";return this.utils.createChecksumStep({title:o,withError:!0}),this.utils.addAutoRecoveryErrorToReport(o,!1),{finalThought:o,stepsThoughts:[],result:"failed"}})}static async build(r){let a=await r.buildFallbackData();return new kVt(r,a)}async invokeCodeHandler(r){let a;return await this.utils.runConditionallyWithinStep(!0,r.thought||"Invoke Code",async()=>{try{let o=await this.utils.invokeCode(r.code);this.utils.createChecksumStep({title:"Code Invoked Successfully"}),a={success:!0,invokeCodeResult:`invokeCodeResult: ${o}`,appState:(await this.utils.buildFallbackData()).applicationState}}catch(o){a={success:!1,invokeCodeResult:`Error while invoking code: ${o}`,appState:(await this.utils.buildFallbackData()).applicationState}}}),a}async getStateHandler(r){return this.utils.createChecksumStep({title:r.thought}),this.utils.analytics.ARGetState(r.thought),{success:!0,appState:(await this.utils.buildFallbackData()).applicationState}}finalResultHandler(r){let a=r.result==="pass",o=this.initData.type==="assertion"?a?"soft_assertion":"hard_assertion":a?"finish":"failed";this.utils.analytics.ARFinalResult({finalThought:r.thought,result:o,stepsThoughts:this.stepsThoughts});let c={finalThought:r.thought,result:o,stepsThoughts:this.stepsThoughts};this.utils.addAutoRecoveryErrorToReport(r.thought,a),this.resolveInitialization(c)}async getElementScreenshotHandler(r){return{success:!0,screenshot:await this.utils.getScreenshotForElement(r.checksumId)}}async waitHandler(r){await new Promise(o=>setTimeout(o,r.time||5e3));let a=await this.utils.buildFallbackData();return{success:!0,waitResult:`waited for ${r.time} seconds, the current HTML of the application after the wait is: ${a.applicationState.reducedHTML}`}}};e(kVt,"AutoRecoveryAgent");var TVt=kVt;var iVn=require("fs"),aVn=rf(require("path"));var y$r=class y$r{constructor(t,r){this.sessionId=null;if(!Gne.getCurrentTestInfo())throw new Error("TestRunAnalytics must be initialized with testInfo before RecoveryAnalytics can be used");let o=Gne.getCurrentInstance();if(!o)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating RecoveryAnalytics");let c=o.getTestSuiteRunInfo();this.analytics=Rme.createFromConfig(c,Gne.isolatedMode,!0),this.fallbackId=t,this.fallbackType=r}updateToSessionId(t){this.sessionId!==t&&(this.sessionId=t)}get tableName(){return"fallbacks"}get metadata(){return{...this.analytics.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(t){this.analytics.trackEventWithTable(t,this.metadata,this.tableName)}setFallbackType(t){this.fallbackType=t}aiFallbackStart(t){this.event({event:"AI Fallback Start",metadata:this.metadata,...t})}aiFallbackConfig(t){this.event({event:"AI Fallback Config",metadata:this.metadata,...t})}aiFallbackIterationResponse(t){this.event({event:"AI Fallback Iteration Response",metadata:this.metadata,...t})}aiFallbackAssertion(t){this.event({event:"AI Fallback Assertion Execution",metadata:this.metadata,...t})}aiFallbackChangeVariable(t){this.event({event:"AI Fallback Change Variable",metadata:this.metadata,...t})}aiFallbackSummary(t){this.event({event:"AI Fallback Summary",metadata:this.metadata,fallbackType:this.fallbackType,...t})}aiFallbackActionExecution(t){this.event({event:"AI Fallback Action Execution",metadata:this.metadata,...t})}aiFallbackActionExecutionFailure(t){this.event({event:"AI Fallback Action Execution Failure",metadata:this.metadata,...t})}aiFallbackEnd(t){this.event({event:"AI Fallback End",metadata:this.metadata,...t})}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(t){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...t})}ARGetState(t){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:t})}ARInvokeCode(t,r){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:t,code:r})}ARFinalResult(t){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...t})}autoRecoveryDisconnect(t){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...t})}ARFinish(t){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...t})}ARError(t){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...t})}};e(y$r,"RecoveryAnalytics");var IVt=y$r;var lFe=class lFe{constructor({page:t,evaluateWithChecksum:r,checksumPage:a,pageInteractor:o,arConfig:c,sessionId:f,runtimeFallbackData:_,fallbackData:v,variableStore:C}){this.reducedHtmlTimeoutMs=3e4;this.page=t,this.evaluateWithChecksum=r,this.checksumPage=a,this.pageInteractor=o,this.arConfig=c,this.sessionId=f,this.runtimeFallbackData=_,this.fallbackData=v,this.variableStore=C,this._analytics=new IVt(this.sessionId,v.type)}static async start(t){return new lFe({...t})}getMatcherResultFileData(t){let r=t.matcherResult;if((r==null?void 0:r.name)!=="toHaveScreenshot")return;let a=e((_,v=!0)=>{if(!_)return"";try{return(0,iVn.readFileSync)(_,v?"base64":"utf-8")}catch{return""}},"readFileSafe"),o=a(r==null?void 0:r.actual),c=a(r==null?void 0:r.diff),f=a(r==null?void 0:r.expected);if(!f)throw new Error("No expected file found for 'toHaveScreenshot'");return{...r,actual:o,diff:c,expected:f}}async getSelectionDataForChecksumId(t){return await this.evaluateWithChecksum(async a=>{let{selector:o,locator:c,clickOffset:f,parentFramesSelectors:_,invalid:v,rrwebId:C}=await window.checksum.testGenerator.getSelectorForChecksumId(a),w=await window.checksum.testGenerator.getElementForChecksumId(a),T=w instanceof HTMLOptionElement&&w.value?w.value:void 0;return{selector:o,locator:c,clickOffset:f,selectOptionValue:T,parentFramesSelectors:_,invalid:v,rrwebId:C}},t)}async getReducedHtml(t=lFe.currentChecksumId){if(this.pageInteractor.getCurrentURL()==="about:blank")return{reducedHTML:"Error: Page is about:blank. Cannot get reduced HTML - either wait or navigate to a valid page before continuing.",currentChecksumId:t};let{reducedHTML:r,currentChecksumId:a}=await this.pageInteractor.getCurrentReducedHTML({stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:t});return lFe.currentChecksumId=a,{reducedHTML:r,currentChecksumId:a}}async getApplicationState(){let{reducedHTML:t}=await this.getReducedHtml();return{reducedHTML:t,screenshot:await this.getPageScreenshot()}}async buildFallbackData(){let t=new Promise((o,c)=>setTimeout(()=>c(new Error(`getReducedHtml timeout after ${this.reducedHtmlTimeoutMs/1e3} seconds`)),this.reducedHtmlTimeoutMs)),{reducedHTML:r,currentChecksumId:a}=await Promise.race([this.getReducedHtml(),t]);return{storyInfo:this.runtimeFallbackData.storyInfo,testIdentification:this.runtimeFallbackData.testIdentification,fallbackConfig:this.runtimeFallbackData.fallbackConfig,thoughts:this.runtimeFallbackData.thoughts,errorData:{error:{name:this.fallbackData.error.name,message:this.fallbackData.error.message,stack:this.fallbackData.error.stack},errorFileContent:await this.getErrorFileContent(this.fallbackData.error)},applicationState:{reducedHTML:r,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:a,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.sessionId,variableStore:this.variableStore.reduce((o,c)=>(o[`variablesStore.${c.name}`]=c.value,o),{}),arConfig:this.arConfig}}async scrollToElement(t){t&&await this.pageInteractor.scrollElementIntoViewByChecksumId(t)}async getPageScreenshot(t=this.arConfig){try{return this.checksumPage.wrapInternalSteps(async()=>{var a;return(await this.page.screenshot({fullPage:!0,type:((a=t.modelConfig)==null?void 0:a.provider)==="anthropic"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(t){try{let r=aVn.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return q$e.toRecord(t,r)}catch{throw new Error("Error while getting error file content for AI fallback")}}async wait(){await this.page.waitForTimeout(5e3)}async preprocessCode(t){var R;let r=t,a=t,o=[],c=t.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),f=c==null?void 0:c[1],_=c==null?void 0:c[2],v=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,C=(R=t.match(v))==null?void 0:R[1];if(!C)throw new Error("Checksum ID not found in the code");let w=await this.getSelectionDataForChecksumId(C);if(!(w!=null&&w.locator)||w.invalid)throw new Error(`Locator or selector not found for checksumId: ${C}`);a=a.replace(v,w.locator);let T=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,k=null;for(;(k=T.exec(t))!==null;){let B=k[1],U=this.variableStore.find(W=>W.name===B);U&&(o.push(U),a=a.replace(k[0],`"${U.value}"`))}return{originalCode:r,modifiedCode:a,usedVariables:o,checksumId:C,locator:w.locator,method:f,methodArgs:_}}async invokeCode(t){try{let r=await this.preprocessCode(t),{modifiedCode:a}=r,o=new Function("page",`return (async () => { return page.${a}; })()`),c;return await this.step(a,async()=>c=await o(this.page),!1,{box:!0,noLocation:!0,obtainStep:e(f=>{this.checksumPage.addAutoRecoveryStepId(f.stepId)},"obtainStep")}),{success:!0,result:c}}catch(r){throw console.log("Error while invoking code",r.message),r}}addAutoRecoveryErrorToReport(t,r){let a=this.runtimeFallbackData.thoughts.failing,o=r?`\u2705 "${a}" auto-recovered`:`\u274C "${a}" failed`;this.checksumPage.addPwAnnotation({type:o,description:t.replace(/^"(.*)"$/,"$1")}),r&&this.checksumPage.addErrorMessage(this.fallbackData.error,`${o}:
1823
1823
  ${t}`)}get createChecksumStep(){return t=>this.checksumPage.createChecksumStep(t)}get step(){return this.checksumPage.step.bind(this.checksumPage)}get runConditionallyWithinStep(){return(t,r,a)=>this.checksumPage.runConditionallyWithinStep(t,r,a)}async getScreenshotForElement(t){var r;try{let a=await this.getSelectionDataForChecksumId(t);if(!a)throw new Error(`Locator not found for checksumId: ${t}`);let o=((r=this.arConfig.modelConfig)==null?void 0:r.provider)==="anthropic"?"jpeg":"png";return(await this.page.locator(a.selector).screenshot({type:o})).toString("base64")}catch{throw new Error(`Failed to get screenshot for element: ${t}`)}}get analytics(){return this._analytics}};e(lFe,"AutoRecoveryRuntimeIteratorUtils"),lFe.currentChecksumId="0";var PVt=lFe;var wbe=class wbe extends jme{init(t){var r;return this.initializationData=t,(r=this.initializationData.fallbackConfig).arMode??(r.arMode="fast"),this}canResolve(t){return!0}get failingThought(){return this.initializationData.thoughts.failing}getRecoveryAttemptTitle(){switch(this.initializationData.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}"...`}}static async registerSession(t){let r=t.config.apiURL,a=t.config.apiKey;return await(await fetch(`${r}${wbe.API_BASE_ROUTE}/register-auto-recovery-session`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:a},body:JSON.stringify({appName:t.testIdentification.testFileName,fallbackData:t})})).json()}async prepareSession(t){let r=await wbe.registerSession(this.initializationData);this.utils=new PVt({page:this.page,evaluateWithChecksum:this.evaluateWithChecksum,checksumPage:this.checksumPage,pageInteractor:this.pageInteractor,arConfig:r.arConfig,sessionId:r.sessionId,runtimeFallbackData:this.initializationData,fallbackData:t,variableStore:this.variables});try{this.agent=await TVt.build(this.utils)}catch{throw new Error("Failed to prepare ARFallback")}}async resolve(t){let r=new Promise((o,c)=>{setTimeout(()=>{this.utils.analytics.ARError({error:`Auto-recovery timed out after ${wbe.TIMEOUT_MS/1e3} seconds`});let f="Auto-Recovery attempt finished unsuccessfully";this.utils.createChecksumStep({title:f,withError:!0}),this.utils.addAutoRecoveryErrorToReport(f,!1),c(new Error(f))},wbe.TIMEOUT_MS)}),a=Date.now();await this.prepareSession(t),this.utils.analytics.ARStart();try{let o=await Promise.race([this.agent.init(),r]);return this.utils.analytics.ARFinish({duration:Date.now()-a}),{fbResult:o.result,thought:o.finalThought,stepsThoughts:o.stepsThoughts,steps:[]}}catch(o){throw this.utils.analytics.ARFinish({duration:Date.now()-a}),o}}};e(wbe,"ARFallback"),wbe.API_BASE_ROUTE="/auto-recovery",wbe.TIMEOUT_MS=12e4;var Sbe=wbe;var sVn=e(i=>{let t=i.info();return t.annotations.some(r=>r.type==="bug")||t.tags.some(r=>r==="@bug")},"isKnownBugTest");var v$r=1e3*30;var b_t=class b_t extends Vze{constructor(r,a="normal",o,c,f,_,v,C,w,T,k,R){var W,X,ne;super(r,T,()=>this.pageInteractor);this.page=r;this.runMode=a;this.testRunAnalytics=o;this.monitorBridge=c;this.testInfo=f;this.checksumTestId=_;this.test=v;this.options=C;this.isReplMode=w;this.config=T;this.pageInteractorAPI=k;this.hasRuntimeStartedTrace=!1;this.unzippedHarData=[];this.fallbacks=[];this.hasUsedAutoRecovery=!1;this.arSummaries=[];this.arStepIds=[];this.arResults=[];this.failedSteps=[];this.thoughtsCounter=0;this.highLevelThoughts=[];this.pages={};this.framesMsgBroker=new p$e;this.previousSteps=[];this.scriptLoadWrapper=e(async(r,a)=>(!this.isTimeMachineFrame(a)&&this.navigationPromise&&await this.navigationPromise,this.wrapInternalSteps(r,a.page())),"scriptLoadWrapper");this.scriptLoadCheck=e(async r=>r.evaluate(()=>!!window.checksum),"scriptLoadCheck");this.scriptLoadCallback=e(async r=>{await r.evaluate(async({appSpecificRules:a,esraTimeout:o,sessionRecorder:c,showFrontendLogs:f,showTMSeeker:_,filesObserver:v,nativeDialogObserver:C,assertionsObserver:w,actionsObserver:T,recordOptions:k})=>{var R;(R=window.checksum)==null||R.testGenerator.init(a,{esraTimeout:o,showFrontendLogs:f,skipElementHighlighting:!0,recordOptions:k},{assertionGenerator:!1,sessionRecorder:c,filesObserver:v,nativeDialogObserver:C,assertionsObserver:w,actionsObserver:T});try{_&&window.checksum.timeMachine.openSeekbar()}catch{}},{appSpecificRules:this.appSpecificRules,esraTimeout:v$r,sessionRecorder:!!(!this.isTimeMachineFrame(r)&&(this.timeMachine||this.isVTG)),showFrontendLogs:V0.isDevMode,showTMSeeker:this.isTimeMachineFrame(r)&&process.env.CHECKSUM_SHOW_TIME_MACHINE==="true",filesObserver:this.isVTG&&!this.isTimeMachineFrame(r),nativeDialogObserver:this.isVTG&&!this.isTimeMachineFrame(r),assertionsObserver:this.isVTG&&!this.isTimeMachineFrame(r),actionsObserver:this.isVTG&&!this.isTimeMachineFrame(r),recordOptions:this.isVTG?this.getVTGRecordOptions():void 0}),Dv(`[init] init script loaded for ${r.page().url()}`)},"scriptLoadCallback");uVn(C.printLogs),this.isVTG&&(this.options={...this.options,useChecksumAI:{actions:!1,assertions:!1,arVersion:1,visualComparison:!1},useMockData:!1,useChecksumSelectors:!1,autoHealPRs:!1},NVt(this.page)),sVn(v)&&this.config.options.useChecksumAI.skipTestsWithKnownBugs&&(console.log("Auto recovery will not run for this test as it is marked as a known bug"),this.config.options.useChecksumAI.actions=!1,this.config.options.useChecksumAI.assertions=!1,this.config.options.useChecksumAI.visualComparison=!1),this.injectedScriptManager.setScriptLoadWrapper(this.scriptLoadWrapper).setScriptLoadCallback(this.scriptLoadCallback).setScriptLoadCheck(this.scriptLoadCheck);let B=Dbe({config:this.config,throwIfAuthFailed:!0}),U=this.getPlaywrightProjectConfig();if(this.pageInteractor=new J6e(this.evaluateWithChecksum.bind(this),()=>this.page.mainFrame(),()=>this.timeMachine,{log:Dv,logError:Dv},{navigationTimeout:(W=U.use)==null?void 0:W.navigationTimeout,actionTimeout:(X=U.use)==null?void 0:X.actionTimeout,testAssetsDir:lft(Fne()),waitActionDelay:1e3},this.pageInteractorAPI,B),this.checkForActiveTracing(),this.resetFallbacks(),R&&(this.highLevelThoughts=R.highLevelThoughts??[],this.pages=R.pages??{},this.timeMachineBrowserContext=R.timeMachineBrowserContext,this.variableStore=R.variableStore),V0.testRun.timeMachine.active){let ce=this.shouldRecordRRwebEvents()?{recordRRwebEventsToFile:!0,recordRRwebEventsToFilePath:AEn(this.checksumTestId,this.testInfo.retry)}:{};this.timeMachine=new xqt(this.framesMsgBroker,this.injectedScriptManager,{...ce,headless:process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"?!1:V0.testRun.timeMachine.headless,webProxy:(ne=f.project.use)==null?void 0:ne.proxy}),this.timeMachineBrowserContext&&this.timeMachine.setTimeMachineBrowserContext(this.timeMachineBrowserContext)}this.pages[this.getPageGuid(r)]=this.proxy}previousThoughtsAndTimestamps(){return this.previousSteps}static async init(r,a,o,c,f,_,v,C,w=!1){_||(_=zBt(5),console.warn(`Checksum test id was not defined for test "${f.title}" and was auto-generated. Please replace - "${f.title}" with -
1824
1824
  test(defineChecksumTest("${f.title}", "${_}"), async ({ page }) => {...`)),o.addTestInfo(_,f.testId),C.options.useChecksumAI!==void 0&&typeof C.options.useChecksumAI=="boolean"&&(C.options.useChecksumAI={actions:C.options.useChecksumAI,assertions:!1,visualComparison:!1});let T=new j$e(C),k=new b_t(r,C.runMode,a,o,f,_,v,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:C.runMode!=="normal",useMockData:!1,printLogs:!1,...C.options},w,C,T,{variableStore:c});return v._checksum.expect.setPage(k),v._checksum.checksumAI.page=k,c.clearAll(),k.testRunAnalytics.testRunStart(),await k.asyncInit(),k.proxy}async asyncInit(r=!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(),r||await this.prepareForTestArtifacts();let a=bZ.resolve(__dirname,"mock-auto-heal-agent.js");await this.page.addInitScript({path:a})}async getPage(r){let a=this.page.context().pages()[r];if(!a)throw new Error(`Page with index ${r} not found`);return this.makePage(a)}async makePage(r){let a=this.getPageGuid(r);if(this.pages[a])return this.pages[a];let o=new b_t(r,this.runMode,this.testRunAnalytics,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 o.asyncInit(!0),o.proxy}getTimeMachinePage(){var r;return(r=this.timeMachine)==null?void 0:r.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}isTimeMachineFrame(r){var a;return r===((a=this.timeMachine)==null?void 0:a.getFrame())}shouldRecordRRwebEvents(){return V0.testRun.timeMachine.recordRRwebEventsToFile&&this.config.options.hostReports}getPageGuid(r){return r._guid}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var o;let a=(o=this.getPlaywrightProjectConfig().use)==null?void 0:o.trace;this.traceMode=typeof a=="string"?a:a==null?void 0:a.mode}registerPageEvents(){super.registerPageEvents(),this.injectedScriptManager.addTrackedFrame(this.page),this.page.on("framenavigated",async r=>{this.injectedScriptManager.onFrameNavigated(r)})}checksumSelector(r){return this.checksumStepId=r,this.options.useChecksumSelectors&&this.setSelectorFallback(r),this.proxy}checksumAI(r,a,o){let c=this.addNewThought(r,"action",!!a);return this.previousSteps.push({thought:c.thought,timestamp:Date.now()}),a&&typeof a=="function"?this.test.step(r,async f=>{var _;try{return o!=null&&o.withDialog&&this.pageInteractor.listenToDialog(),await a()}catch(v){if(c.children=[],!this.options.useChecksumAI.actions||o!=null&&o.withDialog||o!=null&&o.skipAutoRecovery)throw v;this.setAIFallback(r,"action");try{return await this.initiateFallbackSequence({type:"action",error:v,method:void 0,args:[],testInfo:this.testInfo,step:f},{fallbackTypes:[Fve,Sbe]})}catch(C){throw this.testRunAnalytics.testRunError({failedThought:r,error:(C==null?void 0:C.message)||"Unknown error"}),C}}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(_=this.currentThought)==null?void 0:_.parent}}):(this.options.useChecksumAI.actions&&!(o!=null&&o.skipAutoRecovery)&&this.setAIFallback(r,"action"),this.proxy)}resolveAssetsFolder(r){return r.map(a=>bZ.join(lft(Fne()),a))}getRuntimeOptions(){return this.options}addPwAnnotation(r){this.testInfo.annotations.push({type:r.type,description:`
1825
- ${r.description}`})}async onTestComplete(r){this.testRunAnalytics.testRunEnd({success:r,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.hasUsedAutoRecovery&&r}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(r,a=this.page){try{return a.mainFrame()._checksumInternal=!0,a._checksumInternal=!0,await r()}finally{a.mainFrame()._checksumInternal=!1,a._checksumInternal=!1}}async conditionallyWrapInternalSteps(r,a){return r?this.wrapInternalSteps(a):a()}async wrapNoLocationSteps(r){try{return this.testInfo._checksumNoLocation=!0,await r()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(r,a,o=[]){for(let c of r){(c._stepId===a||c.stepId===a)&&o.push(c);let f=[c.steps,c._testInfoSteps,c._steps].filter(Boolean);for(let _ of f)this.findAllStepsRecursively(_,a,o)}return o}makeChecksumStepFunction(r){return a=>{if(!r)return;let o=a._stepId||a.stepId;this.findAllStepsRecursively(a._testInfo._steps,o).forEach(f=>{f.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(r){let a,o={box:!0,noLocation:!0,obtainStep:e(c=>{a=c},"obtainStep")};return await this.step(r.title,this.makeChecksumStepFunction(r.withError),!1,o),this.arStepIds.push(a.stepId),a}async step(r,a,o=!0,{obtainStep:c=void 0,box:f=!1,noLocation:_=void 0}={}){let v=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=o===!0,_!==void 0&&(this.testInfo._checksumNoLocation=_),await this.test.step(r,a||(()=>{}),{obtainStep:c,box:f})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=v}}addErrorMessage(r,a){this.testInfo.addError(r,a)}async evaluateWithChecksum(r,a,o=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(o,()=>this.page.evaluate(r,a))}getChecksumTestId(){return this.checksumTestId}addNewThought(r,a,o=!1){let c={id:void 0,thought:r,type:a,children:o?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(c);else if(this.currentThought.children)this.currentThought.children.push(c),c.parent=this.currentThought;else{let f=this.currentThought.parent;f?(f.children.push(c),c.parent=f):this.highLevelThoughts.push(c)}return c.parent?c.id=`${c.parent.id}.${c.parent.children.length}`:c.id=`${++this.thoughtsCounter}`,this.currentThought=c,c}buildThoughtsChainForFallback(r=this.highLevelThoughts){let a=[];return r.forEach(o=>{a.push(o.thought),o.children&&a.push(...this.buildThoughtsChainForFallback(o.children))}),a}getVTGRecordOptions(){return{recordCanvas:!0,recordCrossOriginIframes:this.isVTG,sampling:{mousemove:!1},slimDOMOptions:"all"}}compoundSelection(...r){let a=super.compoundSelection(...r);return a.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),a}setSelectorFallback(r){let a={checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:v$r};this.pushFallback(this.constructFallback(Ndt).init(a)),this.pushFallback(this.constructFallback(Pdt).init(a))}setCompoundSelectorFallback(r){this.pushFallback(this.constructFallback(Fdt).init({checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:v$r}))}setAIFallback(r,a){var _;let o=((_=this.options.useChecksumAI)==null?void 0:_.arVersion)===1,c=e(()=>{var R,B;let v=this.buildThoughtsChainForFallback(),C={title:this.testInfo.title},w={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},T={previous:v.slice(0,-1),failing:r,next:v.slice(1)},k={storyInfo:C,testIdentification:w,fallbackConfig:{arMode:(R=this.options.useChecksumAI)==null?void 0:R.arMode,overrideOptions:(B=this.options.useChecksumAI)==null?void 0:B.overrideOptions},thoughts:T,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:a};return this.constructFallback(Sbe).init(k)},"createArFallback"),f=e(()=>{var v,C;return this.constructFallback(Fve).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),benchmark:V0.benchmark,arMode:(v=this.options.useChecksumAI)==null?void 0:v.arMode,overrideOptions:(C=this.options.useChecksumAI)==null?void 0:C.overrideOptions,fallbackType:a})},"createAIFallback");return o?this.pushFallback(f()):this.pushFallback(c()),this.proxy}pushFallback(r){this.fallbacks.push(r),this.sortFallbacks()}handleAIFallback(r,a,o,c){let f=r.fallbackAnalyticsPayload.iterationSteps,_=f.length>0?c/f.length:0;this.testRunAnalytics.testRunFallbackExecution({result:o.fbResult,failedThought:r.getFailedThought(),summary:o.summary,stepsPayload:r.fallbackAnalyticsPayload,type:r.fallbackType??a.type,benchmark:V0.benchmark.toString(),duration:c,avgDuration:_,success:["finish","soft_assertion"].includes(o.fbResult)}),this.arResults.push({failedThought:r.getFailedThought(),result:o.fbResult,thought:o.thought})}handleAutoRecovery(r,a,o,c){let f=o.stepsThoughts.length>0?c/o.stepsThoughts.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:r.failingThought,type:a.type,finalThought:o.thought,result:o.fbResult,duration:c,avgStepDuration:f,stepsThoughts:o.stepsThoughts,version:"v1"})}async runFallback(r,a){let o=Date.now(),c=r.resolve(a),f=await lD(c,r.timeout),_=Date.now()-o;r instanceof Fve&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(r,a,f,_)),r instanceof Sbe&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(r,a,f,_));let v=f.thought?`: ${f.thought}`:"";if(!f||f.fbResult==="failed")throw this.createChecksumStep({title:`Recovery Failed${v}`,withError:!0}),new Error("Fallback failed");if(f.fbResult==="hard_assertion")throw this.createChecksumStep({title:`Recovery Failed${v}`,withError:!0}),new Hft(f.fbResult);if(r instanceof Fve&&f.summary&&this.arSummaries.push(f.summary),r instanceof Sbe&&f.thought&&this.arSummaries.push(f.thought),this.createChecksumStep({title:`Recovery Complete${v}`}),f.steps.length===1){let C=f.steps[0];C.thought&&(this.currentThought.thought=C.thought)}else this.currentThought.children=f.steps.map((C,w)=>({id:`${this.currentThought.id}.${w+1}`,thought:C.thought,type:C.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(r,a,o){return r?await this.step(a,o):await o()}async onExecutionError(r){try{return await this.initiateFallbackSequence({type:"action",...r})}catch(a){if(!this.currentThought){let{locator:o,method:c}=r;this.testRunAnalytics.testRunActionExecutionFailure({locator:o.toString(),selector:o._selector,method:c,checksumStepId:this.checksumStepId,error:a.toString()})}throw a}}async initiateFallbackSequence(r,{fallbackTypes:a=void 0}={}){Dv(`[initiateFallbackSequence] with type: ${r.type}...`);let o=this.fallbacks.find(_=>_ instanceof Fve);if(o){let _=o.getFailedThought(),v=this.variableStore.getActiveVariables();this.fallbacks.forEach(C=>{C.setThought(_),C.setVariables(v)})}let c=this.fallbacks.find(_=>_ instanceof Sbe);if(c){let _=c.failingThought;this.fallbacks.forEach(v=>{v instanceof Sbe&&v.setVariables(this.variableStore.getActiveVariables()),v.setThought(_)})}let f=this.fallbacks;a&&(f=f.filter(_=>a.reduce((v,C)=>v||_ instanceof C,!1))),f=f.filter(_=>_.canResolve(r));try{for(let _ of f){let v=_==null?void 0:_.toString();v&&console.log(`Using ${v}`);let C;try{let w=await this.runConditionallyWithinStep(r.type!=="assertion"||!r.withChecksumAI,_.getRecoveryAttemptTitle(r),async()=>await this.runFallback(_,r));C=!0}catch(w){if(C=!1,r.withChecksumAI&&w.message==="fetch failed")throw new Error(x4e);w instanceof Hft&&w.fallbackResult==="hard_assertion"&&(r.error.fallbackResult="hard_assertion"),v&&console.log(`Failed to use ${v}`),_.cancel();continue}return!0}throw r.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(Odt).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()){try{await this.timeMachine.flushRRwebEventsToFile();let r=this.timeMachine.getRRwebFilePath();this.monitorBridge.addAsset({type:"rrweb-recording",path:r,testId:this.checksumTestId,fileName:bZ.basename(r)})}catch(r){Dv("Error shutting down RRweb events recording",r)}if(this.testRunAnalytics)return Dv("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let r=[Odt,Fdt,Ndt,Pdt,Fve];this.fallbacks.sort((a,o)=>r.indexOf(a.constructor)-r.indexOf(o.constructor))}constructFallback(r){return new r(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"})}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let a=await this.getTraceFilePath();a&&this.monitorBridge.addAsset({type:"trace",path:a,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let a=xEn(WBt(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:a,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?EEn(WBt(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let r=Y3r(WBt(this.testInfo.file)),a=bZ.join(r,`${this.checksumTestId}.har.zip`);if(!(0,Cz.existsSync)(a))throw new Error("Could not find har file or zip file");let o=bZ.join(r,"tmp");(0,Cz.existsSync)(o)||(0,Cz.mkdirSync)(o);let c=(0,Cz.readFileSync)(a),f=await(0,oVn.loadAsync)(c);for(let v of Object.keys(f.files)){let C=await f.file(v).async("string"),w=bZ.join(o,v);(0,Cz.writeFileSync)(w,C),this.unzippedHarData.push(w)}let _=bZ.join(o,"test.har");if(!(0,Cz.existsSync)(_))throw this.cleanupMockData(),new Error(`Could not find har file ${_} after unzipping ${a}`);return _}cleanupMockData(){this.unzippedHarData.forEach(r=>{(0,Cz.rmSync)(r)}),this.unzippedHarData.length>0&&(0,Cz.rmSync)(bZ.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let r={GET:0,POST:0,PUT:0,DELETE:0};try{let a=await this.prepareMockData();await this.page.routeFromHAR(a,{url:"*/**",notFound:"fallback",update:!1});let o=this.page._routes[0].handler;await this.page.route("**/*",c=>{let f=c.request().headers(),_=c.request().method();f["Checksum-Id"]=(++r[_]).toString(),c.request()._applyFallbackOverrides({headers:f}),o(c)})}catch(a){Dv("Error setting up mock data",a.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let r=bZ.join(a9e(Fne()),"settings.asr");if(!(0,Cz.existsSync)(r)){Dv("Could not find ASR file");return}let{ungzip:a}=K3r();try{let o=await a((0,Cz.readFileSync)(r));this.appSpecificRules=JSON.parse(o)||{}}catch(o){Dv("Could not read ASR file",o.message)}}addAutoRecoveryStepId(r){this.arStepIds.push(r)}};e(b_t,"RuntimePage");var FVt=b_t;var RVt=require("fs");var d7e={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},Rks={defaultMerge:d7e.defaultMerge};function Zxa(i,t){return t}e(Zxa,"defaultMetaDataUpdater");function eAa(i,t){return i.filter(r=>r!==void 0)}e(eAa,"defaultFilterValues");var cVn;(function(i){i[i.NOT=0]="NOT",i[i.RECORD=1]="RECORD",i[i.ARRAY=2]="ARRAY",i[i.SET=3]="SET",i[i.MAP=4]="MAP",i[i.OTHER=5]="OTHER"})(cVn||(cVn={}));function lVn(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:nAa(i)?1:i instanceof Set?3:i instanceof Map?4:5}e(lVn,"getObjectType");function tAa(i){let t=new Set;for(let r of i)for(let a of[...Object.keys(r),...Object.getOwnPropertySymbols(r)])t.add(a);return t}e(tAa,"getKeys");function rAa(i,t){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,t)}e(rAa,"objectHasProperty");function fVn(i){var a;let t=0,r=(a=i[0])==null?void 0:a[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var o;do{if(r===void 0)return{done:!0,value:void 0};let c=r.next();if(c.done===!0){t+=1,r=(o=i[t])==null?void 0:o[Symbol.iterator]();continue}return{done:!1,value:c.value}}while(!0)}}}}}e(fVn,"getIterableOfIterables");var pVn=["[object Object]","[object Module]"];function nAa(i){if(!pVn.includes(Object.prototype.toString.call(i)))return!1;let{constructor:t}=i;if(t===void 0)return!0;let r=t.prototype;return!(r===null||typeof r!="object"||!pVn.includes(Object.prototype.toString.call(r))||!r.hasOwnProperty("isPrototypeOf"))}e(nAa,"isRecord");function iAa(i,t,r){let a={};for(let o of tAa(i)){let c=[];for(let v of i)rAa(v,o)&&c.push(v[o]);if(c.length===0)continue;let f=t.metaDataUpdater(r,{key:o,parents:i}),_=dVn(c,t,f);_!==d7e.skip&&(o==="__proto__"?Object.defineProperty(a,o,{value:_,configurable:!0,enumerable:!0,writable:!0}):a[o]=_)}return a}e(iAa,"mergeRecords$1");function aAa(i){return i.flat()}e(aAa,"mergeArrays$1");function sAa(i){return new Set(fVn(i))}e(sAa,"mergeSets$1");function oAa(i){return new Map(fVn(i))}e(oAa,"mergeMaps$1");function uAa(i){return i.at(-1)}e(uAa,"mergeOthers$1");var OVt={mergeRecords:iAa,mergeArrays:aAa,mergeSets:sAa,mergeMaps:oAa,mergeOthers:uAa};function BVt(...i){return cAa({})(...i)}e(BVt,"deepmerge");function cAa(i,t){let r=lAa(i,a);function a(...o){return dVn(o,r,t)}return e(a,"customizedDeepmerge"),a}e(cAa,"deepmergeCustom");function lAa(i,t){return{defaultMergeFunctions:OVt,mergeFunctions:{...OVt,...Object.fromEntries(Object.entries(i).filter(([r,a])=>Object.hasOwn(OVt,r)).map(([r,a])=>a===!1?[r,OVt.mergeOthers]:[r,a]))},metaDataUpdater:i.metaDataUpdater??Zxa,deepmerge:t,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??eAa,actions:d7e}}e(lAa,"getUtils");function dVn(i,t,r){var c;let a=((c=t.filterValues)==null?void 0:c.call(t,i,r))??i;if(a.length===0)return;if(a.length===1)return b$r(a,t,r);let o=lVn(a[0]);if(o!==0&&o!==5){for(let f=1;f<a.length;f++)if(lVn(a[f])!==o)return b$r(a,t,r)}switch(o){case 1:return pAa(a,t,r);case 2:return fAa(a,t,r);case 3:return dAa(a,t,r);case 4:return mAa(a,t,r);default:return b$r(a,t,r)}}e(dVn,"mergeUnknowns");function pAa(i,t,r){let a=t.mergeFunctions.mergeRecords(i,t,r);return a===d7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(i,t,r):a}e(pAa,"mergeRecords");function fAa(i,t,r){let a=t.mergeFunctions.mergeArrays(i,t,r);return a===d7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(i):a}e(fAa,"mergeArrays");function dAa(i,t,r){let a=t.mergeFunctions.mergeSets(i,t,r);return a===d7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(i):a}e(dAa,"mergeSets");function mAa(i,t,r){let a=t.mergeFunctions.mergeMaps(i,t,r);return a===d7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(i):a}e(mAa,"mergeMaps");function b$r(i,t,r){let a=t.mergeFunctions.mergeOthers(i,t,r);return a===d7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(i):a}e(b$r,"mergeOthers");var mVn=!1;function uVn(i){mVn=i}e(uVn,"setLogToConsole");function Dv(...i){mVn&&console.log(...i)}e(Dv,"log");async function akn(i,t,r,a=6e4){if(!(t in i))return i;let o=e(()=>i[t](...r),"executor");return a===null?o():lD(o(),a,"Execution timeout")}e(akn,"executePlaywrightMethodWithTimeout");function x_t(i,{role:t,environment:r}={},a=!1){var _,v;let o;if(r&&(o=(_=i.environments)==null?void 0:_.find(({name:C})=>r===C)),o||(o=(v=i.environments)==null?void 0:v.find(({default:C})=>C)),!o)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let c=o.users,f;if(c&&(t!==void 0&&(f=c.find(C=>C.role===t)),f||(f=c.find(C=>C.default))),!f)throw new Error(`User not found. Please make sure the users array for the "${o.name}" environment is properly defined in the checksum.config.ts file.`);if(r&&o.name!==r){if(a)throw new Error(`Could not find environment with name "${r}" in config file`);console.warn(`Could not find environment with name "${r}" in config file, trying to use default environment`)}if(t&&f.role!==t){if(a)throw new Error(`Could not find user with role "${t}" for environment "${r}" in config file`);console.warn(`Could not find user with role "${t}" for environment "${r}" in config file, trying to login with environment's default user`)}return{environment:o,user:f}}e(x_t,"resolveEnvironment");function _Aa(i){let t=`${i??Fne()}/login.ts`;if(!(0,RVt.existsSync)(t))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${t}`),new Error("Could not find login.ts file");try{return require(t).default}catch(r){throw console.warn("Error loading login.ts file",r),r}}e(_Aa,"requireLogin");async function hAa(i,t,{environment:r,user:a,config:o}){try{let c=e(()=>t(i,{environment:r,user:a,config:o}),"performLogin");"checksumAI"in i?await i.checksumAI(`Log in${a!=null&&a.role?` using ${a.role} role`:""}${r!=null&&r.name?` in ${r.name} environment`:""}`,c):await c()}catch(c){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
1825
+ ${r.description}`})}async onTestComplete(r){this.testRunAnalytics.testRunEnd({success:r,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.hasUsedAutoRecovery&&r}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(r,a=this.page){try{return a.mainFrame()._checksumInternal=!0,a._checksumInternal=!0,await r()}finally{a.mainFrame()._checksumInternal=!1,a._checksumInternal=!1}}async conditionallyWrapInternalSteps(r,a){return r?this.wrapInternalSteps(a):a()}async wrapNoLocationSteps(r){try{return this.testInfo._checksumNoLocation=!0,await r()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(r,a,o=[]){for(let c of r){(c._stepId===a||c.stepId===a)&&o.push(c);let f=[c.steps,c._testInfoSteps,c._steps].filter(Boolean);for(let _ of f)this.findAllStepsRecursively(_,a,o)}return o}makeChecksumStepFunction(r){return a=>{if(!r)return;let o=a._stepId||a.stepId;this.findAllStepsRecursively(a._testInfo._steps,o).forEach(f=>{f.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(r){let a,o={box:!0,noLocation:!0,obtainStep:e(c=>{a=c},"obtainStep")};return await this.step(r.title,this.makeChecksumStepFunction(r.withError),!1,o),this.arStepIds.push(a.stepId),a}async step(r,a,o=!0,{obtainStep:c=void 0,box:f=!1,noLocation:_=void 0}={}){let v=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=o===!0,_!==void 0&&(this.testInfo._checksumNoLocation=_),await this.test.step(r,a||(()=>{}),{obtainStep:c,box:f})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=v}}addErrorMessage(r,a){this.testInfo.addError(r,a)}async evaluateWithChecksum(r,a,o=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(o,()=>this.page.evaluate(r,a))}getChecksumTestId(){return this.checksumTestId}addNewThought(r,a,o=!1){let c={id:void 0,thought:r,type:a,children:o?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(c);else if(this.currentThought.children)this.currentThought.children.push(c),c.parent=this.currentThought;else{let f=this.currentThought.parent;f?(f.children.push(c),c.parent=f):this.highLevelThoughts.push(c)}return c.parent?c.id=`${c.parent.id}.${c.parent.children.length}`:c.id=`${++this.thoughtsCounter}`,this.currentThought=c,c}buildThoughtsChainForFallback(r=this.highLevelThoughts){let a=[];return r.forEach(o=>{a.push(o.thought),o.children&&a.push(...this.buildThoughtsChainForFallback(o.children))}),a}getVTGRecordOptions(){return{recordCanvas:!0,recordCrossOriginIframes:this.isVTG,sampling:{mousemove:!1},slimDOMOptions:"all"}}compoundSelection(...r){let a=super.compoundSelection(...r);return a.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),a}setSelectorFallback(r){let a={checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:v$r};this.pushFallback(this.constructFallback(Ndt).init(a)),this.pushFallback(this.constructFallback(Pdt).init(a))}setCompoundSelectorFallback(r){this.pushFallback(this.constructFallback(Fdt).init({checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:v$r}))}setAIFallback(r,a){var _;let o=((_=this.options.useChecksumAI)==null?void 0:_.arVersion)===1,c=e(()=>{var R,B;let v=this.buildThoughtsChainForFallback(),C={title:this.testInfo.title},w={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},T={previous:v.slice(0,-1),failing:r,next:v.slice(1)},k={storyInfo:C,testIdentification:w,fallbackConfig:{arMode:(R=this.options.useChecksumAI)==null?void 0:R.arMode,overrideOptions:(B=this.options.useChecksumAI)==null?void 0:B.overrideOptions},thoughts:T,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:a};return this.constructFallback(Sbe).init(k)},"createArFallback"),f=e(()=>{var v,C;return this.constructFallback(Fve).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),benchmark:V0.benchmark,arMode:(v=this.options.useChecksumAI)==null?void 0:v.arMode,overrideOptions:(C=this.options.useChecksumAI)==null?void 0:C.overrideOptions,fallbackType:a})},"createAIFallback");return o?this.pushFallback(f()):this.pushFallback(c()),this.proxy}pushFallback(r){this.fallbacks.push(r),this.sortFallbacks()}handleAIFallback(r,a,o,c){let f=r.fallbackAnalyticsPayload.iterationSteps,_=f.length>0?c/f.length:0;this.testRunAnalytics.testRunFallbackExecution({result:o.fbResult,failedThought:r.getFailedThought(),summary:o.summary,stepsPayload:r.fallbackAnalyticsPayload,type:r.fallbackType??a.type,benchmark:V0.benchmark.toString(),duration:c,avgDuration:_,success:["finish","soft_assertion"].includes(o.fbResult)}),this.arResults.push({failedThought:r.getFailedThought(),result:o.fbResult,thought:o.thought})}handleAutoRecovery(r,a,o,c){let f=o.stepsThoughts.length>0?c/o.stepsThoughts.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:r.failingThought,type:a.type,finalThought:o.thought,result:o.fbResult,duration:c,avgStepDuration:f,stepsThoughts:o.stepsThoughts,version:"v1"})}async runFallback(r,a){let o=Date.now(),c=r.resolve(a),f=await lD(c,r.timeout),_=Date.now()-o;r instanceof Fve&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(r,a,f,_)),r instanceof Sbe&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(r,a,f,_));let v=f.thought?`: ${f.thought}`:"";if(!f||f.fbResult==="failed")throw this.createChecksumStep({title:`Recovery Failed${v}`,withError:!0}),new Error("Fallback failed");if(f.fbResult==="hard_assertion")throw this.createChecksumStep({title:`Recovery Failed${v}`,withError:!0}),new Hft(f.fbResult);if(r instanceof Fve&&f.summary&&this.arSummaries.push(f.summary),r instanceof Sbe&&f.thought&&this.arSummaries.push(f.thought),this.createChecksumStep({title:`Recovery Complete${v}`}),f.steps.length===1){let C=f.steps[0];C.thought&&(this.currentThought.thought=C.thought)}else this.currentThought.children=f.steps.map((C,w)=>({id:`${this.currentThought.id}.${w+1}`,thought:C.thought,type:C.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(r,a,o){return r?await this.step(a,o):await o()}async onExecutionError(r){try{return await this.initiateFallbackSequence({type:"action",...r})}catch(a){if(!this.currentThought){let{locator:o,method:c}=r;this.testRunAnalytics.testRunActionExecutionFailure({locator:o.toString(),selector:o._selector,method:c,checksumStepId:this.checksumStepId,error:a.toString()})}throw a}}async initiateFallbackSequence(r,{fallbackTypes:a=void 0}={}){Dv(`[initiateFallbackSequence] with type: ${r.type}...`);let o=this.fallbacks.find(_=>_ instanceof Fve);if(o){let _=o.getFailedThought(),v=this.variableStore.getActiveVariables();this.fallbacks.forEach(C=>{C.setThought(_),C.setVariables(v)})}let c=this.fallbacks.find(_=>_ instanceof Sbe);if(c){let _=c.failingThought;this.fallbacks.forEach(v=>{v instanceof Sbe&&v.setVariables(this.variableStore.getActiveVariables()),v.setThought(_)})}let f=this.fallbacks;a&&(f=f.filter(_=>a.reduce((v,C)=>v||_ instanceof C,!1))),f=f.filter(_=>_.canResolve(r));try{for(let _ of f){let v=_==null?void 0:_.toString();v&&console.log(`Using ${v}`);let C;try{let w=await this.runConditionallyWithinStep(r.type!=="assertion"||!r.withChecksumAI,_.getRecoveryAttemptTitle(r),async()=>await this.runFallback(_,r));C=!0}catch(w){if(C=!1,r.withChecksumAI&&w.message==="fetch failed")throw new Error(x4e);w instanceof Hft&&w.fallbackResult==="hard_assertion"&&(r.error.fallbackResult="hard_assertion"),v&&console.log(`Failed to use ${v}`),_.cancel();continue}return!0}throw r.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(Odt).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()){try{await this.timeMachine.flushRRwebEventsToFile();let r=this.timeMachine.getRRwebFilePath();this.monitorBridge.addAsset({type:"rrweb-recording",path:r,testId:this.checksumTestId,fileName:bZ.basename(r)})}catch(r){Dv("Error shutting down RRweb events recording",r)}if(this.testRunAnalytics)return Dv("Flushing analytics events......"),this.testRunAnalytics.close()}this.framesMsgBroker.cleanup()}sortFallbacks(){let r=[Odt,Fdt,Ndt,Pdt,Fve];this.fallbacks.sort((a,o)=>r.indexOf(a.constructor)-r.indexOf(o.constructor))}constructFallback(r){return new r(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"})}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let a=await this.getTraceFilePath();a&&this.monitorBridge.addAsset({type:"trace",path:a,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let a=xEn(WBt(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:a,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?EEn(WBt(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let r=Y3r(WBt(this.testInfo.file)),a=bZ.join(r,`${this.checksumTestId}.har.zip`);if(!(0,Cz.existsSync)(a))throw new Error("Could not find har file or zip file");let o=bZ.join(r,"tmp");(0,Cz.existsSync)(o)||(0,Cz.mkdirSync)(o);let c=(0,Cz.readFileSync)(a),f=await(0,oVn.loadAsync)(c);for(let v of Object.keys(f.files)){let C=await f.file(v).async("string"),w=bZ.join(o,v);(0,Cz.writeFileSync)(w,C),this.unzippedHarData.push(w)}let _=bZ.join(o,"test.har");if(!(0,Cz.existsSync)(_))throw this.cleanupMockData(),new Error(`Could not find har file ${_} after unzipping ${a}`);return _}cleanupMockData(){this.unzippedHarData.forEach(r=>{(0,Cz.rmSync)(r)}),this.unzippedHarData.length>0&&(0,Cz.rmSync)(bZ.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let r={GET:0,POST:0,PUT:0,DELETE:0};try{let a=await this.prepareMockData();await this.page.routeFromHAR(a,{url:"*/**",notFound:"fallback",update:!1});let o=this.page._routes[0].handler;await this.page.route("**/*",c=>{let f=c.request().headers(),_=c.request().method();f["Checksum-Id"]=(++r[_]).toString(),c.request()._applyFallbackOverrides({headers:f}),o(c)})}catch(a){Dv("Error setting up mock data",a.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let r=bZ.join(a9e(Fne()),"settings.asr");if(!(0,Cz.existsSync)(r)){Dv("Could not find ASR file");return}let{ungzip:a}=K3r();try{let o=await a((0,Cz.readFileSync)(r));this.appSpecificRules=JSON.parse(o)||{}}catch(o){Dv("Could not read ASR file",o.message)}}addAutoRecoveryStepId(r){this.arStepIds.push(r)}};e(b_t,"RuntimePage");var FVt=b_t;var RVt=require("fs");var d7e={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},Rks={defaultMerge:d7e.defaultMerge};function Zxa(i,t){return t}e(Zxa,"defaultMetaDataUpdater");function eAa(i,t){return i.filter(r=>r!==void 0)}e(eAa,"defaultFilterValues");var cVn;(function(i){i[i.NOT=0]="NOT",i[i.RECORD=1]="RECORD",i[i.ARRAY=2]="ARRAY",i[i.SET=3]="SET",i[i.MAP=4]="MAP",i[i.OTHER=5]="OTHER"})(cVn||(cVn={}));function lVn(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:nAa(i)?1:i instanceof Set?3:i instanceof Map?4:5}e(lVn,"getObjectType");function tAa(i){let t=new Set;for(let r of i)for(let a of[...Object.keys(r),...Object.getOwnPropertySymbols(r)])t.add(a);return t}e(tAa,"getKeys");function rAa(i,t){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,t)}e(rAa,"objectHasProperty");function fVn(i){var a;let t=0,r=(a=i[0])==null?void 0:a[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var o;do{if(r===void 0)return{done:!0,value:void 0};let c=r.next();if(c.done===!0){t+=1,r=(o=i[t])==null?void 0:o[Symbol.iterator]();continue}return{done:!1,value:c.value}}while(!0)}}}}}e(fVn,"getIterableOfIterables");var pVn=["[object Object]","[object Module]"];function nAa(i){if(!pVn.includes(Object.prototype.toString.call(i)))return!1;let{constructor:t}=i;if(t===void 0)return!0;let r=t.prototype;return!(r===null||typeof r!="object"||!pVn.includes(Object.prototype.toString.call(r))||!r.hasOwnProperty("isPrototypeOf"))}e(nAa,"isRecord");function iAa(i,t,r){let a={};for(let o of tAa(i)){let c=[];for(let v of i)rAa(v,o)&&c.push(v[o]);if(c.length===0)continue;let f=t.metaDataUpdater(r,{key:o,parents:i}),_=dVn(c,t,f);_!==d7e.skip&&(o==="__proto__"?Object.defineProperty(a,o,{value:_,configurable:!0,enumerable:!0,writable:!0}):a[o]=_)}return a}e(iAa,"mergeRecords$1");function aAa(i){return i.flat()}e(aAa,"mergeArrays$1");function sAa(i){return new Set(fVn(i))}e(sAa,"mergeSets$1");function oAa(i){return new Map(fVn(i))}e(oAa,"mergeMaps$1");function uAa(i){return i.at(-1)}e(uAa,"mergeOthers$1");var OVt={mergeRecords:iAa,mergeArrays:aAa,mergeSets:sAa,mergeMaps:oAa,mergeOthers:uAa};function BVt(...i){return cAa({})(...i)}e(BVt,"deepmerge");function cAa(i,t){let r=lAa(i,a);function a(...o){return dVn(o,r,t)}return e(a,"customizedDeepmerge"),a}e(cAa,"deepmergeCustom");function lAa(i,t){return{defaultMergeFunctions:OVt,mergeFunctions:{...OVt,...Object.fromEntries(Object.entries(i).filter(([r,a])=>Object.hasOwn(OVt,r)).map(([r,a])=>a===!1?[r,OVt.mergeOthers]:[r,a]))},metaDataUpdater:i.metaDataUpdater??Zxa,deepmerge:t,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??eAa,actions:d7e}}e(lAa,"getUtils");function dVn(i,t,r){var c;let a=((c=t.filterValues)==null?void 0:c.call(t,i,r))??i;if(a.length===0)return;if(a.length===1)return b$r(a,t,r);let o=lVn(a[0]);if(o!==0&&o!==5){for(let f=1;f<a.length;f++)if(lVn(a[f])!==o)return b$r(a,t,r)}switch(o){case 1:return pAa(a,t,r);case 2:return fAa(a,t,r);case 3:return dAa(a,t,r);case 4:return mAa(a,t,r);default:return b$r(a,t,r)}}e(dVn,"mergeUnknowns");function pAa(i,t,r){let a=t.mergeFunctions.mergeRecords(i,t,r);return a===d7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(i,t,r):a}e(pAa,"mergeRecords");function fAa(i,t,r){let a=t.mergeFunctions.mergeArrays(i,t,r);return a===d7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(i):a}e(fAa,"mergeArrays");function dAa(i,t,r){let a=t.mergeFunctions.mergeSets(i,t,r);return a===d7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(i):a}e(dAa,"mergeSets");function mAa(i,t,r){let a=t.mergeFunctions.mergeMaps(i,t,r);return a===d7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(i):a}e(mAa,"mergeMaps");function b$r(i,t,r){let a=t.mergeFunctions.mergeOthers(i,t,r);return a===d7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(i):a}e(b$r,"mergeOthers");var mVn=!1;function uVn(i){mVn=i}e(uVn,"setLogToConsole");function Dv(...i){mVn&&console.log(...i)}e(Dv,"log");async function akn(i,t,r,a=6e4){if(!(t in i))return i;let o=e(()=>i[t](...r),"executor");return a===null?o():lD(o(),a,"Execution timeout")}e(akn,"executePlaywrightMethodWithTimeout");function x_t(i,{role:t,environment:r}={},a=!1){var _,v;let o;if(r&&(o=(_=i.environments)==null?void 0:_.find(({name:C})=>r===C)),o||(o=(v=i.environments)==null?void 0:v.find(({default:C})=>C)),!o)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let c=o.users,f;if(c&&(t!==void 0&&(f=c.find(C=>C.role===t)),f||(f=c.find(C=>C.default))),!f)throw new Error(`User not found. Please make sure the users array for the "${o.name}" environment is properly defined in the checksum.config.ts file.`);if(r&&o.name!==r){if(a)throw new Error(`Could not find environment with name "${r}" in config file`);console.warn(`Could not find environment with name "${r}" in config file, trying to use default environment`)}if(t&&f.role!==t){if(a)throw new Error(`Could not find user with role "${t}" for environment "${r}" in config file`);console.warn(`Could not find user with role "${t}" for environment "${r}" in config file, trying to login with environment's default user`)}return{environment:o,user:f}}e(x_t,"resolveEnvironment");function _Aa(i){let t=`${i??Fne()}/login.ts`;if(!(0,RVt.existsSync)(t))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${t}`),new Error("Could not find login.ts file");try{return require(t).default}catch(r){throw console.warn("Error loading login.ts file",r),r}}e(_Aa,"requireLogin");async function hAa(i,t,{environment:r,user:a,config:o}){try{let c=e(()=>t(i,{environment:r,user:a,config:o}),"performLogin");"checksumAI"in i?await i.checksumAI(`Log in${a!=null&&a.role?` using ${a.role} role`:""}${r!=null&&r.name?` in ${r.name} environment`:""}`,c):await c()}catch(c){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
1826
1826
  `,c),c}}e(hAa,"proceedWithLogin");function Dbe(i){let{config:t,folder:r,throwIfAuthFailed:a}=i,o=_Aa(r);return async(c,{role:f,environment:_}={})=>{let{environment:v,user:C}=x_t(t,{role:f,environment:_},i.throwIfEnvInfoInvalid);if(a&&!C)throw new Error("Could not find user credentials matching the provided role and/or environment");await hAa(c,o,{environment:v,user:C,config:t})}}e(Dbe,"makeUnboundLogin");function _Vn(i,{environmentName:t,userRole:r}){let a=Dbe(i);return o=>a(o,{environment:t,role:r})}e(_Vn,"makeBoundLogin");var GJe;function Tqt(){if(GJe)return GJe;try{let i=(0,RVt.existsSync)(`${Fne()}/checksum.config.ts`)?"checksum.config.ts":(0,RVt.existsSync)(`${Fne()}/checksum.config.tmp.ts`)?"checksum.config.tmp.ts":void 0;if(i)return LVt(require(`${Fne()}/${i}`).default)}catch{console.warn("Could not find checksum config file, will run with defaults")}return LVt()}e(Tqt,"loadChecksumConfig");function LVt(i={}){var r,a,o,c;let t={apiKey:void 0,runMode:"normal",apiURL:"https://api.checksum.ai",options:{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:!0,useMockData:!1,printLogs:!1,hideReports:process.env.AUTHORIZE_REPORTS==="true"}};return((a=(r=i.options)==null?void 0:r.useChecksumAI)==null?void 0:a.visualComparison)===void 0&&((c=(o=i.options)==null?void 0:o.useChecksumAI)!=null&&c.assertions)&&(i.options.useChecksumAI.visualComparison=!0),GJe=BVt(t,i),V0.testRun.disableAutoRecovery&&(GJe.options.useChecksumAI={actions:!1,assertions:!1,visualComparison:!1}),V0.testRun.disableHostReports&&(GJe.options.hostReports=!1),GJe}e(LVt,"getChecksumConfig");function NVt(i){let t=e(r=>{r.on("dialog",a=>{})},"makeDialogHandler");i.context().pages().forEach(t),i.context().on("page",r=>{t(r)})}e(NVt,"preventDialogAutoDismissal");var x4e="Checksum failed connecting to the server";var Qce=class Qce{constructor(t){this.workerInfo=t;this.hasMonitor=!1;Qce.monitorAgentPort?this.hasMonitor=!0:Dv("CHECKSUM_UPLOAD_AGENT_PORT is not defined"),this.sendPlaywrightConfig()}addAsset(t){this.signalUpload(t,["trace","har","rrweb-recording"].includes(t.type))}addChecksumTestMetadata(t){let r={type:"checksumTestMetadata",payload:t};this.sendMessage(r)}addTestInfo(t,r){this.sendMessage({type:"testInfo",payload:{checksumTestId:t,pwTestId:r}})}addSingleTestStats(t,r){this.sendMessage({type:"testStats",payload:{passed:t,healed:r}})}sendPlaywrightConfig(){Qce.playwrightConfigSent||(this.sendMessage({type:"playwrightConfig",payload:this.buildPlaywrightConfig()}),Qce.playwrightConfigSent=!0)}buildPlaywrightConfig(){let{use:t,testDir:r,testMatch:a,testIgnore:o,timeout:c,outputDir:f,retries:_}=this.workerInfo.project,{reporter:v,configFile:C,projects:w}=this.workerInfo.config,T=Object.keys(w).filter(k=>[t,r,a,o,c,f,_].includes(k)).reduce((k,R)=>({...k,[R]:w[R]}),{});return{reporter:v,configFile:C,filteredProjects:T,use:t,testDir:r,testMatch:a,testIgnore:o,timeout:c,outputDir:f,retries:_}}sendMessage(t){if(this.hasMonitor)return fetch(`${Qce.monitorAgentHost}:${Qce.monitorAgentPort}`,{method:"POST",body:JSON.stringify(t)}).catch(r=>{Dv("Failed to send message to test run monitor",t,r)})}signalUpload(t,r=!1){return this.sendMessage({type:"asset",payload:t,watch:r})}};e(Qce,"TestRunMonitorBridge"),Qce.monitorAgentHost="http://localhost",Qce.monitorAgentPort=process.env.CHECKSUM_UPLOAD_AGENT_PORT,Qce.playwrightConfigSent=!1;var MVt=Qce;var gAa=e(()=>{let t=new Error().stack.split(`
1827
1827
  `).find(r=>r.includes(".checksum.spec.ts"));if(t)return{lineNumber:parseInt(t.split(":")[1]),columnNumber:parseInt(t.split(":")[2])}},"findCodeLocationFromStackTrace"),x$r=class x$r{constructor(){this.store={};this.activeVariablesSet=new Set;return new Proxy(this,this)}clearAll(){for(let t in this.store)Object.prototype.hasOwnProperty.call(this.store,t)&&delete this.store[t];this.activeVariablesSet.clear()}getActiveVariables(){return Array.from(this.activeVariablesSet).map(t=>this.store[t])}setVariable(t,r){this.store[t]={name:t,value:r,type:r instanceof Function?"RandomValueGenerator":"FillValue"}}set(t,r,a){if(typeof r!="string")return!1;let o=gAa();return t.store[r]={name:r,value:a,type:a instanceof Function?"RandomValueGenerator":"FillValue",...o,line:""},!0}get(t,r){var a;if(r in t)return t[r];if(!(r in t.store))throw new Error(`Variable ${r} is not defined`);return t.activeVariablesSet.add(r),(a=t.store[r])==null?void 0:a.value}};e(x$r,"VariableStore");var KJe=x$r;var a_n=require("crypto");var m7e=e(i=>i.name==="up"||i.name==="k"||i.ctrl&&i.name==="p","isUpKey"),YJe=e(i=>i.name==="down"||i.name==="j"||i.ctrl&&i.name==="n","isDownKey"),hVn=e(i=>i.name==="space","isSpaceKey"),XJe=e(i=>i.name==="backspace","isBackspaceKey"),jVt=e(i=>"123456789".includes(i.name),"isNumberKey"),HP=e(i=>i.name==="enter"||i.name==="return","isEnterKey");var A$r=class A$r extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(t){super(),this.cause=t==null?void 0:t.cause}};e(A$r,"AbortPromptError");var UVt=A$r,E$r=class E$r extends Error{name="CancelPromptError";message="Prompt was canceled"};e(E$r,"CancelPromptError");var qVt=E$r,C$r=class C$r extends Error{name="ExitPromptError"};e(C$r,"ExitPromptError");var QVt=C$r,w$r=class w$r extends Error{name="HookError"};e(w$r,"HookError");var $Vt=w$r,S$r=class S$r extends Error{name="ValidationError"};e(S$r,"ValidationError");var _7e=S$r;var I$r=require("async_hooks");var VVt=require("async_hooks");var gVn=new VVt.AsyncLocalStorage;function yAa(i){return{rl:i,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}e(yAa,"createStore");function yVn(i,t){let r=yAa(i);return gVn.run(r,()=>{function a(o){r.handleChange=()=>{r.index=0,o()},r.handleChange()}return e(a,"cycle"),t(a)})}e(yVn,"withHooks");function pFe(){let i=gVn.getStore();if(!i)throw new $Vt("[Inquirer] Hook functions can only be called from within a prompt");return i}e(pFe,"getStore");function D$r(){return pFe().rl}e(D$r,"readline");function T$r(i){let t=e((...r)=>{let a=pFe(),o=!1,c=a.handleChange;a.handleChange=()=>{o=!0};let f=i(...r);return o&&c(),a.handleChange=c,f},"wrapped");return VVt.AsyncResource.bind(t)}e(T$r,"withUpdates");function ZJe(i){let t=pFe(),{index:r}=t,a={get(){return t.hooks[r]},set(c){t.hooks[r]=c},initialized:r in t.hooks},o=i(a);return t.index++,o}e(ZJe,"withPointer");function vVn(){pFe().handleChange()}e(vVn,"handleChange");var fFe={queue(i){let t=pFe(),{index:r}=t;t.hooksEffect.push(()=>{var o,c;(c=(o=t.hooksCleanup)[r])==null||c.call(o);let a=i(D$r());if(a!=null&&typeof a!="function")throw new _7e("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=a})},run(){let i=pFe();T$r(()=>{i.hooksEffect.forEach(t=>{t()}),i.hooksEffect.length=0})()},clearAll(){let i=pFe();i.hooksCleanup.forEach(t=>{t==null||t()}),i.hooksEffect.length=0,i.hooksCleanup.length=0}};function sv(i){return ZJe(t=>{let r=e(o=>{t.get()!==o&&(t.set(o),vVn())},"setFn");if(t.initialized)return[t.get(),r];let a=typeof i=="function"?i():i;return t.set(a),[a,r]})}e(sv,"useState");function $ce(i,t){ZJe(r=>{let a=r.get();(!Array.isArray(a)||t.some((c,f)=>!Object.is(c,a[f])))&&fFe.queue(i),r.set(t)})}e($ce,"useEffect");var Tie=rf(h7e(),1);var Vce=rf(require("process"),1);function bAa(){return Vce.default.platform!=="win32"?Vce.default.env.TERM!=="linux":!!Vce.default.env.WT_SESSION||!!Vce.default.env.TERMINUS_SUBLIME||Vce.default.env.ConEmuTask==="{cmd::Cmder}"||Vce.default.env.TERM_PROGRAM==="Terminus-Sublime"||Vce.default.env.TERM_PROGRAM==="vscode"||Vce.default.env.TERM==="xterm-256color"||Vce.default.env.TERM==="alacritty"||Vce.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}e(bAa,"isUnicodeSupported");var EVn={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},CVn={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},xAa={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},AAa={...EVn,...CVn},EAa={...EVn,...xAa},CAa=bAa(),wAa=CAa?AAa:EAa,Die=wAa,y5s=Object.entries(CVn);var wVn={prefix:{idle:Tie.default.blue("?"),done:Tie.default.green(Die.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(i=>Tie.default.yellow(i))},style:{answer:Tie.default.cyan,message:Tie.default.bold,error:e(i=>Tie.default.red(`> ${i}`),"error"),defaultAnswer:e(i=>Tie.default.dim(`(${i})`),"defaultAnswer"),help:Tie.default.dim,highlight:Tie.default.cyan,key:e(i=>Tie.default.cyan(Tie.default.bold(`<${i}>`)),"key")}};function SVn(i){if(typeof i!="object"||i===null)return!1;let t=i;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(i)===t}e(SVn,"isPlainObject");function DVn(...i){let t={};for(let r of i)for(let[a,o]of Object.entries(r)){let c=t[a];t[a]=SVn(c)&&SVn(o)?DVn(c,o):o}return t}e(DVn,"deepMerge");function P8(...i){let t=[wVn,...i.filter(r=>r!=null)];return DVn(...t)}e(P8,"makeTheme");function OI({status:i="idle",theme:t}){let[r,a]=sv(!1),[o,c]=sv(0),{prefix:f,spinner:_}=P8(t);return $ce(()=>{if(i==="loading"){let C,w=-1,T=setTimeout(I$r.AsyncResource.bind(()=>{a(!0),C=setInterval(I$r.AsyncResource.bind(()=>{w=w+1,c(w%_.frames.length)}),_.interval)}),300);return()=>{clearTimeout(T),clearInterval(C)}}else a(!1)},[i]),r?_.frames[o]:typeof f=="string"?f:f[i==="loading"?"idle":i]??f.idle}e(OI,"usePrefix");function xZ(i,t){return ZJe(r=>{let a=r.get();if(!a||a.dependencies.length!==t.length||a.dependencies.some((o,c)=>o!==t[c])){let o=i();return r.set({value:o,dependencies:t}),o}return a.value})}e(xZ,"useMemo");function kie(i){return sv({current:i})[0]}e(kie,"useRef");function BI(i){let t=kie(i);t.current=i,$ce(r=>{let a=!1,o=T$r((c,f)=>{a||t.current(f,r)});return r.input.on("keypress",o),()=>{a=!0,r.input.removeListener("keypress",o)}},[])}e(BI,"useKeypress");var rzn=rf(kVn(),1),nzn=rf(tzn(),1);function C_t(i,t){return i.split(`
1828
1828
  `).flatMap(r=>(0,nzn.default)(r,t,{trim:!1,hard:!0}).split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checksum-ai/runtime",
3
- "version": "2.0.5-alpha.5",
3
+ "version": "2.0.5-alpha.6",
4
4
  "description": "Checksum.ai test runtime",
5
5
  "main": "index.js",
6
6
  "dependencies": {
@@ -1834,7 +1834,7 @@ ${o.style.description(ne.description)}`:"";return[[B,ce,Fe].filter(Boolean).join
1834
1834
  ${c.style.help("(Use arrow keys to reveal more choices)")}`:X=c.style.help("(Use arrow keys)"));let ce=w9e({items:w,active:R,renderItem({item:be,isActive:De}){if(nw.isSeparator(be))return` ${be.separator}`;if(be.disabled){let Oe=typeof be.disabled=="string"?be.disabled:"(disabled)";return c.style.disabled(`${be.name} ${Oe}`)}let Fe=De?c.style.highlight:Oe=>Oe,ke=De?c.icon.cursor:" ";return Fe(`${ke} ${be.name}`)},pageSize:a,loop:r});if(f==="done")return`${b} ${W} ${c.style.answer(U.short)}`;let fe=U.description?`
1835
1835
  ${c.style.description(U.description)}`:"";return`${[b,W,X].filter(Boolean).join(" ")}
1836
1836
  ${ce}${ne}${fe}${h8n.default.cursorHide}`});var qVt=kf(require("child_process")),jI=require("fs"),MI=require("path");var kPn=kf(yPn());var Qme=kf(require("path")),oBr=require("fs");var tBr=require("path"),yUt=require("fs");function oca(i,t,r=10){let a=i;for(let o=0;o<r;o++){let c=(0,tBr.join)(a,"package.json");if((0,yUt.existsSync)(c))try{if(JSON.parse((0,yUt.readFileSync)(c,"utf8")).name===t)return a}catch{}a=(0,tBr.join)(a,"..")}}e(oca,"findRepositoryRoot");function vPn(i,t=10){return oca(i,"checksum-customer-engineering-workspace",t)}e(vPn,"findCustomerEngineeringRoot");var uBr=kf(CPn());var Mw=e((i,t)=>{if(i==null||i==="")return(t==null?void 0:t.default)??!1;let r=i.toLowerCase().trim();return r==="true"?!0:r==="false"?!1:(t==null?void 0:t.default)??!1},"parseBoolean");var Cca=__dirname,wPn=Qme.join(__dirname,".."),TPn=(0,oBr.existsSync)(wPn)?wPn:Cca;(0,uBr.config)({path:Qme.resolve(TPn,".env")});var aBr=Mw(process.env.CHECKSUM_RUNTIME_DEV_MODE);function wca(){let i=__dirname;for(;!(0,oBr.existsSync)(Qme.join(i,"package.json"));)i=Qme.join(i,"..");return i}e(wca,"findRoot");var ize=wca(),Sca=vPn(ize,10);(0,uBr.config)({path:[TPn,Sca].filter(Boolean).map(i=>Qme.resolve(i,".env")),override:!1});var bUt=Mw(process.env.CHECKSUM_VTG_E2E_TEST_MODE),SPn=Qme.join(ize,"vtg-build","index.html"),sBr=bUt?!0:Mw(process.env.CHECKSUM_RUNTIME_REPO_MODE),DPn=Mw(process.env.CHECKSUM_VTG_SEPARATE_PROCESS),Dca=sBr?Qme.join(ize,"package","pw-report-template.html"):Qme.join(ize,"pw-report-template.html"),Tca=Mw(process.env.CHECKSUM_DEBUG_ANALYTICS),kca=Mw(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),i_={isDevMode:aBr,isRepoMode:sBr,CI:!!process.env.CI,checksumRootFolderBypass:bUt?"packages/runtime/test/e2e/checksum":sBr&&process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE?process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE:process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS,logLevel:process.env.CHECKSUM_RUNTIME_LOG_LEVEL??"warnings",checksumScript:{source:process.env.CHECKSUM_RUNTIME_SCRIPT_SOURCE??(aBr?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:ize+"/checksumlib.js"},runtimeRoot:ize,playwrightReporter:{htmlReportTemplatePath:Dca},bypassProxyForLocalhost:Mw(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),promptKillActivePlaywrightProcesses:Mw(process.env.CHECKSUM_RUNTIME_PROMPT_KILL_ACTIVE_PLAYWRIGHT_PROCESSES,{default:!0}),useCLIDebug:Mw(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),useRemoteDebugging:{enabled:Mw(process.env.CHECKSUM_RUNTIME_USE_REMOTE_DEBUGGING),port:parseInt(process.env.CHECKSUM_AGENT_RUNTIME_REMOTE_DEBUGGING_PORT??"9500")},testRun:{timeMachine:{active:!0,headless:!Mw(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:Mw(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0})},monitoring:{defaultProvider:process.env.CHECKSUM_RUNTIME_MONITORING_DEFAULT_PROVIDER??"newrelic",debugAnalytics:Tca,logToConsole:kca,newrelic:{appName:process.env.CHECKSUM_RUNTIME_MONITORING_NEWRELIC_APP_NAME??"checksum-runtime",licenseKey:"b4f3f644f40df19fe3d385c75428a450FFFFNRAL",logging:Mw(process.env.NEW_RELIC_LOG_ENABLED,{default:!1})},segment:{writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},autoRecovery:{verboseConsoleLog:Mw(process.env.CHECKSUM_RUNTIME_AUTO_RECOVERY_CONSOLE_LOG,{default:!1}),sessionTimeout:18e4},disableAutoRecovery:Mw(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:Mw(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),request:{userEmail:process.env.CHECKSUM_RUNTIME_REQUEST_USER_EMAIL,reason:process.env.CHECKSUM_RUNTIME_REQUEST_REASON},platform:{name:process.env.CHECKSUM_RUNTIME_PLATFORM_NAME,jobURL:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_URL,jobName:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_NAME},runType:process.env.CHECKSUM_RUNTIME_RUN_TYPE},vtg:{isSeparateProcess:DPn,isE2ETestMode:bUt,writeLogFile:Mw(process.env.CHECKSUM_VTG_WRITE_LOG_FILE,{default:!0}),appSource:process.env.CHECKSUM_VTG_APP_SOURCE??(aBr?"served-app":"served-build-file"),localUrl:`file://${SPn}`,localBuildPath:SPn,appURL:process.env.CHECKSUM_VTG_APP_URL,writeRrwebEventsToFile:Mw(process.env.CHECKSUM_VTG_RECORD_EVENTS_TO_FILE),useFakeStory:Mw(process.env.CHECKSUM_VTG_USE_FAKE_STORY)||bUt,logAPIServer:{interval:Mw(process.env.CHECKSUM_VTG_LOG_API_SERVER_INTERVAL),httpTransactions:Mw(process.env.CHECKSUM_VTG_LOG_API_SERVER_HTTP_TRANSACTIONS,{default:!0})},customerEngRepoInternalUtilsRelativePath:process.env.CHECKSUM_VTG_CUSTOMER_ENG_REPO_INTERNAL_UTILS_RELATIVE_PATH??"tools/internal-utils.ts",fakeStory:{goal:process.env.CHECKSUM_VTG_FAKE_STORY_GOAL??"Send email via outreach list",instructions:process.env.CHECKSUM_VTG_FAKE_STORY_INSTRUCTIONS??"Make sure to select a user from the list first"},fakeTestGeneration:{internalTestId:process.env.CHECKSUM_VTG_FAKE_STORY_INTERNAL_TEST_ID??`tempID${Date.now().toString().slice(-5)}`,generationBatchId:process.env.CHECKSUM_VTG_FAKE_GENERATION_BATCH_ID??`tempID${Date.now().toString().slice(-5)}`},remoteDebugging:DPn?!0:Mw(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING),appRemoteDebuggingPort:parseInt(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING_PORT??"9230"),vtgRemoteDebuggingPort:parseInt(process.env.CHECKSUM_VTG_REMOTE_DEBUGGING_PORT??"9231"),taskTimeMachine:{showTaskTimeMachine:Mw(process.env.CHECKSUM_VTG_SHOW_TASK_TIME_MACHINE),taskTimeout:parseInt(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_TIMEOUT??"240000"),debugPort:parseInt(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_DEBUG_PORT??"9232"),logPerformance:Mw(process.env.CHECKSUM_VTG_TASK_TIME_MACHINE_LOG_PERFORMANCE,{default:!0})},aiAssertions:{disabled:Mw(process.env.CHECKSUM_VTG_AI_ASSERTIONS_DISABLED),allowRefactoring:Mw(process.env.CHECKSUM_VTG_ALLOW_AI_ASSERTIONS_REFACTORING),allowFiltering:Mw(process.env.CHECKSUM_VTG_ALLOW_AI_ASSERTIONS_FILTERING),logPerformance:Mw(process.env.CHECKSUM_VTG_AI_ASSERTIONS_LOG_PERFORMANCE,{default:!1})},aiLocators:{disabled:Mw(process.env.CHECKSUM_VTG_AI_LOCATORS_DISABLED),useFakeAILocators:Mw(process.env.CHECKSUM_VTG_USE_FAKE_AI_LOCATORS)}},benchmark:Mw(process.env.BENCHMARK_MODE),buildTime:process.env.CHECKSUM_RUNTIME_BUILD_TIME??"unknown",llm:{models:{openai:{key:process.env.CHECKSUM_RUNTIME_OPENAI_API_KEY},anthropic:{key:process.env.CHECKSUM_RUNTIME_ANTHROPIC_API_KEY},gemini:{model:process.env.CHECKSUM_RUNTIME_GEMINI_MODEL},groq:{apiKey:process.env.CHECKSUM_RUNTIME_GROQ_API_KEY}}},gcp:{credentialsFile:process.env.CHECKSUM_RUNTIME_GCP_CREDENTIALS_FILE}};var aze=class aze{constructor(t,r,a,o,c){this.traits=t;this.flushPromise=null;this.client=null;this.initialized=!1;this.isolatedMode=r,this.debugAnalytics=a,this.shouldLogToConsole=o,this.config=c||{enabled:!0,debugMode:a,logToConsole:o}}async executeWithPromise(t){return this.flushPromise?this.flushPromise:(this.flushPromise=(async()=>{try{await t()}finally{this.flushPromise=null}})(),this.flushPromise)}static flattenEvent(t){let r=e((a,o=[])=>{if(a==null||typeof a!="object")return{};try{return Object.entries(a).reduce((c,[f,_])=>{let b=[...o,f],C=b.join(".");if(typeof _=="object"&&_!==null&&!Array.isArray(_)){let w=r(_,b);Object.assign(c,w)}else c[C]=_;return c},{})}catch{return{}}},"flattenDeep");return r(t)}get analyticsEnabled(){var t;return this.isolatedMode&&!this.debugAnalytics?!1:((t=this.config)==null?void 0:t.enabled)??!0}get metadata(){return{...this.traits}}makeTableName(t){let r=this.debugAnalytics?"dev":"";return r?`${r}_${t}`:t}trackEventWithTable(t,r,a,o){if(o||this.shouldLogToConsole){let c=aze.flattenEvent(t);console.log("Analytics event tracked:",{eventType:t.event,tableName:this.makeTableName(a),testSuiteRunId:r.testSuiteRunId,metadata:r,eventData:c,timestamp:new Date().toISOString()})}this.trackEventWithTableImpl(t,r,a,o)}trackEventWithTableImpl(t,r,a,o=!1){!this.analyticsEnabled||!this.config.enabled||(this.initialized||(this.initializeClient(),this.initialized=!0),this.safeExecute(()=>{let f={...aze.flattenEvent(t),tableName:this.makeTableName(a),testSuiteRunId:r.testSuiteRunId,eventType:t.event,...r};this.sendEvent(f,a),(o||this.shouldLogToConsole)&&this.logEvent(t.event,f)},"tracking event"))}flushEvents(){return Promise.resolve()}async close(){if(!(!this.analyticsEnabled||!this.config.enabled||!this.initialized))return this.executeWithPromise(async()=>{await this.safeExecuteAsync(async()=>{await this.flushEvents(),this.shouldLogToConsoleEnabled&&console.log(`${this.getProviderName()} analytics session ended successfully`)},"closing analytics session")})}safeExecute(t,r){try{t()}catch(a){this.handleError(a,r)}}async safeExecuteAsync(t,r){try{await t()}catch(a){this.handleError(a,r)}}handleError(t,r){this.shouldLogToConsoleEnabled&&console.error(`Error ${r} in ${this.getProviderName()}:`,t.message)}logEvent(t,r){console.log(`${this.getProviderName()} event tracked: ${t}`,r)}get isClientReady(){return this.initialized&&this.client!==null}get shouldLogToConsoleEnabled(){return this.shouldLogToConsole}};e(aze,"AbstractAnalytics"),aze.DEFAULT_TABLE="generic_events";var sze=aze;var cBr=class cBr extends sze{constructor(r,a){let o={writeKey:i_.testRun.monitoring.segment.writeKey,enabled:!!i_.testRun.monitoring.segment.writeKey,debugMode:i_.testRun.monitoring.debugAnalytics,logToConsole:i_.testRun.monitoring.logToConsole};super(r,a,i_.testRun.monitoring.debugAnalytics,i_.testRun.monitoring.logToConsole,o);this.traits=r}initializeClient(){this.client||(this.client=new kPn.default({writeKey:this.config.writeKey,flushAt:1,flushInterval:1e3}))}sendEvent(r,a){this.client&&this.client.track({anonymousId:r.testSuiteRunId,event:r.eventType,properties:r})}async flushEvents(){this.client&&await dT(this.client.flush(),2e4)}getProviderName(){return"Segment"}};e(cBr,"SegmentRuntimeAnalytics");var xUt=cBr;var lBr=class lBr extends sze{constructor(r,a){let o={licenseKey:i_.testRun.monitoring.newrelic.licenseKey,appName:i_.testRun.monitoring.newrelic.appName,logging:i_.testRun.monitoring.newrelic.logging,enabled:!!i_.testRun.monitoring.newrelic.licenseKey,debugMode:i_.testRun.monitoring.debugAnalytics,logToConsole:i_.testRun.monitoring.logToConsole};super(r,a,i_.testRun.monitoring.debugAnalytics,i_.testRun.monitoring.logToConsole,o);this.traits=r}initializeClient(){this.client||(process.env.NEW_RELIC_LICENSE_KEY=this.config.licenseKey,process.env.NEW_RELIC_APP_NAME=this.config.appName,process.env.NEW_RELIC_LOG_ENABLED=this.config.logging.toString(),this.client=require("newrelic"))}sendEvent(r,a){this.client&&this.client.recordCustomEvent(this.makeTableName(a),r)}getProviderName(){return"New Relic"}recordMetric(r,a){!this.analyticsEnabled||!this.config.enabled||!this.isClientReady||this.safeExecute(()=>{this.client.recordMetric(r,a)},"recording metric")}addCustomAttributes(r){!this.analyticsEnabled||!this.config.enabled||!this.isClientReady||this.safeExecute(()=>{this.client.addCustomAttributes(r)},"adding custom attributes")}noticeError(r,a){!this.analyticsEnabled||!this.config.enabled||!this.isClientReady||this.safeExecute(()=>{this.client.noticeError(r,a)},"recording error")}};e(lBr,"NewRelicRuntimeAnalytics");var AUt=lBr;var pBr=class pBr{static createAnalytics(t,r={},a=!1,o=!1){switch(t){case"segment":return new xUt(r,a);case"newrelic":return new AUt(r,a);default:throw new Error(`Unsupported analytics provider: ${t}`)}}static createFromConfig(t={},r=!1,a=!1){return i_.testRun.monitoring.defaultProvider==="newrelic"?this.createAnalytics("newrelic",t,r,a):this.createAnalytics("segment",t,r)}};e(pBr,"AnalyticsFactory");var $me=pBr;var W9e=class W9e{constructor(t,r){this.analytics=$me.createFromConfig(t,r)}static getInstance(t={},r=!1){return W9e.instance||(W9e.instance=new W9e(t,r)),W9e.instance}get tableName(){return"runtime"}event(t){this.analytics.trackEventWithTable(t,this.metadata,this.tableName)}checksumConfig(t){this.event({event:"Checksum Config",metadata:this.metadata,config:t})}eventWithMessage(t,r){this.event({event:t,metadata:this.metadata,message:r})}get metadata(){return{...this.analytics.metadata,appName:"unknown",commitHash:"unknown",envName:"unknown",branch:"unknown",testSuiteRunId:"unknown",checksumRuntimeVersion:"unknown",...this.analytics.metadata}}async close(){return this.analytics.close()}};e(W9e,"RuntimeAnalytics");var EUt=W9e;var Vme=(C=>(C.Locator="locator",C.GetByRole="getByRole",C.GetByText="getByText",C.GetByLabel="getByLabel",C.GetByPlaceholder="getByPlaceholder",C.GetByAltText="getByAltText",C.GetByTitle="getByTitle",C.GetByTestId="getByTestId",C.FrameLocator="frameLocator",C))(Vme||{});var oze=(f=>(f.First="first",f.Last="last",f.Nth="nth",f.Filter="filter",f.Or="or",f.And="and",f))(oze||{});uQ();var Mca=!1,gBr=class gBr{constructor(){this.frames={};this.pages=[];this.channels={};this.events=[];this.pendingMessages={};this.uuid=db();this.log=e(t=>{Mca&&console.log(`[FramesMsgBroker] ${this.uuid}:
1837
- ${t}`)},"log");this.exposeFunctionsPromises=new WeakMap}getFrameName(t){return Object.keys(this.frames).find(a=>this.frames[a]===t)}async safeExposeFunction(t,r,a){try{await t.exposeFunction(r,a),this.log(`[safeExposeFunction] ${r} exposed successfully`)}catch(o){this.log(`[safeExposeFunction] ${r}: ${o.message}`)}}async register(t,r,a){if(this.log(`[register] ${t} ${AI(r)}`),this.frames[t]){let f=r.page(),_=this.exposeFunctionsPromises.get(f);_&&await _;return}this.frames[t]=r;let o=r.page();if(this.pages.includes(o)){let f=this.exposeFunctionsPromises.get(o);f&&await f;return}this.pages.push(o);let c=(async()=>{await this.safeExposeFunction(o,"checksumSendMessage",async(f,_,b=!1)=>{var w;this.log(`[checksumSendMessage] from ${t} to ${f}`);let C=this.frames[f];if(!C){if(b){(w=this.pendingMessages)[f]??(w[f]=[]),this.pendingMessages[f].push(_);return}throw new Error(`Frame ${f} not found`)}try{await C.evaluate(({message:T})=>{window.postMessage(T,"*")},{message:_})}catch{}}),await this.safeExposeFunction(o,"checksumSendBroadcastMessage",async(f,_)=>{let b=this.channels[f]??[];if(this.log(`[checksumSendBroadcastMessage] on channel ${f} from ${t}`),this.log(`subscribers: ${b.map(C=>`(${C.originFrameGuid}) ${C.frame.url()}`).join(", ")}`),a){let C=require("fs"),w=require("path");this.events.push(..._),this.events.length%10===0&&C.writeFileSync(w.join(process.cwd(),"rrweb-player","events.json"),JSON.stringify(this.events))}b.forEach(async C=>{if(C.originFrameGuid&&C.originFrameGuid!==AI(r))return;let w=this.getFrameName(C.frame);this.log(`handling message from ${t} to subscriber ${w}`);try{C.handler?await C.handler(_):await r.evaluate(({message:T})=>{window.postMessage(T,"*")},{message:_})}catch{}})}),await this.safeExposeFunction(o,"checksumBringPageToFront",async f=>{let _=this.frames[f];_&&await _.page().bringToFront()})})();this.exposeFunctionsPromises.set(o,c),await c,this.pendingMessages[t]&&(this.pendingMessages[t].forEach(async f=>{try{await r.evaluate(({message:_})=>{window.postMessage(_,"*")},{message:f})}catch{}}),delete this.pendingMessages[t])}subscribeToChannel(t,r,{originFrame:a,handler:o}={}){var c;this.log(`[subscribeToChannel] ${t} frame ${AI(r)}`),(c=this.channels)[t]??(c[t]=[]),this.channels[t].push({frame:r,originFrameGuid:a?AI(a):void 0,handler:o})}unsubscribeFromChannel(t,r){var a;(a=this.channels)[t]??(a[t]=[]),this.channels[t]=this.channels[t].filter(o=>o.frame!==r)}};e(gBr,"FramesMsgBroker");var Xdt=gBr;var iAa=kf(oLr());var uLr=class uLr{constructor(){this.config={}}};e(uLr,"PageInteractorAPI");var vqt=uLr;var cLr=class cLr{constructor(t){this.options=t;this.health=e(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(t=>(console.log(t),null)),"health");this.getCanvasDetection=e(async t=>{try{let r=t.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:r}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(r){return console.log(r),null}},"getCanvasDetection")}};e(cLr,"ChecksumClient");var Oze=cLr;var lLr=class lLr extends vqt{constructor(r){super();this.config=r;this.getTextDetection=e(async r=>{let a=await this.api.getCanvasDetection(r);if(!a)throw new Error("No data returned from canvas detection");return a},"getTextDetection");this.config=r,this.api=new Oze({apiKey:r.apiKey,apiURL:r.apiURL})}};e(lLr,"RuntimePageInteractorAPI");var O0t=lLr;var pLr=kf(require("fs"));function y0a(i){return i.replace(/(\s*)try\s*\{([\s\S]*?)\}[\s\n]*catch\s*\(.*?\)\s*\{[\s\S]*?\}[\s\n]*\1testInfo\.status\s*=\s*["']failed["'];?/g,(t,r,a)=>a.trimEnd())}e(y0a,"removeTryCatchAndTestInfo");var fLr=class fLr{static toString(t,r){let a=tRn(t,r);return Object.entries(a).map(([o,c])=>`
1837
+ ${t}`)},"log");this.exposeFunctionsPromises=new WeakMap}getFrameName(t){return Object.keys(this.frames).find(a=>this.frames[a]===t)}async safeExposeFunction(t,r,a){try{await t.exposeFunction(r,a),this.log(`[safeExposeFunction] ${r} exposed successfully`)}catch(o){this.log(`[safeExposeFunction] ${r}: ${o.message}`)}}async register(t,r,a){if(this.log(`[register] ${t} ${AI(r)}`),this.frames[t]){let f=r.page(),_=this.exposeFunctionsPromises.get(f);_&&await _;return}this.frames[t]=r;let o=r.page();if(this.pages.includes(o)){let f=this.exposeFunctionsPromises.get(o);f&&await f;return}this.pages.push(o);let c=(async()=>{await this.safeExposeFunction(o,"checksumSendMessage",async(f,_,b=!1)=>{var w;this.log(`[checksumSendMessage] from ${t} to ${f}`);let C=this.frames[f];if(!C){if(b){(w=this.pendingMessages)[f]??(w[f]=[]),this.pendingMessages[f].push(_);return}throw new Error(`Frame ${f} not found`)}try{await C.evaluate(({message:T})=>{window.postMessage(T,"*")},{message:_})}catch{}}),await this.safeExposeFunction(o,"checksumSendBroadcastMessage",async(f,_)=>{let b=this.channels[f]??[];if(this.log(`[checksumSendBroadcastMessage] on channel ${f} from ${t}`),this.log(`subscribers: ${b.map(C=>`(${C.originFrameGuid}) ${C.frame.url()}`).join(", ")}`),a){let C=require("fs"),w=require("path");this.events.push(..._),this.events.length%10===0&&C.writeFileSync(w.join(process.cwd(),"rrweb-player","events.json"),JSON.stringify(this.events))}b.forEach(async C=>{if(C.originFrameGuid&&C.originFrameGuid!==AI(r))return;let w=this.getFrameName(C.frame);this.log(`handling message from ${t} to subscriber ${w}`);try{C.handler?await C.handler(_):await r.evaluate(({message:T})=>{window.postMessage(T,"*")},{message:_})}catch{}})}),await this.safeExposeFunction(o,"checksumBringPageToFront",async f=>{let _=this.frames[f];_&&await _.page().bringToFront()})})();this.exposeFunctionsPromises.set(o,c),await c,this.pendingMessages[t]&&(this.pendingMessages[t].forEach(async f=>{try{await r.evaluate(({message:_})=>{window.postMessage(_,"*")},{message:f})}catch{}}),delete this.pendingMessages[t])}subscribeToChannel(t,r,{originFrame:a,handler:o}={}){var c;this.log(`[subscribeToChannel] ${t} frame ${AI(r)}`),(c=this.channels)[t]??(c[t]=[]),this.channels[t].push({frame:r,originFrameGuid:a?AI(a):void 0,handler:o})}unsubscribeFromChannel(t,r){var a;(a=this.channels)[t]??(a[t]=[]),this.channels[t]=this.channels[t].filter(o=>o.frame!==r)}unregister(t){this.log(`[unregister] ${t}`);let r=this.frames[t];if(!r)return;delete this.frames[t],delete this.pendingMessages[t];let a=r.page();if(!Object.values(this.frames).some(c=>c.page()===a)){let c=this.pages.indexOf(a);c!==-1&&this.pages.splice(c,1)}for(let c of Object.keys(this.channels))this.channels[c]=this.channels[c].filter(f=>f.frame!==r),this.channels[c].length===0&&delete this.channels[c]}cleanup(){this.log("[cleanup] Cleaning up all resources"),this.frames={},this.pages=[],this.channels={},this.events=[],this.pendingMessages={}}};e(gBr,"FramesMsgBroker");var Xdt=gBr;var iAa=kf(oLr());var uLr=class uLr{constructor(){this.config={}}};e(uLr,"PageInteractorAPI");var vqt=uLr;var cLr=class cLr{constructor(t){this.options=t;this.health=e(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(t=>(console.log(t),null)),"health");this.getCanvasDetection=e(async t=>{try{let r=t.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:r}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(r){return console.log(r),null}},"getCanvasDetection")}};e(cLr,"ChecksumClient");var Oze=cLr;var lLr=class lLr extends vqt{constructor(r){super();this.config=r;this.getTextDetection=e(async r=>{let a=await this.api.getCanvasDetection(r);if(!a)throw new Error("No data returned from canvas detection");return a},"getTextDetection");this.config=r,this.api=new Oze({apiKey:r.apiKey,apiURL:r.apiURL})}};e(lLr,"RuntimePageInteractorAPI");var O0t=lLr;var pLr=kf(require("fs"));function y0a(i){return i.replace(/(\s*)try\s*\{([\s\S]*?)\}[\s\n]*catch\s*\(.*?\)\s*\{[\s\S]*?\}[\s\n]*\1testInfo\.status\s*=\s*["']failed["'];?/g,(t,r,a)=>a.trimEnd())}e(y0a,"removeTryCatchAndTestInfo");var fLr=class fLr{static toString(t,r){let a=tRn(t,r);return Object.entries(a).map(([o,c])=>`
1838
1838
  ${c}`).join("")}static toRecord(t,r){return tRn(t,r)}};e(fLr,"ErrorFormatter");var Bze=fLr;function tRn(i,t){let a=(i.stack||"No stack trace available").split(`
1839
1839
  `),o={};for(let f of a){let _=f.match(/\(([^)]+):(\d+):(\d+)\)/)||f.match(/at ((?:[a-zA-Z]:\\|\/)[^:]+):(\d+):(\d+)/);if(_){let b=_[1];if(!b.includes(t)||b.includes("node_modules")||b.includes("<anonymous>")||b.includes("internal")||b.includes("loader")||b.startsWith("eval"))continue;try{if(!o[b]&&pLr.default.existsSync(b)){let C=pLr.default.readFileSync(b,"utf-8");o[b]=y0a(C)}}catch(C){o[b]=`Error reading file: ${C.message}`}}}let c={};for(let[f,_]of Object.entries(o)){let b=`
1840
1840
  --- File: ${f} ---