@testrelic/playwright-analytics 2.16.4-next.167 → 2.16.4-next.191

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.
@@ -1,10 +1,10 @@
1
- import {randomUUID,createHash}from'crypto';import {writeFileSync,renameSync,mkdirSync,copyFileSync,unlinkSync,existsSync,readFileSync,appendFileSync,readdirSync,statSync,openSync,readSync,closeSync,createReadStream,rmSync}from'fs';import {join,dirname,resolve,relative,extname,basename}from'path';import {tmpdir,platform}from'os';import {isValidConfig,createError,ErrorCode,ATTACHMENT_NAME,isTestRelicFilePayload,isTestRelicDataPayload,isValidEndpointUrl,isValidCloudConfig,isValidQueueEntry}from'@testrelic/core';import {spawn,execFile,execSync}from'child_process';import {createServer}from'http';import {createInterface}from'readline';import {copyFile}from'fs/promises';import {gzip}from'zlib';import {promisify}from'util';import {Readable}from'stream';var us=".testrelic-report";function Be(e,t,r,a){let s=`${e}|${t.join("|")}|${r}|${a}`;return createHash("sha256").update(s).digest("hex").substring(0,12)}function Oe(e,t,r){let a=`${e}|${t.join("|")}|${r}`;return createHash("sha256").update(a).digest("hex").substring(0,12)}var ie=class{constructor(t){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=join(t,us),this.testsDir=join(this.reportDir,"tests"),mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(t,r,a){try{let s=join(this.testsDir,t);mkdirSync(s,{recursive:!0});let n=join(s,"meta.json"),o=n+".tmp",i=JSON.stringify(r);return writeFileSync(o,i,"utf-8"),renameSync(o,n),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),a?.networkRequestsFile&&this.moveFile(a.networkRequestsFile,join(s,"network.jsonl")),a?.consoleLogsFile&&this.moveFile(a.consoleLogsFile,join(s,"console.jsonl")),a?.apiCallsFile&&this.moveFile(a.apiCallsFile,join(s,"api-calls.jsonl")),!0}catch(s){let n=s instanceof Error?s.message:String(s);return this.writeErrors.push({testId:t,error:n,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${t}: ${n}
1
+ import {randomUUID,createHash}from'crypto';import {writeFileSync,renameSync,mkdirSync,copyFileSync,unlinkSync,existsSync,readFileSync,appendFileSync,readdirSync,statSync,openSync,readSync,closeSync,createReadStream,rmSync}from'fs';import {join,dirname,resolve,relative,extname,basename}from'path';import {tmpdir,platform}from'os';import {isValidConfig,createError,ErrorCode,ATTACHMENT_NAME,isTestRelicFilePayload,isTestRelicDataPayload,isValidEndpointUrl,isValidCloudConfig,isValidQueueEntry}from'@testrelic/core';import {spawn,execFile,execSync}from'child_process';import {createServer}from'http';import {createInterface}from'readline';import {copyFile}from'fs/promises';import {gzip}from'zlib';import {promisify}from'util';import {Readable}from'stream';var fs=".testrelic-report";function Be(e,t,r,a){let s=`${e}|${t.join("|")}|${r}|${a}`;return createHash("sha256").update(s).digest("hex").substring(0,12)}function Oe(e,t,r){let a=`${e}|${t.join("|")}|${r}`;return createHash("sha256").update(a).digest("hex").substring(0,12)}var ie=class{constructor(t){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=join(t,fs),this.testsDir=join(this.reportDir,"tests"),mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(t,r,a){try{let s=join(this.testsDir,t);mkdirSync(s,{recursive:!0});let n=join(s,"meta.json"),i=n+".tmp",o=JSON.stringify(r);return writeFileSync(i,o,"utf-8"),renameSync(i,n),this.totalBytesWritten+=Buffer.byteLength(o,"utf-8"),a?.networkRequestsFile&&this.moveFile(a.networkRequestsFile,join(s,"network.jsonl")),a?.consoleLogsFile&&this.moveFile(a.consoleLogsFile,join(s,"console.jsonl")),a?.apiCallsFile&&this.moveFile(a.apiCallsFile,join(s,"api-calls.jsonl")),!0}catch(s){let n=s instanceof Error?s.message:String(s);return this.writeErrors.push({testId:t,error:n,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${t}: ${n}
2
2
  `),false}}moveFile(t,r){try{renameSync(t,r);}catch{try{copyFileSync(t,r);try{unlinkSync(t);}catch{}}catch(a){process.stderr.write(`[testrelic] Failed to move file ${t} \u2192 ${r}: ${a instanceof Error?a.message:String(a)}
3
- `);}}}writeIndex(t){let r=join(this.reportDir,"index.json"),a=r+".tmp",s=JSON.stringify(t);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(t){let r=join(this.reportDir,"index-compact.json"),a=r+".tmp",s=t.map(({titlePath:o,project:i,...l})=>l),n=JSON.stringify(s);writeFileSync(a,n,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeSummary(t){let r=join(this.reportDir,"summary.json"),a=r+".tmp",s=JSON.stringify(t);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(t){let r=join(this.reportDir,"manifest.json"),a=r+".tmp",s=JSON.stringify(t);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var dr=".testrelic",vs="testrelic-config.json",bs=".testrelic",ys=5,xs=new Set(["__proto__","constructor","prototype"]),or=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,uploadBudgetMs:12e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${dr}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),ws={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function cr(e){let t=resolve(e);for(let r=0;r<=ys;r++){let a=join(t,dr,vs);if(existsSync(a))try{if(statSync(a).isFile())return a}catch{}let s=join(t,bs);if(existsSync(s))try{if(statSync(s).isFile())return process.stderr.write(`[testrelic] Deprecation: config file ".testrelic" has moved to ".testrelic/testrelic-config.json". Please migrate your config file to the new location.
4
- `),s}catch{}let n=dirname(t);if(n===t)break;t=n;}return null}function ur(e){try{let t=readFileSync(e,"utf-8"),r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)||!pr(r)?null:r}catch{return null}}function pr(e){for(let t of Object.keys(e)){if(xs.has(t))return false;let r=e[t];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!pr(r))return false}return true}function fr(e){let t=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(e);if(t)return process.env[t[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);return r?process.env[r[1]]??null:e}function Ue(e){let t=Object.create(null);for(let r of Object.keys(e)){let a=e[r];typeof a=="string"&&a.startsWith("$")?t[r]=fr(a):typeof a=="object"&&a!==null&&!Array.isArray(a)?t[r]=Ue(a):t[r]=a;}return t}function lr(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let r=parseInt(t[1],10),a=t[2],s=ws[a];return !s||r<=0?null:r*s}function gr(e,t){let r=Object.create(null);if(Object.assign(r,or),e){let l=e.cloud;l&&typeof l=="object"&&(typeof l.endpoint=="string"&&(r.endpoint=l.endpoint),typeof l.upload=="string"&&(r.uploadStrategy=l.upload),typeof l.timeout=="number"&&(r.timeout=l.timeout),typeof l.uploadBudgetMs=="number"&&(r.uploadBudgetMs=l.uploadBudgetMs),typeof l.apiKey=="string"&&l.apiKey.length>0&&(r.apiKey=l.apiKey));let d=e["testrelic-repo"]??e.project;d&&typeof d=="object"&&typeof d.name=="string"&&(r.projectName=d.name),e.project&&!e["testrelic-repo"]&&process.stderr.write(`[testrelic] Deprecation: "project" key in config is deprecated. Rename it to "testrelic-repo".
5
- `);let c=e.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let p=lr(c.maxAge);p!==null&&(r.queueMaxAge=p);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(t){if(typeof t.apiKey=="string"&&t.apiKey.length>0){let l=t.apiKey.startsWith("$")?fr(t.apiKey):t.apiKey;l&&(r.apiKey=l);}if(typeof t.endpoint=="string"&&(r.endpoint=t.endpoint),typeof t.upload=="string"&&(r.uploadStrategy=t.upload),typeof t.timeout=="number"&&(r.timeout=t.timeout),typeof t.uploadBudgetMs=="number"&&(r.uploadBudgetMs=t.uploadBudgetMs),typeof t.projectName=="string"&&(r.projectName=t.projectName),typeof t.queueMaxAge=="string"){let l=lr(t.queueMaxAge);l!==null&&(r.queueMaxAge=l);}typeof t.queueDirectory=="string"&&(r.queueDirectory=t.queueDirectory),typeof t.uploadArtifacts=="boolean"&&(r.uploadArtifacts=t.uploadArtifacts),typeof t.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=t.artifactMaxSizeMb);}let a=process.env.TESTRELIC_API_KEY;a&&a.length>0&&(r.apiKey=a);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&isValidEndpointUrl(s)&&(r.endpoint=s);let n=process.env.TESTRELIC_UPLOAD_STRATEGY;n&&["batch","realtime","both"].includes(n)&&(r.uploadStrategy=n);let o=process.env.TESTRELIC_CLOUD_TIMEOUT;if(o){let l=parseInt(o,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let i=Object.freeze(r);return isValidCloudConfig(i)?i:or}var Ts=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],Rs=["authorization","cookie","set-cookie","x-api-key"],As=["password","secret","token","apiKey","api_key"];function hr(e){let t=Object.create(null);return t.trackApiCalls=e?.trackApiCalls??true,t.captureRequestHeaders=e?.captureRequestHeaders??true,t.captureResponseHeaders=e?.captureResponseHeaders??true,t.captureRequestBody=e?.captureRequestBody??true,t.captureResponseBody=e?.captureResponseBody??true,t.captureAssertions=e?.captureAssertions??true,t.redactHeaders=e?.redactHeaders??[...Rs],t.redactBodyFields=e?.redactBodyFields??[...As],t.apiIncludeUrls=e?.apiIncludeUrls??[],t.apiExcludeUrls=e?.apiExcludeUrls??[],Object.freeze(t)}function mr(e){if(e!==void 0&&!isValidConfig(e))throw createError(ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let t=Object.create(null);t.outputPath=e?.outputPath??"./test-results/analytics-timeline.json",t.includeStackTrace=e?.includeStackTrace??false,t.includeCodeSnippets=e?.includeCodeSnippets??true,t.codeContextLines=e?.codeContextLines??3,t.includeNetworkStats=e?.includeNetworkStats??true,t.captureNavigation=e?.captureNavigation??true,t.navigationTypes=e?.navigationTypes??null,t.redactPatterns=[...Ts,...e?.redactPatterns??[]],t.testRunId=e?.testRunId??null,t.metadata=e?.metadata??null;let r=t.outputPath;t.openReport=e?.openReport??true,t.htmlReportPath=e?.htmlReportPath??r.replace(/\.json$/,".html"),t.includeArtifacts=e?.includeArtifacts??true,t.trackApiCalls=e?.trackApiCalls??true,t.quiet=e?.quiet??false,t.includeActionSteps=e?.includeActionSteps??true,t.captureConsoleLogs=e?.captureConsoleLogs??true;let a=cr(process.cwd()),s=a?ur(a):null,n=s?Ue(s):null,o=gr(n,e?.cloud);return t.cloud=o.apiKey?o:null,t.reportMode=e?.reportMode??"streaming",t.streamingThreshold=e?.streamingThreshold??0,Object.freeze(t)}var ze="1.9.0";function vr(e,t,r){try{let s=readFileSync(e,"utf-8").split(`
6
- `);if(t<1||t>s.length)return null;let n=Math.max(1,t-r),o=Math.min(s.length,t+r),i=[];for(let l=n;l<=o;l++){let d=l===t?">":" ",c=String(l).padStart(String(o).length," ");i.push(`${d} ${c} | ${s[l-1]}`);}return i.join(`
7
- `)}catch{return null}}function br(e){return t=>{let r=t;for(let a of e)if(typeof a=="string"){let s=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=a.flags.includes("g")?a.flags:a.flags+"g",n=new RegExp(a.source,s);r=r.replace(n,"[REDACTED]");}return r}}function Is(e){return e.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:e.GITHUB_RUN_ID??null,commitSha:e.GITHUB_SHA??null,branch:e.GITHUB_REF_NAME??null,runUrl:e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:null}}function Ms(e){return e.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:e.CI_PIPELINE_ID??null,commitSha:e.CI_COMMIT_SHA??null,branch:e.CI_COMMIT_BRANCH??e.CI_COMMIT_REF_NAME??null,runUrl:e.CI_PIPELINE_URL??null}}function Es(e){if(!e.JENKINS_URL)return null;let t=e.GIT_BRANCH??null;return t?.startsWith("origin/")&&(t=t.slice(7)),{provider:"jenkins",buildId:e.BUILD_ID??null,commitSha:e.GIT_COMMIT??null,branch:t,runUrl:e.BUILD_URL??null}}function Ps(e){return e.CIRCLECI!=="true"?null:{provider:"circleci",buildId:e.CIRCLE_BUILD_NUM??null,commitSha:e.CIRCLE_SHA1??null,branch:e.CIRCLE_BRANCH??null,runUrl:e.CIRCLE_BUILD_URL??null}}function Ds(e){if(!e.BITBUCKET_PIPELINE_UUID)return null;let t=e.BITBUCKET_WORKSPACE&&e.BITBUCKET_REPO_SLUG&&e.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${e.BITBUCKET_WORKSPACE}/${e.BITBUCKET_REPO_SLUG}/pipelines/results/${e.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:e.BITBUCKET_BUILD_NUMBER??null,commitSha:e.BITBUCKET_COMMIT??null,branch:e.BITBUCKET_BRANCH??null,runUrl:t}}var Ls=[Is,Ms,Es,Ps,Ds];function U(e){let t=process.env;for(let r of Ls){let a=r(t);if(a)return a}return null}var He=`
3
+ `);}}}writeIndex(t){let r=join(this.reportDir,"index.json"),a=r+".tmp",s=JSON.stringify(t);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(t){let r=join(this.reportDir,"index-compact.json"),a=r+".tmp",s=t.map(({titlePath:i,project:o,...l})=>l),n=JSON.stringify(s);writeFileSync(a,n,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeSummary(t){let r=join(this.reportDir,"summary.json"),a=r+".tmp",s=JSON.stringify(t);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(t){let r=join(this.reportDir,"manifest.json"),a=r+".tmp",s=JSON.stringify(t);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var ur=".testrelic",bs="testrelic-config.json",xs=".testrelic",ws=5,ks=new Set(["__proto__","constructor","prototype"]),dr=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,uploadBudgetMs:12e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${ur}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),Ss={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function pr(e){let t=resolve(e);for(let r=0;r<=ws;r++){let a=join(t,ur,bs);if(existsSync(a))try{if(statSync(a).isFile())return a}catch{}let s=join(t,xs);if(existsSync(s))try{if(statSync(s).isFile())return process.stderr.write(`[testrelic] Deprecation: config file ".testrelic" has moved to ".testrelic/testrelic-config.json". Please migrate your config file to the new location.
4
+ `),s}catch{}let n=dirname(t);if(n===t)break;t=n;}return null}function fr(e){try{let t=readFileSync(e,"utf-8"),r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)||!gr(r)?null:r}catch{return null}}function gr(e){for(let t of Object.keys(e)){if(ks.has(t))return false;let r=e[t];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!gr(r))return false}return true}function hr(e){let t=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(e);if(t)return process.env[t[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);return r?process.env[r[1]]??null:e}function Ue(e){let t=Object.create(null);for(let r of Object.keys(e)){let a=e[r];typeof a=="string"&&a.startsWith("$")?t[r]=hr(a):typeof a=="object"&&a!==null&&!Array.isArray(a)?t[r]=Ue(a):t[r]=a;}return t}function cr(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let r=parseInt(t[1],10),a=t[2],s=Ss[a];return !s||r<=0?null:r*s}function mr(e,t){let r=Object.create(null);if(Object.assign(r,dr),e){let l=e.cloud;l&&typeof l=="object"&&(typeof l.endpoint=="string"&&(r.endpoint=l.endpoint),typeof l.upload=="string"&&(r.uploadStrategy=l.upload),typeof l.timeout=="number"&&(r.timeout=l.timeout),typeof l.uploadBudgetMs=="number"&&(r.uploadBudgetMs=l.uploadBudgetMs),typeof l.apiKey=="string"&&l.apiKey.length>0&&(r.apiKey=l.apiKey));let d=e["testrelic-repo"]??e.project;d&&typeof d=="object"&&typeof d.name=="string"&&(r.projectName=d.name),e.project&&!e["testrelic-repo"]&&process.stderr.write(`[testrelic] Deprecation: "project" key in config is deprecated. Rename it to "testrelic-repo".
5
+ `);let c=e.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let p=cr(c.maxAge);p!==null&&(r.queueMaxAge=p);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(t){if(typeof t.apiKey=="string"&&t.apiKey.length>0){let l=t.apiKey.startsWith("$")?hr(t.apiKey):t.apiKey;l&&(r.apiKey=l);}if(typeof t.endpoint=="string"&&(r.endpoint=t.endpoint),typeof t.upload=="string"&&(r.uploadStrategy=t.upload),typeof t.timeout=="number"&&(r.timeout=t.timeout),typeof t.uploadBudgetMs=="number"&&(r.uploadBudgetMs=t.uploadBudgetMs),typeof t.projectName=="string"&&(r.projectName=t.projectName),typeof t.queueMaxAge=="string"){let l=cr(t.queueMaxAge);l!==null&&(r.queueMaxAge=l);}typeof t.queueDirectory=="string"&&(r.queueDirectory=t.queueDirectory),typeof t.uploadArtifacts=="boolean"&&(r.uploadArtifacts=t.uploadArtifacts),typeof t.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=t.artifactMaxSizeMb);}let a=process.env.TESTRELIC_API_KEY;a&&a.length>0&&(r.apiKey=a);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&isValidEndpointUrl(s)&&(r.endpoint=s);let n=process.env.TESTRELIC_UPLOAD_STRATEGY;n&&["batch","realtime","both"].includes(n)&&(r.uploadStrategy=n);let i=process.env.TESTRELIC_CLOUD_TIMEOUT;if(i){let l=parseInt(i,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let o=Object.freeze(r);return isValidCloudConfig(o)?o:dr}var As=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],_s=["authorization","cookie","set-cookie","x-api-key"],Is=["password","secret","token","apiKey","api_key"];function vr(e){let t=Object.create(null);return t.trackApiCalls=e?.trackApiCalls??true,t.captureRequestHeaders=e?.captureRequestHeaders??true,t.captureResponseHeaders=e?.captureResponseHeaders??true,t.captureRequestBody=e?.captureRequestBody??true,t.captureResponseBody=e?.captureResponseBody??true,t.captureAssertions=e?.captureAssertions??true,t.redactHeaders=e?.redactHeaders??[..._s],t.redactBodyFields=e?.redactBodyFields??[...Is],t.apiIncludeUrls=e?.apiIncludeUrls??[],t.apiExcludeUrls=e?.apiExcludeUrls??[],Object.freeze(t)}function yr(e){if(e!==void 0&&!isValidConfig(e))throw createError(ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let t=Object.create(null);t.outputPath=e?.outputPath??"./test-results/analytics-timeline.json",t.includeStackTrace=e?.includeStackTrace??false,t.includeCodeSnippets=e?.includeCodeSnippets??true,t.codeContextLines=e?.codeContextLines??3,t.includeNetworkStats=e?.includeNetworkStats??true,t.captureNavigation=e?.captureNavigation??true,t.navigationTypes=e?.navigationTypes??null,t.redactPatterns=[...As,...e?.redactPatterns??[]],t.testRunId=e?.testRunId??null,t.metadata=e?.metadata??null;let r=t.outputPath;t.openReport=e?.openReport??true,t.htmlReportPath=e?.htmlReportPath??r.replace(/\.json$/,".html"),t.includeArtifacts=e?.includeArtifacts??true,t.trackApiCalls=e?.trackApiCalls??true,t.quiet=e?.quiet??false,t.includeActionSteps=e?.includeActionSteps??true,t.captureConsoleLogs=e?.captureConsoleLogs??true;let a=pr(process.cwd()),s=a?fr(a):null,n=s?Ue(s):null,i=mr(n,e?.cloud);return t.cloud=i.apiKey?i:null,t.reportMode=e?.reportMode??"streaming",t.streamingThreshold=e?.streamingThreshold??0,Object.freeze(t)}var ze="1.10.0";function br(e,t,r){try{let s=readFileSync(e,"utf-8").split(`
6
+ `);if(t<1||t>s.length)return null;let n=Math.max(1,t-r),i=Math.min(s.length,t+r),o=[];for(let l=n;l<=i;l++){let d=l===t?">":" ",c=String(l).padStart(String(i).length," ");o.push(`${d} ${c} | ${s[l-1]}`);}return o.join(`
7
+ `)}catch{return null}}function xr(e){return t=>{let r=t;for(let a of e)if(typeof a=="string"){let s=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=a.flags.includes("g")?a.flags:a.flags+"g",n=new RegExp(a.source,s);r=r.replace(n,"[REDACTED]");}return r}}function Es(e){return e.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:e.GITHUB_RUN_ID??null,commitSha:e.GITHUB_SHA??null,branch:e.GITHUB_REF_NAME??null,runUrl:e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:null}}function Ps(e){return e.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:e.CI_PIPELINE_ID??null,commitSha:e.CI_COMMIT_SHA??null,branch:e.CI_COMMIT_BRANCH??e.CI_COMMIT_REF_NAME??null,runUrl:e.CI_PIPELINE_URL??null}}function Ds(e){if(!e.JENKINS_URL)return null;let t=e.GIT_BRANCH??null;return t?.startsWith("origin/")&&(t=t.slice(7)),{provider:"jenkins",buildId:e.BUILD_ID??null,commitSha:e.GIT_COMMIT??null,branch:t,runUrl:e.BUILD_URL??null}}function Ls(e){return e.CIRCLECI!=="true"?null:{provider:"circleci",buildId:e.CIRCLE_BUILD_NUM??null,commitSha:e.CIRCLE_SHA1??null,branch:e.CIRCLE_BRANCH??null,runUrl:e.CIRCLE_BUILD_URL??null}}function Ns(e){if(!e.BITBUCKET_PIPELINE_UUID)return null;let t=e.BITBUCKET_WORKSPACE&&e.BITBUCKET_REPO_SLUG&&e.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${e.BITBUCKET_WORKSPACE}/${e.BITBUCKET_REPO_SLUG}/pipelines/results/${e.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:e.BITBUCKET_BUILD_NUMBER??null,commitSha:e.BITBUCKET_COMMIT??null,branch:e.BITBUCKET_BRANCH??null,runUrl:t}}var Fs=[Es,Ps,Ds,Ls,Ns];function U(e){let t=process.env;for(let r of Fs){let a=r(t);if(a)return a}return null}var He=`
8
8
  /* Theme Variables */
9
9
  :root,[data-theme="dark"]{
10
10
  --bg:#0f1117;--bg-1:#161b22;--bg-2:#1c2128;--bg-3:#21262d;--bg-code:#13111c;
@@ -578,7 +578,7 @@ body{
578
578
  <path fill-rule="evenodd" clip-rule="evenodd" d="M4.75 1.08009C2.034 2.66209 -0.130999 7.63009 0.610001 10.5821C0.969001 12.0121 3.021 15.2131 5.17 17.6971C14.375 28.3321 18 39.7791 18 58.2101V71.0001H12.434C1.16501 71.0001 0 73.4641 0 97.3051C0 106.858 0.298003 128.922 0.662003 146.337L1.323 178H33.606C65.786 178 65.897 178.007 68.544 180.284C72.228 183.453 72.244 189.21 68.579 192.877L65.957 195.5L33.479 195.801L1 196.103V204.551V213H24.577H48.154L51.077 215.923C55.007 219.853 55.007 224.147 51.077 228.077L48.154 231H26.469H4.783L5.41901 233.534C5.76901 234.927 7.143 238.527 8.472 241.534L10.89 247H40.945H71L71.006 241.75C71.017 230.748 76.027 221.606 84.697 216.767C97.854 209.424 114.086 213.895 121.323 226.857C123.659 231.041 124.418 233.833 124.789 239.607L125.263 247H155.187H185.11L187.528 241.534C188.857 238.527 190.231 234.927 190.581 233.534L191.217 231H169.531H147.846L144.923 228.077C142.928 226.082 142 224.152 142 222C142 219.848 142.928 217.918 144.923 215.923L147.846 213H171.423H195V204.551V196.103L162.521 195.801L130.043 195.5L127.421 192.877C123.991 189.445 123.835 183.869 127.074 180.421L129.349 178H162.013H194.677L195.338 146.337C195.702 128.922 196 106.858 196 97.3051C196 73.4641 194.835 71.0001 183.566 71.0001H178V58.2101C178 39.6501 181.397 28.7731 190.538 18.0651C195.631 12.0971 196.572 9.00809 194.511 5.02109C192.672 1.46509 190.197 9.12233e-05 186.028 9.12233e-05C179.761 9.12233e-05 168.713 14.8831 163.388 30.5001C160.975 37.5771 160.608 40.3751 160.213 54.7501L159.765 71.0001H150.732H141.7L142.286 53.2501C142.904 34.5511 144.727 24.3761 148.938 16.1211C151.823 10.4671 151.628 5.90109 148.364 2.63609C145 -0.726907 140.105 -0.887909 136.596 2.25009C133.481 5.03609 128.686 17.0811 126.507 27.5921C125.569 32.1191 124.617 43.0901 124.28 53.2501L123.69 71.0001H115.345H107V38.4231V5.84609L104.077 2.92309C102.082 0.928088 100.152 9.12233e-05 98 9.12233e-05C95.848 9.12233e-05 93.918 0.928088 91.923 2.92309L89 5.84609V38.4231V71.0001H80.655H72.31L71.72 53.2501C71.383 43.0901 70.431 32.1191 69.493 27.5921C67.314 17.0811 62.519 5.03609 59.404 2.25009C55.998 -0.795909 51.059 -0.710905 47.646 2.45209C44.221 5.62609 44.191 9.92109 47.539 17.4911C51.71 26.9241 53.007 34.4791 53.676 53.2501L54.31 71.0001H45.272H36.235L35.787 54.7501C35.392 40.3751 35.025 37.5771 32.612 30.5001C27.194 14.6091 16.228 -0.02891 9.787 0.03009C7.979 0.04709 5.712 0.519093 4.75 1.08009ZM42.687 108.974C33.431 112.591 20.036 125.024 18.408 131.512C17.476 135.223 20.677 140.453 28.253 147.599C37.495 156.319 44.191 159.471 53.5 159.485C59.317 159.494 61.645 158.953 67.274 156.289C77.634 151.385 88.987 139.161 88.996 132.9C89.004 127.304 76.787 114.707 66.745 109.956C59.16 106.368 50.285 106.006 42.687 108.974ZM129.255 109.904C119.151 114.768 106.996 127.33 107.004 132.9C107.013 139.108 118.562 151.475 128.939 156.389C134.338 158.945 136.744 159.496 142.521 159.498C152.526 159.501 160.369 155.502 169.771 145.605C180.444 134.368 180.278 130.975 168.486 119.388C160.043 111.094 152.727 107.595 143 107.201C136.364 106.933 134.78 107.244 129.255 109.904ZM48.5 125.922C46.3 126.969 43.152 128.945 41.505 130.314L38.511 132.802L40.504 135.005C41.601 136.216 44.434 138.342 46.8 139.728C52.577 143.114 57.36 142.466 64.009 137.395L68.978 133.606L66.756 131.24C60.944 125.054 54.357 123.135 48.5 125.922ZM138.386 125.063C136.674 125.571 133.375 127.677 131.057 129.743L126.841 133.5L131.901 137.343C138.65 142.468 143.407 143.124 149.2 139.728C151.566 138.342 154.351 136.269 155.389 135.122C157.684 132.587 156.742 131.097 150.58 127.511C145.438 124.519 142.329 123.895 138.386 125.063ZM91.923 162.923C89.043 165.804 89 166.008 89 176.973C89 184.805 89.435 188.941 90.47 190.941C92.356 194.589 96.918 196.273 101.03 194.84C105.82 193.17 107 189.638 107 176.973C107 166.008 106.957 165.804 104.077 162.923C102.082 160.928 100.152 160 98 160C95.848 160 93.918 160.928 91.923 162.923ZM94.5 232.155C91.026 234.055 90 236.229 90 241.691V247H98H106V242.082C106 235.732 105.37 234.242 101.928 232.463C98.591 230.737 97.197 230.679 94.5 232.155Z" fill="url(#paint0_linear_55_11)"/>
579
579
  <defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
580
580
  <stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
581
- </linearGradient></defs></svg>`;var $e={"failed|failed":"passed","failed|passed":"failed"},yr={"failed|failed":"Failed as expected","failed|passed":"Expected to fail, but passed."};function Ns(e,t){return `${t??"passed"}|${e}`}function Fs(e,t){return $e[Ns(e,t)]??e}function je(e,t){let r={passed:e.passed,failed:e.failed,flaky:e.flaky,skipped:e.skipped,timedout:e.timedout},a=0,s=0;for(let n of t){let o=Fs(n.status,n.expectedStatus);o!==n.status&&(r[n.status]--,r[o]++,o==="passed"?a++:s++);}return {total:e.total,...r,expectedFailures:a,unexpectedPasses:s}}var Ge=`
581
+ </linearGradient></defs></svg>`;var $e={"failed|failed":"passed","failed|passed":"failed"},wr={"failed|failed":"Failed as expected","failed|passed":"Expected to fail, but passed."};function Bs(e,t){return `${t??"passed"}|${e}`}function Os(e,t){return $e[Bs(e,t)]??e}function je(e,t){let r={passed:e.passed,failed:e.failed,flaky:e.flaky,skipped:e.skipped,timedout:e.timedout},a=0,s=0;for(let n of t){let i=Os(n.status,n.expectedStatus);i!==n.status&&(r[n.status]--,r[i]++,i==="passed"?a++:s++);}return {total:e.total,...r,expectedFailures:a,unexpectedPasses:s}}var Ge=`
582
582
  /* \u2500\u2500 Utilities \u2500\u2500 */
583
583
  function esc(s){if(!s)return '';return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;')}
584
584
  function stripAnsi(s){return s?s.replace(/\\u001b\\[[0-9;]*m/g,'').replace(/\\x1b\\[[0-9;]*m/g,''):''}
@@ -595,25 +595,26 @@ body{
595
595
  interpolated as JSON data (not code), so the report and the terminal box
596
596
  cannot disagree about a pair. Defined before the data transformation
597
597
  below, which is their first caller. */
598
- var PW_VERDICT=${JSON.stringify($e)};var PW_NOTE=${JSON.stringify(yr)};
598
+ var PW_VERDICT=${JSON.stringify($e)};var PW_NOTE=${JSON.stringify(wr)};
599
599
  function pwKey(s,e){return (e||'passed')+'|'+s;}
600
600
  function pwVerdict(s,e){return PW_VERDICT[pwKey(s,e)]||s;}
601
601
  function pwNote(s,e){return PW_NOTE[pwKey(s,e)]||null;}
602
602
 
603
603
  /* \u2500\u2500 Data Transformation \u2500\u2500 */
604
604
  var testMap={};
605
+ /* One entry per ATTEMPT: a retried test lists every attempt under the same
606
+ testId, told apart by retry. Reports written before retry existed
607
+ collapse to one entry per test, as they always did. */
605
608
  for(var i=0;i<data.timeline.length;i++){
606
609
  var entry=data.timeline[i];
607
610
  for(var j=0;j<entry.tests.length;j++){
608
611
  var t=entry.tests[j];
609
- /* Known and not fixed here: this keeps the FIRST attempt the timeline
610
- lists, so a retried test's row can show an earlier attempt's status
611
- while the verdict band counts final attempts. */
612
- if(!testMap[t.testId]){
612
+ var _ak=t.testId+'#'+(t.retry||0);
613
+ if(!testMap[_ak]){
613
614
  /* status is the verdict every surface reads (colour, filters, needs
614
615
  attention); rawStatus keeps the actual result for the detail notes. */
615
- testMap[t.testId]={
616
- testId:t.testId,title:t.title,status:pwVerdict(t.status,t.expectedStatus),rawStatus:t.status,duration:t.duration,
616
+ testMap[_ak]={
617
+ testId:t.testId,retryIndex:t.retry||0,title:t.title,status:pwVerdict(t.status,t.expectedStatus),rawStatus:t.status,duration:t.duration,
617
618
  startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,
618
619
  tags:t.tags,failure:t.failure,filePath:t.filePath,suiteName:t.suiteName,
619
620
  testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,
@@ -624,14 +625,14 @@ body{
624
625
  assertionsPassed:0,assertionsFailed:0,
625
626
  device:t.device||null,aiDefects:t.aiDefects||[]
626
627
  };
627
- var _as=testMap[t.testId].apiAssertions;
628
+ var _as=testMap[_ak].apiAssertions;
628
629
  for(var _ai=0;_ai<_as.length;_ai++){
629
- if(_as[_ai].status==='failed')testMap[t.testId].assertionsFailed++;
630
- else testMap[t.testId].assertionsPassed++;
630
+ if(_as[_ai].status==='failed')testMap[_ak].assertionsFailed++;
631
+ else testMap[_ak].assertionsPassed++;
631
632
  }
632
633
  }
633
634
  if(entry.type==='api_call'){
634
- var _mt=testMap[t.testId];
635
+ var _mt=testMap[_ak];
635
636
  _mt.apiCallCount++;
636
637
  var _code=entry.response&&typeof entry.response.status==='number'?entry.response.status:null;
637
638
  var _bucket=_code===null?'error':(_code>=500?'5xx':(_code>=400?'4xx':(_code>=300?'3xx':(_code>=200?'2xx':'error'))));
@@ -642,7 +643,7 @@ body{
642
643
  request:entry.request,response:entry.response,assertions:entry.assertions
643
644
  });
644
645
  }else{
645
- testMap[t.testId].steps.push({
646
+ testMap[_ak].steps.push({
646
647
  url:entry.url,navigationType:entry.navigationType,
647
648
  visitedAt:entry.visitedAt||entry.timestamp,duration:entry.duration||entry.durationOnUrl||0,specFile:entry.specFile,
648
649
  domContentLoadedAt:entry.domContentLoadedAt,networkIdleAt:entry.networkIdleAt,
@@ -651,8 +652,40 @@ body{
651
652
  }
652
653
  }
653
654
  }
655
+ /* Group attempts under the final (highest-retry) one, as the streaming
656
+ index below does: the final attempt is the row and owns the testId; each
657
+ earlier attempt is a nested row with its own drawer, keyed
658
+ <testId>#retry-<n>, carrying that attempt's own steps, actions,
659
+ failure and artifacts. Keeping whichever attempt came first in the
660
+ timeline showed an earlier attempt's status on the row. */
661
+ var _byTest={};
662
+ for(var _k in testMap){
663
+ if(!testMap.hasOwnProperty(_k))continue;
664
+ var _at=testMap[_k];
665
+ (_byTest[_at.testId]=_byTest[_at.testId]||[]).push(_at);
666
+ }
667
+ testMap={};
654
668
  var tests=[];
655
- for(var id in testMap){if(testMap.hasOwnProperty(id))tests.push(testMap[id])}
669
+ for(var _tid in _byTest){
670
+ if(!_byTest.hasOwnProperty(_tid))continue;
671
+ var _atts=_byTest[_tid].sort(function(a,b){return a.retryIndex-b.retryIndex;});
672
+ var _fin=_atts[_atts.length-1];
673
+ var _prev=_atts.slice(0,-1);
674
+ _fin.retryAttempts=_prev.map(function(a){
675
+ return {testId:a.testId+'#retry-'+a.retryIndex,retryIndex:a.retryIndex,status:a.status,rawStatus:a.rawStatus,expectedStatus:a.expectedStatus||'passed',duration:a.duration,
676
+ errorMessage:a.failure&&a.failure.message?String(a.failure.message).split('\\n')[0]:null};
677
+ });
678
+ testMap[_tid]=_fin;
679
+ tests.push(_fin);
680
+ for(var _pi=0;_pi<_prev.length;_pi++){
681
+ var _pa=_prev[_pi];
682
+ _pa.title=_fin.title+' (attempt '+(_pa.retryIndex+1)+')';
683
+ _pa.retryStatus='attempt '+(_pa.retryIndex+1)+' of '+_atts.length;
684
+ _pa.retryCount=0;_pa.isFlaky=false;
685
+ _pa.testId=_tid+'#retry-'+_pa.retryIndex;
686
+ testMap[_pa.testId]=_pa;
687
+ }
688
+ }
656
689
  tests.sort(function(a,b){
657
690
  if(a.filePath!==b.filePath)return a.filePath<b.filePath?-1:1;
658
691
  return a.startedAt<b.startedAt?-1:1;
@@ -4061,7 +4094,7 @@ function _updateCard(cls,val){
4061
4094
  @media (max-width:1100px){
4062
4095
  .tband-3,.tband-2{grid-template-columns:1fr}
4063
4096
  }
4064
- `;var Bs=`
4097
+ `;var Us=`
4065
4098
  (function(){
4066
4099
  var data=JSON.parse(document.getElementById('report-data').textContent);
4067
4100
  ${Ge}
@@ -4086,7 +4119,7 @@ function _updateCard(cls,val){
4086
4119
  renderNeedsAttention();
4087
4120
  routeFromHash();
4088
4121
  var _lo=document.getElementById('loading-overlay');if(_lo)_lo.remove();
4089
- })();`;function xr(e,t,r){let a=e.replace(/<\//g,"<\\/"),s=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
4122
+ })();`;function kr(e,t,r){let a=e.replace(/<\//g,"<\\/"),s=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
4090
4123
  <!DOCTYPE html>
4091
4124
  <html lang="en" data-theme="">
4092
4125
  <head>
@@ -4140,15 +4173,15 @@ ${""}
4140
4173
  </aside>
4141
4174
  <script id="report-data" type="application/json">${a}</script>
4142
4175
  ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:""}
4143
- <script>${Bs}</script>
4176
+ <script>${Us}</script>
4144
4177
  </body>
4145
- </html>`}function dt(e,t,r,a,s){let n=e.replace(/<\//g,"<\\/"),o=s?s.replace(/<\//g,"<\\/"):"null",i=t.replace(/<\//g,"<\\/"),l=a?a.replace(/<\//g,"<\\/"):null,d={};try{d=JSON.parse(e);}catch{}let c=`{
4178
+ </html>`}function dt(e,t,r,a,s){let n=e.replace(/<\//g,"<\\/"),i=s?s.replace(/<\//g,"<\\/"):"null",o=t.replace(/<\//g,"<\\/"),l=a?a.replace(/<\//g,"<\\/"):null,d={};try{d=JSON.parse(e);}catch{}let c=`{
4146
4179
  "schemaVersion":"2.0",
4147
4180
  "reportMode":"streaming",
4148
4181
  "serverPort":${r??"null"},
4149
4182
  "summary":${n},
4150
- "presentedSummary":${o},
4151
- "index":${i},
4183
+ "presentedSummary":${i},
4184
+ "index":${o},
4152
4185
  "timeline":[],
4153
4186
  "testRunId":${JSON.stringify(String(d.testRunId??""))},
4154
4187
  "startedAt":${JSON.stringify(String(d.startedAt??""))},
@@ -4310,37 +4343,37 @@ ${l?`<script id="artifact-manifest-data" type="application/json">${l}</script>`:
4310
4343
  <script>${p}</script>
4311
4344
  </body>
4312
4345
  </html>`}function ct(e){try{let t=process.platform,r,a;t==="darwin"?(r="open",a=[e]):t==="win32"?(r="cmd",a=["/c","start","",e]):(r="xdg-open",a=[e]),execFile(r,a,s=>{s&&process.stderr.write(`[testrelic] Failed to open browser: ${s.message}
4313
- `);});}catch{}}join(tmpdir(),"testrelic-data");async function wr(e,t,r,a){let s=(t-1)*r,n=[],o=0,i=createInterface({input:createReadStream(e,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of i)if(c.length!==0){if(o>=s&&n.length<r)try{n.push(JSON.parse(c));}catch{}if(o++,n.length>=r&&a!==void 0)break}let l=a??o,d=Math.max(1,Math.ceil(l/r));return {items:n,total:l,page:t,pageSize:r,totalPages:d}}var Tr=/^[a-f0-9]{12}$/,ft=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Rr=500;function S(e,t,r){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(r));}function Ar(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type");}function he(e){try{return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):null}catch{return null}}function me(e){let t=0;try{let r=readdirSync(e,{withFileTypes:!0});for(let a of r){let s=join(e,a.name);a.isFile()?t+=statSync(s).size:a.isDirectory()&&(t+=me(s));}}catch{}return t}function _r(e,t,r,a){let s=he(join(r,"index.json"));S(t,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-a)/1e3)});}function Ir(e,t,r){let a=he(join(r,"summary.json"));if(!a){S(t,404,{error:"Summary not found"});return}S(t,200,a);}function Mr(e,t,r){let a=he(join(r,"index.json"));if(!a){S(t,404,{error:"Test index not found"});return}let n=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,o=Math.max(1,parseInt(n.get("page")??"1",10)||1),i=Math.min(Rr,Math.max(1,parseInt(n.get("pageSize")??"100",10)||100)),l=n.get("status")?.split(",").filter(Boolean)??null,d=n.get("file")??null,c=n.get("search")?.toLowerCase()??null,p=n.get("tag")?.split(",").filter(Boolean)??null,v=n.get("sort")??"file",g=n.get("order")==="desc"?-1:1,u=a;l&&l.length>0&&(u=u.filter(b=>l.includes(b.status))),d&&(u=u.filter(b=>b.filePath===d||b.filePath.startsWith(d+"/"))),c&&(u=u.filter(b=>b.title.toLowerCase().includes(c)||b.filePath.toLowerCase().includes(c))),p&&p.length>0&&(u=u.filter(b=>p.some(x=>b.tags.includes(x)))),u=[...u].sort((b,x)=>{let w=0;switch(v){case "duration":w=b.duration-x.duration;break;case "status":w=b.status.localeCompare(x.status);break;case "title":w=b.title.localeCompare(x.title);break;default:w=b.filePath.localeCompare(x.filePath);break}return w*g});let m=u.length,h=Math.max(1,Math.ceil(m/i)),y=(o-1)*i,f=u.slice(y,y+i);S(t,200,{tests:f,pagination:{page:o,pageSize:i,totalItems:m,totalPages:h},filters:{status:l,file:d,search:c,tag:p}});}function Er(e,t,r,a){if(!Tr.test(a)){S(t,400,{error:"Invalid test ID format"});return}let s=join(r,"tests",a,"meta.json"),n=join(r,"tests",`${a}.json`),o=existsSync(s)?s:existsSync(n)?n:null;if(!o){S(t,404,{error:`Test not found: ${a}`});return}try{let i=readFileSync(o,"utf-8");t.writeHead(200,{"Content-Type":"application/json"}),t.end(i);}catch(i){S(t,500,{error:i instanceof Error?i.message:String(i)});}}async function Pr(e,t,r,a,s){if(!Tr.test(a)){S(t,400,{error:"Invalid test ID format"});return}let o=join(r,"tests",a,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!existsSync(o)){S(t,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),c=Math.min(Rr,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),p,v=join(r,"tests",a,"meta.json");if(existsSync(v))try{let u=JSON.parse(readFileSync(v,"utf-8"));switch(s){case "network":p=u.networkRequestsCount;break;case "console":p=u.consoleLogsCount;break;case "api-calls":p=u.apiCallsCount;break}}catch{}let g=await wr(o,d,c,p);S(t,200,g);}catch(i){S(t,500,{error:i instanceof Error?i.message:String(i)});}}function Dr(e,t,r){let a=he(join(r,"index.json"));if(!a){S(t,404,{error:"Test index not found"});return}let s=new Map;for(let o of a){if(o.isRetry)continue;let i=s.get(o.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.set(o.filePath,i)),i.total++,o.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let n=Array.from(s.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));S(t,200,{files:n});}function Lr(e,t,r){if(!existsSync(r)){S(t,200,{runs:[],totalSizeBytes:0});return}try{let a=[],s=0,n=readdirSync(r,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!ft.test(o.name))continue;let i=join(r,o.name),l=me(i),d=readdirSync(i,{withFileTypes:!0}).filter(c=>c.isDirectory());a.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),s+=l;}a.sort((o,i)=>i.folderName.localeCompare(o.folderName)),S(t,200,{runs:a,totalSizeBytes:s});}catch(a){S(t,500,{error:a instanceof Error?a.message:String(a)});}}function Nr(e,t,r){try{let a=0,s=0;if(existsSync(r)){let n=readdirSync(r,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!ft.test(o.name))continue;let i=join(r,o.name),l=me(i);rmSync(i,{recursive:!0,force:!0}),s+=l,a++;}}S(t,200,{deletedCount:a,freedBytes:s});}catch(a){S(t,500,{error:a instanceof Error?a.message:String(a)});}}function Fr(e,t,r,a){if(!ft.test(a)){S(t,400,{error:"Invalid folder name"});return}let s=join(r,a);try{if(!statSync(s).isDirectory()){S(t,404,{error:"Not found"});return}}catch{S(t,404,{error:"Not found"});return}try{let n=me(s);rmSync(s,{recursive:!0,force:!0}),S(t,200,{deleted:a,freedBytes:n});}catch(n){S(t,500,{error:n instanceof Error?n.message:String(n)});}}function Br(e,t,r){S(t,200,{status:"shutting_down"}),r.close();}function gt(e,t,r){if(!existsSync(r)){S(t,404,{error:"File not found"});return}try{let a=statSync(r).size,s=extname(r).toLowerCase(),n=js[s]??"application/octet-stream",o=$s(e.headers.range,a);if(o==="unsatisfiable"){t.writeHead(416,{"Content-Range":`bytes */${a}`,"Accept-Ranges":"bytes"}),t.end();return}if(o){t.writeHead(206,{"Content-Type":n,"Content-Length":o.end-o.start+1,"Content-Range":`bytes ${o.start}-${o.end}/${a}`,"Accept-Ranges":"bytes"}),Sr(createReadStream(r,{start:o.start,end:o.end}),t);return}t.writeHead(200,{"Content-Type":n,"Content-Length":a,"Accept-Ranges":"bytes"}),Sr(createReadStream(r),t);}catch(a){S(t,500,{error:a instanceof Error?a.message:String(a)});}}function Sr(e,t){e.on("error",()=>{e.destroy(),t.destroy();}),t.on("close",()=>{e.destroy();}),e.pipe(t);}function $s(e,t){if(!e)return null;let r=/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!r)return null;let[,a,s]=r;if(a===""&&s==="")return null;let n,o;if(a===""){let i=Number(s);if(i<=0)return "unsatisfiable";n=Math.max(0,t-i),o=t-1;}else n=Number(a),o=s===""?t-1:Math.min(Number(s),t-1);return !Number.isFinite(n)||!Number.isFinite(o)?null:t===0||n>=t||n>o?"unsatisfiable":{start:n,end:o}}var js={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".json":"application/json",".html":"text/html",".css":"text/css",".js":"text/javascript",".svg":"image/svg+xml"};var Js=9323,Ys=10,Xs=1800*1e3;function oe(e,t){return new Promise((r,a)=>{let s=t?.port??Js,n=Date.now(),o,i=0,l=existsSync(join(e,"artifacts"))?join(e,"artifacts"):existsSync(join(e,"..","artifacts"))?join(e,"..","artifacts"):join(e,"artifacts");function d(){clearTimeout(o),o=setTimeout(()=>{p.close();},Xs);}let c=t?.htmlPath??null;if(!c){let g=dirname(e);try{let u=readdirSync(g).find(m=>m.endsWith(".html"));u&&(c=join(g,u));}catch{}}let p=createServer((g,u)=>{if(d(),Ar(u),g.method==="OPTIONS"){u.writeHead(204),u.end();return}let m;try{m=new URL(g.url??"/",`http://${g.headers.host??"localhost"}`).pathname;}catch{S(u,400,{error:"Invalid URL"});return}if(g.method==="GET"&&(m==="/"||m==="/index.html")){if(c&&existsSync(c)){gt(g,u,c);return}S(u,404,{error:"HTML report not found"});return}if(g.method==="GET"&&m==="/api/health"){_r(g,u,e,n);return}if(g.method==="GET"&&m==="/api/summary"){Ir(g,u,e);return}if(g.method==="GET"&&m==="/api/tests"){Mr(g,u,e);return}if(g.method==="GET"&&m==="/api/files"){Dr(g,u,e);return}let h=m.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(g.method==="GET"&&h){Pr(g,u,e,h[1],h[2]);return}let y=m.match(/^\/api\/tests\/([a-f0-9]+)$/);if(g.method==="GET"&&y){Er(g,u,e,y[1]);return}if(g.method==="GET"&&m==="/api/artifacts"){Lr(g,u,l);return}if(g.method==="DELETE"&&m==="/api/artifacts"){Nr(g,u,l);return}let f=m.match(/^\/api\/artifacts\/(.+)$/);if(g.method==="DELETE"&&f){Fr(g,u,l,decodeURIComponent(f[1]));return}if(g.method==="GET"&&m.startsWith("/artifacts/")){let b=decodeURIComponent(m.slice(11));if(b.includes("..")||b.includes("\0")){S(u,400,{error:"Invalid path"});return}gt(g,u,join(l,b));return}if(g.method==="POST"&&m==="/api/shutdown"){Br(g,u,p);return}S(u,404,{error:"Not found"});});function v(g){let u=m=>{m.code==="EADDRINUSE"&&i<Ys?(i++,v(g+1)):a(m);};p.once("error",u),p.listen(g,"127.0.0.1",()=>{p.removeListener("error",u);let m=p.address();if(!m||typeof m=="string"){a(new Error("Failed to get server address"));return}d(),r({port:m.port,dispose:()=>new Promise(h=>{clearTimeout(o),p.close(()=>h());})});});}v(s);})}async function Or(e){let t=await oe(e);return {port:t.port,dispose:t.dispose}}function en(e,t,r,a){let s=JSON.stringify(a?{...e,presentedSummary:a}:e),n=r?JSON.stringify(r):null;return xr(s,t,n)}async function mt(e,t,r,a){try{let s=null,n=null,o=t.reportMode==="streaming"||t.reportMode==="auto"&&e.timeline.length===0&&e.summary.total>=t.streamingThreshold,i,l=t.htmlReportPath,d=dirname(l);mkdirSync(d,{recursive:!0});let c="",p="[]",v=null,g=a?JSON.stringify(a):null;if(o){c=JSON.stringify({...e.summary,testRunId:e.testRunId,startedAt:e.startedAt,completedAt:e.completedAt,totalDuration:e.totalDuration,ci:e.ci,metadata:e.metadata,shardRunIds:e.shardRunIds});let m=dirname(t.outputPath),h=join(m,".testrelic-report");try{let y=join(h,"index-compact.json"),f=join(h,"index.json");existsSync(y)?p=readFileSync(y,"utf-8"):existsSync(f)&&(p=readFileSync(f,"utf-8"));}catch{}v=r?JSON.stringify(r):null,i=dt(c,p,null,v,g);}else i=en(e,null,r,a);let u=l+".tmp";if(writeFileSync(u,i,"utf-8"),renameSync(u,l),o){if(e.ci===null){let m=dirname(t.outputPath),h=join(m,".testrelic-report"),y=resolve(l);try{if(await rn(),s=await an(h),!s){n=await oe(h,{htmlPath:y}),s=n.port;let f=setInterval(()=>{},6e4),b=()=>{clearInterval(f),n?.dispose();};process.on("SIGINT",b),process.on("SIGTERM",b),setTimeout(b,1800*1e3).unref();}if(s){process.stderr.write(`
4346
+ `);});}catch{}}join(tmpdir(),"testrelic-data");async function Sr(e,t,r,a){let s=(t-1)*r,n=[],i=0,o=createInterface({input:createReadStream(e,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of o)if(c.length!==0){if(i>=s&&n.length<r)try{n.push(JSON.parse(c));}catch{}if(i++,n.length>=r&&a!==void 0)break}let l=a??i,d=Math.max(1,Math.ceil(l/r));return {items:n,total:l,page:t,pageSize:r,totalPages:d}}var Ar=/^[a-f0-9]{12}$/,ft=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,_r=500;function S(e,t,r){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(r));}function Ir(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type");}function he(e){try{return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):null}catch{return null}}function me(e){let t=0;try{let r=readdirSync(e,{withFileTypes:!0});for(let a of r){let s=join(e,a.name);a.isFile()?t+=statSync(s).size:a.isDirectory()&&(t+=me(s));}}catch{}return t}function Mr(e,t,r,a){let s=he(join(r,"index.json"));S(t,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-a)/1e3)});}function Er(e,t,r){let a=he(join(r,"summary.json"));if(!a){S(t,404,{error:"Summary not found"});return}S(t,200,a);}function Pr(e,t,r){let a=he(join(r,"index.json"));if(!a){S(t,404,{error:"Test index not found"});return}let n=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,i=Math.max(1,parseInt(n.get("page")??"1",10)||1),o=Math.min(_r,Math.max(1,parseInt(n.get("pageSize")??"100",10)||100)),l=n.get("status")?.split(",").filter(Boolean)??null,d=n.get("file")??null,c=n.get("search")?.toLowerCase()??null,p=n.get("tag")?.split(",").filter(Boolean)??null,y=n.get("sort")??"file",f=n.get("order")==="desc"?-1:1,u=a;l&&l.length>0&&(u=u.filter(v=>l.includes(v.status))),d&&(u=u.filter(v=>v.filePath===d||v.filePath.startsWith(d+"/"))),c&&(u=u.filter(v=>v.title.toLowerCase().includes(c)||v.filePath.toLowerCase().includes(c))),p&&p.length>0&&(u=u.filter(v=>p.some(w=>v.tags.includes(w)))),u=[...u].sort((v,w)=>{let x=0;switch(y){case "duration":x=v.duration-w.duration;break;case "status":x=v.status.localeCompare(w.status);break;case "title":x=v.title.localeCompare(w.title);break;default:x=v.filePath.localeCompare(w.filePath);break}return x*f});let m=u.length,b=Math.max(1,Math.ceil(m/o)),h=(i-1)*o,g=u.slice(h,h+o);S(t,200,{tests:g,pagination:{page:i,pageSize:o,totalItems:m,totalPages:b},filters:{status:l,file:d,search:c,tag:p}});}function Dr(e,t,r,a){if(!Ar.test(a)){S(t,400,{error:"Invalid test ID format"});return}let s=join(r,"tests",a,"meta.json"),n=join(r,"tests",`${a}.json`),i=existsSync(s)?s:existsSync(n)?n:null;if(!i){S(t,404,{error:`Test not found: ${a}`});return}try{let o=readFileSync(i,"utf-8");t.writeHead(200,{"Content-Type":"application/json"}),t.end(o);}catch(o){S(t,500,{error:o instanceof Error?o.message:String(o)});}}async function Lr(e,t,r,a,s){if(!Ar.test(a)){S(t,400,{error:"Invalid test ID format"});return}let i=join(r,"tests",a,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!existsSync(i)){S(t,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),c=Math.min(_r,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),p,y=join(r,"tests",a,"meta.json");if(existsSync(y))try{let u=JSON.parse(readFileSync(y,"utf-8"));switch(s){case "network":p=u.networkRequestsCount;break;case "console":p=u.consoleLogsCount;break;case "api-calls":p=u.apiCallsCount;break}}catch{}let f=await Sr(i,d,c,p);S(t,200,f);}catch(o){S(t,500,{error:o instanceof Error?o.message:String(o)});}}function Nr(e,t,r){let a=he(join(r,"index.json"));if(!a){S(t,404,{error:"Test index not found"});return}let s=new Map;for(let i of a){if(i.isRetry)continue;let o=s.get(i.filePath);switch(o||(o={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.set(i.filePath,o)),o.total++,i.status){case "passed":o.passed++;break;case "failed":o.failed++;break;case "flaky":o.flaky++;break;case "skipped":o.skipped++;break;case "timedout":o.timedOut++;break}}let n=Array.from(s.entries()).map(([i,o])=>({filePath:i,...o})).sort((i,o)=>i.filePath.localeCompare(o.filePath));S(t,200,{files:n});}function Fr(e,t,r){if(!existsSync(r)){S(t,200,{runs:[],totalSizeBytes:0});return}try{let a=[],s=0,n=readdirSync(r,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||!ft.test(i.name))continue;let o=join(r,i.name),l=me(o),d=readdirSync(o,{withFileTypes:!0}).filter(c=>c.isDirectory());a.push({folderName:i.name,totalSizeBytes:l,testCount:d.length}),s+=l;}a.sort((i,o)=>o.folderName.localeCompare(i.folderName)),S(t,200,{runs:a,totalSizeBytes:s});}catch(a){S(t,500,{error:a instanceof Error?a.message:String(a)});}}function Br(e,t,r){try{let a=0,s=0;if(existsSync(r)){let n=readdirSync(r,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||!ft.test(i.name))continue;let o=join(r,i.name),l=me(o);rmSync(o,{recursive:!0,force:!0}),s+=l,a++;}}S(t,200,{deletedCount:a,freedBytes:s});}catch(a){S(t,500,{error:a instanceof Error?a.message:String(a)});}}function Or(e,t,r,a){if(!ft.test(a)){S(t,400,{error:"Invalid folder name"});return}let s=join(r,a);try{if(!statSync(s).isDirectory()){S(t,404,{error:"Not found"});return}}catch{S(t,404,{error:"Not found"});return}try{let n=me(s);rmSync(s,{recursive:!0,force:!0}),S(t,200,{deleted:a,freedBytes:n});}catch(n){S(t,500,{error:n instanceof Error?n.message:String(n)});}}function Ur(e,t,r){S(t,200,{status:"shutting_down"}),r.close();}function gt(e,t,r){if(!existsSync(r)){S(t,404,{error:"File not found"});return}try{let a=statSync(r).size,s=extname(r).toLowerCase(),n=Ws[s]??"application/octet-stream",i=Gs(e.headers.range,a);if(i==="unsatisfiable"){t.writeHead(416,{"Content-Range":`bytes */${a}`,"Accept-Ranges":"bytes"}),t.end();return}if(i){t.writeHead(206,{"Content-Type":n,"Content-Length":i.end-i.start+1,"Content-Range":`bytes ${i.start}-${i.end}/${a}`,"Accept-Ranges":"bytes"}),Tr(createReadStream(r,{start:i.start,end:i.end}),t);return}t.writeHead(200,{"Content-Type":n,"Content-Length":a,"Accept-Ranges":"bytes"}),Tr(createReadStream(r),t);}catch(a){S(t,500,{error:a instanceof Error?a.message:String(a)});}}function Tr(e,t){e.on("error",()=>{e.destroy(),t.destroy();}),t.on("close",()=>{e.destroy();}),e.pipe(t);}function Gs(e,t){if(!e)return null;let r=/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!r)return null;let[,a,s]=r;if(a===""&&s==="")return null;let n,i;if(a===""){let o=Number(s);if(o<=0)return "unsatisfiable";n=Math.max(0,t-o),i=t-1;}else n=Number(a),i=s===""?t-1:Math.min(Number(s),t-1);return !Number.isFinite(n)||!Number.isFinite(i)?null:t===0||n>=t||n>i?"unsatisfiable":{start:n,end:i}}var Ws={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".json":"application/json",".html":"text/html",".css":"text/css",".js":"text/javascript",".svg":"image/svg+xml"};var Xs=9323,Zs=10,Qs=1800*1e3;function oe(e,t){return new Promise((r,a)=>{let s=t?.port??Xs,n=Date.now(),i,o=0,l=existsSync(join(e,"artifacts"))?join(e,"artifacts"):existsSync(join(e,"..","artifacts"))?join(e,"..","artifacts"):join(e,"artifacts");function d(){clearTimeout(i),i=setTimeout(()=>{p.close();},Qs);}let c=t?.htmlPath??null;if(!c){let f=dirname(e);try{let u=readdirSync(f).find(m=>m.endsWith(".html"));u&&(c=join(f,u));}catch{}}let p=createServer((f,u)=>{if(d(),Ir(u),f.method==="OPTIONS"){u.writeHead(204),u.end();return}let m;try{m=new URL(f.url??"/",`http://${f.headers.host??"localhost"}`).pathname;}catch{S(u,400,{error:"Invalid URL"});return}if(f.method==="GET"&&(m==="/"||m==="/index.html")){if(c&&existsSync(c)){gt(f,u,c);return}S(u,404,{error:"HTML report not found"});return}if(f.method==="GET"&&m==="/api/health"){Mr(f,u,e,n);return}if(f.method==="GET"&&m==="/api/summary"){Er(f,u,e);return}if(f.method==="GET"&&m==="/api/tests"){Pr(f,u,e);return}if(f.method==="GET"&&m==="/api/files"){Nr(f,u,e);return}let b=m.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(f.method==="GET"&&b){Lr(f,u,e,b[1],b[2]);return}let h=m.match(/^\/api\/tests\/([a-f0-9]+)$/);if(f.method==="GET"&&h){Dr(f,u,e,h[1]);return}if(f.method==="GET"&&m==="/api/artifacts"){Fr(f,u,l);return}if(f.method==="DELETE"&&m==="/api/artifacts"){Br(f,u,l);return}let g=m.match(/^\/api\/artifacts\/(.+)$/);if(f.method==="DELETE"&&g){Or(f,u,l,decodeURIComponent(g[1]));return}if(f.method==="GET"&&m.startsWith("/artifacts/")){let v=decodeURIComponent(m.slice(11));if(v.includes("..")||v.includes("\0")){S(u,400,{error:"Invalid path"});return}gt(f,u,join(l,v));return}if(f.method==="POST"&&m==="/api/shutdown"){Ur(f,u,p);return}S(u,404,{error:"Not found"});});function y(f){let u=m=>{m.code==="EADDRINUSE"&&o<Zs?(o++,y(f+1)):a(m);};p.once("error",u),p.listen(f,"127.0.0.1",()=>{p.removeListener("error",u);let m=p.address();if(!m||typeof m=="string"){a(new Error("Failed to get server address"));return}d(),r({port:m.port,dispose:()=>new Promise(b=>{clearTimeout(i),p.close(()=>b());})});});}y(s);})}async function zr(e){let t=await oe(e);return {port:t.port,dispose:t.dispose}}function rn(e,t,r,a){let s=JSON.stringify(a?{...e,presentedSummary:a}:e),n=r?JSON.stringify(r):null;return kr(s,t,n)}async function mt(e,t,r,a){try{let s=null,n=null,i=t.reportMode==="streaming"||t.reportMode==="auto"&&e.timeline.length===0&&e.summary.total>=t.streamingThreshold,o,l=t.htmlReportPath,d=dirname(l);mkdirSync(d,{recursive:!0});let c="",p="[]",y=null,f=a?JSON.stringify(a):null;if(i){c=JSON.stringify({...e.summary,testRunId:e.testRunId,startedAt:e.startedAt,completedAt:e.completedAt,totalDuration:e.totalDuration,ci:e.ci,metadata:e.metadata,shardRunIds:e.shardRunIds});let m=dirname(t.outputPath),b=join(m,".testrelic-report");try{let h=join(b,"index-compact.json"),g=join(b,"index.json");existsSync(h)?p=readFileSync(h,"utf-8"):existsSync(g)&&(p=readFileSync(g,"utf-8"));}catch{}y=r?JSON.stringify(r):null,o=dt(c,p,null,y,f);}else o=rn(e,null,r,a);let u=l+".tmp";if(writeFileSync(u,o,"utf-8"),renameSync(u,l),i){if(e.ci===null){let m=dirname(t.outputPath),b=join(m,".testrelic-report"),h=resolve(l);try{if(await sn(),s=await nn(b),!s){n=await oe(b,{htmlPath:h}),s=n.port;let g=setInterval(()=>{},6e4),v=()=>{clearInterval(g),n?.dispose();};process.on("SIGINT",v),process.on("SIGTERM",v),setTimeout(v,1800*1e3).unref();}if(s){process.stderr.write(`
4314
4347
  Report server: http://127.0.0.1:${s}
4315
- `);try{let f=dt(c,p,s,v,g),b=l+".tmp";writeFileSync(b,f,"utf-8"),renameSync(b,l);}catch{}}}catch{}}}else if(t.openReport&&e.ci===null&&t.includeArtifacts){let m=dirname(t.outputPath),h=join(m,"artifacts");if(existsSync(h))try{let y=await Or(h);s=y.port,process.on("exit",()=>{y.dispose();});}catch{}}if(t.openReport&&e.ci===null)if(o&&s)ct(`http://127.0.0.1:${s}`);else {let m=resolve(l);ct(m);}}catch(s){process.stderr.write(`[testrelic] Failed to write HTML report: ${s instanceof Error?s.message:String(s)}
4316
- `);}}var ye=9323,Vr=10;async function tn(){for(let e=ye;e<ye+Vr;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),500),a=await fetch(`http://127.0.0.1:${e}/api/health`,{signal:t.signal});if(clearTimeout(r),a.ok)return e}catch{}return null}async function rn(){for(let e=ye;e<ye+Vr;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),1e3);await fetch(`http://127.0.0.1:${e}/api/shutdown`,{method:"POST",signal:t.signal}),clearTimeout(r);}catch{}await new Promise(e=>setTimeout(e,300));}async function an(e){let r=[join(__dirname,"cli.cjs"),join(__dirname,"cli.js"),join(__dirname,"..","dist","cli.cjs"),join(__dirname,"..","dist","cli.js")].find(a=>existsSync(a));if(!r){let a=await oe(e);return process.on("exit",()=>{a?.dispose();}),a.port}return new Promise(a=>{let s=spawn(process.execPath,[r,"serve",e],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),n="",o=false,i=setTimeout(()=>{o||(o=true,s.stderr?.removeAllListeners(),tn().then(a));},5e3);s.stderr?.on("data",l=>{n+=l.toString();let d=n.match(/127\.0\.0\.1:(\d+)/);d&&!o&&(o=true,clearTimeout(i),s.stderr?.removeAllListeners(),s.unref(),a(Number(d[1])));}),s.on("error",()=>{o||(o=true,clearTimeout(i),a(null));}),s.on("exit",()=>{o||(o=true,clearTimeout(i),a(null));}),s.unref();})}var $r=Buffer.from([137,80,78,71,13,10,26,10]),sn=16,nn=20,xe=24;function jr(e){if(e.length<xe||!e.subarray(0,$r.length).equals($r))return null;let t=e.readUInt32BE(sn),r=e.readUInt32BE(nn);return t===0||r===0?null:{width:t,height:r}}var on=/(\d+) pixels \(ratio [\d.]+ of all image pixels\) are different/,Gr=/Expected an image (\d+)px by (\d+)px, received (\d+)px by (\d+)px/;function Wr(e){return e?Gr.test(e):false}var ln=/^\s*Snapshot:\s*(.+?)\s*$/m;function Kr(e){if(!e)return {};let t={},r=on.exec(e);if(r){let n=Number.parseInt(r[1],10);Number.isFinite(n)&&(t.diffPixels=n);}let a=Gr.exec(e);if(a){let[,n,o,i,l]=a,d=[n,o,i,l].map(c=>Number.parseInt(c,10));d.every(c=>Number.isFinite(c))&&(t.expectedWidth=d[0],t.expectedHeight=d[1],t.actualWidth=d[2],t.actualHeight=d[3]);}let s=ln.exec(e);return s&&(t.snapshotName=s[1]),t}function Jr(e,t){if(e===void 0||!t)return;let r=t.width*t.height;if(!(r<=0))return e/r}var hn=20,vt=0,bt=[];async function le(e,t){vt>=hn&&await new Promise(r=>bt.push(r)),vt++;try{return await copyFile(e,t),!0}catch{return false}finally{vt--,bt.length>0&&bt.shift()();}}var H=[];async function Zr(){H.length!==0&&(await Promise.allSettled(H),H.length=0);}function Qr(e){let t=new Date,r=n=>String(n).padStart(2,"0"),a=`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())}T${r(t.getHours())}-${r(t.getMinutes())}-${r(t.getSeconds())}`;if(!existsSync(join(e,a)))return a;let s=1;for(;existsSync(join(e,`${a}-${s}`));)s++;return `${a}-${s}`}function yt(e){let t=e.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length>100&&(t=t.substring(0,100).replace(/-+$/,"")),t||"unnamed-test"}var mn=8;function ea(e,t,r){let a=yt(e),s=r?yt(r).substring(0,mn):"";return s&&(a+=`--${s}`),t>0&&(a+=`--retry-${t}`),a}function ta(e,t,r,a,s,n){let o=e.find(u=>u.name==="screenshot"&&u.path),i=e.find(u=>u.name==="video"&&u.path),l=e.find(u=>u.name==="trace"&&u.path);if(!o&&!i&&!l)return null;let d=ea(t,r,n),c=s?["artifacts",s,d]:["artifacts",d],p=join(a,...c),v=c,g={};try{mkdirSync(p,{recursive:!0});}catch{return null}if(o?.path&&existsSync(o.path)){let m=`screenshot${extname(o.path)||".png"}`,h=join(p,m);H.push(le(o.path,h).then(()=>{})),g.screenshot=`${v.join("/")}/${m}`;}if(i?.path&&existsSync(i.path)){let m=`video${extname(i.path)||".webm"}`,h=join(p,m);H.push(le(i.path,h).then(()=>{})),g.video=`${v.join("/")}/${m}`;}if(l?.path&&existsSync(l.path)){let m=`trace${extname(l.path)||".zip"}`,h=join(p,m);H.push(le(l.path,h).then(()=>{})),g.trace=`${v.join("/")}/${m}`;}return !g.screenshot&&!g.video&&!g.trace?null:g}var xt="visual",vn=6;function bn(e){let t=createHash("sha256").update(e).digest("hex").substring(0,vn);return `${yt(e)}--${t}`}function Yr(e){let t=null;try{t=openSync(e,"r");let r=Buffer.alloc(xe),a=readSync(t,r,0,xe,0);return jr(r.subarray(0,a))}catch{return null}finally{if(t!==null)try{closeSync(t);}catch{}}}var Xr=[{key:"expectedPath",dest:"baseline",field:"baseline"},{key:"actualPath",dest:"actual",field:"actual"},{key:"diffPath",dest:"diff",field:"diff"},{key:"previousPath",dest:"previous",field:"previous"}],yn=[{key:"baselineDomPath",dest:"baseline.dom.json",field:"baselineDom"},{key:"actualDomPath",dest:"actual.dom.json",field:"actualDom"}];function xn(e,t,r,a){let s=bn(e.name),n=join(t,s),o=Xr.some(u=>e[u.key]);if(o||e.dom)try{mkdirSync(n,{recursive:!0});}catch{return null}let i={},l=false;for(let u of Xr){let m=e[u.key];if(!m||!existsSync(m))continue;let h=extname(m)||".png",y=`${u.dest}${h}`;H.push(le(m,join(n,y)).then(()=>{})),i[u.field]=`${r}/${xt}/${s}/${y}`,l=true;}let d=e.dom;if(d)for(let u of yn){let m=d[u.key];!m||!existsSync(m)||(H.push(le(m,join(n,u.dest)).then(()=>{})),i[u.field]=`${r}/${xt}/${s}/${u.dest}`);}if(!l&&o)return null;let c=e.expectedPath?Yr(e.expectedPath):e.actualPath?Yr(e.actualPath):null,p=Jr(e.diffPixels,c),v=e.committedPath??e.expectedPath,g=v?relative(a,v).replace(/\\/g,"/"):void 0;return {name:e.name,status:e.status,source:e.source,...i,...g?{baselinePath:g}:{},...c?{width:c.width,height:c.height}:{},...e.actualWidth!==void 0?{actualWidth:e.actualWidth}:{},...e.actualHeight!==void 0?{actualHeight:e.actualHeight}:{},...e.diffPixels!==void 0?{diffPixels:e.diffPixels}:{},...p!==void 0?{diffPixelRatio:p}:{},...d?{domChanges:d.changes,domChangeCount:d.total,domRootCauses:d.rootCauses,domTruncated:d.truncated,domCaptureBox:d.captureBox}:{}}}function ra(e,t,r,a,s,n,o=process.cwd()){if(e.length===0)return null;let i=ea(t,r,n),l=s?["artifacts",s,i]:["artifacts",i],d=join(a,...l,xt),c=l.join("/");try{mkdirSync(d,{recursive:!0});}catch{return null}let p=[];for(let v of e){let g=xn(v,d,c,o);g&&p.push(g);}return p.length>0?p:null}var aa="testrelic-visual-dom";var wn="testrelic-visual",kn=/^(.+)-(expected|actual|diff|previous)(\.[A-Za-z0-9]+)$/;function Sn(e){let t=new Map;for(let r of e)if(!(r.name!==wn||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let s of a){let n=Tn(s);n&&t.set(n.stem,n);}}catch{}return t}var Cn=["passed","failed","new","updated"];function Tn(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.stem!="string"||!t.stem||typeof t.name!="string"||!t.name||typeof t.status!="string"||!Cn.includes(t.status)?null:{stem:t.stem,name:t.name,status:t.status,...typeof t.committedPath=="string"&&t.committedPath?{committedPath:t.committedPath}:{}}}function Rn(e){let t=new Map;for(let r of e)if(!(r.name!==aa||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let s of a){if(typeof s!="object"||s===null)continue;let n=s;typeof n.stem!="string"||!Array.isArray(n.changes)||t.set(n.stem,s);}}catch{}return t}function An(e){let t=new Map;for(let r of e){if(!r.path)continue;let a=kn.exec(r.name);if(!a)continue;let[,s,n]=a,o=t.get(s)??{};o[n]=r.path,t.set(s,o);}return t}function _n(e){return !!(e.actual&&(e.expected||e.diff))}function In(e,t,r){return e.diff||Wr(r)?"failed":t?"updated":"new"}function Mn(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;let r=t.replace(/\.[A-Za-z0-9]+$/,""),a=e.filter(s=>s===r||s.endsWith(`/${r}`));return a.length===1?a[0]:null}function ia(e,t={}){if(e.length===0)return [];let r=Sn(e),a=Rn(e),s=An(e);if(s.size===0&&r.size===0)return [];let n=t.updatingSnapshots===true,o=[];for(let[i,l]of s){let d=r.get(i);!d&&!_n(l)||o.push({name:d?.name??i,status:d?.status??In(l,n,t.failureMessage),source:d?"toMatchVisualBaseline":"toHaveScreenshot",...l.expected?{expectedPath:l.expected}:{},...d?.committedPath?{committedPath:d.committedPath}:{},...l.actual?{actualPath:l.actual}:{},...l.diff?{diffPath:l.diff}:{},...l.previous?{previousPath:l.previous}:{},...a.has(i)?{dom:a.get(i)}:{}});}for(let[i,l]of r)s.has(i)||o.push({name:l.name,status:l.status,source:"toMatchVisualBaseline",...l.committedPath?{committedPath:l.committedPath}:{},...a.has(i)?{dom:a.get(i)}:{}});return En(o,s,t.failureMessage)}function En(e,t,r){let a=Kr(r);if(a.diffPixels===void 0&&a.actualWidth===void 0)return [...e];let s=e.filter(o=>o.status==="failed"&&sa(o)).map(o=>na(o,t)),n=Mn(s,a.snapshotName);return n===null?[...e]:e.map(o=>sa(o)&&na(o,t)===n?{...o,...a.diffPixels!==void 0?{diffPixels:a.diffPixels}:{},...a.actualWidth!==void 0?{actualWidth:a.actualWidth}:{},...a.actualHeight!==void 0?{actualHeight:a.actualHeight}:{}}:o)}function sa(e){return !!(e.expectedPath||e.actualPath||e.diffPath||e.previousPath)}function na(e,t){if(t.has(e.name))return e.name;for(let[r,a]of t)if(a.actual===e.actualPath&&a.expected===e.expectedPath&&a.diff===e.diffPath)return r;return e.name}var Pn=new RegExp("[\x1B\x9B][[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[0-9A-PR-TZcf-nqry=><]","g");function ke(e){return !e||e.indexOf("\x1B")===-1&&e.indexOf("\x9B")===-1?e:e.replace(Pn,"")}function oa(e){return e==null?null:ke(e)}var Dn=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Ln="1.0",kt="visual";function ua(e){let t=extname(e).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(t)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(t)?"video":t===".zip"&&basename(e,t)==="trace"?"trace":"other"}function Nn(e){if(e.endsWith(".dom.json"))return "dom";let t=basename(e,extname(e));return t==="baseline"?"baseline":t==="diff"?"diff":ua(e)}function Fn(e,t,r){let a=[];try{for(let s of readdirSync(e,{withFileTypes:!0})){if(!s.isFile())continue;let n=statSync(join(e,s.name));a.push({name:`${kt}/${r}/${s.name}`,type:Nn(s.name),relativePath:`${t}/${kt}/${r}/${s.name}`,sizeBytes:n.size});}}catch{}return a}function pa(e,t,r){let a=[],s=`artifacts/${t}/${r}`;try{let n=readdirSync(e,{withFileTypes:!0});for(let o of n){if(o.isDirectory()&&o.name===kt){let d=join(e,o.name);for(let c of readdirSync(d,{withFileTypes:!0}))c.isDirectory()&&a.push(...Fn(join(d,c.name),s,c.name));continue}if(!o.isFile())continue;let i=join(e,o.name),l=statSync(i);a.push({name:o.name,type:ua(o.name),relativePath:`${s}/${o.name}`,sizeBytes:l.size});}}catch{}return {testName:r,files:a}}function Bn(e,t){let r=join(e,t),a=[],s=0;try{let o=readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=pa(join(r,i.name),t,i.name);a.push(l);for(let d of l.files)s+=d.sizeBytes;}}catch{}let n=t.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return a.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:t,timestamp:n,totalSizeBytes:s,testCount:a.length,tests:a,isCurrentRun:false}}function fa(e,t){let r=join(e,"artifacts"),a=[],s=[],n=0;try{let i=readdirSync(r,{withFileTypes:!0});for(let l of i)if(l.isDirectory())if(Dn.test(l.name)){let d=Bn(r,l.name);a.push({...d,isCurrentRun:l.name===t});}else {let d=pa(join(r,l.name),l.name,l.name);s.push(d);for(let c of d.files)n+=c.sizeBytes;}}catch{}a.sort((i,l)=>l.timestamp.localeCompare(i.timestamp)),s.length>0&&(s.sort((i,l)=>i.testName.localeCompare(l.testName)),a.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:n,testCount:s.length,tests:s,isCurrentRun:false}));let o=a.reduce((i,l)=>i+l.totalSizeBytes,0);return {schemaVersion:Ln,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:a,serverPort:null}}var Vn=256;function $n(e){let t=resolve(e);for(let r=0;r<Vn;r++){if(existsSync(join(t,".git")))return t;let a=dirname(t);if(a===t)return null;t=a;}return null}function ma(e){try{let t=$n(e);if(!t)return;let r=join(t,".gitignore"),a=relative(t,e).replace(/\\/g,"/"),s=a.endsWith("/")?a:`${a}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
4348
+ `);try{let g=dt(c,p,s,y,f),v=l+".tmp";writeFileSync(v,g,"utf-8"),renameSync(v,l);}catch{}}}catch{}}}else if(t.openReport&&e.ci===null&&t.includeArtifacts){let m=dirname(t.outputPath),b=join(m,"artifacts");if(existsSync(b))try{let h=await zr(b);s=h.port,process.on("exit",()=>{h.dispose();});}catch{}}if(t.openReport&&e.ci===null)if(i&&s)ct(`http://127.0.0.1:${s}`);else {let m=resolve(l);ct(m);}}catch(s){process.stderr.write(`[testrelic] Failed to write HTML report: ${s instanceof Error?s.message:String(s)}
4349
+ `);}}var be=9323,jr=10;async function an(){for(let e=be;e<be+jr;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),500),a=await fetch(`http://127.0.0.1:${e}/api/health`,{signal:t.signal});if(clearTimeout(r),a.ok)return e}catch{}return null}async function sn(){for(let e=be;e<be+jr;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),1e3);await fetch(`http://127.0.0.1:${e}/api/shutdown`,{method:"POST",signal:t.signal}),clearTimeout(r);}catch{}await new Promise(e=>setTimeout(e,300));}async function nn(e){let r=[join(__dirname,"cli.cjs"),join(__dirname,"cli.js"),join(__dirname,"..","dist","cli.cjs"),join(__dirname,"..","dist","cli.js")].find(a=>existsSync(a));if(!r){let a=await oe(e);return process.on("exit",()=>{a?.dispose();}),a.port}return new Promise(a=>{let s=spawn(process.execPath,[r,"serve",e],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),n="",i=false,o=setTimeout(()=>{i||(i=true,s.stderr?.removeAllListeners(),an().then(a));},5e3);s.stderr?.on("data",l=>{n+=l.toString();let d=n.match(/127\.0\.0\.1:(\d+)/);d&&!i&&(i=true,clearTimeout(o),s.stderr?.removeAllListeners(),s.unref(),a(Number(d[1])));}),s.on("error",()=>{i||(i=true,clearTimeout(o),a(null));}),s.on("exit",()=>{i||(i=true,clearTimeout(o),a(null));}),s.unref();})}var Gr=Buffer.from([137,80,78,71,13,10,26,10]),on=16,ln=20,xe=24;function Wr(e){if(e.length<xe||!e.subarray(0,Gr.length).equals(Gr))return null;let t=e.readUInt32BE(on),r=e.readUInt32BE(ln);return t===0||r===0?null:{width:t,height:r}}var dn=/(\d+) pixels \(ratio [\d.]+ of all image pixels\) are different/,Kr=/Expected an image (\d+)px by (\d+)px, received (\d+)px by (\d+)px/;function Jr(e){return e?Kr.test(e):false}var cn=/^\s*Snapshot:\s*(.+?)\s*$/m;function Yr(e){if(!e)return {};let t={},r=dn.exec(e);if(r){let n=Number.parseInt(r[1],10);Number.isFinite(n)&&(t.diffPixels=n);}let a=Kr.exec(e);if(a){let[,n,i,o,l]=a,d=[n,i,o,l].map(c=>Number.parseInt(c,10));d.every(c=>Number.isFinite(c))&&(t.expectedWidth=d[0],t.expectedHeight=d[1],t.actualWidth=d[2],t.actualHeight=d[3]);}let s=cn.exec(e);return s&&(t.snapshotName=s[1]),t}function Xr(e,t){if(e===void 0||!t)return;let r=t.width*t.height;if(!(r<=0))return e/r}var vn=20,vt=0,yt=[];async function le(e,t){vt>=vn&&await new Promise(r=>yt.push(r)),vt++;try{return await copyFile(e,t),!0}catch{return false}finally{vt--,yt.length>0&&yt.shift()();}}var H=[];async function ea(){H.length!==0&&(await Promise.allSettled(H),H.length=0);}function ta(e){let t=new Date,r=n=>String(n).padStart(2,"0"),a=`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())}T${r(t.getHours())}-${r(t.getMinutes())}-${r(t.getSeconds())}`;if(!existsSync(join(e,a)))return a;let s=1;for(;existsSync(join(e,`${a}-${s}`));)s++;return `${a}-${s}`}function bt(e){let t=e.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length>100&&(t=t.substring(0,100).replace(/-+$/,"")),t||"unnamed-test"}var yn=8;function ra(e,t,r){let a=bt(e),s=r?bt(r).substring(0,yn):"";return s&&(a+=`--${s}`),t>0&&(a+=`--retry-${t}`),a}function aa(e,t,r,a,s,n){let i=e.find(u=>u.name==="screenshot"&&u.path),o=e.find(u=>u.name==="video"&&u.path),l=e.find(u=>u.name==="trace"&&u.path);if(!i&&!o&&!l)return null;let d=ra(t,r,n),c=s?["artifacts",s,d]:["artifacts",d],p=join(a,...c),y=c,f={};try{mkdirSync(p,{recursive:!0});}catch{return null}if(i?.path&&existsSync(i.path)){let m=`screenshot${extname(i.path)||".png"}`,b=join(p,m);H.push(le(i.path,b).then(()=>{})),f.screenshot=`${y.join("/")}/${m}`;}if(o?.path&&existsSync(o.path)){let m=`video${extname(o.path)||".webm"}`,b=join(p,m);H.push(le(o.path,b).then(()=>{})),f.video=`${y.join("/")}/${m}`;}if(l?.path&&existsSync(l.path)){let m=`trace${extname(l.path)||".zip"}`,b=join(p,m);H.push(le(l.path,b).then(()=>{})),f.trace=`${y.join("/")}/${m}`;}return !f.screenshot&&!f.video&&!f.trace?null:f}var xt="visual",bn=6;function xn(e){let t=createHash("sha256").update(e).digest("hex").substring(0,bn);return `${bt(e)}--${t}`}function Zr(e){let t=null;try{t=openSync(e,"r");let r=Buffer.alloc(xe),a=readSync(t,r,0,xe,0);return Wr(r.subarray(0,a))}catch{return null}finally{if(t!==null)try{closeSync(t);}catch{}}}var Qr=[{key:"expectedPath",dest:"baseline",field:"baseline"},{key:"actualPath",dest:"actual",field:"actual"},{key:"diffPath",dest:"diff",field:"diff"},{key:"previousPath",dest:"previous",field:"previous"}],wn=[{key:"baselineDomPath",dest:"baseline.dom.json",field:"baselineDom"},{key:"actualDomPath",dest:"actual.dom.json",field:"actualDom"}];function kn(e,t,r,a){let s=xn(e.name),n=join(t,s),i=Qr.some(u=>e[u.key]);if(i||e.dom)try{mkdirSync(n,{recursive:!0});}catch{return null}let o={},l=false;for(let u of Qr){let m=e[u.key];if(!m||!existsSync(m))continue;let b=extname(m)||".png",h=`${u.dest}${b}`;H.push(le(m,join(n,h)).then(()=>{})),o[u.field]=`${r}/${xt}/${s}/${h}`,l=true;}let d=e.dom;if(d)for(let u of wn){let m=d[u.key];!m||!existsSync(m)||(H.push(le(m,join(n,u.dest)).then(()=>{})),o[u.field]=`${r}/${xt}/${s}/${u.dest}`);}if(!l&&i)return null;let c=e.expectedPath?Zr(e.expectedPath):e.actualPath?Zr(e.actualPath):null,p=Xr(e.diffPixels,c),y=e.committedPath??e.expectedPath,f=y?relative(a,y).replace(/\\/g,"/"):void 0;return {name:e.name,status:e.status,source:e.source,...o,...f?{baselinePath:f}:{},...c?{width:c.width,height:c.height}:{},...e.actualWidth!==void 0?{actualWidth:e.actualWidth}:{},...e.actualHeight!==void 0?{actualHeight:e.actualHeight}:{},...e.diffPixels!==void 0?{diffPixels:e.diffPixels}:{},...p!==void 0?{diffPixelRatio:p}:{},...d?{domChanges:d.changes,domChangeCount:d.total,domRootCauses:d.rootCauses,domTruncated:d.truncated,domCaptureBox:d.captureBox}:{}}}function sa(e,t,r,a,s,n,i=process.cwd()){if(e.length===0)return null;let o=ra(t,r,n),l=s?["artifacts",s,o]:["artifacts",o],d=join(a,...l,xt),c=l.join("/");try{mkdirSync(d,{recursive:!0});}catch{return null}let p=[];for(let y of e){let f=kn(y,d,c,i);f&&p.push(f);}return p.length>0?p:null}var na="testrelic-visual-dom";var Sn="testrelic-visual",Cn=/^(.+)-(expected|actual|diff|previous)(\.[A-Za-z0-9]+)$/;function Tn(e){let t=new Map;for(let r of e)if(!(r.name!==Sn||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let s of a){let n=An(s);n&&t.set(n.stem,n);}}catch{}return t}var Rn=["passed","failed","new","updated"];function An(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.stem!="string"||!t.stem||typeof t.name!="string"||!t.name||typeof t.status!="string"||!Rn.includes(t.status)?null:{stem:t.stem,name:t.name,status:t.status,...typeof t.committedPath=="string"&&t.committedPath?{committedPath:t.committedPath}:{}}}function _n(e){let t=new Map;for(let r of e)if(!(r.name!==na||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let s of a){if(typeof s!="object"||s===null)continue;let n=s;typeof n.stem!="string"||!Array.isArray(n.changes)||t.set(n.stem,s);}}catch{}return t}function In(e){let t=new Map;for(let r of e){if(!r.path)continue;let a=Cn.exec(r.name);if(!a)continue;let[,s,n]=a,i=t.get(s)??{};i[n]=r.path,t.set(s,i);}return t}function Mn(e){return !!(e.actual&&(e.expected||e.diff))}function En(e,t,r){return e.diff||Jr(r)?"failed":t?"updated":"new"}function Pn(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;let r=t.replace(/\.[A-Za-z0-9]+$/,""),a=e.filter(s=>s===r||s.endsWith(`/${r}`));return a.length===1?a[0]:null}function la(e,t={}){if(e.length===0)return [];let r=Tn(e),a=_n(e),s=In(e);if(s.size===0&&r.size===0)return [];let n=t.updatingSnapshots===true,i=[];for(let[o,l]of s){let d=r.get(o);!d&&!Mn(l)||i.push({name:d?.name??o,status:d?.status??En(l,n,t.failureMessage),source:d?"toMatchVisualBaseline":"toHaveScreenshot",...l.expected?{expectedPath:l.expected}:{},...d?.committedPath?{committedPath:d.committedPath}:{},...l.actual?{actualPath:l.actual}:{},...l.diff?{diffPath:l.diff}:{},...l.previous?{previousPath:l.previous}:{},...a.has(o)?{dom:a.get(o)}:{}});}for(let[o,l]of r)s.has(o)||i.push({name:l.name,status:l.status,source:"toMatchVisualBaseline",...l.committedPath?{committedPath:l.committedPath}:{},...a.has(o)?{dom:a.get(o)}:{}});return Dn(i,s,t.failureMessage)}function Dn(e,t,r){let a=Yr(r);if(a.diffPixels===void 0&&a.actualWidth===void 0)return [...e];let s=e.filter(i=>i.status==="failed"&&ia(i)).map(i=>oa(i,t)),n=Pn(s,a.snapshotName);return n===null?[...e]:e.map(i=>ia(i)&&oa(i,t)===n?{...i,...a.diffPixels!==void 0?{diffPixels:a.diffPixels}:{},...a.actualWidth!==void 0?{actualWidth:a.actualWidth}:{},...a.actualHeight!==void 0?{actualHeight:a.actualHeight}:{}}:i)}function ia(e){return !!(e.expectedPath||e.actualPath||e.diffPath||e.previousPath)}function oa(e,t){if(t.has(e.name))return e.name;for(let[r,a]of t)if(a.actual===e.actualPath&&a.expected===e.expectedPath&&a.diff===e.diffPath)return r;return e.name}var Ln=new RegExp("[\x1B\x9B][[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[0-9A-PR-TZcf-nqry=><]","g");function ke(e){return !e||e.indexOf("\x1B")===-1&&e.indexOf("\x9B")===-1?e:e.replace(Ln,"")}function da(e){return e==null?null:ke(e)}var Nn=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Fn="1.0",kt="visual";function fa(e){let t=extname(e).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(t)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(t)?"video":t===".zip"&&basename(e,t)==="trace"?"trace":"other"}function Bn(e){if(e.endsWith(".dom.json"))return "dom";let t=basename(e,extname(e));return t==="baseline"?"baseline":t==="diff"?"diff":fa(e)}function On(e,t,r){let a=[];try{for(let s of readdirSync(e,{withFileTypes:!0})){if(!s.isFile())continue;let n=statSync(join(e,s.name));a.push({name:`${kt}/${r}/${s.name}`,type:Bn(s.name),relativePath:`${t}/${kt}/${r}/${s.name}`,sizeBytes:n.size});}}catch{}return a}function ga(e,t,r){let a=[],s=`artifacts/${t}/${r}`;try{let n=readdirSync(e,{withFileTypes:!0});for(let i of n){if(i.isDirectory()&&i.name===kt){let d=join(e,i.name);for(let c of readdirSync(d,{withFileTypes:!0}))c.isDirectory()&&a.push(...On(join(d,c.name),s,c.name));continue}if(!i.isFile())continue;let o=join(e,i.name),l=statSync(o);a.push({name:i.name,type:fa(i.name),relativePath:`${s}/${i.name}`,sizeBytes:l.size});}}catch{}return {testName:r,files:a}}function Un(e,t){let r=join(e,t),a=[],s=0;try{let i=readdirSync(r,{withFileTypes:!0});for(let o of i){if(!o.isDirectory())continue;let l=ga(join(r,o.name),t,o.name);a.push(l);for(let d of l.files)s+=d.sizeBytes;}}catch{}let n=t.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return a.sort((i,o)=>i.testName.localeCompare(o.testName)),{folderName:t,timestamp:n,totalSizeBytes:s,testCount:a.length,tests:a,isCurrentRun:false}}function ha(e,t){let r=join(e,"artifacts"),a=[],s=[],n=0;try{let o=readdirSync(r,{withFileTypes:!0});for(let l of o)if(l.isDirectory())if(Nn.test(l.name)){let d=Un(r,l.name);a.push({...d,isCurrentRun:l.name===t});}else {let d=ga(join(r,l.name),l.name,l.name);s.push(d);for(let c of d.files)n+=c.sizeBytes;}}catch{}a.sort((o,l)=>l.timestamp.localeCompare(o.timestamp)),s.length>0&&(s.sort((o,l)=>o.testName.localeCompare(l.testName)),a.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:n,testCount:s.length,tests:s,isCurrentRun:false}));let i=a.reduce((o,l)=>o+l.totalSizeBytes,0);return {schemaVersion:Fn,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:i,runs:a,serverPort:null}}var jn=256;function Gn(e){let t=resolve(e);for(let r=0;r<jn;r++){if(existsSync(join(t,".git")))return t;let a=dirname(t);if(a===t)return null;t=a;}return null}function ya(e){try{let t=Gn(e);if(!t)return;let r=join(t,".gitignore"),a=relative(t,e).replace(/\\/g,"/"),s=a.endsWith("/")?a:`${a}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
4317
4350
  `).map(l=>l.trim()).some(l=>l===s||l===a))return;let n=`
4318
4351
  # TestRelic test artifacts
4319
4352
  ${s}
4320
- `;appendFileSync(r,n,"utf-8");}catch{}}var va=Symbol("testrelic.timeout"),ba=3e4,St=12e4,Ct=6e4,ya=15e3;async function J(e,t,r){let a,s=new Promise(n=>{a=setTimeout(()=>n(va),t),typeof a?.unref=="function"&&a.unref();});try{let n=await Promise.race([e(),s]);if(n===va){process.stderr.write(`[testrelic] ${r} timed out after ${Math.round(t/1e3)}s \u2014 continuing without it. Your tests are unaffected.
4353
+ `;appendFileSync(r,n,"utf-8");}catch{}}var ba=Symbol("testrelic.timeout"),xa=3e4,St=12e4,Ct=6e4,wa=15e3;async function J(e,t,r){let a,s=new Promise(n=>{a=setTimeout(()=>n(ba),t),typeof a?.unref=="function"&&a.unref();});try{let n=await Promise.race([e(),s]);if(n===ba){process.stderr.write(`[testrelic] ${r} timed out after ${Math.round(t/1e3)}s \u2014 continuing without it. Your tests are unaffected.
4321
4354
  `);return}return n}catch(n){process.stderr.write(`[testrelic] ${r} failed \u2014 continuing without it. Your tests are unaffected. (${n instanceof Error?n.message:String(n)})
4322
- `);return}finally{a&&clearTimeout(a);}}function ka(e,t){let r=[];for(let a of e){let s=jn(a),n=Gn(a),o=Wn(a,s,n,t),i=Kn(a,s,n);if(o.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:a.startedAt,durationOnUrl:a.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:a.specFile,test:s,tests:[n],_testTitle:a.title});continue}r.push(...o,...i);}return r.sort(Jn),Yn(r,e),r.map((a,s)=>a.type==="navigation"?{...{index:s,type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:a.durationOnUrl??0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:a.specFile,test:a.test},tests:a.tests}:{...{index:s,type:"api_call",callId:a.callId,method:a.method,url:a.url,timestamp:a.timestamp,responseTime:a.responseTime??null,request:a.request,response:a.response??null,...a.error?{error:a.error}:{},assertions:a.assertions??[],specFile:a.specFile,test:a.test},tests:a.tests})}function jn(e){return {title:e.title,fullTitle:e.titlePath,status:e.status,duration:e.duration,retries:e.retryCount,retry:e.retry,tags:e.tags,failure:e.failure}}function Gn(e){return {title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:e.networkRequests,apiCalls:e.apiCalls,apiAssertions:e.apiAssertions,actions:e.actions,consoleLogs:e.consoleLogs}}function Wn(e,t,r,a){let s=[];for(let n of e.navigations)a.navigationTypes!==null&&!a.navigationTypes.includes(n.navigationType)||s.push({type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title});return s}function Kn(e,t,r){if(!e.apiCalls||e.apiCalls.length===0)return [];let a=e.apiAssertions??[];return e.apiCalls.map(s=>{let n=a.filter(i=>i.callId===s.id).map(i=>({type:i.type,expected:i.expected,actual:i.actual,status:i.status,location:i.location,...i.expression!==void 0?{expression:i.expression}:{}})),o=null;return s.responseStatusCode!==null&&s.responseStatusText!==null&&(o={statusCode:s.responseStatusCode,statusText:s.responseStatusText,headers:s.responseHeaders,body:wa(s.responseBody)}),{type:"api_call",callId:s.id,method:s.method,url:s.url,timestamp:s.timestamp,responseTime:s.error?null:s.responseTimeMs,request:{headers:s.requestHeaders,body:wa(s.requestBody)},response:o,...s.error?{error:s.error}:{},assertions:n,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title}})}function Jn(e,t){let r=new Date(e.timestamp).getTime(),a=new Date(t.timestamp).getTime();if(r!==a)return r-a;let s={navigation:0,api_call:1},n=s[e.type],o=s[t.type];return n!==o?n-o:e.type==="api_call"&&t.type==="api_call"&&e.callId&&t.callId?xa(e.callId)-xa(t.callId):0}function xa(e){let t=e.match(/(\d+)$/);return t?parseInt(t[1],10):0}function Yn(e,t){for(let r=0;r<e.length;r++){let a=e[r];if(a.type!=="navigation")continue;let s=new Date(a.timestamp).getTime(),n=null;for(let o=r+1;o<e.length;o++)if(e[o]._testTitle===a._testTitle){n=new Date(e[o].timestamp).getTime();break}if(n!==null)a.durationOnUrl=Math.max(0,n-s);else {let o=t.find(i=>i.title===a._testTitle);if(o){let i=new Date(o.completedAt).getTime();a.durationOnUrl=Math.max(0,i-s);}}}}function wa(e){if(e==null)return null;try{return JSON.parse(e)}catch{return e}}function Y(e,t){let r=e.length,a=Math.min(Math.ceil(t/100*r)-1,r-1);return e[Math.max(0,a)]}function Tt(e){try{let t=new URL(e);return t.origin+t.pathname}catch{return e}}function Xn(e){return e==null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function Sa(e,t){let r=0,a=0,s=0,n=0,o=0;for(let k of e)switch(k.status){case "passed":r++;break;case "failed":a++;break;case "flaky":s++;break;case "skipped":n++;break;case "timedout":o++;break}let i=[];for(let k of e)k.apiCalls&&i.push(...k.apiCalls);let l=i.length,d=new Set,c={},p={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},v=[];for(let k of i)d.add(Tt(k.url)),c[k.method]=(c[k.method]??0)+1,p[Xn(k.responseStatusCode)]+=1,v.push(k.responseTimeMs);let g=null;if(v.length>0){let k=[...v].sort((X,G)=>X-G),C=k.reduce((X,G)=>X+G,0);g={avg:Math.round(C/k.length),min:k[0],max:k[k.length-1],p50:Y(k,50),p95:Y(k,95),p99:Y(k,99)};}let u=0,m=0,h=0;for(let k of e)if(k.apiAssertions)for(let C of k.apiAssertions)u++,C.status==="passed"?m++:h++;let y=0,f=new Set;for(let k of e){y+=k.navigations.length;for(let C of k.navigations)f.add(C.url);}let b=0,x={};function w(k){for(let C of k)b++,x[C.category]=(x[C.category]??0)+1,C.children.length>0&&w(C.children);}for(let k of e)k.actions&&w(k.actions);let M=0,A=0,R=0,D=0;for(let k of e)if(k.visual)for(let C of k.visual)M++,C.status==="failed"?A++:(C.status==="new"||C.status==="updated")&&R++,D+=C.domChangeCount??0;return {total:e.length,passed:r,failed:a,flaky:s,skipped:n,timedout:o,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:c,apiCallsByStatusRange:p,apiResponseTime:g,totalAssertions:u,passedAssertions:m,failedAssertions:h,totalNavigations:y,uniqueNavigationUrls:f.size,totalTimelineSteps:t,totalActionSteps:b,actionStepsByCategory:x,visualChecks:M,visualFailures:A,visualNew:R,visualDomChanges:D}}function Zn(e){let t=56-e.length;return t>0?e+" ".repeat(t):e}function I(e){return `\u2502 ${Zn(e)} \u2502
4355
+ `);return}finally{a&&clearTimeout(a);}}function Ca(e,t){let r=[];for(let a of e){let s=Wn(a),n=Kn(a),i=Jn(a,s,n,t),o=Yn(a,s,n);if(i.length===0&&o.length===0){r.push({type:"navigation",url:"about:blank",timestamp:a.startedAt,durationOnUrl:a.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:a.specFile,test:s,tests:[n],_testTitle:a.title});continue}r.push(...i,...o);}return r.sort(Xn),Zn(r,e),r.map((a,s)=>a.type==="navigation"?{...{index:s,type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:a.durationOnUrl??0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:a.specFile,test:a.test},tests:a.tests}:{...{index:s,type:"api_call",callId:a.callId,method:a.method,url:a.url,timestamp:a.timestamp,responseTime:a.responseTime??null,request:a.request,response:a.response??null,...a.error?{error:a.error}:{},assertions:a.assertions??[],specFile:a.specFile,test:a.test},tests:a.tests})}function Wn(e){return {title:e.title,fullTitle:e.titlePath,status:e.status,duration:e.duration,retries:e.retryCount,retry:e.retry,tags:e.tags,failure:e.failure}}function Kn(e){return {title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,retry:e.retry,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:e.networkRequests,apiCalls:e.apiCalls,apiAssertions:e.apiAssertions,actions:e.actions,consoleLogs:e.consoleLogs}}function Jn(e,t,r,a){let s=[];for(let n of e.navigations)a.navigationTypes!==null&&!a.navigationTypes.includes(n.navigationType)||s.push({type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title});return s}function Yn(e,t,r){if(!e.apiCalls||e.apiCalls.length===0)return [];let a=e.apiAssertions??[];return e.apiCalls.map(s=>{let n=a.filter(o=>o.callId===s.id).map(o=>({type:o.type,expected:o.expected,actual:o.actual,status:o.status,location:o.location,...o.expression!==void 0?{expression:o.expression}:{}})),i=null;return s.responseStatusCode!==null&&s.responseStatusText!==null&&(i={statusCode:s.responseStatusCode,statusText:s.responseStatusText,headers:s.responseHeaders,body:Sa(s.responseBody)}),{type:"api_call",callId:s.id,method:s.method,url:s.url,timestamp:s.timestamp,responseTime:s.error?null:s.responseTimeMs,request:{headers:s.requestHeaders,body:Sa(s.requestBody)},response:i,...s.error?{error:s.error}:{},assertions:n,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title}})}function Xn(e,t){let r=new Date(e.timestamp).getTime(),a=new Date(t.timestamp).getTime();if(r!==a)return r-a;let s={navigation:0,api_call:1},n=s[e.type],i=s[t.type];return n!==i?n-i:e.type==="api_call"&&t.type==="api_call"&&e.callId&&t.callId?ka(e.callId)-ka(t.callId):0}function ka(e){let t=e.match(/(\d+)$/);return t?parseInt(t[1],10):0}function Zn(e,t){for(let r=0;r<e.length;r++){let a=e[r];if(a.type!=="navigation")continue;let s=new Date(a.timestamp).getTime(),n=null;for(let i=r+1;i<e.length;i++)if(e[i]._testTitle===a._testTitle&&e[i].test.retry===a.test.retry){n=new Date(e[i].timestamp).getTime();break}if(n!==null)a.durationOnUrl=Math.max(0,n-s);else {let i=t.find(o=>o.title===a._testTitle&&o.retry===a.test.retry);if(i){let o=new Date(i.completedAt).getTime();a.durationOnUrl=Math.max(0,o-s);}}}}function Sa(e){if(e==null)return null;try{return JSON.parse(e)}catch{return e}}function Y(e,t){let r=e.length,a=Math.min(Math.ceil(t/100*r)-1,r-1);return e[Math.max(0,a)]}function Tt(e){try{let t=new URL(e);return t.origin+t.pathname}catch{return e}}function Qn(e){return e==null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function Ta(e,t){let r=0,a=0,s=0,n=0,i=0;for(let k of e)switch(k.status){case "passed":r++;break;case "failed":a++;break;case "flaky":s++;break;case "skipped":n++;break;case "timedout":i++;break}let o=[];for(let k of e)k.apiCalls&&o.push(...k.apiCalls);let l=o.length,d=new Set,c={},p={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},y=[];for(let k of o)d.add(Tt(k.url)),c[k.method]=(c[k.method]??0)+1,p[Qn(k.responseStatusCode)]+=1,y.push(k.responseTimeMs);let f=null;if(y.length>0){let k=[...y].sort((X,G)=>X-G),C=k.reduce((X,G)=>X+G,0);f={avg:Math.round(C/k.length),min:k[0],max:k[k.length-1],p50:Y(k,50),p95:Y(k,95),p99:Y(k,99)};}let u=0,m=0,b=0;for(let k of e)if(k.apiAssertions)for(let C of k.apiAssertions)u++,C.status==="passed"?m++:b++;let h=0,g=new Set;for(let k of e){h+=k.navigations.length;for(let C of k.navigations)g.add(C.url);}let v=0,w={};function x(k){for(let C of k)v++,w[C.category]=(w[C.category]??0)+1,C.children.length>0&&x(C.children);}for(let k of e)k.actions&&x(k.actions);let A=0,T=0,R=0,I=0;for(let k of e)if(k.visual)for(let C of k.visual)A++,C.status==="failed"?T++:(C.status==="new"||C.status==="updated")&&R++,I+=C.domChangeCount??0;return {total:e.length,passed:r,failed:a,flaky:s,skipped:n,timedout:i,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:c,apiCallsByStatusRange:p,apiResponseTime:f,totalAssertions:u,passedAssertions:m,failedAssertions:b,totalNavigations:h,uniqueNavigationUrls:g.size,totalTimelineSteps:t,totalActionSteps:v,actionStepsByCategory:w,visualChecks:A,visualFailures:T,visualNew:R,visualDomChanges:I}}function ei(e){let t=56-e.length;return t>0?e+" ".repeat(t):e}function E(e){return `\u2502 ${ei(e)} \u2502
4323
4356
  `}function Rt(e,t,r,a,s){if(a||e.total===0)return;let n=`\u250C${"\u2500".repeat(58)}\u2510
4324
- `,o=`\u2514${"\u2500".repeat(58)}\u2518
4325
- `,i=I(""),l=n;l+=I("TestRelic AI - Playwright Test Report"),l+=i;let d=s??e,c=[];if(d.passed>0&&c.push(`${d.passed} \u2713`),d.failed>0&&c.push(`${d.failed} \u2717`),d.flaky>0&&c.push(`${d.flaky} \u26A0`),d.skipped>0&&c.push(`${d.skipped} skipped`),d.timedout>0&&c.push(`${d.timedout} timedout`),l+=I(`Tests: ${e.total} total (${c.join(" ")})`),s&&s.expectedFailures>0&&(l+=I(` ${s.expectedFailures} failed as expected (test.fail)`)),s&&s.unexpectedPasses>0&&(l+=I(` ${s.unexpectedPasses} expected to fail, but passed (test.fail)`)),e.totalNavigations>0&&(l+=I(`Navigations: ${e.totalNavigations} visits across ${e.uniqueNavigationUrls} unique URLs`)),e.totalApiCalls>0){l+=I(`API Calls: ${e.totalApiCalls} calls across ${e.uniqueApiUrls} unique endpoints`);let p=Object.entries(e.apiCallsByMethod).filter(([,g])=>g>0).map(([g,u])=>`${g}: ${u}`);p.length>0&&(l+=I(` ${p.join(" ")}`));let v=Object.entries(e.apiCallsByStatusRange).filter(([,g])=>g>0).map(([g,u])=>`${g}: ${u}`);v.length>0&&(l+=I(` ${v.join(" ")}`)),e.apiResponseTime&&(l+=I(` Avg response: ${e.apiResponseTime.avg}ms P95: ${e.apiResponseTime.p95}ms`));}if(e.totalAssertions>0&&(l+=I(`Assertions: ${e.totalAssertions} total (${e.passedAssertions} \u2713 ${e.failedAssertions} \u2717)`)),e.totalActionSteps>0){let p=[],v=e.actionStepsByCategory;v.ui_action&&p.push(`${v.ui_action} UI`),v.assertion&&p.push(`${v.assertion} assertions`),v.custom_step&&p.push(`${v.custom_step} custom`);let g=p.length>0?` (${p.join(" ")})`:"";l+=I(`Actions: ${e.totalActionSteps} steps${g}`);}l+=I(`Report: ${r}`),l+=I(`Data: ${t}`),l+=o,l+=`For more information visit us at https://docs.testrelic.ai
4326
- `,process.stderr.write(l);}var Qn=new Set(["pw:api","expect","test.step"]);function ei(e){return e==="expect"?"assertion":e==="test.step"?"custom_step":"ui_action"}function At(e,t,r){if(Qn.has(e.category)){let a=[];for(let n of e.steps)At(n,t,a);let s=e.startTime.getTime()-t.getTime();r.push({title:e.title,category:ei(e.category),timestamp:e.startTime.toISOString(),duration:e.duration,videoOffset:s>=0?s/1e3:null,status:e.error?"failed":"passed",error:oa(e.error?.message),children:a});}else for(let a of e.steps)At(a,t,r);}function Ca(e,t){let r=[];for(let a of e)At(a,t,r);return r}var ai=new Set(["localhost","127.0.0.1","0.0.0.0"]);function Ra(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&ai.has(t.hostname)))throw createError(ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${t.protocol}//${t.hostname}`)}var si=3e3;async function _t(e){let t=new AbortController,r=setTimeout(()=>t.abort(),si);try{return (await fetch(`${e}/health`,{method:"GET",signal:t.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function Aa(e){return new Promise(t=>setTimeout(t,e))}async function Ta(e){try{let r=(await e.json()).error;if(r&&typeof r.message=="string"){let a=r.details;if(Array.isArray(a)&&a.length>0){let s=a.map(n=>`${n.field}: ${n.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${e.status}`}async function It(e,t,r){let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let n=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:a.signal});if(n.ok){let i=await n.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(n.status===429){let i=n.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;if(!isNaN(l)&&l>0){await Aa(l);let d=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:a.signal});if(d.ok){let c=await d.json();return {accessToken:c.accessToken,refreshToken:c.refreshToken,expiresIn:c.expiresIn,orgId:c.orgId,orgName:c.orgName,userId:c.userId,userName:c.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return n.status===400?{code:"validation_error",message:await Ta(n),statusCode:400}:n.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:n.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await Ta(n),statusCode:n.status}}catch(n){return n instanceof DOMException&&n.name==="AbortError"?{code:"timeout",message:"Token exchange timed out.",statusCode:null}:{code:"network_error",message:"Failed to reach cloud for token exchange.",statusCode:null}}finally{clearTimeout(s);}}function Mt(e){return "code"in e&&typeof e.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(e.code)}async function _a(e,t,r){let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let n=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:a.signal});if(n.status===429){let i=n.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;!isNaN(l)&&l>0&&(await Aa(l),n=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:a.signal}));}if(!n.ok)return null;let o=await n.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn}}catch{return null}finally{clearTimeout(s);}}async function Ia(e,t,r,a,s,n){let o=new AbortController,i=setTimeout(()=>o.abort(),s);try{let l={gitId:r,displayName:a};n&&(l.branch=n);let d=await fetch(`${e}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(l),signal:o.signal});if(!d.ok)return null;let c=await d.json();return {repoId:c.repoId,displayName:c.displayName}}catch{return null}finally{clearTimeout(i);}}var di=5e3;function V(e,t){try{return execSync(e,{cwd:t,timeout:di,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Ma(e){let t=V("git rev-parse --abbrev-ref HEAD",e),r=V("git rev-parse --short HEAD",e),a=V("git log -1 --pretty=%s",e),s=V("git log -1 --format=%an",e)??V("git config user.name",e),n=ci(e),o=n?ce(n):null;return {branch:t,commitSha:r,commitMessage:a,commitAuthor:s,remoteUrl:o}}function ci(e){let t=V("git remote get-url origin",e);if(t)return t;let r=V("git remote",e);if(!r)return null;let a=r.split(`
4327
- `)[0]?.trim();return a?V(`git remote get-url ${a}`,e):null}function ce(e){let t=e.trim();return t=t.replace(/^[a-z+]+:\/\//,""),t=t.replace(/^[^@]+@/,""),t=t.replace(/:(?!\d)/,"/"),t=t.replace(/\.git$/,""),t=t.replace(/\/+$/,""),t=t.replace(/^[^@/]+@/,""),t.toLowerCase()}function Ea(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function Et(e){try{let t=readFileSync(join(e,"package.json"),"utf-8"),r=JSON.parse(t);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function ue(e){let t=Et(e);return t||`local/${basename(e)}`}var ui=new Set(["smoke","regression","nightly","ci"]);function Se(){let e=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(e&&ui.has(e))return e}async function $(e,t,r){let a=new AbortController,s=setTimeout(()=>a.abort(),Math.max(1,r));try{return await fetch(e,{...t,signal:a.signal})}finally{clearTimeout(s);}}function Pa(e,t){let r=t+Math.ceil(Math.max(0,e)/1e3);return Math.min(6e5,Math.max(3e4,r))}var Ce=class{constructor(t=12e4,r=Date.now()){this.deadline=r+Math.max(0,t);}remaining(t=Date.now()){return Math.max(0,this.deadline-t)}expired(t=Date.now()){return this.remaining(t)===0}slice(t,r=Date.now()){return Math.min(t,this.remaining(r))}};var gi=1048576,Te=[1e3,3e3,9e3],Re=3,La=3e4,hi=90*1048576,mi=new Set(["e2e","mobile","unit"]);function Dt(e){if(e&&e.length>0&&e.every(s=>s.testType==="api")){let s=new Map;for(let i of e){let l=i.apiProtocol??"rest";s.set(l,(s.get(l)??0)+1);}let n="rest",o=0;for(let[i,l]of s)l>o&&(o=l,n=i);return {testType:"api",apiProtocol:n,metadata:{testType:"api",primaryProtocol:n}}}let t=new Map;for(let s of e??[])mi.has(s.testType)&&t.set(s.testType,(t.get(s.testType)??0)+1);let r=null,a=0;for(let[s,n]of t)n>a&&(a=n,r=s);return {testType:r??"e2e"}}function Lt(e,t,r,a,s,n){let o=n?.cloudPlatform?n.cloudPlatform:a?.provider&&a.provider!=="unknown"?a.provider:"local",i=Se(),l=Dt(s),d=l.testType==="api"?l:null,c=d&&s?s.map(v=>v.apiProtocol?v:{...v,apiProtocol:d.apiProtocol}):s;return {runId:e.testRunId,repoGitId:t,startedAt:e.startedAt,summary:e.summary,timeline:e.timeline,environment:o,...i?{runType:i}:{},...d?{testType:d.testType,apiProtocol:d.apiProtocol,metadata:d.metadata}:{testType:l.testType},...c&&c.length>0?{tests:c}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...e.completedAt?{finishedAt:e.completedAt}:{},...e.totalDuration?{duration:e.totalDuration}:{},...a?.provider?{ciProvider:a.provider}:{},...a?.runUrl?{ciRunUrl:a.runUrl}:{},...n?.cloudPlatform?{cloudPlatform:n.cloudPlatform}:{},...n?.cloudBuildId?{cloudBuildId:n.cloudBuildId}:{},...n?.cloudSessionId?{cloudSessionId:n.cloudSessionId}:{}}}function Pt(e){return typeof e=="string"?Buffer.byteLength(e,"utf-8"):0}function Nt(e){return Array.isArray(e)?e.map(t=>{let r=t.statusCode??t.responseStatusCode??null;return {...t.id!=null?{id:t.id}:{},...t.protocol!=null?{protocol:t.protocol}:{},method:t.method??null,url:t.url??null,statusCode:r,statusText:t.statusText??t.responseStatusText??null,ok:typeof r=="number"?r<400:t.ok??null,durationMs:t.durationMs??t.responseTimeMs??null,bytesIn:typeof t.bytesIn=="number"?t.bytesIn:Pt(t.responseBody),bytesOut:typeof t.bytesOut=="number"?t.bytesOut:Pt(t.requestBody),requestHeaders:t.requestHeaders??null,responseHeaders:t.responseHeaders??null,requestBody:t.requestBody??null,responseBody:t.responseBody??null,requestCookies:t.requestCookies??null,responseCookies:t.responseCookies??null}}):[]}function Ft(e){return Array.isArray(e)?e.map(t=>{let r=t.responseStatusCode??t.statusCode??0,a=t.timestamp??null;return {method:t.method??"GET",url:t.url??"",status:r,statusCode:r,type:"xhr",size:Pt(t.responseBody),duration:t.responseTimeMs??t.durationMs??0,responseTimeMs:t.responseTimeMs??t.durationMs??0,requestHeaders:t.requestHeaders??null,responseHeaders:t.responseHeaders??null,requestBody:t.requestBody??null,responseBody:t.responseBody??null,timestamp:a,startedAt:a}}):[]}function Bt(e){if(!Array.isArray(e))return [];let t=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return e.map(r=>{let a=r.status==="failed"?"failed":"passed",s=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,n=r.kind??r.type??"assertion",o=a==="failed"?`expected ${t(r.expected)}, received ${t(r.actual)}`:r.expected!==void 0?`expected ${t(r.expected)}`:null;return {...r.callId!=null?{callId:r.callId}:{},kind:n,description:s??r.description??`${n} assertion`,status:a,detail:o}})}async function Ae(e){return new Promise(t=>setTimeout(t,e))}function vi(e){let t={};for(let[r,a]of Object.entries(e))a!=null&&(t[r]=a);return t}async function Na(e,t,r,a=La,s){for(let n=0;n<Re;n++){if(s?.expired())return null;let o=s?s.slice(a):a;if(o<=0)return null;try{let i=await $(e,t,o);if(i.ok)return i;if(i.status===401&&r&&n===0){let l=await r();if(l){let d={...t,headers:{...t.headers,Authorization:`Bearer ${l}`}},c=await $(e,d,o);if(c.ok)return c}return null}if(i.status===429&&n<Re-1){let l=i.headers.get("Retry-After"),d=l?parseInt(l,10)*1e3:Te[n];!isNaN(d)&&d>0?await Ae(d):await Ae(Te[n]);continue}if(i.status>=500&&n<Re-1){await Ae(Te[n]);continue}return i}catch{if(n<Re-1){await Ae(Te[n]);continue}return null}}return null}var bi=promisify(gzip);function Da(e,t){if(!Array.isArray(e.tests))return e;let r=e.tests.map(a=>{let{consoleLogs:s,networkRequests:n,apiCalls:o,...i}=a;return t?i:{...i,...o!==void 0?{apiCalls:o}:{}}});return {...e,tests:r}}var yi=["consoleLogs","networkRequests","apiCalls","actions","navigations","protocolAssertions","visual"];function xi(e){if(!Array.isArray(e.tests))return e;let t=new Set(yi),r=e.tests.map(a=>{let s={};for(let n in a)if(!t.has(n))if(n==="failure"&&a[n]&&typeof a[n]=="object"){let o=a[n];s.failure={message:o.message??null,line:o.line??null};}else s[n]=a[n];return s});return {...e,tests:r}}function wi(e){let t=new Set(["tests","timeline","unifiedTimeline","navigations"]),r={};for(let a in e)t.has(a)||(r[a]=e[a]);return r.tests=[],r}async function Ot(e,t=hi){let r={"Content-Type":"application/json"},a=JSON.stringify(e),s=e,n=Array.isArray(s?.tests)?s.tests.length:0,o=i=>Buffer.byteLength(i,"utf-8")>t;if(n>0&&o(a)){let i=Math.max(1,Math.round(t/1048576));process.stderr.write(`[testrelic] WARNING: batch payload exceeds ${i}MB \u2014 dropping consoleLogs/networkRequests from ${n} test(s) to avoid HTTP 413. Console/network detail will be missing in the cloud.
4328
- `),a=JSON.stringify(Da(s,false)),o(a)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB after dropping logs \u2014 also dropping apiCalls from ${n} test(s). API request/response detail will be missing in the cloud.
4329
- `),a=JSON.stringify(Da(s,true))),o(a)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB \u2014 shedding remaining per-test detail (actions/navigations/assertions) from ${n} test(s). Only test results + summary will reach the cloud.
4330
- `),a=JSON.stringify(xi(s))),o(a)&&(process.stderr.write(`[testrelic] ERROR: batch still exceeds ${i}MB after shedding all per-test detail \u2014 uploading run summary only (${n} per-test result(s) omitted) to avoid losing the run to HTTP 413.
4331
- `),a=JSON.stringify(wi(s)));}if(Buffer.byteLength(a,"utf-8")>gi){r["Content-Encoding"]="gzip";let i=await bi(Buffer.from(a,"utf-8")),l=i.buffer;return {body:new Uint8Array(l,i.byteOffset,i.byteLength),headers:r}}return {body:a,headers:r}}async function Fa(e,t,r,a,s,n){let o=`${e}/runs`,{body:i,headers:l}=await Ot(r);l.Authorization=`Bearer ${t}`;let d=await Na(o,{method:"POST",headers:l,body:i},a,s,n);return d?.ok?{success:true,statusCode:d.status,error:null}:d?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:d?`Upload failed with status ${d.status}`:"Upload failed after retries",statusCode:d?.status??null,payload:r,targetEndpoint:o,method:"POST"}}async function Ba(e,t,r,a){let s=`${e}/runs/init`;try{let n=await $(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(vi(r))},a??La);return n.ok?{runId:(await n.json()).runId}:null}catch{return null}}function Oa(e,t,r,a){let s=`${e}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a)}).catch(()=>{});}async function Ua(e,t,r,a){let s=`${e}/runs/${r}/finalize`;return (await Na(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a)}))?.ok??false}function Ut(e,t,r,a){let s=`${e}/runs/${r}/finalize`,n=new Date,o={finishedAt:n.toISOString(),duration:n.getTime()-new Date(a).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(o)}).catch(()=>{});}var Ri="1.0.0",za=10;function Ha(e){return e instanceof Error?e.message:String(e)}function Ai(e){return e>=400&&e<500&&e!==408&&e!==429}function pe(e,t,r,a,s,n,o,i){try{mkdirSync(e,{recursive:!0});let l=Date.now(),d=`${l}-${t}-${r}.json`,c=join(e,d),p={version:Ri,queuedAt:new Date(l).toISOString(),reason:a,retryCount:0,targetEndpoint:s,method:n,payload:o,headers:i},v=c+".tmp";writeFileSync(v,JSON.stringify(p,null,2),"utf-8"),renameSync(v,c);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
4357
+ `,i=`\u2514${"\u2500".repeat(58)}\u2518
4358
+ `,o=E(""),l=n;l+=E("TestRelic AI - Playwright Test Report"),l+=o;let d=s??e,c=[];if(d.passed>0&&c.push(`${d.passed} \u2713`),d.failed>0&&c.push(`${d.failed} \u2717`),d.flaky>0&&c.push(`${d.flaky} \u26A0`),d.skipped>0&&c.push(`${d.skipped} skipped`),d.timedout>0&&c.push(`${d.timedout} timedout`),l+=E(`Tests: ${e.total} total (${c.join(" ")})`),s&&s.expectedFailures>0&&(l+=E(` ${s.expectedFailures} failed as expected (test.fail)`)),s&&s.unexpectedPasses>0&&(l+=E(` ${s.unexpectedPasses} expected to fail, but passed (test.fail)`)),e.totalNavigations>0&&(l+=E(`Navigations: ${e.totalNavigations} visits across ${e.uniqueNavigationUrls} unique URLs`)),e.totalApiCalls>0){l+=E(`API Calls: ${e.totalApiCalls} calls across ${e.uniqueApiUrls} unique endpoints`);let p=Object.entries(e.apiCallsByMethod).filter(([,f])=>f>0).map(([f,u])=>`${f}: ${u}`);p.length>0&&(l+=E(` ${p.join(" ")}`));let y=Object.entries(e.apiCallsByStatusRange).filter(([,f])=>f>0).map(([f,u])=>`${f}: ${u}`);y.length>0&&(l+=E(` ${y.join(" ")}`)),e.apiResponseTime&&(l+=E(` Avg response: ${e.apiResponseTime.avg}ms P95: ${e.apiResponseTime.p95}ms`));}if(e.totalAssertions>0&&(l+=E(`Assertions: ${e.totalAssertions} total (${e.passedAssertions} \u2713 ${e.failedAssertions} \u2717)`)),e.totalActionSteps>0){let p=[],y=e.actionStepsByCategory;y.ui_action&&p.push(`${y.ui_action} UI`),y.assertion&&p.push(`${y.assertion} assertions`),y.custom_step&&p.push(`${y.custom_step} custom`);let f=p.length>0?` (${p.join(" ")})`:"";l+=E(`Actions: ${e.totalActionSteps} steps${f}`);}l+=E(`Report: ${r}`),l+=E(`Data: ${t}`),l+=i,l+=`For more information visit us at https://docs.testrelic.ai
4359
+ `,process.stderr.write(l);}var ti=new Set(["pw:api","expect","test.step"]);function ri(e){return e==="expect"?"assertion":e==="test.step"?"custom_step":"ui_action"}function At(e,t,r){if(ti.has(e.category)){let a=[];for(let n of e.steps)At(n,t,a);let s=e.startTime.getTime()-t.getTime();r.push({title:e.title,category:ri(e.category),timestamp:e.startTime.toISOString(),duration:e.duration,videoOffset:s>=0?s/1e3:null,status:e.error?"failed":"passed",error:da(e.error?.message),children:a});}else for(let a of e.steps)At(a,t,r);}function Ra(e,t){let r=[];for(let a of e)At(a,t,r);return r}var ni=new Set(["localhost","127.0.0.1","0.0.0.0"]);function _a(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&ni.has(t.hostname)))throw createError(ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${t.protocol}//${t.hostname}`)}var ii=3e3;async function _t(e){let t=new AbortController,r=setTimeout(()=>t.abort(),ii);try{return (await fetch(`${e}/health`,{method:"GET",signal:t.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function Ia(e){return new Promise(t=>setTimeout(t,e))}async function Aa(e){try{let r=(await e.json()).error;if(r&&typeof r.message=="string"){let a=r.details;if(Array.isArray(a)&&a.length>0){let s=a.map(n=>`${n.field}: ${n.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${e.status}`}async function It(e,t,r){let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let n=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:a.signal});if(n.ok){let o=await n.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn,orgId:o.orgId,orgName:o.orgName,userId:o.userId,userName:o.userName}}if(n.status===429){let o=n.headers.get("Retry-After"),l=o?parseInt(o,10)*1e3:5e3;if(!isNaN(l)&&l>0){await Ia(l);let d=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:a.signal});if(d.ok){let c=await d.json();return {accessToken:c.accessToken,refreshToken:c.refreshToken,expiresIn:c.expiresIn,orgId:c.orgId,orgName:c.orgName,userId:c.userId,userName:c.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return n.status===400?{code:"validation_error",message:await Aa(n),statusCode:400}:n.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:n.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await Aa(n),statusCode:n.status}}catch(n){return n instanceof DOMException&&n.name==="AbortError"?{code:"timeout",message:"Token exchange timed out.",statusCode:null}:{code:"network_error",message:"Failed to reach cloud for token exchange.",statusCode:null}}finally{clearTimeout(s);}}function Mt(e){return "code"in e&&typeof e.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(e.code)}async function Ma(e,t,r){let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let n=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:a.signal});if(n.status===429){let o=n.headers.get("Retry-After"),l=o?parseInt(o,10)*1e3:5e3;!isNaN(l)&&l>0&&(await Ia(l),n=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:a.signal}));}if(!n.ok)return null;let i=await n.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn}}catch{return null}finally{clearTimeout(s);}}async function Ea(e,t,r,a,s,n){let i=new AbortController,o=setTimeout(()=>i.abort(),s);try{let l={gitId:r,displayName:a};n&&(l.branch=n);let d=await fetch(`${e}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(l),signal:i.signal});if(!d.ok)return null;let c=await d.json();return {repoId:c.repoId,displayName:c.displayName}}catch{return null}finally{clearTimeout(o);}}var ui=5e3;function V(e,t){try{return execSync(e,{cwd:t,timeout:ui,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Pa(e){let t=V("git rev-parse --abbrev-ref HEAD",e),r=V("git rev-parse --short HEAD",e),a=V("git log -1 --pretty=%s",e),s=V("git log -1 --format=%an",e)??V("git config user.name",e),n=pi(e),i=n?ce(n):null;return {branch:t,commitSha:r,commitMessage:a,commitAuthor:s,remoteUrl:i}}function pi(e){let t=V("git remote get-url origin",e);if(t)return t;let r=V("git remote",e);if(!r)return null;let a=r.split(`
4360
+ `)[0]?.trim();return a?V(`git remote get-url ${a}`,e):null}function ce(e){let t=e.trim();return t=t.replace(/^[a-z+]+:\/\//,""),t=t.replace(/^[^@]+@/,""),t=t.replace(/:(?!\d)/,"/"),t=t.replace(/\.git$/,""),t=t.replace(/\/+$/,""),t=t.replace(/^[^@/]+@/,""),t.toLowerCase()}function Da(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function Et(e){try{let t=readFileSync(join(e,"package.json"),"utf-8"),r=JSON.parse(t);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function ue(e){let t=Et(e);return t||`local/${basename(e)}`}var fi=new Set(["smoke","regression","nightly","ci"]);function Se(){let e=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(e&&fi.has(e))return e}async function $(e,t,r){let a=new AbortController,s=setTimeout(()=>a.abort(),Math.max(1,r));try{return await fetch(e,{...t,signal:a.signal})}finally{clearTimeout(s);}}function La(e,t){let r=t+Math.ceil(Math.max(0,e)/1e3);return Math.min(6e5,Math.max(3e4,r))}var Ce=class{constructor(t=12e4,r=Date.now()){this.deadline=r+Math.max(0,t);}remaining(t=Date.now()){return Math.max(0,this.deadline-t)}expired(t=Date.now()){return this.remaining(t)===0}slice(t,r=Date.now()){return Math.min(t,this.remaining(r))}};var mi=1048576,Te=[1e3,3e3,9e3],Re=3,Fa=3e4,vi=90*1048576,yi=new Set(["e2e","mobile","unit"]);function Dt(e){if(e&&e.length>0&&e.every(s=>s.testType==="api")){let s=new Map;for(let o of e){let l=o.apiProtocol??"rest";s.set(l,(s.get(l)??0)+1);}let n="rest",i=0;for(let[o,l]of s)l>i&&(i=l,n=o);return {testType:"api",apiProtocol:n,metadata:{testType:"api",primaryProtocol:n}}}let t=new Map;for(let s of e??[])yi.has(s.testType)&&t.set(s.testType,(t.get(s.testType)??0)+1);let r=null,a=0;for(let[s,n]of t)n>a&&(a=n,r=s);return {testType:r??"e2e"}}function Lt(e,t,r,a,s,n){let i=n?.cloudPlatform?n.cloudPlatform:a?.provider&&a.provider!=="unknown"?a.provider:"local",o=Se(),l=Dt(s),d=l.testType==="api"?l:null,c=d&&s?s.map(y=>y.apiProtocol?y:{...y,apiProtocol:d.apiProtocol}):s;return {runId:e.testRunId,repoGitId:t,startedAt:e.startedAt,summary:e.summary,timeline:e.timeline,environment:i,...o?{runType:o}:{},...d?{testType:d.testType,apiProtocol:d.apiProtocol,metadata:d.metadata}:{testType:l.testType},...c&&c.length>0?{tests:c}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...e.completedAt?{finishedAt:e.completedAt}:{},...e.totalDuration?{duration:e.totalDuration}:{},...a?.provider?{ciProvider:a.provider}:{},...a?.runUrl?{ciRunUrl:a.runUrl}:{},...n?.cloudPlatform?{cloudPlatform:n.cloudPlatform}:{},...n?.cloudBuildId?{cloudBuildId:n.cloudBuildId}:{},...n?.cloudSessionId?{cloudSessionId:n.cloudSessionId}:{}}}function Pt(e){return typeof e=="string"?Buffer.byteLength(e,"utf-8"):0}function Nt(e){return Array.isArray(e)?e.map(t=>{let r=t.statusCode??t.responseStatusCode??null;return {...t.id!=null?{id:t.id}:{},...t.protocol!=null?{protocol:t.protocol}:{},method:t.method??null,url:t.url??null,statusCode:r,statusText:t.statusText??t.responseStatusText??null,ok:typeof r=="number"?r<400:t.ok??null,durationMs:t.durationMs??t.responseTimeMs??null,bytesIn:typeof t.bytesIn=="number"?t.bytesIn:Pt(t.responseBody),bytesOut:typeof t.bytesOut=="number"?t.bytesOut:Pt(t.requestBody),requestHeaders:t.requestHeaders??null,responseHeaders:t.responseHeaders??null,requestBody:t.requestBody??null,responseBody:t.responseBody??null,requestCookies:t.requestCookies??null,responseCookies:t.responseCookies??null}}):[]}function Ft(e){return Array.isArray(e)?e.map(t=>{let r=t.responseStatusCode??t.statusCode??0,a=t.timestamp??null;return {method:t.method??"GET",url:t.url??"",status:r,statusCode:r,type:"xhr",size:Pt(t.responseBody),duration:t.responseTimeMs??t.durationMs??0,responseTimeMs:t.responseTimeMs??t.durationMs??0,requestHeaders:t.requestHeaders??null,responseHeaders:t.responseHeaders??null,requestBody:t.requestBody??null,responseBody:t.responseBody??null,timestamp:a,startedAt:a}}):[]}function Bt(e){if(!Array.isArray(e))return [];let t=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return e.map(r=>{let a=r.status==="failed"?"failed":"passed",s=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,n=r.kind??r.type??"assertion",i=a==="failed"?`expected ${t(r.expected)}, received ${t(r.actual)}`:r.expected!==void 0?`expected ${t(r.expected)}`:null;return {...r.callId!=null?{callId:r.callId}:{},kind:n,description:s??r.description??`${n} assertion`,status:a,detail:i}})}async function Ae(e){return new Promise(t=>setTimeout(t,e))}function bi(e){let t={};for(let[r,a]of Object.entries(e))a!=null&&(t[r]=a);return t}async function Ba(e,t,r,a=Fa,s){for(let n=0;n<Re;n++){if(s?.expired())return null;let i=s?s.slice(a):a;if(i<=0)return null;try{let o=await $(e,t,i);if(o.ok)return o;if(o.status===401&&r&&n===0){let l=await r();if(l){let d={...t,headers:{...t.headers,Authorization:`Bearer ${l}`}},c=await $(e,d,i);if(c.ok)return c}return null}if(o.status===429&&n<Re-1){let l=o.headers.get("Retry-After"),d=l?parseInt(l,10)*1e3:Te[n];!isNaN(d)&&d>0?await Ae(d):await Ae(Te[n]);continue}if(o.status>=500&&n<Re-1){await Ae(Te[n]);continue}return o}catch{if(n<Re-1){await Ae(Te[n]);continue}return null}}return null}var xi=promisify(gzip);function Na(e,t){if(!Array.isArray(e.tests))return e;let r=e.tests.map(a=>{let{consoleLogs:s,networkRequests:n,apiCalls:i,...o}=a;return t?o:{...o,...i!==void 0?{apiCalls:i}:{}}});return {...e,tests:r}}var wi=["consoleLogs","networkRequests","apiCalls","actions","navigations","protocolAssertions","visual"];function ki(e){if(!Array.isArray(e.tests))return e;let t=new Set(wi),r=e.tests.map(a=>{let s={};for(let n in a)if(!t.has(n))if(n==="failure"&&a[n]&&typeof a[n]=="object"){let i=a[n];s.failure={message:i.message??null,line:i.line??null};}else s[n]=a[n];return s});return {...e,tests:r}}function Si(e){let t=new Set(["tests","timeline","unifiedTimeline","navigations"]),r={};for(let a in e)t.has(a)||(r[a]=e[a]);return r.tests=[],r}async function Ot(e,t=vi){let r={"Content-Type":"application/json"},a=JSON.stringify(e),s=e,n=Array.isArray(s?.tests)?s.tests.length:0,i=o=>Buffer.byteLength(o,"utf-8")>t;if(n>0&&i(a)){let o=Math.max(1,Math.round(t/1048576));process.stderr.write(`[testrelic] WARNING: batch payload exceeds ${o}MB \u2014 dropping consoleLogs/networkRequests from ${n} test(s) to avoid HTTP 413. Console/network detail will be missing in the cloud.
4361
+ `),a=JSON.stringify(Na(s,false)),i(a)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${o}MB after dropping logs \u2014 also dropping apiCalls from ${n} test(s). API request/response detail will be missing in the cloud.
4362
+ `),a=JSON.stringify(Na(s,true))),i(a)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${o}MB \u2014 shedding remaining per-test detail (actions/navigations/assertions) from ${n} test(s). Only test results + summary will reach the cloud.
4363
+ `),a=JSON.stringify(ki(s))),i(a)&&(process.stderr.write(`[testrelic] ERROR: batch still exceeds ${o}MB after shedding all per-test detail \u2014 uploading run summary only (${n} per-test result(s) omitted) to avoid losing the run to HTTP 413.
4364
+ `),a=JSON.stringify(Si(s)));}if(Buffer.byteLength(a,"utf-8")>mi){r["Content-Encoding"]="gzip";let o=await xi(Buffer.from(a,"utf-8")),l=o.buffer;return {body:new Uint8Array(l,o.byteOffset,o.byteLength),headers:r}}return {body:a,headers:r}}async function Oa(e,t,r,a,s,n){let i=`${e}/runs`,{body:o,headers:l}=await Ot(r);l.Authorization=`Bearer ${t}`;let d=await Ba(i,{method:"POST",headers:l,body:o},a,s,n);return d?.ok?{success:true,statusCode:d.status,error:null}:d?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:d?`Upload failed with status ${d.status}`:"Upload failed after retries",statusCode:d?.status??null,payload:r,targetEndpoint:i,method:"POST"}}async function Ua(e,t,r,a){let s=`${e}/runs/init`;try{let n=await $(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(bi(r))},a??Fa);return n.ok?{runId:(await n.json()).runId}:null}catch{return null}}function za(e,t,r,a){let s=`${e}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a)}).catch(()=>{});}async function Ha(e,t,r,a){let s=`${e}/runs/${r}/finalize`;return (await Ba(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a)}))?.ok??false}function Ut(e,t,r,a){let s=`${e}/runs/${r}/finalize`,n=new Date,i={finishedAt:n.toISOString(),duration:n.getTime()-new Date(a).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(i)}).catch(()=>{});}var _i="1.0.0",qa=10;function Va(e){return e instanceof Error?e.message:String(e)}function Ii(e){return e>=400&&e<500&&e!==408&&e!==429}function pe(e,t,r,a,s,n,i,o){try{mkdirSync(e,{recursive:!0});let l=Date.now(),d=`${l}-${t}-${r}.json`,c=join(e,d),p={version:_i,queuedAt:new Date(l).toISOString(),reason:a,retryCount:0,targetEndpoint:s,method:n,payload:i,headers:o},y=c+".tmp";writeFileSync(y,JSON.stringify(p,null,2),"utf-8"),renameSync(y,c);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
4332
4365
  `):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
4333
- `);}}async function ja(e,t,r){let a;try{a=readdirSync(e).filter(n=>n.endsWith(".json")&&!n.endsWith(".tmp")).sort();}catch{return}if(a.length===0)return;let s=[];for(let n=0;n<a.length;n+=za)s.push(a.slice(n,n+za));for(let n of s)for(let o of n){let i=join(e,o),l;try{if(!statSync(i).isFile())continue;let c=JSON.parse(readFileSync(i,"utf-8"));if(!isValidQueueEntry(c)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
4334
- `),unlinkSync(i);continue}l=c;}catch(d){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${o}: ${Ha(d)}
4335
- `);try{unlinkSync(i);}catch{}continue}try{let{body:d,headers:c}=await Ot(l.payload),p={...l.headers,...c,Authorization:`Bearer ${r}`},v=await fetch(l.targetEndpoint,{method:l.method,headers:p,body:d});if(v.ok)unlinkSync(i);else if(Ai(v.status)){process.stderr.write(`\u26A0 TestRelic: Queue entry ${o} rejected (HTTP ${v.status}) \u2014 moving aside; it will not be retried.
4336
- `);try{renameSync(i,`${i}.failed`);}catch{try{unlinkSync(i);}catch{}}}else {process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 server returned HTTP ${v.status} for ${o}; will retry later.
4337
- `);return}}catch(d){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${Ha(d)}; will retry later.
4338
- `);return}}}function Ga(e,t){try{let r=readdirSync(e).filter(s=>(s.endsWith(".json")||s.endsWith(".failed"))&&!s.endsWith(".tmp")),a=Date.now();for(let s of r){let n=join(e,s);try{let o=readFileSync(n,"utf-8"),l=JSON.parse(o).queuedAt;if(typeof l=="string"){let d=new Date(l).getTime();a-d>t&&unlinkSync(n);}}catch{try{unlinkSync(n);}catch{}}}}catch{}}var Li=3e5,Ni=864e5,Fi=6e4,Wa=3e4,qt="https://platform.testrelic.ai/settings/api-keys";function Ka(e){return new Promise(t=>{let r=setTimeout(t,e);typeof r?.unref=="function"&&r.unref();})}var _e=class{constructor(t){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=t,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
4339
- `);return}try{if(Ra(this.config.endpoint),this.gitMetadata=Ma(),!await _t(this.config.endpoint)){this.setLocalMode("cloud_unreachable"),process.stderr.write(`\u26A0 TestRelic: Cloud unreachable. Switching to local mode. Data will be queued for later upload.
4366
+ `);}}async function Wa(e,t,r){let a;try{a=readdirSync(e).filter(n=>n.endsWith(".json")&&!n.endsWith(".tmp")).sort();}catch{return}if(a.length===0)return;let s=[];for(let n=0;n<a.length;n+=qa)s.push(a.slice(n,n+qa));for(let n of s)for(let i of n){let o=join(e,i),l;try{if(!statSync(o).isFile())continue;let c=JSON.parse(readFileSync(o,"utf-8"));if(!isValidQueueEntry(c)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${i}
4367
+ `),unlinkSync(o);continue}l=c;}catch(d){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${i}: ${Va(d)}
4368
+ `);try{unlinkSync(o);}catch{}continue}try{let{body:d,headers:c}=await Ot(l.payload),p={...l.headers,...c,Authorization:`Bearer ${r}`},y=await fetch(l.targetEndpoint,{method:l.method,headers:p,body:d});if(y.ok)unlinkSync(o);else if(Ii(y.status)){process.stderr.write(`\u26A0 TestRelic: Queue entry ${i} rejected (HTTP ${y.status}) \u2014 moving aside; it will not be retried.
4369
+ `);try{renameSync(o,`${o}.failed`);}catch{try{unlinkSync(o);}catch{}}}else {process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 server returned HTTP ${y.status} for ${i}; will retry later.
4370
+ `);return}}catch(d){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${Va(d)}; will retry later.
4371
+ `);return}}}function Ka(e,t){try{let r=readdirSync(e).filter(s=>(s.endsWith(".json")||s.endsWith(".failed"))&&!s.endsWith(".tmp")),a=Date.now();for(let s of r){let n=join(e,s);try{let i=readFileSync(n,"utf-8"),l=JSON.parse(i).queuedAt;if(typeof l=="string"){let d=new Date(l).getTime();a-d>t&&unlinkSync(n);}}catch{try{unlinkSync(n);}catch{}}}}catch{}}var Fi=3e5,Bi=864e5,Oi=6e4,Ja=3e4,qt="https://platform.testrelic.ai/settings/api-keys";function Ya(e){return new Promise(t=>{let r=setTimeout(t,e);typeof r?.unref=="function"&&r.unref();})}var _e=class{constructor(t){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=t,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
4372
+ `);return}try{if(_a(this.config.endpoint),this.gitMetadata=Pa(),!await _t(this.config.endpoint)){this.setLocalMode("cloud_unreachable"),process.stderr.write(`\u26A0 TestRelic: Cloud unreachable. Switching to local mode. Data will be queued for later upload.
4340
4373
  `);return}let r=await It(this.config.endpoint,this.config.apiKey,this.config.timeout);if(Mt(r)){this.handleAuthError(r.code,r.statusCode);return}let a=r;this.authState={mode:"cloud",accessToken:a.accessToken,refreshToken:a.refreshToken,expiresAt:Date.now()+a.expiresIn*1e3,orgId:a.orgId,orgName:a.orgName,userId:a.userId,userName:a.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${a.orgName} / ${a.userName})
4341
- `),await this.resolveRepoId(),this.config.queueDirectory&&(Ga(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(t){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode. ${t instanceof Error?t.message:String(t)}
4342
- `);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}getRepoId(){return this.repoId}getGitMetadata(){return this.gitMetadata}getConfig(){return this.config}getFailureReason(){return this.failureReason}getEndpoint(){return this.config?.endpoint??"https://platform.testrelic.ai/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let t=this.authState.expiresAt??0;if(Date.now()+Li<t)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await _a(this.config.endpoint,this.authState.refreshToken,this.config.timeout);return r?(this.authState.accessToken=r.accessToken,this.authState.refreshToken=r.refreshToken,this.authState.expiresAt=Date.now()+r.expiresIn*1e3,!0):(this.switchToLocalMode("token_refresh_failed"),!1)}catch{return this.switchToLocalMode("token_refresh_error"),false}}switchToLocalMode(t){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=t,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${t}).
4343
- `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,Ka(Wa)]);}catch{}this.flushPromise=null;}this.authState={mode:"local",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null},this.repoId=null,this.gitMetadata=null;}setLocalMode(t){this.authState.mode="local",this.failureReason=t;}handleAuthError(t,r){switch(t){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
4374
+ `),await this.resolveRepoId(),this.config.queueDirectory&&(Ka(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(t){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode. ${t instanceof Error?t.message:String(t)}
4375
+ `);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}getRepoId(){return this.repoId}getGitMetadata(){return this.gitMetadata}getConfig(){return this.config}getFailureReason(){return this.failureReason}getEndpoint(){return this.config?.endpoint??"https://platform.testrelic.ai/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let t=this.authState.expiresAt??0;if(Date.now()+Fi<t)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Ma(this.config.endpoint,this.authState.refreshToken,this.config.timeout);return r?(this.authState.accessToken=r.accessToken,this.authState.refreshToken=r.refreshToken,this.authState.expiresAt=Date.now()+r.expiresIn*1e3,!0):(this.switchToLocalMode("token_refresh_failed"),!1)}catch{return this.switchToLocalMode("token_refresh_error"),false}}switchToLocalMode(t){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=t,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${t}).
4376
+ `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,Ya(Ja)]);}catch{}this.flushPromise=null;}this.authState={mode:"local",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null},this.repoId=null,this.gitMetadata=null;}setLocalMode(t){this.authState.mode="local",this.failureReason=t;}handleAuthError(t,r){switch(t){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
4344
4377
  \u2192 Manage keys: ${qt}
4345
4378
  `);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
4346
4379
  \u2192 Generate a new key: ${qt}
@@ -4349,32 +4382,32 @@ ${s}
4349
4382
  `);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
4350
4383
  `);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
4351
4384
  `);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
4352
- `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let t=this.gitMetadata?.remoteUrl?ce(this.gitMetadata.remoteUrl):null,r=t?Ea(t):this.config.projectName??ue(process.cwd()),a=t??this.config.projectName??ue(process.cwd()),s=this.readRepoCache(a);if(s){this.repoId=s.repoId;return}try{let n=await Ia(this.config.endpoint,this.authState.accessToken,a,r,this.config.timeout,this.gitMetadata?.branch);n&&(this.repoId=n.repoId,this.writeRepoCache(a,n.repoId,n.displayName));}catch{}!t&&!this.config.projectName&&!Et(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
4353
- `);}readRepoCache(t){if(!this.config)return null;let r=join(this.config.queueDirectory,"..","cache","repo.json");try{if(!existsSync(r))return null;let a=readFileSync(r,"utf-8"),s=JSON.parse(a);if(s.gitId!==t||Date.now()-s.resolvedAt>Ni)return null;let n=this.hashApiKey();return n&&s.apiKeyHash!==n?null:s}catch{return null}}writeRepoCache(t,r,a){if(!this.config)return;let s=join(this.config.queueDirectory,"..","cache"),n=join(s,"repo.json");try{mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:t,displayName:a,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=n+".tmp";writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),renameSync(i,n);}catch{}}hashApiKey(){return this.config?.apiKey?createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let t=this.authState.accessToken,r=this.config.queueDirectory,a=this.config.endpoint;this.flushPromise=Promise.race([ja(r,a,t),Ka(Wa)]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let t=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await _t(t))return;if(this.config?.apiKey){let a=await It(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Mt(a)){let s=a;this.authState={mode:"cloud",accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:Date.now()+s.expiresIn*1e3,orgId:s.orgId,orgName:s.orgName,userId:s.userId,userName:s.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
4354
- `),this.startBackgroundFlush();}}}catch{}},Fi),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};function zi(e,t){return t?e?{"2xx":e["2xx"]+t["2xx"],"3xx":e["3xx"]+t["3xx"],"4xx":e["4xx"]+t["4xx"],"5xx":e["5xx"]+t["5xx"],error:e.error+t.error}:{...t}:e}function Ja(e,t,r,a){let s=[],n=[],o=null,i=0,l=null,d=0,c=null,p=0,v=null,g=e.filter(h=>h.name===ATTACHMENT_NAME&&h.body),u=false;if(g.length>0)for(let h of g)try{let y=JSON.parse(h.body.toString());if(isTestRelicFilePayload(y)){s=s.concat(y.navigations),n=n.concat(y.apiAssertions),y.networkRequestsFile&&(o=y.networkRequestsFile,i+=y.networkRequestsCount),y.consoleLogsFile&&(l=y.consoleLogsFile,d+=y.consoleLogsCount),y.apiCallsFile&&(c=y.apiCallsFile,p+=y.apiCallsCount),v=zi(v,y.apiStatusMix),u=!0;continue}if(isTestRelicDataPayload(y)){s=s.concat(y.navigations),Array.isArray(y.apiAssertions)&&(n=n.concat(y.apiAssertions)),i+=y.networkRequests?.length??0,p+=y.apiCalls?.length??0;let f=y.consoleLogs;Array.isArray(f)&&(d+=f.length),u=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
4355
- `);}return u||(s=t.filter(h=>h.type==="lambdatest-navigation"&&h.description).map(h=>{try{return JSON.parse(h.description)}catch{return null}}).filter(h=>h!==null)),s.length===0&&i===0&&p===0&&!a&&!u&&process.stderr.write(`[testrelic] Warning: No data found for test "${r}". Make sure your tests import { test, expect } from '@testrelic/playwright-analytics/fixture' instead of '@playwright/test'. Without the TestRelic fixture, network logs, video sync, and Test Navigation data cannot be captured.
4356
- `),{navigations:s,apiAssertions:n,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:c,apiCallsCount:p,apiStatusMix:v}}function Ie(e=process.env){let t=Hi(e.TESTRELIC_CLOUD_PLATFORM);if(t)return {cloudPlatform:t,cloudBuildId:e.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:e.TESTRELIC_CLOUD_SESSION_ID||void 0};if(e.BROWSERSTACK_USERNAME||e.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:e.BROWSERSTACK_BUILD_NAME||e.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:e.BROWSERSTACK_SESSION_ID||void 0};if(e.LT_USERNAME||e.LAMBDATEST_USERNAME||e.LT_ACCESS_KEY||e.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:e.LT_BUILD||e.LAMBDATEST_BUILD||void 0,cloudSessionId:e.LT_SESSION_ID||e.LAMBDATEST_SESSION_ID||void 0};let r=e.PLAYWRIGHT_WS_ENDPOINT;if(r){if(/cdp\.lambdatest\.com/i.test(r))return {cloudPlatform:"lambdatest"};if(/cdp\.browserstack\.com/i.test(r))return {cloudPlatform:"browserstack"}}return {}}function Hi(e){if(!e)return;let t=e.toLowerCase().trim();if(t==="browserstack"||t==="bs")return "browserstack";if(t==="lambdatest"||t==="lt")return "lambdatest"}var Gi=5,Me=[1e3,3e3,9e3],te=3,jt=3e4,Wi={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip",".json":"application/json"},Vt=0,$t=[];async function Ki(){Vt>=Gi&&await new Promise(e=>$t.push(e)),Vt++;}function Ji(){Vt--,$t.length>0&&$t.shift()();}async function Ee(e){return new Promise(t=>setTimeout(t,e))}function Yi(e){let t=e.substring(e.lastIndexOf(".")).toLowerCase();return Wi[t]??"application/octet-stream"}function Xi(e){try{return statSync(e).size}catch{return 0}}async function Zi(e,t,r,a,s){let n=`${e}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:basename(r.filePath),contentType:s,type:r.type,sizeBytes:a});for(let i=0;i<te;i++)try{let l=await $(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:o},jt);if(l.ok)return await l.json();if(l.status>=500&&i<te-1){await Ee(Me[i]);continue}return null}catch{if(i<te-1){await Ee(Me[i]);continue}return null}return null}async function Qi(e,t,r,a){let s=Pa(a,jt);for(let n=0;n<te;n++)try{let o=createReadStream(t),i=Readable.toWeb(o),l=await $(e,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(a)},body:i,duplex:"half"},s);if(l.ok)return !0;if(l.status>=500&&n<te-1){await Ee(Me[n]);continue}return !1}catch{if(n<te-1){await Ee(Me[n]);continue}return false}return false}async function eo(e,t,r){let a=`${e}/artifacts/confirm`;try{return (await $(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({artifactId:r})},jt)).ok}catch{return false}}async function to(e,t,r,a){let s=Xi(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>a*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let n=Yi(r.filePath);await Ki();try{let o=await Zi(e,t,r,s,n);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await Qi(o.uploadUrl,r.filePath,n,s))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let l=await eo(e,t,o.artifactId);return {success:l,storageKey:o.storageKey,artifactId:o.artifactId,error:l?null:"confirm_failed"}}finally{Ji();}}async function Ya(e,t,r,a,s){let n=new Map,o=r.map(async i=>{if(s?.expired()){n.set(i.filePath,{success:false,storageKey:null,artifactId:null,error:"upload_budget_exhausted"});return}let l=await to(e,t,i,a);n.set(i.filePath,l);});return await Promise.allSettled(o),n}function Wt(e){let r=e.getGitMetadata()?.remoteUrl;return r?ce(r):e.getConfig()?.projectName??ue(process.cwd())}async function Xa(e,t,r,a,s){if(!e.isCloudMode()||t!=="realtime"&&t!=="both"||!await e.ensureValidToken())return null;let o=e.getGitMetadata(),i=U(),l=Ie(),d=Se();return (await Ba(e.getEndpoint(),e.getAccessToken(),{runId:r,repoGitId:Wt(e),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:a,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:s??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{},testType:"e2e"}))?.runId??null}var ao=[{field:"baseline",keyField:"baselineKey",type:"baseline"},{field:"actual",keyField:"actualKey",type:"screenshot"},{field:"diff",keyField:"diffKey",type:"diff"},{field:"baselineDom",keyField:"baselineDomKey",type:"dom"},{field:"actualDom",keyField:"actualDomKey",type:"dom"}],so=true,no=50,Gt={keyMap:new Map,visualKeyMap:new Map,total:0,uploaded:0};async function io(e,t,r,a,s){let n=new Map,o=new Map;if(!(t?.uploadArtifacts??so)||!await e.ensureValidToken())return Gt;let d=[],c=new Map,p=new Map;for(let h of a){if(h.artifacts.screenshot){let f=join(h.outputDir,h.artifacts.screenshot);d.push({filePath:f,runId:r,testId:h.testId,type:"screenshot"}),c.set(f,{testId:h.testId,field:"screenshot"});}if(h.artifacts.video){let f=join(h.outputDir,h.artifacts.video);d.push({filePath:f,runId:r,testId:h.testId,type:"video"}),c.set(f,{testId:h.testId,field:"video"});}if(h.artifacts.trace){let f=join(h.outputDir,h.artifacts.trace);d.push({filePath:f,runId:r,testId:h.testId,type:"trace"}),c.set(f,{testId:h.testId,field:"trace"});}let y=h.visual??[];for(let f=0;f<y.length;f++){let b=y[f];if(b)for(let x of ao){let w=b[x.field];if(!w)continue;let M=join(h.outputDir,w);d.push({filePath:M,runId:r,testId:h.testId,type:x.type}),c.set(M,{testId:h.testId,field:"visual",visualIndex:f,visualKey:x.keyField});}}}if(d.length===0)return Gt;let v=t?.artifactMaxSizeMb??no,g=await Ya(e.getEndpoint(),e.getAccessToken(),d,v,s),u=new Map;for(let[h,y]of g){if(!y.success||!y.storageKey)continue;let f=c.get(h);if(!f)continue;let b=u.get(f.testId)??{};if(f.field==="screenshot"&&(b.screenshotKey=y.storageKey),f.field==="video"&&(b.videoKey=y.storageKey),f.field==="trace"&&(b.traceKey=y.storageKey),f.field==="visual"&&f.visualIndex!==void 0&&f.visualKey){let x=p.get(f.testId)??new Map,w=x.get(f.visualIndex)??{};w[f.visualKey]=y.storageKey,x.set(f.visualIndex,w),p.set(f.testId,x);}u.set(f.testId,b);}for(let h of a){if(h.visual&&h.visual.length>0){let f=p.get(h.testId);o.set(h.testId,h.visual.map((b,x)=>({...b,...f?.get(x)??{}})));}let y=u.get(h.testId);n.set(h.testId,{...h.artifacts,...y?.screenshotKey?{screenshotKey:y.screenshotKey}:{},...y?.videoKey?{videoKey:y.videoKey}:{},...y?.traceKey?{traceKey:y.traceKey}:{}});}let m=Array.from(g.values()).filter(h=>h.success).length;return m>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${m} artifact(s) to cloud storage.
4357
- `),{keyMap:n,visualKeyMap:o,total:d.length,uploaded:m}}async function Kt(e,t,r,a,s,n,o,i,l,d,c){let p={realtimeFinalizeAttempted:false,realtimeFinalized:false,batchAttempted:false,batchAcknowledged:false,artifactsTotal:0,artifactsUploaded:0,failureReason:null},v=new Ce(t?.uploadBudgetMs??12e4),g=u=>{p.failureReason||(p.failureReason=u);};try{if(e.isCloudMode()&&s&&(r==="realtime"||r==="both")){p.realtimeFinalizeAttempted=!0;let h=await e.ensureValidToken(),y=e.getGitMetadata(),f=Dt(c),b={finishedAt:o,duration:i,summary:l,...y?.commitMessage?{commitMessage:y.commitMessage}:{},testType:f.testType,...f.testType==="api"?{apiProtocol:f.apiProtocol,metadata:f.metadata}:{}};if(h){let x=await Ua(e.getEndpoint(),e.getAccessToken(),s,b);if(p.realtimeFinalized=x,!x){g("finalize_failed_after_retries");let w=t?.queueDirectory??".testrelic/queue";pe(w,a,"finalize","finalize_failed_after_retries",`${e.getEndpoint()}/runs/${s}/finalize`,"POST",b,{"Content-Type":"application/json"});}}else {g(e.getFailureReason()??"token_invalid");let x=t?.queueDirectory??".testrelic/queue";pe(x,a,"finalize",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs/${s}/finalize`,"POST",b,{"Content-Type":"application/json"});}}let u=new Map,m=new Map;if(e.isCloudMode()&&d&&d.length>0){let h=await io(e,t,a,d,v);u=h.keyMap,m=h.visualKeyMap,p.artifactsTotal=h.total,p.artifactsUploaded=h.uploaded;}if(e.isCloudMode()&&(!r||r==="batch"||r==="both"))if(p.batchAttempted=!0,await e.ensureValidToken()){let y=e.getGitMetadata(),f=U(),b=Wt(e),x=lo(co(n,u),m),w=Lt(x,b,y,f,oo(c,m),Ie()),M=await Fa(e.getEndpoint(),e.getAccessToken(),w,async()=>await e.ensureValidToken()?e.getAccessToken():null,t?.timeout,v);if(p.batchAcknowledged=M.success,!M.success){let A=M;g(A.reason);let R=t?.queueDirectory??".testrelic/queue";pe(R,a,"batch",A.reason,A.targetEndpoint,A.method,A.payload,{"Content-Type":"application/json"});}}else {g(e.getFailureReason()??"token_invalid");let y=t?.queueDirectory??".testrelic/queue",f=e.getGitMetadata(),b=U(),x=Wt(e),w=Lt(n,x,f,b,void 0,Ie());pe(y,a,"batch",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs`,"POST",w,{"Content-Type":"application/json"});}await e.dispose();}catch(u){g(u instanceof Error?u.message:"unexpected_upload_error");try{await e.dispose();}catch{}}return p}function oo(e,t){return !e||t.size===0?e:e.map(r=>{let a=t.get(r.testId);return a?{...r,visual:a}:r})}function lo(e,t){if(t.size===0)return e;let r=e.timeline.map(a=>{let s=a.tests;if(!Array.isArray(s))return a;let n=false,o=s.map(i=>{let l=i.testId;if(!l)return i;let d=t.get(l);return d?(n=true,{...i,visual:d}):i});return n?{...a,tests:o}:a});return {...e,timeline:r}}function co(e,t){if(t.size===0)return e;let r=e.timeline.map(a=>{let s=a.testId;if(!s)return a;let n=t.get(s);return n?{...a,...n.screenshotKey?{screenshotKey:n.screenshotKey}:{},...n.videoKey?{videoKey:n.videoKey}:{}}:a});return {...e,timeline:r}}var uo=new Set(["batch","realtime","both"]),fe=Object.freeze({attempted:false,acknowledged:false,runId:null,endpoint:null,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:"cloud reporting was never initialised"});function po(e){switch(e){case "no_api_key":return "cloud mode off \u2014 no API key configured";case "cloud_unreachable":case "network_error":return "cloud endpoint unreachable \u2014 the run stayed local";case "invalid_api_key":return "API key rejected as invalid or revoked \u2014 the run stayed local";case "expired_api_key":return "API key has expired \u2014 the run stayed local";case "validation_error":return "API key format rejected \u2014 the run stayed local";case "rate_limited":return "rate limited during authentication \u2014 the run stayed local";case "auth_timeout":return "authentication timed out \u2014 the run stayed local";case "token_expired_no_refresh":case "token_refresh_failed":case "token_refresh_error":return "access token could not be refreshed \u2014 the run stayed local";case "init_error":return "cloud initialisation timed out \u2014 the run stayed local";case "unexpected_error":return "cloud initialisation failed \u2014 the run stayed local";default:return e?`cloud mode off (${e}) \u2014 the run stayed local`:"cloud mode off \u2014 the run stayed local"}}function Za(e,t,r){if(!e)return fe;if(!e.isCloudMode())return {...fe,detail:po(e.getFailureReason())};let a=t??"batch";if(!uo.has(a))return {...fe,detail:`upload strategy '${a}' is not recognised \u2014 nothing was sent`};let s=e.getEndpoint(),n=a==="realtime"||a==="both";return n&&r?{attempted:true,acknowledged:true,runId:r,endpoint:s,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:null}:{attempted:true,acknowledged:false,runId:null,endpoint:s,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:n?"run init failed \u2014 the platform did not acknowledge this run":`upload runs at the end of the run under the '${a}' strategy \u2014 not sent yet`}}function Jt(e,t,r){if(!e.attempted)return e;if(!t)return {...e,detail:e.acknowledged?"upload timed out before it completed \u2014 the run may be incomplete on the platform":"upload timed out before the platform acknowledged this run",acknowledged:e.acknowledged};let a=e.acknowledged||t.batchAcknowledged,s=e.runId??(t.batchAcknowledged?r:null),n=t.realtimeFinalizeAttempted?t.realtimeFinalized:t.batchAcknowledged,o=null;return a?n||(o="run acknowledged but not closed out \u2014 finalize failed and was queued for retry"):o=t.failureReason?`upload failed (${t.failureReason}) \u2014 queued locally for retry`:"upload failed \u2014 the platform did not acknowledge this run",{attempted:true,acknowledged:a,runId:s,endpoint:e.endpoint,finalized:n,artifactsUploaded:t.artifactsUploaded,artifactsTotal:t.artifactsTotal,detail:o}}function j(e){try{return readFileSync(e,"utf-8").split(`
4358
- `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function yo(e){if(!e)return null;let t=e.split(`
4359
- `).map(n=>n.trim()).filter(Boolean);if(t.length===0)return null;let r=t.filter(n=>!/^Error:\s*expect\(/.test(n));if(r.length===0)return t[0]??null;let a=r[0],s=r[1];return s!==void 0&&/^Received:/.test(s)&&/^Expected:/.test(a)?`${a} \xB7 ${s}`:a}function Xt(e){switch(e){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function xo(e,t,r){let a=`${e}::${t}::${r}`;return createHash("sha256").update(a).digest("hex").substring(0,16)}function wo(e){return e.length<=3?"":e[e.length-2]}function ko(e){let t=e.findIndex(r=>r.status==="passed");return t>0?`passed on retry ${t}`:null}function ns(e){return e===null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function So(e){let t={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},r=t;for(let a of e){let s=typeof a.responseStatusCode=="number"?a.responseStatusCode:null;r[ns(s)]++;}return t}function rs(e){if(e){for(let t of e)if(t.status==="failed")return {type:t.type,expected:as(t.expected),actual:as(t.actual),...t.expression?{expression:t.expression}:{}}}}function as(e){if(e===void 0)return "undefined";if(e===null)return "null";let t;if(typeof e=="string")t=e;else try{t=JSON.stringify(e)??String(e);}catch{t=String(e);}return t.length>200?t.slice(0,200)+"\u2026":t}function De(e,t){if(!e)return 0;let r=0;for(let a of e)a.status===t&&r++;return r}function is(e,t){for(let r of e)t[r.category]=(t[r.category]??0)+1,r.children.length>0&&is(r.children,t);}function Co(e){if(e.length===0)return null;let t=[...e].sort((a,s)=>a-s),r=t.reduce((a,s)=>a+s,0);return {avg:Math.round(r/t.length),min:t[0],max:t[t.length-1],p50:Y(t,50),p95:Y(t,95),p99:Y(t,99)}}var os=2e5,Le=1e5;function ss(e,t,r,a,s,n,o){let i={retryIndex:e,apiCalls:t?.length??0,apiUrls:[],methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,assertions:r.length,navigations:a.length,navUrls:[],networkRequests:s,consoleLogs:n,actionSteps:o?.length??0,actionCategories:{}};if(t){let d=new Set;for(let c of t){let p=typeof c.method=="string"?c.method:"OTHER";i.methodCounts[p]=(i.methodCounts[p]??0)+1;let v=typeof c.url=="string"?c.url:null;v&&d.size<Le&&d.add(Tt(v));let g=typeof c.responseStatusCode=="number"?c.responseStatusCode:typeof c.statusCode=="number"?c.statusCode:null,u=g!==null&&Number.isFinite(g)?g:null;i.statusRanges[ns(u)]++;let m=typeof c.responseTimeMs=="number"?c.responseTimeMs:typeof c.durationMs=="number"?c.durationMs:null;m!==null&&Number.isFinite(m)&&i.responseTimes.length<os&&i.responseTimes.push(m);}i.apiUrls=Array.from(d);}for(let d of r)d.status==="passed"?i.passedAssertions++:i.failedAssertions++;let l=new Set;for(let d of a)d.url&&l.size<Le&&l.add(d.url);return i.navUrls=Array.from(l),o&&is(o,i.actionCategories),i}function To(){return {apiUrlSet:new Set,methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,navUrlSet:new Set,actionCategoryCounts:{},volApiCalls:0,volAssertions:0,volNavigations:0,volNetworkRequests:0,volConsoleLogs:0,volActionSteps:0}}function Ro(e){return process.env.BROWSERSTACK_USERNAME?"BrowserStack":e?{"github-actions":"GitHub Actions","gitlab-ci":"GitLab CI",jenkins:"Jenkins",circleci:"CircleCI","bitbucket-pipelines":"Bitbucket Pipelines"}[e.provider]??"CI":"Local"}function Ao(){let e=platform();return e==="win32"?"Windows":e==="darwin"?"macOS":"Linux"}function _o(e){let t=e.parent?.project?.()?.use;if(!t)return;let{browserName:r,channel:a}=t;if(a){let n=a.toLowerCase();return n==="chrome"||n==="chrome-stable"?"Chrome":n.startsWith("chrome-beta")?"Chrome Beta":n.startsWith("chrome-dev")?"Chrome Dev":n.startsWith("chrome-canary")?"Chrome Canary":n==="msedge"||n==="msedge-stable"?"Microsoft Edge":n.startsWith("msedge-beta")?"Edge Beta":n.startsWith("msedge-dev")?"Edge Dev":n.startsWith("msedge-canary")?"Edge Canary":a}if(r){let n=r.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":r}let s=t.defaultBrowserType;if(s){let n=s.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":s}}function Io(e,t,r){let a=r.parent?.project?.(),s="unknown";a!==void 0&&(a.use.isMobile===true?s="mobile":s="e2e");let n=["e2e","api","unit","mobile"];for(let l of n)if(e.some(d=>d===`@${l}`||d===l))return l;let o=t.replace(/\\/g,"/"),i=["e2e","api","unit"];for(let l of i)if(o.includes(`/${l}/`))return l;return s}var Mo="__testrelic_api_config";function Eo(e){return JSON.stringify(e,(t,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var Ne=class{constructor(t){this.rootDir="";this.configDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.navigationsCaptured=false;this.memoryPressureWarned=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.updatingSnapshots=false;this.cloudReceipt=fe;this.pendingArtifactEntries=[];this.detectedOs="";this.detectedSource="";this.cloudTestsBuffer=[];this.activeReportMode="embedded";this.streamingWriter=null;this.testIndex=[];this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};this.streamingTestAgg=new Map;this.config=mr(t),this.apiConfig=hr(t);}upsertAggContribution(t,r){let a=this.streamingTestAgg.get(t);(!a||r.retryIndex>a.retryIndex)&&this.streamingTestAgg.set(t,r);}async onBegin(t,r){try{this.rootDir=t.rootDir,this.configDir=t.configFile?dirname(t.configFile):"";let a=t.updateSnapshots;if(this.updatingSnapshots=a==="all"||a==="changed",this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??randomUUID(),this.config.reportMode==="auto"){let i=r.allTests().length;this.activeReportMode=i>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let s=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${s} tests)
4360
- `),this.activeReportMode==="streaming"){let i=dirname(this.config.outputPath);this.streamingWriter=new ie(i);let l=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let d={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(d);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let d=this.cloudClient.getAccessToken();d&&Ut(this.cloudClient.getEndpoint(),d,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",l),process.on("SIGINT",l);}if(this.config.includeArtifacts){let i=dirname(this.config.outputPath);this.runTimestamp=Qr(join(i,"artifacts"));try{ma(join(i,"artifacts"));}catch{}}let n=U();this.detectedOs=Ao(),this.detectedSource=Ro(n);let o=await J(async()=>(this.cloudClient=new _e(this.config.cloud),await this.cloudClient.initialize(),Xa(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),ba,"Cloud initialization");if(this.cloudRunId=o??null,o===void 0&&this.cloudClient?.switchToLocalMode("init_error"),this.cloudReceipt=Za(this.cloudClient,this.config.cloud?.uploadStrategy,this.cloudRunId),this.activeReportMode!=="streaming"){let i=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let l=this.cloudClient.getAccessToken();l&&Ut(this.cloudClient.getEndpoint(),l,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",i),process.on("SIGINT",i);}}catch{}}onTestBegin(t,r){try{t.annotations.push({type:Mo,description:Eo(this.apiConfig)});}catch{}}onTestEnd(t,r){try{let a=r,s=t.outcome(),n;s==="flaky"?n="flaky":s==="skipped"?n="skipped":n=Xt(a.status);let o=a.startTime.toISOString(),i=new Date(a.startTime.getTime()+a.duration).toISOString(),l=t.tags?[...t.tags]:t.annotations.filter(_=>_.type==="tag").map(_=>_.description??""),d=Ja(a.attachments,t.annotations,t.title,n==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0),d.navigations.length>0&&(this.navigationsCaptured=!0),!this.config.captureNavigation&&d.navigations.length>0&&(d={...d,navigations:[]});let c=null;if(n==="failed"||n==="flaky"){let T=(n==="flaky"?t.results.find(B=>B.status!=="passed")?.errors??[]:a.errors)[0];if(T){let B=br(this.config.redactPatterns),ae=T.location?.file??null,E=d.apiAssertions.find(ls=>ls.status==="failed")?.location??null,Z=E!==null&&(ae===null||resolve(ae)!==resolve(t.location.file)),tr=Z?E.file:ae,Fe=Z?E.line:T.location?.line??null,se=null;this.config.includeCodeSnippets&&Fe!==null&&tr&&(se=vr(tr,Fe,this.config.codeContextLines),se&&(se=B(se))),c={message:B(ke(T.message??"Unknown error")),line:Fe,code:se,stack:this.config.includeStackTrace&&T.stack?B(ke(T.stack)):null};}}let p=t.titlePath().filter(Boolean),v=relative(this.rootDir||".",t.location.file).replace(/\\/g,"/"),g=wo(p),u=p.join(" > "),m=v,h=xo(m,g,u),y=Io(l,m,t),f=y!=="mobile"&&d.apiCallsCount>0?"api":y,b=s==="flaky",x=ko(t.results),w=Xt(t.expectedStatus),M=Xt(a.status),A=null;if(this.config.includeArtifacts&&n!=="skipped"&&a.attachments){let _=dirname(this.config.outputPath),T=p[p.length-1]??t.title;A=ta(a.attachments,T,a.retry,_,this.runTimestamp||void 0,h);}let R=null;if(this.config.includeArtifacts&&n!=="skipped"&&a.attachments)try{let _=ia(a.attachments,{updatingSnapshots:this.updatingSnapshots,failureMessage:a.errors.map(T=>T.message??"").join(`
4361
- `)});if(_.length>0){let T=dirname(this.config.outputPath),B=p[p.length-1]??t.title;R=ra(_,B,a.retry,T,this.runTimestamp||void 0,h,this.configDir||this.rootDir||process.cwd());}}catch{}let D=this.config.includeActionSteps&&a.steps?Ca(a.steps,a.startTime):null,k=_o(t),C={titlePath:p,title:u,status:n,duration:a.duration,startedAt:o,completedAt:i,retryCount:t.results.length-1,retry:a.retry,tags:l,failure:c,specFile:v,navigations:d.navigations,testId:h,filePath:m,suiteName:g,testType:f,isFlaky:b,retryStatus:x,expectedStatus:w,actualStatus:M,artifacts:A,visual:R,apiAssertions:d.apiAssertions,actions:D,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount,apiStatusMix:d.apiStatusMix,browser:k,os:this.detectedOs||void 0,source:this.detectedSource||void 0},X=d.consoleLogsFile&&d.consoleLogsCount>0?j(d.consoleLogsFile):void 0,G=d.networkRequestsFile&&d.networkRequestsCount>0?j(d.networkRequestsFile):void 0,re=d.apiCallsFile&&d.apiCallsCount>0?j(d.apiCallsFile):void 0,Zt=re?Nt(re):void 0,Qt=!G&&re?Ft(re):void 0,er=d.apiAssertions&&d.apiAssertions.length>0?Bt(d.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:h,title:u,status:n,duration:a.duration,suiteName:g,filePath:m,testType:f,isFlaky:b,startedAt:o,completedAt:i,tags:l,failure:c,retry:a.retry,retryCount:t.results.length-1,retryStatus:x,browser:k,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...D&&D.length>0?{actions:D}:{},...d.navigations&&d.navigations.length>0?{navigations:d.navigations}:{},...X?{consoleLogs:X}:{},...G?{networkRequests:G}:Qt?{networkRequests:Qt}:{},...Zt?{apiCalls:Zt}:{},...er?{protocolAssertions:er}:{},...R&&R.length>0?{visual:R}:{}});try{let _=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(_==="realtime"||_==="both")){let T=this.cloudClient.getAccessToken();T&&Oa(this.cloudClient.getEndpoint(),T,this.cloudRunId,this.buildCloudTestPayload(C));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let _=Be(m,p,t.id??"",a.retry),T=a.retry===t.results.length-1,B={id:_,...w!=="passed"?{expectedStatus:w}:{},navigations:d.navigations,apiAssertions:d.apiAssertions,actions:D??[],artifacts:A,visual:R,failureDiagnostic:c,hasNetworkFile:d.networkRequestsFile!==null,networkRequestsCount:d.networkRequestsCount,hasConsoleFile:d.consoleLogsFile!==null,consoleLogsCount:d.consoleLogsCount,hasApiCallsFile:d.apiCallsFile!==null,apiCallsCount:d.apiCallsCount,startedAt:o};this.streamingWriter.writeTestDetail(_,B,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let ae={id:_,title:p[p.length-1]??t.title,titlePath:p,filePath:m,status:n,...w!=="passed"?{expectedStatus:w}:{},duration:a.duration,project:p[1]??"",retryIndex:a.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:A!==null,hasActionSteps:(D?.length??0)>0,visualCount:R?.length??0,visualFailedCount:R?.filter(E=>E.status==="failed").length??0,domChangeCount:R?.reduce((E,Z)=>E+(Z.domChangeCount??0),0)??0,...(()=>{let E=R?.find(Z=>Z.diff);return E?.diff?{visualDiffPath:E.diff}:{}})(),errorMessage:yo(c?.message),networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:D?.length??0,testType:f,apiCallCount:d.apiCallsCount,...d.apiStatusMix?{apiStatusMix:d.apiStatusMix}:{},assertionsPassed:De(d.apiAssertions,"passed"),assertionsFailed:De(d.apiAssertions,"failed"),...(()=>{let E=rs(d.apiAssertions);return E?{firstFailedAssertion:E}:{}})(),isRetry:!T,retryGroupKey:Oe(m,p,t.id??"")};if(this.testIndex.push(ae),T)switch(this.summaryCounters.total++,n){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${m}::${p.join(" > ")}`,ss(a.retry,re,d.apiAssertions,d.navigations,d.networkRequestsCount,d.consoleLogsCount,D)),(A||R)&&this.pendingArtifactEntries.push({testId:h,artifacts:A??{},visual:R,outputDir:dirname(this.config.outputPath)}),C.actions=null,C.apiAssertions=null,C.navigations=[],C.artifacts=null,C.failure=null,C.networkRequestsFile=null,C.consoleLogsFile=null,C.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(C),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(t){try{let r=new Date().toISOString(),a=new Date(this.startedAt).getTime(),n=new Date(r).getTime()-a,o=this.activeReportMode==="streaming"?this.testIndex.some(l=>l.status!=="skipped"):this.collectedTests.some(l=>l.status!=="skipped");!this.fixtureDataReceived&&o&&process.stderr.write(`
4385
+ `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let t=this.gitMetadata?.remoteUrl?ce(this.gitMetadata.remoteUrl):null,r=t?Da(t):this.config.projectName??ue(process.cwd()),a=t??this.config.projectName??ue(process.cwd()),s=this.readRepoCache(a);if(s){this.repoId=s.repoId;return}try{let n=await Ea(this.config.endpoint,this.authState.accessToken,a,r,this.config.timeout,this.gitMetadata?.branch);n&&(this.repoId=n.repoId,this.writeRepoCache(a,n.repoId,n.displayName));}catch{}!t&&!this.config.projectName&&!Et(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
4386
+ `);}readRepoCache(t){if(!this.config)return null;let r=join(this.config.queueDirectory,"..","cache","repo.json");try{if(!existsSync(r))return null;let a=readFileSync(r,"utf-8"),s=JSON.parse(a);if(s.gitId!==t||Date.now()-s.resolvedAt>Bi)return null;let n=this.hashApiKey();return n&&s.apiKeyHash!==n?null:s}catch{return null}}writeRepoCache(t,r,a){if(!this.config)return;let s=join(this.config.queueDirectory,"..","cache"),n=join(s,"repo.json");try{mkdirSync(s,{recursive:!0});let i={repoId:r,gitId:t,displayName:a,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},o=n+".tmp";writeFileSync(o,JSON.stringify(i,null,2),"utf-8"),renameSync(o,n);}catch{}}hashApiKey(){return this.config?.apiKey?createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let t=this.authState.accessToken,r=this.config.queueDirectory,a=this.config.endpoint;this.flushPromise=Promise.race([Wa(r,a,t),Ya(Ja)]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let t=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await _t(t))return;if(this.config?.apiKey){let a=await It(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Mt(a)){let s=a;this.authState={mode:"cloud",accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:Date.now()+s.expiresIn*1e3,orgId:s.orgId,orgName:s.orgName,userId:s.userId,userName:s.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
4387
+ `),this.startBackgroundFlush();}}}catch{}},Oi),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};function qi(e,t){return t?e?{"2xx":e["2xx"]+t["2xx"],"3xx":e["3xx"]+t["3xx"],"4xx":e["4xx"]+t["4xx"],"5xx":e["5xx"]+t["5xx"],error:e.error+t.error}:{...t}:e}function Xa(e,t,r,a){let s=[],n=[],i=null,o=0,l=null,d=0,c=null,p=0,y=null,f=e.filter(b=>b.name===ATTACHMENT_NAME&&b.body),u=false;if(f.length>0)for(let b of f)try{let h=JSON.parse(b.body.toString());if(isTestRelicFilePayload(h)){s=s.concat(h.navigations),n=n.concat(h.apiAssertions),h.networkRequestsFile&&(i=h.networkRequestsFile,o+=h.networkRequestsCount),h.consoleLogsFile&&(l=h.consoleLogsFile,d+=h.consoleLogsCount),h.apiCallsFile&&(c=h.apiCallsFile,p+=h.apiCallsCount),y=qi(y,h.apiStatusMix),u=!0;continue}if(isTestRelicDataPayload(h)){s=s.concat(h.navigations),Array.isArray(h.apiAssertions)&&(n=n.concat(h.apiAssertions)),o+=h.networkRequests?.length??0,p+=h.apiCalls?.length??0;let g=h.consoleLogs;Array.isArray(g)&&(d+=g.length),u=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
4388
+ `);}return u||(s=t.filter(b=>b.type==="lambdatest-navigation"&&b.description).map(b=>{try{return JSON.parse(b.description)}catch{return null}}).filter(b=>b!==null)),s.length===0&&o===0&&p===0&&!a&&!u&&process.stderr.write(`[testrelic] Warning: No data found for test "${r}". Make sure your tests import { test, expect } from '@testrelic/playwright-analytics/fixture' instead of '@playwright/test'. Without the TestRelic fixture, network logs, video sync, and Test Navigation data cannot be captured.
4389
+ `),{navigations:s,apiAssertions:n,networkRequestsFile:i,networkRequestsCount:o,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:c,apiCallsCount:p,apiStatusMix:y}}function Ie(e=process.env){let t=Vi(e.TESTRELIC_CLOUD_PLATFORM);if(t)return {cloudPlatform:t,cloudBuildId:e.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:e.TESTRELIC_CLOUD_SESSION_ID||void 0};if(e.BROWSERSTACK_USERNAME||e.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:e.BROWSERSTACK_BUILD_NAME||e.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:e.BROWSERSTACK_SESSION_ID||void 0};if(e.LT_USERNAME||e.LAMBDATEST_USERNAME||e.LT_ACCESS_KEY||e.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:e.LT_BUILD||e.LAMBDATEST_BUILD||void 0,cloudSessionId:e.LT_SESSION_ID||e.LAMBDATEST_SESSION_ID||void 0};let r=e.PLAYWRIGHT_WS_ENDPOINT;if(r){if(/cdp\.lambdatest\.com/i.test(r))return {cloudPlatform:"lambdatest"};if(/cdp\.browserstack\.com/i.test(r))return {cloudPlatform:"browserstack"}}return {}}function Vi(e){if(!e)return;let t=e.toLowerCase().trim();if(t==="browserstack"||t==="bs")return "browserstack";if(t==="lambdatest"||t==="lt")return "lambdatest"}var Ki=5,Me=[1e3,3e3,9e3],te=3,jt=3e4,Ji={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip",".json":"application/json"},Vt=0,$t=[];async function Yi(){Vt>=Ki&&await new Promise(e=>$t.push(e)),Vt++;}function Xi(){Vt--,$t.length>0&&$t.shift()();}async function Ee(e){return new Promise(t=>setTimeout(t,e))}function Zi(e){let t=e.substring(e.lastIndexOf(".")).toLowerCase();return Ji[t]??"application/octet-stream"}function Qi(e){try{return statSync(e).size}catch{return 0}}async function eo(e,t,r,a,s){let n=`${e}/artifacts/upload-url`,i=JSON.stringify({runId:r.runId,testId:r.testId,...r.retry!==void 0?{retry:r.retry}:{},fileName:basename(r.filePath),contentType:s,type:r.type,sizeBytes:a});for(let o=0;o<te;o++)try{let l=await $(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:i},jt);if(l.ok)return await l.json();if(l.status>=500&&o<te-1){await Ee(Me[o]);continue}return null}catch{if(o<te-1){await Ee(Me[o]);continue}return null}return null}async function to(e,t,r,a){let s=La(a,jt);for(let n=0;n<te;n++)try{let i=createReadStream(t),o=Readable.toWeb(i),l=await $(e,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(a)},body:o,duplex:"half"},s);if(l.ok)return !0;if(l.status>=500&&n<te-1){await Ee(Me[n]);continue}return !1}catch{if(n<te-1){await Ee(Me[n]);continue}return false}return false}async function ro(e,t,r){let a=`${e}/artifacts/confirm`;try{return (await $(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({artifactId:r})},jt)).ok}catch{return false}}async function ao(e,t,r,a){let s=Qi(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>a*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let n=Zi(r.filePath);await Yi();try{let i=await eo(e,t,r,s,n);if(!i)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await to(i.uploadUrl,r.filePath,n,s))return {success:!1,storageKey:i.storageKey,artifactId:i.artifactId,error:"presigned_put_failed"};let l=await ro(e,t,i.artifactId);return {success:l,storageKey:i.storageKey,artifactId:i.artifactId,error:l?null:"confirm_failed"}}finally{Xi();}}async function Za(e,t,r,a,s){let n=new Map,i=r.map(async o=>{if(s?.expired()){n.set(o.filePath,{success:false,storageKey:null,artifactId:null,error:"upload_budget_exhausted"});return}let l=await ao(e,t,o,a);n.set(o.filePath,l);});return await Promise.allSettled(i),n}function Wt(e){let r=e.getGitMetadata()?.remoteUrl;return r?ce(r):e.getConfig()?.projectName??ue(process.cwd())}async function Qa(e,t,r,a,s){if(!e.isCloudMode()||t!=="realtime"&&t!=="both"||!await e.ensureValidToken())return null;let i=e.getGitMetadata(),o=U(),l=Ie(),d=Se();return (await Ua(e.getEndpoint(),e.getAccessToken(),{runId:r,repoGitId:Wt(e),branch:i?.branch??null,commit:i?.commitSha??null,commitMessage:i?.commitMessage??null,commitAuthor:i?.commitAuthor??null,startedAt:a,totalTests:null,ciProvider:o?.provider??null,ciRunUrl:o?.runUrl??null,environment:s??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{},testType:"e2e"}))?.runId??null}var no=[{field:"baseline",keyField:"baselineKey",type:"baseline"},{field:"actual",keyField:"actualKey",type:"screenshot"},{field:"diff",keyField:"diffKey",type:"diff"},{field:"baselineDom",keyField:"baselineDomKey",type:"dom"},{field:"actualDom",keyField:"actualDomKey",type:"dom"}];function Kt(e,t){return `${e}#${t??0}`}function Jt(e,t,r){return r===void 0?e.get(t):e.get(Kt(t,r))}var io=true,oo=50,Gt={keyMap:new Map,visualKeyMap:new Map,total:0,uploaded:0};async function lo(e,t,r,a,s){let n=new Map,i=new Map;if(!(t?.uploadArtifacts??io)||!await e.ensureValidToken())return Gt;let d=[],c=new Map,p=new Map;for(let h of a){let g=Kt(h.testId,h.retry),v={runId:r,testId:h.testId,...h.retry!==void 0?{retry:h.retry}:{}};if(h.artifacts.screenshot){let x=join(h.outputDir,h.artifacts.screenshot);d.push({filePath:x,...v,type:"screenshot"}),c.set(x,{attemptKey:g,field:"screenshot"});}if(h.artifacts.video){let x=join(h.outputDir,h.artifacts.video);d.push({filePath:x,...v,type:"video"}),c.set(x,{attemptKey:g,field:"video"});}if(h.artifacts.trace){let x=join(h.outputDir,h.artifacts.trace);d.push({filePath:x,...v,type:"trace"}),c.set(x,{attemptKey:g,field:"trace"});}let w=h.visual??[];for(let x=0;x<w.length;x++){let A=w[x];if(A)for(let T of no){let R=A[T.field];if(!R)continue;let I=join(h.outputDir,R);d.push({filePath:I,...v,type:T.type}),c.set(I,{attemptKey:g,field:"visual",visualIndex:x,visualKey:T.keyField});}}}if(d.length===0)return Gt;let y=t?.artifactMaxSizeMb??oo,f=await Za(e.getEndpoint(),e.getAccessToken(),d,y,s),u=new Map;for(let[h,g]of f){if(!g.success||!g.storageKey)continue;let v=c.get(h);if(!v)continue;let w=u.get(v.attemptKey)??{};if(v.field==="screenshot"&&(w.screenshotKey=g.storageKey),v.field==="video"&&(w.videoKey=g.storageKey),v.field==="trace"&&(w.traceKey=g.storageKey),v.field==="visual"&&v.visualIndex!==void 0&&v.visualKey){let x=p.get(v.attemptKey)??new Map,A=x.get(v.visualIndex)??{};A[v.visualKey]=g.storageKey,x.set(v.visualIndex,A),p.set(v.attemptKey,x);}u.set(v.attemptKey,w);}let m=new Map;for(let h of a){let g=h.retry??0;(m.get(h.testId)??-1)<g&&m.set(h.testId,g);}for(let h of a){let g=Kt(h.testId,h.retry),v=(h.retry??0)===m.get(h.testId);if(h.visual&&h.visual.length>0){let A=p.get(g),T=h.visual.map((R,I)=>({...R,...A?.get(I)??{}}));i.set(g,T),v&&i.set(h.testId,T);}let w=u.get(g),x={...h.artifacts,...w?.screenshotKey?{screenshotKey:w.screenshotKey}:{},...w?.videoKey?{videoKey:w.videoKey}:{},...w?.traceKey?{traceKey:w.traceKey}:{}};n.set(g,x),v&&n.set(h.testId,x);}let b=Array.from(f.values()).filter(h=>h.success).length;return b>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${b} artifact(s) to cloud storage.
4390
+ `),{keyMap:n,visualKeyMap:i,total:d.length,uploaded:b}}async function Yt(e,t,r,a,s,n,i,o,l,d,c){let p={realtimeFinalizeAttempted:false,realtimeFinalized:false,batchAttempted:false,batchAcknowledged:false,artifactsTotal:0,artifactsUploaded:0,failureReason:null},y=new Ce(t?.uploadBudgetMs??12e4),f=u=>{p.failureReason||(p.failureReason=u);};try{if(e.isCloudMode()&&s&&(r==="realtime"||r==="both")){p.realtimeFinalizeAttempted=!0;let b=await e.ensureValidToken(),h=e.getGitMetadata(),g=Dt(c),v={finishedAt:i,duration:o,summary:l,...h?.commitMessage?{commitMessage:h.commitMessage}:{},testType:g.testType,...g.testType==="api"?{apiProtocol:g.apiProtocol,metadata:g.metadata}:{}};if(b){let w=await Ha(e.getEndpoint(),e.getAccessToken(),s,v);if(p.realtimeFinalized=w,!w){f("finalize_failed_after_retries");let x=t?.queueDirectory??".testrelic/queue";pe(x,a,"finalize","finalize_failed_after_retries",`${e.getEndpoint()}/runs/${s}/finalize`,"POST",v,{"Content-Type":"application/json"});}}else {f(e.getFailureReason()??"token_invalid");let w=t?.queueDirectory??".testrelic/queue";pe(w,a,"finalize",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs/${s}/finalize`,"POST",v,{"Content-Type":"application/json"});}}let u=new Map,m=new Map;if(e.isCloudMode()&&d&&d.length>0){let b=await lo(e,t,a,d,y);u=b.keyMap,m=b.visualKeyMap,p.artifactsTotal=b.total,p.artifactsUploaded=b.uploaded;}if(e.isCloudMode()&&(!r||r==="batch"||r==="both"))if(p.batchAttempted=!0,await e.ensureValidToken()){let h=e.getGitMetadata(),g=U(),v=Wt(e),w=uo(po(n,u),m),x=Lt(w,v,h,g,co(c,m),Ie()),A=await Oa(e.getEndpoint(),e.getAccessToken(),x,async()=>await e.ensureValidToken()?e.getAccessToken():null,t?.timeout,y);if(p.batchAcknowledged=A.success,!A.success){let T=A;f(T.reason);let R=t?.queueDirectory??".testrelic/queue";pe(R,a,"batch",T.reason,T.targetEndpoint,T.method,T.payload,{"Content-Type":"application/json"});}}else {f(e.getFailureReason()??"token_invalid");let h=t?.queueDirectory??".testrelic/queue",g=e.getGitMetadata(),v=U(),w=Wt(e),x=Lt(n,w,g,v,void 0,Ie());pe(h,a,"batch",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs`,"POST",x,{"Content-Type":"application/json"});}await e.dispose();}catch(u){f(u instanceof Error?u.message:"unexpected_upload_error");try{await e.dispose();}catch{}}return p}function co(e,t){return !e||t.size===0?e:e.map(r=>{let a=Jt(t,r.testId,r.retry);return a?{...r,visual:a}:r})}function uo(e,t){if(t.size===0)return e;let r=e.timeline.map(a=>{let s=a.tests;if(!Array.isArray(s))return a;let n=false,i=s.map(o=>{let{testId:l,retry:d}=o;if(!l)return o;let c=Jt(t,l,d);return c?(n=true,{...o,visual:c}):o});return n?{...a,tests:i}:a});return {...e,timeline:r}}function po(e,t){if(t.size===0)return e;let r=e.timeline.map(a=>{let s=a,n=s.testId;if(!n)return a;let i=Jt(t,n,s.retry);return i?{...a,...i.screenshotKey?{screenshotKey:i.screenshotKey}:{},...i.videoKey?{videoKey:i.videoKey}:{}}:a});return {...e,timeline:r}}var fo=new Set(["batch","realtime","both"]),fe=Object.freeze({attempted:false,acknowledged:false,runId:null,endpoint:null,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:"cloud reporting was never initialised"});function go(e){switch(e){case "no_api_key":return "cloud mode off \u2014 no API key configured";case "cloud_unreachable":case "network_error":return "cloud endpoint unreachable \u2014 the run stayed local";case "invalid_api_key":return "API key rejected as invalid or revoked \u2014 the run stayed local";case "expired_api_key":return "API key has expired \u2014 the run stayed local";case "validation_error":return "API key format rejected \u2014 the run stayed local";case "rate_limited":return "rate limited during authentication \u2014 the run stayed local";case "auth_timeout":return "authentication timed out \u2014 the run stayed local";case "token_expired_no_refresh":case "token_refresh_failed":case "token_refresh_error":return "access token could not be refreshed \u2014 the run stayed local";case "init_error":return "cloud initialisation timed out \u2014 the run stayed local";case "unexpected_error":return "cloud initialisation failed \u2014 the run stayed local";default:return e?`cloud mode off (${e}) \u2014 the run stayed local`:"cloud mode off \u2014 the run stayed local"}}function es(e,t,r){if(!e)return fe;if(!e.isCloudMode())return {...fe,detail:go(e.getFailureReason())};let a=t??"batch";if(!fo.has(a))return {...fe,detail:`upload strategy '${a}' is not recognised \u2014 nothing was sent`};let s=e.getEndpoint(),n=a==="realtime"||a==="both";return n&&r?{attempted:true,acknowledged:true,runId:r,endpoint:s,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:null}:{attempted:true,acknowledged:false,runId:null,endpoint:s,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:n?"run init failed \u2014 the platform did not acknowledge this run":`upload runs at the end of the run under the '${a}' strategy \u2014 not sent yet`}}function Xt(e,t,r){if(!e.attempted)return e;if(!t)return {...e,detail:e.acknowledged?"upload timed out before it completed \u2014 the run may be incomplete on the platform":"upload timed out before the platform acknowledged this run",acknowledged:e.acknowledged};let a=e.acknowledged||t.batchAcknowledged,s=e.runId??(t.batchAcknowledged?r:null),n=t.realtimeFinalizeAttempted?t.realtimeFinalized:t.batchAcknowledged,i=null;return a?n||(i="run acknowledged but not closed out \u2014 finalize failed and was queued for retry"):i=t.failureReason?`upload failed (${t.failureReason}) \u2014 queued locally for retry`:"upload failed \u2014 the platform did not acknowledge this run",{attempted:true,acknowledged:a,runId:s,endpoint:e.endpoint,finalized:n,artifactsUploaded:t.artifactsUploaded,artifactsTotal:t.artifactsTotal,detail:i}}function j(e){try{return readFileSync(e,"utf-8").split(`
4391
+ `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function wo(e){if(!e)return null;let t=e.split(`
4392
+ `).map(n=>n.trim()).filter(Boolean);if(t.length===0)return null;let r=t.filter(n=>!/^Error:\s*expect\(/.test(n));if(r.length===0)return t[0]??null;let a=r[0],s=r[1];return s!==void 0&&/^Received:/.test(s)&&/^Expected:/.test(a)?`${a} \xB7 ${s}`:a}function Qt(e){switch(e){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function ko(e,t,r){let a=`${e}::${t}::${r}`;return createHash("sha256").update(a).digest("hex").substring(0,16)}function So(e){return e.length<=3?"":e[e.length-2]}function Co(e){let t=e.findIndex(r=>r.status==="passed");return t>0?`passed on retry ${t}`:null}function os(e){return e===null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function To(e){let t={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},r=t;for(let a of e){let s=typeof a.responseStatusCode=="number"?a.responseStatusCode:null;r[os(s)]++;}return t}function ss(e){if(e){for(let t of e)if(t.status==="failed")return {type:t.type,expected:ns(t.expected),actual:ns(t.actual),...t.expression?{expression:t.expression}:{}}}}function ns(e){if(e===void 0)return "undefined";if(e===null)return "null";let t;if(typeof e=="string")t=e;else try{t=JSON.stringify(e)??String(e);}catch{t=String(e);}return t.length>200?t.slice(0,200)+"\u2026":t}function De(e,t){if(!e)return 0;let r=0;for(let a of e)a.status===t&&r++;return r}function ls(e,t){for(let r of e)t[r.category]=(t[r.category]??0)+1,r.children.length>0&&ls(r.children,t);}function Ro(e){if(e.length===0)return null;let t=[...e].sort((a,s)=>a-s),r=t.reduce((a,s)=>a+s,0);return {avg:Math.round(r/t.length),min:t[0],max:t[t.length-1],p50:Y(t,50),p95:Y(t,95),p99:Y(t,99)}}var ds=2e5,Le=1e5;function is(e,t,r,a,s,n,i){let o={retryIndex:e,apiCalls:t?.length??0,apiUrls:[],methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,assertions:r.length,navigations:a.length,navUrls:[],networkRequests:s,consoleLogs:n,actionSteps:i?.length??0,actionCategories:{}};if(t){let d=new Set;for(let c of t){let p=typeof c.method=="string"?c.method:"OTHER";o.methodCounts[p]=(o.methodCounts[p]??0)+1;let y=typeof c.url=="string"?c.url:null;y&&d.size<Le&&d.add(Tt(y));let f=typeof c.responseStatusCode=="number"?c.responseStatusCode:typeof c.statusCode=="number"?c.statusCode:null,u=f!==null&&Number.isFinite(f)?f:null;o.statusRanges[os(u)]++;let m=typeof c.responseTimeMs=="number"?c.responseTimeMs:typeof c.durationMs=="number"?c.durationMs:null;m!==null&&Number.isFinite(m)&&o.responseTimes.length<ds&&o.responseTimes.push(m);}o.apiUrls=Array.from(d);}for(let d of r)d.status==="passed"?o.passedAssertions++:o.failedAssertions++;let l=new Set;for(let d of a)d.url&&l.size<Le&&l.add(d.url);return o.navUrls=Array.from(l),i&&ls(i,o.actionCategories),o}function Ao(){return {apiUrlSet:new Set,methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,navUrlSet:new Set,actionCategoryCounts:{},volApiCalls:0,volAssertions:0,volNavigations:0,volNetworkRequests:0,volConsoleLogs:0,volActionSteps:0}}function _o(e){return process.env.BROWSERSTACK_USERNAME?"BrowserStack":e?{"github-actions":"GitHub Actions","gitlab-ci":"GitLab CI",jenkins:"Jenkins",circleci:"CircleCI","bitbucket-pipelines":"Bitbucket Pipelines"}[e.provider]??"CI":"Local"}function Io(){let e=platform();return e==="win32"?"Windows":e==="darwin"?"macOS":"Linux"}function Mo(e){let t=e.parent?.project?.()?.use;if(!t)return;let{browserName:r,channel:a}=t;if(a){let n=a.toLowerCase();return n==="chrome"||n==="chrome-stable"?"Chrome":n.startsWith("chrome-beta")?"Chrome Beta":n.startsWith("chrome-dev")?"Chrome Dev":n.startsWith("chrome-canary")?"Chrome Canary":n==="msedge"||n==="msedge-stable"?"Microsoft Edge":n.startsWith("msedge-beta")?"Edge Beta":n.startsWith("msedge-dev")?"Edge Dev":n.startsWith("msedge-canary")?"Edge Canary":a}if(r){let n=r.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":r}let s=t.defaultBrowserType;if(s){let n=s.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":s}}function Eo(e,t,r){let a=r.parent?.project?.(),s="unknown";a!==void 0&&(a.use.isMobile===true?s="mobile":s="e2e");let n=["e2e","api","unit","mobile"];for(let l of n)if(e.some(d=>d===`@${l}`||d===l))return l;let i=t.replace(/\\/g,"/"),o=["e2e","api","unit"];for(let l of o)if(i.includes(`/${l}/`))return l;return s}var Po="__testrelic_api_config";function Do(e){return JSON.stringify(e,(t,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var Ne=class{constructor(t){this.rootDir="";this.configDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.navigationsCaptured=false;this.memoryPressureWarned=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.updatingSnapshots=false;this.cloudReceipt=fe;this.pendingArtifactEntries=[];this.detectedOs="";this.detectedSource="";this.cloudTestsBuffer=[];this.activeReportMode="embedded";this.streamingWriter=null;this.testIndex=[];this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};this.streamingTestAgg=new Map;this.config=yr(t),this.apiConfig=vr(t);}upsertAggContribution(t,r){let a=this.streamingTestAgg.get(t);(!a||r.retryIndex>a.retryIndex)&&this.streamingTestAgg.set(t,r);}async onBegin(t,r){try{this.rootDir=t.rootDir,this.configDir=t.configFile?dirname(t.configFile):"";let a=t.updateSnapshots;if(this.updatingSnapshots=a==="all"||a==="changed",this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??randomUUID(),this.config.reportMode==="auto"){let o=r.allTests().length;this.activeReportMode=o>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let s=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${s} tests)
4393
+ `),this.activeReportMode==="streaming"){let o=dirname(this.config.outputPath);this.streamingWriter=new ie(o);let l=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let d={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(d);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let d=this.cloudClient.getAccessToken();d&&Ut(this.cloudClient.getEndpoint(),d,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",l),process.on("SIGINT",l);}if(this.config.includeArtifacts){let o=dirname(this.config.outputPath);this.runTimestamp=ta(join(o,"artifacts"));try{ya(join(o,"artifacts"));}catch{}}let n=U();this.detectedOs=Io(),this.detectedSource=_o(n);let i=await J(async()=>(this.cloudClient=new _e(this.config.cloud),await this.cloudClient.initialize(),Qa(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),xa,"Cloud initialization");if(this.cloudRunId=i??null,i===void 0&&this.cloudClient?.switchToLocalMode("init_error"),this.cloudReceipt=es(this.cloudClient,this.config.cloud?.uploadStrategy,this.cloudRunId),this.activeReportMode!=="streaming"){let o=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let l=this.cloudClient.getAccessToken();l&&Ut(this.cloudClient.getEndpoint(),l,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}}catch{}}onTestBegin(t,r){try{t.annotations.push({type:Po,description:Do(this.apiConfig)});}catch{}}onTestEnd(t,r){try{let a=r,s=t.outcome(),n;s==="flaky"?n="flaky":s==="skipped"?n="skipped":n=Qt(a.status);let i=a.startTime.toISOString(),o=new Date(a.startTime.getTime()+a.duration).toISOString(),l=t.tags?[...t.tags]:t.annotations.filter(M=>M.type==="tag").map(M=>M.description??""),d=Xa(a.attachments,t.annotations,t.title,n==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0),d.navigations.length>0&&(this.navigationsCaptured=!0),!this.config.captureNavigation&&d.navigations.length>0&&(d={...d,navigations:[]});let c=null;if(n==="failed"||n==="flaky"){let _=(n==="flaky"?t.results.find(B=>B.status!=="passed")?.errors??[]:a.errors)[0];if(_){let B=xr(this.config.redactPatterns),ae=_.location?.file??null,P=d.apiAssertions.find(cs=>cs.status==="failed")?.location??null,Z=P!==null&&(ae===null||resolve(ae)!==resolve(t.location.file)),ar=Z?P.file:ae,Fe=Z?P.line:_.location?.line??null,se=null;this.config.includeCodeSnippets&&Fe!==null&&ar&&(se=br(ar,Fe,this.config.codeContextLines),se&&(se=B(se))),c={message:B(ke(_.message??"Unknown error")),line:Fe,code:se,stack:this.config.includeStackTrace&&_.stack?B(ke(_.stack)):null};}}let p=t.titlePath().filter(Boolean),y=relative(this.rootDir||".",t.location.file).replace(/\\/g,"/"),f=So(p),u=p.join(" > "),m=y,b=ko(m,f,u),h=Eo(l,m,t),g=h!=="mobile"&&d.apiCallsCount>0?"api":h,v=s==="flaky",w=Co(t.results),x=Qt(t.expectedStatus),A=Qt(a.status),T=null;if(this.config.includeArtifacts&&n!=="skipped"&&a.attachments){let M=dirname(this.config.outputPath),_=p[p.length-1]??t.title;T=aa(a.attachments,_,a.retry,M,this.runTimestamp||void 0,b);}let R=null;if(this.config.includeArtifacts&&n!=="skipped"&&a.attachments)try{let M=la(a.attachments,{updatingSnapshots:this.updatingSnapshots,failureMessage:a.errors.map(_=>_.message??"").join(`
4394
+ `)});if(M.length>0){let _=dirname(this.config.outputPath),B=p[p.length-1]??t.title;R=sa(M,B,a.retry,_,this.runTimestamp||void 0,b,this.configDir||this.rootDir||process.cwd());}}catch{}let I=this.config.includeActionSteps&&a.steps?Ra(a.steps,a.startTime):null,k=Mo(t),C={titlePath:p,title:u,status:n,duration:a.duration,startedAt:i,completedAt:o,retryCount:t.results.length-1,retry:a.retry,tags:l,failure:c,specFile:y,navigations:d.navigations,testId:b,filePath:m,suiteName:f,testType:g,isFlaky:v,retryStatus:w,expectedStatus:x,actualStatus:A,artifacts:T,visual:R,apiAssertions:d.apiAssertions,actions:I,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount,apiStatusMix:d.apiStatusMix,browser:k,os:this.detectedOs||void 0,source:this.detectedSource||void 0},X=d.consoleLogsFile&&d.consoleLogsCount>0?j(d.consoleLogsFile):void 0,G=d.networkRequestsFile&&d.networkRequestsCount>0?j(d.networkRequestsFile):void 0,re=d.apiCallsFile&&d.apiCallsCount>0?j(d.apiCallsFile):void 0,er=re?Nt(re):void 0,tr=!G&&re?Ft(re):void 0,rr=d.apiAssertions&&d.apiAssertions.length>0?Bt(d.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:b,title:u,status:n,duration:a.duration,suiteName:f,filePath:m,testType:g,isFlaky:v,startedAt:i,completedAt:o,tags:l,failure:c,retry:a.retry,retryCount:t.results.length-1,retryStatus:w,browser:k,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...I&&I.length>0?{actions:I}:{},...d.navigations&&d.navigations.length>0?{navigations:d.navigations}:{},...X?{consoleLogs:X}:{},...G?{networkRequests:G}:tr?{networkRequests:tr}:{},...er?{apiCalls:er}:{},...rr?{protocolAssertions:rr}:{},...R&&R.length>0?{visual:R}:{}});try{let M=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(M==="realtime"||M==="both")){let _=this.cloudClient.getAccessToken();_&&za(this.cloudClient.getEndpoint(),_,this.cloudRunId,this.buildCloudTestPayload(C));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let M=Be(m,p,t.id??"",a.retry),_=a.retry===t.results.length-1,B={id:M,...x!=="passed"?{expectedStatus:x}:{},navigations:d.navigations,apiAssertions:d.apiAssertions,actions:I??[],artifacts:T,visual:R,failureDiagnostic:c,hasNetworkFile:d.networkRequestsFile!==null,networkRequestsCount:d.networkRequestsCount,hasConsoleFile:d.consoleLogsFile!==null,consoleLogsCount:d.consoleLogsCount,hasApiCallsFile:d.apiCallsFile!==null,apiCallsCount:d.apiCallsCount,startedAt:i};this.streamingWriter.writeTestDetail(M,B,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let ae={id:M,title:p[p.length-1]??t.title,titlePath:p,filePath:m,status:n,...x!=="passed"?{expectedStatus:x}:{},duration:a.duration,project:p[1]??"",retryIndex:a.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:T!==null,hasActionSteps:(I?.length??0)>0,visualCount:R?.length??0,visualFailedCount:R?.filter(P=>P.status==="failed").length??0,domChangeCount:R?.reduce((P,Z)=>P+(Z.domChangeCount??0),0)??0,...(()=>{let P=R?.find(Z=>Z.diff);return P?.diff?{visualDiffPath:P.diff}:{}})(),errorMessage:wo(c?.message),networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:I?.length??0,testType:g,apiCallCount:d.apiCallsCount,...d.apiStatusMix?{apiStatusMix:d.apiStatusMix}:{},assertionsPassed:De(d.apiAssertions,"passed"),assertionsFailed:De(d.apiAssertions,"failed"),...(()=>{let P=ss(d.apiAssertions);return P?{firstFailedAssertion:P}:{}})(),isRetry:!_,retryGroupKey:Oe(m,p,t.id??"")};if(this.testIndex.push(ae),_)switch(this.summaryCounters.total++,n){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${m}::${p.join(" > ")}`,is(a.retry,re,d.apiAssertions,d.navigations,d.networkRequestsCount,d.consoleLogsCount,I)),(T||R)&&this.pendingArtifactEntries.push({testId:b,retry:a.retry,artifacts:T??{},visual:R,outputDir:dirname(this.config.outputPath)}),C.actions=null,C.apiAssertions=null,C.navigations=[],C.artifacts=null,C.failure=null,C.networkRequestsFile=null,C.consoleLogsFile=null,C.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(C),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(t){try{let r=new Date().toISOString(),a=new Date(this.startedAt).getTime(),n=new Date(r).getTime()-a,i=this.activeReportMode==="streaming"?this.testIndex.some(l=>l.status!=="skipped"):this.collectedTests.some(l=>l.status!=="skipped");!this.fixtureDataReceived&&i&&process.stderr.write(`
4362
4395
  \u26A0 TestRelic: No fixture data received from any test.
4363
4396
  To enable network logs, video sync, and Test Navigation tracking, import the TestRelic fixture:
4364
4397
  import { test, expect } from '@testrelic/playwright-analytics/fixture';
4365
4398
  instead of:
4366
4399
  import { test, expect } from '@playwright/test';
4367
4400
 
4368
- `),this.config.captureNavigation?this.fixtureDataReceived&&!this.navigationsCaptured&&o&&process.stderr.write(`[testrelic] Test Navigation: 0 navigation events captured this run. Navigation is recorded automatically on page.goto()/clicks; if you expected a navigation graph, ensure your tests drive page navigations (and use the '@testrelic/playwright-analytics/fixture' import).
4401
+ `),this.config.captureNavigation?this.fixtureDataReceived&&!this.navigationsCaptured&&i&&process.stderr.write(`[testrelic] Test Navigation: 0 navigation events captured this run. Navigation is recorded automatically on page.goto()/clicks; if you expected a navigation graph, ensure your tests drive page navigations (and use the '@testrelic/playwright-analytics/fixture' import).
4369
4402
  `):process.stderr.write(`[testrelic] Test Navigation capture is disabled (captureNavigation: false). Remove the option or set it to true to capture the navigation graph.
4370
- `),await J(()=>Zr(),Ct,"Artifact flush");let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let l=dirname(this.config.outputPath);i=fa(l,this.runTimestamp);let d=join(l,"artifact-manifest.json"),c=JSON.stringify(i),p=d+".tmp";writeFileSync(p,c,"utf-8"),renameSync(p,d);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await J(()=>this.finalizeStreamingReport(r,n,t,i),St,"Report finalization");else {let l=this.buildTimeline(),d=new Map;for(let u of this.collectedTests){let m=d.get(u.testId);(!m||u.retry>m.retry)&&d.set(u.testId,u);}let c=Array.from(d.values()),p=Sa(c,l.length),v={schemaVersion:ze,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:n,summary:p,ci:U(),metadata:this.config.metadata,timeline:l,shardRunIds:null},g=je(p,c);if(this.writeReport(v),await J(()=>mt(v,this.config,i,g),Ct,"HTML report write"),Rt(p,this.config.outputPath,this.config.htmlReportPath,this.config.quiet,g),this.cloudClient){let u=this.collectArtifactEntries(),m=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0;let h=await J(()=>Kt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,v,r,n,p,u,m),St,"Cloud upload");this.cloudReceipt=Jt(this.cloudReceipt,h,this.testRunId);}}}catch{}finally{await this.disposeCloudClient();}}async disposeCloudClient(){let t=this.cloudClient;t&&(this.cloudClient=null,await J(()=>t.dispose(),ya,"Cloud client shutdown"));}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let t=dirname(this.config.outputPath),r=[];for(let a of this.collectedTests)(a.artifacts||a.visual)&&r.push({testId:a.testId,artifacts:a.artifacts??{},visual:a.visual,outputDir:t});return r}async finalizeStreamingReport(t,r,a,s){if(!this.streamingWriter)return;this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};let n=new Map,o=new Map;for(let f of this.testIndex){let b=`${f.filePath}::${f.titlePath.join(" > ")}`,x=n.get(b);(x===void 0||f.retryIndex>x)&&n.set(b,f.retryIndex);}let i=0,l=[];for(let f of this.testIndex){let b=`${f.filePath}::${f.titlePath.join(" > ")}`,x=n.get(b);if(f.isRetry=f.retryIndex<x,f.isRetry)continue;switch(l.push(f),i++,this.summaryCounters.total++,f.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.summaryCounters.visualChecks+=f.visualCount??0,this.summaryCounters.visualFailures+=f.visualFailedCount??0,this.summaryCounters.visualDomChanges+=f.domChangeCount??0;let w=o.get(f.filePath);switch(w||(w={filePath:f.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},o.set(f.filePath,w)),w.total++,f.status){case "passed":w.passed++;break;case "failed":w.failed++;break;case "flaky":w.flaky++;break;case "skipped":w.skipped++;break;case "timedout":w.timedOut++;break}}let d=Array.from(o.values()),c=To();for(let f of this.streamingTestAgg.values()){c.volApiCalls+=f.apiCalls,c.volAssertions+=f.assertions,c.volNavigations+=f.navigations,c.volNetworkRequests+=f.networkRequests,c.volConsoleLogs+=f.consoleLogs,c.volActionSteps+=f.actionSteps;for(let b in f.methodCounts)c.methodCounts[b]=(c.methodCounts[b]??0)+f.methodCounts[b];c.statusRanges["2xx"]+=f.statusRanges["2xx"],c.statusRanges["3xx"]+=f.statusRanges["3xx"],c.statusRanges["4xx"]+=f.statusRanges["4xx"],c.statusRanges["5xx"]+=f.statusRanges["5xx"],c.statusRanges.error+=f.statusRanges.error,c.passedAssertions+=f.passedAssertions,c.failedAssertions+=f.failedAssertions;for(let b in f.actionCategories)c.actionCategoryCounts[b]=(c.actionCategoryCounts[b]??0)+f.actionCategories[b];for(let b of f.apiUrls){if(c.apiUrlSet.size>=Le)break;c.apiUrlSet.add(b);}for(let b of f.navUrls){if(c.navUrlSet.size>=Le)break;c.navUrlSet.add(b);}for(let b of f.responseTimes){if(c.responseTimes.length>=os)break;c.responseTimes.push(b);}}this.summaryCounters.totalApiCalls=c.volApiCalls,this.summaryCounters.totalAssertions=c.volAssertions,this.summaryCounters.totalNavigations=c.volNavigations,this.summaryCounters.totalNetworkRequests=c.volNetworkRequests,this.summaryCounters.totalConsoleLogs=c.volConsoleLogs,this.summaryCounters.totalActionSteps=c.volActionSteps,this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let p={reporterTotal:this.summaryCounters.total,indexTotal:i,playwrightStatus:a.status,isValid:this.summaryCounters.total===i};p.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${p.reporterTotal}, index: ${p.indexTotal}
4371
- `);let v={total:this.summaryCounters.total,passed:this.summaryCounters.passed,failed:this.summaryCounters.failed,flaky:this.summaryCounters.flaky,skipped:this.summaryCounters.skipped,timedout:this.summaryCounters.timedOut,totalApiCalls:this.summaryCounters.totalApiCalls,uniqueApiUrls:c.apiUrlSet.size,apiCallsByMethod:{...c.methodCounts},apiCallsByStatusRange:{"2xx":c.statusRanges["2xx"],"3xx":c.statusRanges["3xx"],"4xx":c.statusRanges["4xx"],"5xx":c.statusRanges["5xx"],error:c.statusRanges.error},apiResponseTime:Co(c.responseTimes),totalAssertions:this.summaryCounters.totalAssertions,passedAssertions:c.passedAssertions,failedAssertions:c.failedAssertions,totalNavigations:this.summaryCounters.totalNavigations,uniqueNavigationUrls:c.navUrlSet.size,totalTimelineSteps:i,totalActionSteps:this.summaryCounters.totalActionSteps,actionStepsByCategory:{...c.actionCategoryCounts},visualChecks:this.summaryCounters.visualChecks,visualFailures:this.summaryCounters.visualFailures,visualDomChanges:this.summaryCounters.visualDomChanges},g={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:t,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:d,enrichedSummary:v,validation:p,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(g);let u={schemaVersion:"2.0",generatedAt:new Date().toISOString(),reportMode:"streaming",summaryFile:"summary.json",indexFile:"index.json",testsDir:"tests",artifactsDir:"artifacts",testCount:this.testIndex.length,totalSizeBytes:this.streamingWriter.computeTotalSize()};this.streamingWriter.writeManifest(u);let m=je(v,l);await mt(this.buildStreamingReport(g,v,t,r),this.config,s,m),Rt(v,this.config.outputPath,this.config.htmlReportPath,this.config.quiet,m);let h=this.streamingWriter.getReportDir();process.stderr.write(`[testrelic] Streaming report written to ${h}
4403
+ `),await J(()=>ea(),Ct,"Artifact flush");let o=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let l=dirname(this.config.outputPath);o=ha(l,this.runTimestamp);let d=join(l,"artifact-manifest.json"),c=JSON.stringify(o),p=d+".tmp";writeFileSync(p,c,"utf-8"),renameSync(p,d);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await J(()=>this.finalizeStreamingReport(r,n,t,o),St,"Report finalization");else {let l=this.buildTimeline(),d=new Map;for(let u of this.collectedTests){let m=d.get(u.testId);(!m||u.retry>m.retry)&&d.set(u.testId,u);}let c=Array.from(d.values()),p=Ta(c,l.length),y={schemaVersion:ze,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:n,summary:p,ci:U(),metadata:this.config.metadata,timeline:l,shardRunIds:null},f=je(p,c);if(this.writeReport(y),await J(()=>mt(y,this.config,o,f),Ct,"HTML report write"),Rt(p,this.config.outputPath,this.config.htmlReportPath,this.config.quiet,f),this.cloudClient){let u=this.collectArtifactEntries(),m=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0;let b=await J(()=>Yt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,y,r,n,p,u,m),St,"Cloud upload");this.cloudReceipt=Xt(this.cloudReceipt,b,this.testRunId);}}}catch{}finally{await this.disposeCloudClient();}}async disposeCloudClient(){let t=this.cloudClient;t&&(this.cloudClient=null,await J(()=>t.dispose(),wa,"Cloud client shutdown"));}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let t=dirname(this.config.outputPath),r=[];for(let a of this.collectedTests)(a.artifacts||a.visual)&&r.push({testId:a.testId,retry:a.retry,artifacts:a.artifacts??{},visual:a.visual,outputDir:t});return r}async finalizeStreamingReport(t,r,a,s){if(!this.streamingWriter)return;this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};let n=new Map,i=new Map;for(let g of this.testIndex){let v=`${g.filePath}::${g.titlePath.join(" > ")}`,w=n.get(v);(w===void 0||g.retryIndex>w)&&n.set(v,g.retryIndex);}let o=0,l=[];for(let g of this.testIndex){let v=`${g.filePath}::${g.titlePath.join(" > ")}`,w=n.get(v);if(g.isRetry=g.retryIndex<w,g.isRetry)continue;switch(l.push(g),o++,this.summaryCounters.total++,g.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.summaryCounters.visualChecks+=g.visualCount??0,this.summaryCounters.visualFailures+=g.visualFailedCount??0,this.summaryCounters.visualDomChanges+=g.domChangeCount??0;let x=i.get(g.filePath);switch(x||(x={filePath:g.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},i.set(g.filePath,x)),x.total++,g.status){case "passed":x.passed++;break;case "failed":x.failed++;break;case "flaky":x.flaky++;break;case "skipped":x.skipped++;break;case "timedout":x.timedOut++;break}}let d=Array.from(i.values()),c=Ao();for(let g of this.streamingTestAgg.values()){c.volApiCalls+=g.apiCalls,c.volAssertions+=g.assertions,c.volNavigations+=g.navigations,c.volNetworkRequests+=g.networkRequests,c.volConsoleLogs+=g.consoleLogs,c.volActionSteps+=g.actionSteps;for(let v in g.methodCounts)c.methodCounts[v]=(c.methodCounts[v]??0)+g.methodCounts[v];c.statusRanges["2xx"]+=g.statusRanges["2xx"],c.statusRanges["3xx"]+=g.statusRanges["3xx"],c.statusRanges["4xx"]+=g.statusRanges["4xx"],c.statusRanges["5xx"]+=g.statusRanges["5xx"],c.statusRanges.error+=g.statusRanges.error,c.passedAssertions+=g.passedAssertions,c.failedAssertions+=g.failedAssertions;for(let v in g.actionCategories)c.actionCategoryCounts[v]=(c.actionCategoryCounts[v]??0)+g.actionCategories[v];for(let v of g.apiUrls){if(c.apiUrlSet.size>=Le)break;c.apiUrlSet.add(v);}for(let v of g.navUrls){if(c.navUrlSet.size>=Le)break;c.navUrlSet.add(v);}for(let v of g.responseTimes){if(c.responseTimes.length>=ds)break;c.responseTimes.push(v);}}this.summaryCounters.totalApiCalls=c.volApiCalls,this.summaryCounters.totalAssertions=c.volAssertions,this.summaryCounters.totalNavigations=c.volNavigations,this.summaryCounters.totalNetworkRequests=c.volNetworkRequests,this.summaryCounters.totalConsoleLogs=c.volConsoleLogs,this.summaryCounters.totalActionSteps=c.volActionSteps,this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let p={reporterTotal:this.summaryCounters.total,indexTotal:o,playwrightStatus:a.status,isValid:this.summaryCounters.total===o};p.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${p.reporterTotal}, index: ${p.indexTotal}
4404
+ `);let y={total:this.summaryCounters.total,passed:this.summaryCounters.passed,failed:this.summaryCounters.failed,flaky:this.summaryCounters.flaky,skipped:this.summaryCounters.skipped,timedout:this.summaryCounters.timedOut,totalApiCalls:this.summaryCounters.totalApiCalls,uniqueApiUrls:c.apiUrlSet.size,apiCallsByMethod:{...c.methodCounts},apiCallsByStatusRange:{"2xx":c.statusRanges["2xx"],"3xx":c.statusRanges["3xx"],"4xx":c.statusRanges["4xx"],"5xx":c.statusRanges["5xx"],error:c.statusRanges.error},apiResponseTime:Ro(c.responseTimes),totalAssertions:this.summaryCounters.totalAssertions,passedAssertions:c.passedAssertions,failedAssertions:c.failedAssertions,totalNavigations:this.summaryCounters.totalNavigations,uniqueNavigationUrls:c.navUrlSet.size,totalTimelineSteps:o,totalActionSteps:this.summaryCounters.totalActionSteps,actionStepsByCategory:{...c.actionCategoryCounts},visualChecks:this.summaryCounters.visualChecks,visualFailures:this.summaryCounters.visualFailures,visualDomChanges:this.summaryCounters.visualDomChanges},f={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:t,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:d,enrichedSummary:y,validation:p,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(f);let u={schemaVersion:"2.0",generatedAt:new Date().toISOString(),reportMode:"streaming",summaryFile:"summary.json",indexFile:"index.json",testsDir:"tests",artifactsDir:"artifacts",testCount:this.testIndex.length,totalSizeBytes:this.streamingWriter.computeTotalSize()};this.streamingWriter.writeManifest(u);let m=je(y,l);await mt(this.buildStreamingReport(f,y,t,r),this.config,s,m),Rt(y,this.config.outputPath,this.config.htmlReportPath,this.config.quiet,m);let b=this.streamingWriter.getReportDir();process.stderr.write(`[testrelic] Streaming report written to ${b}
4372
4405
  [testrelic] ${this.testIndex.length} test detail files on disk
4373
- [testrelic] View report: npx testrelic serve ${h}
4406
+ [testrelic] View report: npx testrelic serve ${b}
4374
4407
  `),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
4375
- `);let y=this.streamingWriter;try{if(this.cloudClient){let f=this.buildStreamingReport(g,v,t,r),b=this.collectArtifactEntries(),x=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0;let w=await Kt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,f,t,r,v,b,x);this.cloudReceipt=Jt(this.cloudReceipt,w,this.testRunId);let M={...g,cloudUpload:this.cloudReceipt};try{y.writeSummary(M);}catch{}}}finally{y.dispose();}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(t,r,a,s){return {schemaVersion:ze,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:a,totalDuration:s,summary:r,ci:U(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let t=process.memoryUsage(),r=t.heapUsed/1024/1024;if(r<200)return;let a=t.heapUsed/t.heapTotal;a>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
4408
+ `);let h=this.streamingWriter;try{if(this.cloudClient){let g=this.buildStreamingReport(f,y,t,r),v=this.collectArtifactEntries(),w=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0;let x=await Yt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,g,t,r,y,v,w);this.cloudReceipt=Xt(this.cloudReceipt,x,this.testRunId);let A={...f,cloudUpload:this.cloudReceipt};try{h.writeSummary(A);}catch{}}}finally{h.dispose();}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(t,r,a,s){return {schemaVersion:ze,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:a,totalDuration:s,summary:r,ci:U(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let t=process.memoryUsage(),r=t.heapUsed/1024/1024;if(r<200)return;let a=t.heapUsed/t.heapTotal;a>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
4376
4409
  `),this.switchToStreamingMode()):a>.8&&r>=500&&!this.memoryPressureWarned&&(this.memoryPressureWarned=!0,process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
4377
- `));}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let t=dirname(this.config.outputPath);this.streamingWriter=new ie(t);for(let r of this.collectedTests){let a=Be(r.filePath,r.titlePath,r.testId,r.retry),s=r.apiCallsFile&&r.apiCallsCount>0?j(r.apiCallsFile):void 0,n={id:a,...r.expectedStatus!=="passed"?{expectedStatus:r.expectedStatus}:{},navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(a,n,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let o={id:a,title:r.titlePath[r.titlePath.length-1]??r.title,titlePath:r.titlePath,filePath:r.filePath,status:r.status,...r.expectedStatus!=="passed"?{expectedStatus:r.expectedStatus}:{},duration:r.duration,project:r.titlePath[1]??"",retryIndex:r.retry,tags:r.tags,hasNetworkData:r.networkRequestsCount>0,hasConsoleData:r.consoleLogsCount>0,hasArtifacts:r.artifacts!==null,hasActionSteps:(r.actions?.length??0)>0,errorMessage:r.failure?.message?.split(`
4378
- `)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,testType:r.testType,apiCallCount:r.apiCallsCount,...r.apiStatusMix?{apiStatusMix:r.apiStatusMix}:s?{apiStatusMix:So(s)}:{},assertionsPassed:De(r.apiAssertions,"passed"),assertionsFailed:De(r.apiAssertions,"failed"),...(()=>{let i=rs(r.apiAssertions);return i?{firstFailedAssertion:i}:{}})(),isRetry:!1,retryGroupKey:Oe(r.filePath,r.titlePath,r.testId)};switch(this.testIndex.push(o),this.summaryCounters.total++,r.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${r.filePath}::${r.titlePath.join(" > ")}`,ss(r.retry,s,r.apiAssertions??[],r.navigations??[],r.networkRequestsCount,r.consoleLogsCount,r.actions??null));}this.collectedTests.length=0;}catch{}}buildTimeline(){let t=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return ka(t,{navigationTypes:this.config.navigationTypes})}readJsonlFile(t){if(!t)return null;let r=j(t);return r.length>0?r:null}toTestResult(t,r){let a=null,s=null,n=null;return r?.loadFiles&&(a=this.readJsonlFile(t.networkRequestsFile),s=this.readJsonlFile(t.consoleLogsFile),n=this.readJsonlFile(t.apiCallsFile)),{title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,visual:t.visual,networkRequests:a,apiCalls:n,apiAssertions:t.apiAssertions,actions:t.actions??null,consoleLogs:s}}buildCloudTestPayload(t){let r={title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retry:t.retry,retryCount:t.retryCount,retryStatus:t.retryStatus,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,visual:t.visual??[],actions:t.actions??[],navigations:t.navigations??[],steps:t.actions??[],browser:t.browser,os:t.os,source:t.source};if(t.apiAssertions&&t.apiAssertions.length>0&&(r.protocolAssertions=Bt(t.apiAssertions)),t.consoleLogsFile&&(r.consoleLogs=j(t.consoleLogsFile)),t.networkRequestsFile&&(r.networkRequests=j(t.networkRequestsFile)),t.apiCallsFile){let a=j(t.apiCallsFile);r.apiCalls=Nt(a),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=Ft(a));}return r}writeReport(t){try{let r=JSON.stringify(t),a=this.config.outputPath,s=dirname(a);mkdirSync(s,{recursive:!0});let n=a+".tmp";writeFileSync(n,r,"utf-8"),renameSync(n,a);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
4410
+ `));}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let t=dirname(this.config.outputPath);this.streamingWriter=new ie(t);for(let r of this.collectedTests){let a=Be(r.filePath,r.titlePath,r.testId,r.retry),s=r.apiCallsFile&&r.apiCallsCount>0?j(r.apiCallsFile):void 0,n={id:a,...r.expectedStatus!=="passed"?{expectedStatus:r.expectedStatus}:{},navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(a,n,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let i={id:a,title:r.titlePath[r.titlePath.length-1]??r.title,titlePath:r.titlePath,filePath:r.filePath,status:r.status,...r.expectedStatus!=="passed"?{expectedStatus:r.expectedStatus}:{},duration:r.duration,project:r.titlePath[1]??"",retryIndex:r.retry,tags:r.tags,hasNetworkData:r.networkRequestsCount>0,hasConsoleData:r.consoleLogsCount>0,hasArtifacts:r.artifacts!==null,hasActionSteps:(r.actions?.length??0)>0,errorMessage:r.failure?.message?.split(`
4411
+ `)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,testType:r.testType,apiCallCount:r.apiCallsCount,...r.apiStatusMix?{apiStatusMix:r.apiStatusMix}:s?{apiStatusMix:To(s)}:{},assertionsPassed:De(r.apiAssertions,"passed"),assertionsFailed:De(r.apiAssertions,"failed"),...(()=>{let o=ss(r.apiAssertions);return o?{firstFailedAssertion:o}:{}})(),isRetry:!1,retryGroupKey:Oe(r.filePath,r.titlePath,r.testId)};switch(this.testIndex.push(i),this.summaryCounters.total++,r.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${r.filePath}::${r.titlePath.join(" > ")}`,is(r.retry,s,r.apiAssertions??[],r.navigations??[],r.networkRequestsCount,r.consoleLogsCount,r.actions??null));}this.collectedTests.length=0;}catch{}}buildTimeline(){let t=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return Ca(t,{navigationTypes:this.config.navigationTypes})}readJsonlFile(t){if(!t)return null;let r=j(t);return r.length>0?r:null}toTestResult(t,r){let a=null,s=null,n=null;return r?.loadFiles&&(a=this.readJsonlFile(t.networkRequestsFile),s=this.readJsonlFile(t.consoleLogsFile),n=this.readJsonlFile(t.apiCallsFile)),{title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,retry:t.retry,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,visual:t.visual,networkRequests:a,apiCalls:n,apiAssertions:t.apiAssertions,actions:t.actions??null,consoleLogs:s}}buildCloudTestPayload(t){let r={title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retry:t.retry,retryCount:t.retryCount,retryStatus:t.retryStatus,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,visual:t.visual??[],actions:t.actions??[],navigations:t.navigations??[],steps:t.actions??[],browser:t.browser,os:t.os,source:t.source};if(t.apiAssertions&&t.apiAssertions.length>0&&(r.protocolAssertions=Bt(t.apiAssertions)),t.consoleLogsFile&&(r.consoleLogs=j(t.consoleLogsFile)),t.networkRequestsFile&&(r.networkRequests=j(t.networkRequestsFile)),t.apiCallsFile){let a=j(t.apiCallsFile);r.apiCalls=Nt(a),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=Ft(a));}return r}writeReport(t){try{let r=JSON.stringify(t),a=this.config.outputPath,s=dirname(a);mkdirSync(s,{recursive:!0});let n=a+".tmp";writeFileSync(n,r,"utf-8"),renameSync(n,a);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
4379
4412
  `);}}};export{Ne as default};//# sourceMappingURL=reporter-entry.js.map
4380
4413
  //# sourceMappingURL=reporter-entry.js.map