@testrelic/playwright-analytics 2.16.3 → 2.16.4-next.186

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var crypto=require('crypto'),fs$1=require('fs'),path=require('path'),os$1=require('os'),core=require('@testrelic/core'),child_process=require('child_process'),http=require('http'),readline=require('readline'),promises=require('fs/promises'),zlib=require('zlib'),util=require('util'),stream=require('stream'),test=require('@playwright/test'),perf_hooks=require('perf_hooks'),url=require('url');var fa=".testrelic-report";function Qe(t,e,r,n){let s=`${t}|${e.join("|")}|${r}|${n}`;return crypto.createHash("sha256").update(s).digest("hex").substring(0,12)}function et(t,e,r){let n=`${t}|${e.join("|")}|${r}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,12)}var he=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=path.join(e,fa),this.testsDir=path.join(this.reportDir,"tests"),fs$1.mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(e,r,n){try{let s=path.join(this.testsDir,e);fs$1.mkdirSync(s,{recursive:!0});let a=path.join(s,"meta.json"),o=a+".tmp",i=JSON.stringify(r);return fs$1.writeFileSync(o,i,"utf-8"),fs$1.renameSync(o,a),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),n?.networkRequestsFile&&this.moveFile(n.networkRequestsFile,path.join(s,"network.jsonl")),n?.consoleLogsFile&&this.moveFile(n.consoleLogsFile,path.join(s,"console.jsonl")),n?.apiCallsFile&&this.moveFile(n.apiCallsFile,path.join(s,"api-calls.jsonl")),!0}catch(s){let a=s instanceof Error?s.message:String(s);return this.writeErrors.push({testId:e,error:a,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${e}: ${a}
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var crypto=require('crypto'),fs$1=require('fs'),path=require('path'),os$1=require('os'),core=require('@testrelic/core'),child_process=require('child_process'),http=require('http'),readline=require('readline'),promises=require('fs/promises'),zlib=require('zlib'),util=require('util'),stream=require('stream'),test=require('@playwright/test'),perf_hooks=require('perf_hooks'),url=require('url');var ma=".testrelic-report";function Qe(t,e,r,n){let s=`${t}|${e.join("|")}|${r}|${n}`;return crypto.createHash("sha256").update(s).digest("hex").substring(0,12)}function et(t,e,r){let n=`${t}|${e.join("|")}|${r}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,12)}var he=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=path.join(e,ma),this.testsDir=path.join(this.reportDir,"tests"),fs$1.mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(e,r,n){try{let s=path.join(this.testsDir,e);fs$1.mkdirSync(s,{recursive:!0});let a=path.join(s,"meta.json"),o=a+".tmp",i=JSON.stringify(r);return fs$1.writeFileSync(o,i,"utf-8"),fs$1.renameSync(o,a),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),n?.networkRequestsFile&&this.moveFile(n.networkRequestsFile,path.join(s,"network.jsonl")),n?.consoleLogsFile&&this.moveFile(n.consoleLogsFile,path.join(s,"console.jsonl")),n?.apiCallsFile&&this.moveFile(n.apiCallsFile,path.join(s,"api-calls.jsonl")),!0}catch(s){let a=s instanceof Error?s.message:String(s);return this.writeErrors.push({testId:e,error:a,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${e}: ${a}
2
2
  `),false}}moveFile(e,r){try{fs$1.renameSync(e,r);}catch{try{fs$1.copyFileSync(e,r);try{fs$1.unlinkSync(e);}catch{}}catch(n){process.stderr.write(`[testrelic] Failed to move file ${e} \u2192 ${r}: ${n instanceof Error?n.message:String(n)}
3
- `);}}}writeIndex(e){let r=path.join(this.reportDir,"index.json"),n=r+".tmp",s=JSON.stringify(e);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(e){let r=path.join(this.reportDir,"index-compact.json"),n=r+".tmp",s=e.map(({titlePath:o,project:i,...d})=>d),a=JSON.stringify(s);fs$1.writeFileSync(n,a,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeSummary(e){let r=path.join(this.reportDir,"summary.json"),n=r+".tmp",s=JSON.stringify(e);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(e){let r=path.join(this.reportDir,"manifest.json"),n=r+".tmp",s=JSON.stringify(e);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var Er=".testrelic",ba="testrelic-config.json",xa=".testrelic",wa=5,ka=new Set(["__proto__","constructor","prototype"]),Mr=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,uploadBudgetMs:12e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${Er}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),Ca={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function Lr(t){let e=path.resolve(t);for(let r=0;r<=wa;r++){let n=path.join(e,Er,ba);if(fs$1.existsSync(n))try{if(fs$1.statSync(n).isFile())return n}catch{}let s=path.join(e,xa);if(fs$1.existsSync(s))try{if(fs$1.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 a=path.dirname(e);if(a===e)break;e=a;}return null}function Nr(t){try{let e=fs$1.readFileSync(t,"utf-8"),r=JSON.parse(e);return typeof r!="object"||r===null||Array.isArray(r)||!Dr(r)?null:r}catch{return null}}function Dr(t){for(let e of Object.keys(t)){if(ka.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!Dr(r))return false}return true}function Fr(t){let e=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(t);if(e)return process.env[e[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(t);return r?process.env[r[1]]??null:t}function tt(t){let e=Object.create(null);for(let r of Object.keys(t)){let n=t[r];typeof n=="string"&&n.startsWith("$")?e[r]=Fr(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?e[r]=tt(n):e[r]=n;}return e}function Pr(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),n=e[2],s=Ca[n];return !s||r<=0?null:r*s}function Br(t,e){let r=Object.create(null);if(Object.assign(r,Mr),t){let d=t.cloud;d&&typeof d=="object"&&(typeof d.endpoint=="string"&&(r.endpoint=d.endpoint),typeof d.upload=="string"&&(r.uploadStrategy=d.upload),typeof d.timeout=="number"&&(r.timeout=d.timeout),typeof d.uploadBudgetMs=="number"&&(r.uploadBudgetMs=d.uploadBudgetMs),typeof d.apiKey=="string"&&d.apiKey.length>0&&(r.apiKey=d.apiKey));let l=t["testrelic-repo"]??t.project;l&&typeof l=="object"&&typeof l.name=="string"&&(r.projectName=l.name),t.project&&!t["testrelic-repo"]&&process.stderr.write(`[testrelic] Deprecation: "project" key in config is deprecated. Rename it to "testrelic-repo".
5
- `);let c=t.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let u=Pr(c.maxAge);u!==null&&(r.queueMaxAge=u);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let d=e.apiKey.startsWith("$")?Fr(e.apiKey):e.apiKey;d&&(r.apiKey=d);}if(typeof e.endpoint=="string"&&(r.endpoint=e.endpoint),typeof e.upload=="string"&&(r.uploadStrategy=e.upload),typeof e.timeout=="number"&&(r.timeout=e.timeout),typeof e.uploadBudgetMs=="number"&&(r.uploadBudgetMs=e.uploadBudgetMs),typeof e.projectName=="string"&&(r.projectName=e.projectName),typeof e.queueMaxAge=="string"){let d=Pr(e.queueMaxAge);d!==null&&(r.queueMaxAge=d);}typeof e.queueDirectory=="string"&&(r.queueDirectory=e.queueDirectory),typeof e.uploadArtifacts=="boolean"&&(r.uploadArtifacts=e.uploadArtifacts),typeof e.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=e.artifactMaxSizeMb);}let n=process.env.TESTRELIC_API_KEY;n&&n.length>0&&(r.apiKey=n);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&core.isValidEndpointUrl(s)&&(r.endpoint=s);let a=process.env.TESTRELIC_UPLOAD_STRATEGY;a&&["batch","realtime","both"].includes(a)&&(r.uploadStrategy=a);let o=process.env.TESTRELIC_CLOUD_TIMEOUT;if(o){let d=parseInt(o,10);!isNaN(d)&&d>=1e3&&d<=12e4&&(r.timeout=d);}let i=Object.freeze(r);return core.isValidCloudConfig(i)?i:Mr}var Aa=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],_a=["authorization","cookie","set-cookie","x-api-key"],Ia=["password","secret","token","apiKey","api_key"];function Or(t){let e=Object.create(null);return e.trackApiCalls=t?.trackApiCalls??true,e.captureRequestHeaders=t?.captureRequestHeaders??true,e.captureResponseHeaders=t?.captureResponseHeaders??true,e.captureRequestBody=t?.captureRequestBody??true,e.captureResponseBody=t?.captureResponseBody??true,e.captureAssertions=t?.captureAssertions??true,e.redactHeaders=t?.redactHeaders??[..._a],e.redactBodyFields=t?.redactBodyFields??[...Ia],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function qr(t){if(t!==void 0&&!core.isValidConfig(t))throw core.createError(core.ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let e=Object.create(null);e.outputPath=t?.outputPath??"./test-results/analytics-timeline.json",e.includeStackTrace=t?.includeStackTrace??false,e.includeCodeSnippets=t?.includeCodeSnippets??true,e.codeContextLines=t?.codeContextLines??3,e.includeNetworkStats=t?.includeNetworkStats??true,e.captureNavigation=t?.captureNavigation??true,e.navigationTypes=t?.navigationTypes??null,e.redactPatterns=[...Aa,...t?.redactPatterns??[]],e.testRunId=t?.testRunId??null,e.metadata=t?.metadata??null;let r=e.outputPath;e.openReport=t?.openReport??true,e.htmlReportPath=t?.htmlReportPath??r.replace(/\.json$/,".html"),e.includeArtifacts=t?.includeArtifacts??true,e.trackApiCalls=t?.trackApiCalls??true,e.quiet=t?.quiet??false,e.includeActionSteps=t?.includeActionSteps??true,e.captureConsoleLogs=t?.captureConsoleLogs??true;let n=Lr(process.cwd()),s=n?Nr(n):null,a=s?tt(s):null,o=Br(a,t?.cloud);return e.cloud=o.apiKey?o:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var Ce="1.8.0";function Hr(t,e,r){try{let s=fs$1.readFileSync(t,"utf-8").split(`
6
- `);if(e<1||e>s.length)return null;let a=Math.max(1,e-r),o=Math.min(s.length,e+r),i=[];for(let d=a;d<=o;d++){let l=d===e?">":" ",c=String(d).padStart(String(o).length," ");i.push(`${l} ${c} | ${s[d-1]}`);}return i.join(`
7
- `)}catch{return null}}function Ur(t){return e=>{let r=e;for(let n of t)if(typeof n=="string"){let s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=n.flags.includes("g")?n.flags:n.flags+"g",a=new RegExp(n.source,s);r=r.replace(a,"[REDACTED]");}return r}}function Pa(t){return t.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:t.GITHUB_RUN_ID??null,commitSha:t.GITHUB_SHA??null,branch:t.GITHUB_REF_NAME??null,runUrl:t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY&&t.GITHUB_RUN_ID?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}/actions/runs/${t.GITHUB_RUN_ID}`:null}}function Ea(t){return t.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:t.CI_PIPELINE_ID??null,commitSha:t.CI_COMMIT_SHA??null,branch:t.CI_COMMIT_BRANCH??t.CI_COMMIT_REF_NAME??null,runUrl:t.CI_PIPELINE_URL??null}}function La(t){if(!t.JENKINS_URL)return null;let e=t.GIT_BRANCH??null;return e?.startsWith("origin/")&&(e=e.slice(7)),{provider:"jenkins",buildId:t.BUILD_ID??null,commitSha:t.GIT_COMMIT??null,branch:e,runUrl:t.BUILD_URL??null}}function Na(t){return t.CIRCLECI!=="true"?null:{provider:"circleci",buildId:t.CIRCLE_BUILD_NUM??null,commitSha:t.CIRCLE_SHA1??null,branch:t.CIRCLE_BRANCH??null,runUrl:t.CIRCLE_BUILD_URL??null}}function Da(t){if(!t.BITBUCKET_PIPELINE_UUID)return null;let e=t.BITBUCKET_WORKSPACE&&t.BITBUCKET_REPO_SLUG&&t.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${t.BITBUCKET_WORKSPACE}/${t.BITBUCKET_REPO_SLUG}/pipelines/results/${t.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:t.BITBUCKET_BUILD_NUMBER??null,commitSha:t.BITBUCKET_COMMIT??null,branch:t.BITBUCKET_BRANCH??null,runUrl:e}}var Fa=[Pa,Ea,La,Na,Da];function V(t){let e=process.env;for(let r of Fa){let n=r(e);if(n)return n}return null}var rt=`
3
+ `);}}}writeIndex(e){let r=path.join(this.reportDir,"index.json"),n=r+".tmp",s=JSON.stringify(e);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(e){let r=path.join(this.reportDir,"index-compact.json"),n=r+".tmp",s=e.map(({titlePath:o,project:i,...l})=>l),a=JSON.stringify(s);fs$1.writeFileSync(n,a,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeSummary(e){let r=path.join(this.reportDir,"summary.json"),n=r+".tmp",s=JSON.stringify(e);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(e){let r=path.join(this.reportDir,"manifest.json"),n=r+".tmp",s=JSON.stringify(e);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var Lr=".testrelic",ka="testrelic-config.json",Ca=".testrelic",Sa=5,Ta=new Set(["__proto__","constructor","prototype"]),Er=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,uploadBudgetMs:12e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${Lr}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),Ra={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function Dr(t){let e=path.resolve(t);for(let r=0;r<=Sa;r++){let n=path.join(e,Lr,ka);if(fs$1.existsSync(n))try{if(fs$1.statSync(n).isFile())return n}catch{}let s=path.join(e,Ca);if(fs$1.existsSync(s))try{if(fs$1.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 a=path.dirname(e);if(a===e)break;e=a;}return null}function Fr(t){try{let e=fs$1.readFileSync(t,"utf-8"),r=JSON.parse(e);return typeof r!="object"||r===null||Array.isArray(r)||!Br(r)?null:r}catch{return null}}function Br(t){for(let e of Object.keys(t)){if(Ta.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!Br(r))return false}return true}function Or(t){let e=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(t);if(e)return process.env[e[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(t);return r?process.env[r[1]]??null:t}function tt(t){let e=Object.create(null);for(let r of Object.keys(t)){let n=t[r];typeof n=="string"&&n.startsWith("$")?e[r]=Or(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?e[r]=tt(n):e[r]=n;}return e}function Nr(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),n=e[2],s=Ra[n];return !s||r<=0?null:r*s}function qr(t,e){let r=Object.create(null);if(Object.assign(r,Er),t){let l=t.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=t["testrelic-repo"]??t.project;d&&typeof d=="object"&&typeof d.name=="string"&&(r.projectName=d.name),t.project&&!t["testrelic-repo"]&&process.stderr.write(`[testrelic] Deprecation: "project" key in config is deprecated. Rename it to "testrelic-repo".
5
+ `);let c=t.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let u=Nr(c.maxAge);u!==null&&(r.queueMaxAge=u);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let l=e.apiKey.startsWith("$")?Or(e.apiKey):e.apiKey;l&&(r.apiKey=l);}if(typeof e.endpoint=="string"&&(r.endpoint=e.endpoint),typeof e.upload=="string"&&(r.uploadStrategy=e.upload),typeof e.timeout=="number"&&(r.timeout=e.timeout),typeof e.uploadBudgetMs=="number"&&(r.uploadBudgetMs=e.uploadBudgetMs),typeof e.projectName=="string"&&(r.projectName=e.projectName),typeof e.queueMaxAge=="string"){let l=Nr(e.queueMaxAge);l!==null&&(r.queueMaxAge=l);}typeof e.queueDirectory=="string"&&(r.queueDirectory=e.queueDirectory),typeof e.uploadArtifacts=="boolean"&&(r.uploadArtifacts=e.uploadArtifacts),typeof e.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=e.artifactMaxSizeMb);}let n=process.env.TESTRELIC_API_KEY;n&&n.length>0&&(r.apiKey=n);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&core.isValidEndpointUrl(s)&&(r.endpoint=s);let a=process.env.TESTRELIC_UPLOAD_STRATEGY;a&&["batch","realtime","both"].includes(a)&&(r.uploadStrategy=a);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 core.isValidCloudConfig(i)?i:Er}var Ma=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],Pa=["authorization","cookie","set-cookie","x-api-key"],Ea=["password","secret","token","apiKey","api_key"];function Hr(t){let e=Object.create(null);return e.trackApiCalls=t?.trackApiCalls??true,e.captureRequestHeaders=t?.captureRequestHeaders??true,e.captureResponseHeaders=t?.captureResponseHeaders??true,e.captureRequestBody=t?.captureRequestBody??true,e.captureResponseBody=t?.captureResponseBody??true,e.captureAssertions=t?.captureAssertions??true,e.redactHeaders=t?.redactHeaders??[...Pa],e.redactBodyFields=t?.redactBodyFields??[...Ea],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function Ur(t){if(t!==void 0&&!core.isValidConfig(t))throw core.createError(core.ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let e=Object.create(null);e.outputPath=t?.outputPath??"./test-results/analytics-timeline.json",e.includeStackTrace=t?.includeStackTrace??false,e.includeCodeSnippets=t?.includeCodeSnippets??true,e.codeContextLines=t?.codeContextLines??3,e.includeNetworkStats=t?.includeNetworkStats??true,e.captureNavigation=t?.captureNavigation??true,e.navigationTypes=t?.navigationTypes??null,e.redactPatterns=[...Ma,...t?.redactPatterns??[]],e.testRunId=t?.testRunId??null,e.metadata=t?.metadata??null;let r=e.outputPath;e.openReport=t?.openReport??true,e.htmlReportPath=t?.htmlReportPath??r.replace(/\.json$/,".html"),e.includeArtifacts=t?.includeArtifacts??true,e.trackApiCalls=t?.trackApiCalls??true,e.quiet=t?.quiet??false,e.includeActionSteps=t?.includeActionSteps??true,e.captureConsoleLogs=t?.captureConsoleLogs??true;let n=Dr(process.cwd()),s=n?Fr(n):null,a=s?tt(s):null,o=qr(a,t?.cloud);return e.cloud=o.apiKey?o:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var Ce="1.9.0";function zr(t,e,r){try{let s=fs$1.readFileSync(t,"utf-8").split(`
6
+ `);if(e<1||e>s.length)return null;let a=Math.max(1,e-r),o=Math.min(s.length,e+r),i=[];for(let l=a;l<=o;l++){let d=l===e?">":" ",c=String(l).padStart(String(o).length," ");i.push(`${d} ${c} | ${s[l-1]}`);}return i.join(`
7
+ `)}catch{return null}}function jr(t){return e=>{let r=e;for(let n of t)if(typeof n=="string"){let s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=n.flags.includes("g")?n.flags:n.flags+"g",a=new RegExp(n.source,s);r=r.replace(a,"[REDACTED]");}return r}}function La(t){return t.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:t.GITHUB_RUN_ID??null,commitSha:t.GITHUB_SHA??null,branch:t.GITHUB_REF_NAME??null,runUrl:t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY&&t.GITHUB_RUN_ID?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}/actions/runs/${t.GITHUB_RUN_ID}`:null}}function Da(t){return t.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:t.CI_PIPELINE_ID??null,commitSha:t.CI_COMMIT_SHA??null,branch:t.CI_COMMIT_BRANCH??t.CI_COMMIT_REF_NAME??null,runUrl:t.CI_PIPELINE_URL??null}}function Fa(t){if(!t.JENKINS_URL)return null;let e=t.GIT_BRANCH??null;return e?.startsWith("origin/")&&(e=e.slice(7)),{provider:"jenkins",buildId:t.BUILD_ID??null,commitSha:t.GIT_COMMIT??null,branch:e,runUrl:t.BUILD_URL??null}}function Ba(t){return t.CIRCLECI!=="true"?null:{provider:"circleci",buildId:t.CIRCLE_BUILD_NUM??null,commitSha:t.CIRCLE_SHA1??null,branch:t.CIRCLE_BRANCH??null,runUrl:t.CIRCLE_BUILD_URL??null}}function Oa(t){if(!t.BITBUCKET_PIPELINE_UUID)return null;let e=t.BITBUCKET_WORKSPACE&&t.BITBUCKET_REPO_SLUG&&t.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${t.BITBUCKET_WORKSPACE}/${t.BITBUCKET_REPO_SLUG}/pipelines/results/${t.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:t.BITBUCKET_BUILD_NUMBER??null,commitSha:t.BITBUCKET_COMMIT??null,branch:t.BITBUCKET_BRANCH??null,runUrl:e}}var qa=[La,Da,Fa,Ba,Oa];function V(t){let e=process.env;for(let r of qa){let n=r(e);if(n)return n}return null}var rt=`
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;
@@ -162,6 +162,7 @@ body{
162
162
  .trb-tag{background:rgba(59,130,246,0.12);color:#60a5fa}
163
163
  .trb-retry{background:rgba(245,158,11,0.12);color:#fbbf24}
164
164
  .trb-flaky{background:rgba(245,158,11,0.12);color:#fbbf24}
165
+ .trb-xfail{background:rgba(107,114,128,0.12);color:var(--fg-1)}
165
166
  .test-row-dur{font-size:13px;font-weight:700;color:var(--fg-1);flex-shrink:0;white-space:nowrap}
166
167
  .test-row-arrow{color:var(--fg-2);flex-shrink:0;transition:color .15s}
167
168
  .test-row:hover .test-row-arrow{color:var(--fg-1)}
@@ -289,6 +290,8 @@ body{
289
290
  .dm-tag{background:rgba(59,130,246,0.12);color:#60a5fa}
290
291
  .dm-retry{background:rgba(245,158,11,0.12);color:#fbbf24}
291
292
  .dm-flaky{background:rgba(245,158,11,0.12);color:#fbbf24}
293
+ .dm-xfail{background:rgba(34,197,94,0.1);color:#22c55e}
294
+ .dm-xfail-bad{background:rgba(239,68,68,0.12);color:#ef4444}
292
295
  .detail-sub-meta{display:flex;gap:14px;font-size:11px;color:var(--fg-1);flex-wrap:wrap;margin-top:6px}
293
296
  .meta-k{font-weight:600;color:var(--fg-2);text-transform:uppercase;letter-spacing:.04em;font-size:10px;margin-right:3px}
294
297
  .detail-id{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:10px;color:var(--fg-1);background:var(--bg-2);padding:1px 6px;border-radius:4px}
@@ -575,7 +578,7 @@ body{
575
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)"/>
576
579
  <defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
577
580
  <stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
578
- </linearGradient></defs></svg>`;var at=`
581
+ </linearGradient></defs></svg>`;var at={"failed|failed":"passed","failed|passed":"failed"},Vr={"failed|failed":"Failed as expected","failed|passed":"Expected to fail, but passed."};function Ha(t,e){return `${e??"passed"}|${t}`}function Ua(t,e){return at[Ha(t,e)]??t}function it(t,e){let r={passed:t.passed,failed:t.failed,flaky:t.flaky,skipped:t.skipped,timedout:t.timedout},n=0,s=0;for(let a of e){let o=Ua(a.status,a.expectedStatus);o!==a.status&&(r[a.status]--,r[o]++,o==="passed"?n++:s++);}return {total:t.total,...r,expectedFailures:n,unexpectedPasses:s}}var ot=`
579
582
  /* \u2500\u2500 Utilities \u2500\u2500 */
580
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;')}
581
584
  function stripAnsi(s){return s?s.replace(/\\u001b\\[[0-9;]*m/g,'').replace(/\\x1b\\[[0-9;]*m/g,''):''}
@@ -584,15 +587,33 @@ body{
584
587
  function fmtDate(iso){try{return new Date(iso).toLocaleString()}catch(e){return iso}}
585
588
  function shortTitle(t){var p=t.split(' > ');return p.length>1?p[p.length-1]:t}
586
589
 
590
+ /* \u2500\u2500 Playwright's verdict \u2500\u2500
591
+ The status on an index row or a timeline entry is the actual result.
592
+ Playwright counts a result as expected only when it equals the test's
593
+ expected status, so a test.fail() that failed is a pass and one that
594
+ passed is a failure. The tables are expected-status.ts's own,
595
+ interpolated as JSON data (not code), so the report and the terminal box
596
+ cannot disagree about a pair. Defined before the data transformation
597
+ below, which is their first caller. */
598
+ var PW_VERDICT=${JSON.stringify(at)};var PW_NOTE=${JSON.stringify(Vr)};
599
+ function pwKey(s,e){return (e||'passed')+'|'+s;}
600
+ function pwVerdict(s,e){return PW_VERDICT[pwKey(s,e)]||s;}
601
+ function pwNote(s,e){return PW_NOTE[pwKey(s,e)]||null;}
602
+
587
603
  /* \u2500\u2500 Data Transformation \u2500\u2500 */
588
604
  var testMap={};
589
605
  for(var i=0;i<data.timeline.length;i++){
590
606
  var entry=data.timeline[i];
591
607
  for(var j=0;j<entry.tests.length;j++){
592
608
  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. */
593
612
  if(!testMap[t.testId]){
613
+ /* status is the verdict every surface reads (colour, filters, needs
614
+ attention); rawStatus keeps the actual result for the detail notes. */
594
615
  testMap[t.testId]={
595
- testId:t.testId,title:t.title,status:t.status,duration:t.duration,
616
+ testId:t.testId,title:t.title,status:pwVerdict(t.status,t.expectedStatus),rawStatus:t.status,duration:t.duration,
596
617
  startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,
597
618
  tags:t.tags,failure:t.failure,filePath:t.filePath,suiteName:t.suiteName,
598
619
  testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,
@@ -660,13 +681,15 @@ body{
660
681
  }
661
682
  if(!final)continue;
662
683
  var ix2=final;
684
+ /* The row carries expectedStatus since #135; it was thrown away here,
685
+ so a test.fail() that failed as expected rendered as a failure. */
663
686
  var st={
664
- testId:ix2.id,title:ix2.title,status:ix2.status,duration:ix2.duration,
687
+ testId:ix2.id,title:ix2.title,status:pwVerdict(ix2.status,ix2.expectedStatus),rawStatus:ix2.status,duration:ix2.duration,
665
688
  filePath:ix2.filePath,tags:ix2.tags||[],isFlaky:ix2.status==='flaky',
666
689
  testType:ix2.testType||'e2e',retryCount:grp.attempts.length,suiteName:'',
667
690
  startedAt:'',completedAt:'',
668
691
  networkRequests:[],steps:[],apiCalls:[],actions:[],consoleLogs:[],
669
- artifacts:null,failure:null,retryStatus:null,expectedStatus:null,actualStatus:null,
692
+ artifacts:null,failure:null,retryStatus:null,expectedStatus:ix2.expectedStatus||'passed',actualStatus:null,
670
693
  hasNetworkData:ix2.hasNetworkData,hasConsoleData:ix2.hasConsoleData,
671
694
  hasActionSteps:ix2.hasActionSteps,hasArtifacts:ix2.hasArtifacts,
672
695
  errorMessage:ix2.errorMessage,networkCount:ix2.networkCount||0,
@@ -684,7 +707,7 @@ body{
684
707
  deviceLogErrors:ix2.deviceLogErrors||0,hasCrashLog:!!ix2.hasCrashLog,
685
708
  hasVideo:!!ix2.hasVideo,aiDefectCount:ix2.aiDefectCount||0,
686
709
  retryAttempts:grp.attempts.slice().sort(function(a,b){return a.retryIndex-b.retryIndex;}).map(function(a){
687
- return {testId:a.id,retryIndex:a.retryIndex,status:a.status,duration:a.duration,errorMessage:a.errorMessage};
710
+ return {testId:a.id,retryIndex:a.retryIndex,status:pwVerdict(a.status,a.expectedStatus),rawStatus:a.status,expectedStatus:a.expectedStatus||'passed',duration:a.duration,errorMessage:a.errorMessage};
688
711
  })
689
712
  };
690
713
  testMap[st.testId]=st;
@@ -695,12 +718,12 @@ body{
695
718
  for(var ai=0;ai<st.retryAttempts.length;ai++){
696
719
  var ra=st.retryAttempts[ai];
697
720
  testMap[ra.testId]={
698
- testId:ra.testId,title:st.title+' (attempt '+(ra.retryIndex+1)+')',status:ra.status,
721
+ testId:ra.testId,title:st.title+' (attempt '+(ra.retryIndex+1)+')',status:ra.status,rawStatus:ra.rawStatus,
699
722
  duration:ra.duration,filePath:st.filePath,tags:st.tags,isFlaky:false,
700
723
  testType:st.testType,retryCount:0,suiteName:'',startedAt:'',completedAt:'',
701
724
  networkRequests:[],steps:[],apiCalls:[],actions:[],consoleLogs:[],
702
725
  artifacts:null,failure:null,retryStatus:'attempt '+(ra.retryIndex+1)+' of '+(st.retryAttempts.length+1),
703
- expectedStatus:null,actualStatus:null,errorMessage:ra.errorMessage,
726
+ expectedStatus:ra.expectedStatus,actualStatus:null,errorMessage:ra.errorMessage,
704
727
  networkCount:0,consoleCount:0,actionCount:0
705
728
  };
706
729
  }
@@ -863,11 +886,13 @@ body{
863
886
  h+='<div class="status-indicator si-'+t.status+'"></div>';
864
887
  h+='<div class="test-row-info tri-inline">';
865
888
  h+='<div class="test-row-title" title="'+esc(t.title)+'">'+esc(shortTitle(t.title))+'</div>';
866
- var hasBadges=(t.testType&&t.testType!=='unknown')||t.isFlaky||(t.tags&&t.tags.length>0);
889
+ var hasBadges=(t.testType&&t.testType!=='unknown')||t.isFlaky||(t.tags&&t.tags.length>0)||t.expectedStatus==='failed';
867
890
  if(hasBadges){
868
891
  h+='<div class="test-row-badges">';
869
892
  if(t.testType&&t.testType!=='unknown')h+='<span class="trb trb-type">'+esc(t.testType)+'</span>';
870
893
  if(t.isFlaky)h+='<span class="trb trb-flaky">flaky</span>';
894
+ /* A green row whose test failed needs saying so, or it reads as a bug. */
895
+ if(t.expectedStatus==='failed')h+='<span class="trb trb-xfail" title="test.fail(): Playwright expects this test to fail">expected to fail</span>';
871
896
  if(t.retryCount>0)h+='<span class="trb trb-retry">'+t.retryCount+' retries</span>';
872
897
  if(t.tags){for(var ti=0;ti<t.tags.length;ti++){if(t.tags[ti])h+='<span class="trb trb-tag">'+esc(t.tags[ti])+'</span>';}}
873
898
  h+='</div>';
@@ -884,7 +909,8 @@ body{
884
909
  var ra=t.retryAttempts[ri];
885
910
  h+='<div class="test-row test-row-retry-item" data-testid="'+esc(ra.testId)+'">';
886
911
  h+='<div class="status-indicator si-'+ra.status+'"></div>';
887
- h+='<div class="test-row-info"><div class="test-row-title">Attempt '+(ra.retryIndex+1)+' &mdash; '+esc(ra.status)+(ra.errorMessage?': '+esc(ra.errorMessage):'')+'</div></div>';
912
+ var _raNote=ra.errorMessage?null:pwNote(ra.rawStatus,ra.expectedStatus);
913
+ h+='<div class="test-row-info"><div class="test-row-title">Attempt '+(ra.retryIndex+1)+' &mdash; '+esc(ra.status)+(ra.errorMessage?': '+esc(ra.errorMessage):(_raNote?': '+esc(_raNote):''))+'</div></div>';
888
914
  h+='<span class="test-row-dur">'+fmtDur(ra.duration)+'</span>';
889
915
  h+='<svg class="test-row-arrow" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18l6-6-6-6"/></svg>';
890
916
  h+='</div>';
@@ -1020,6 +1046,9 @@ body{
1020
1046
  function renderDrawer(testId,detail){
1021
1047
  var t=detail||testMap[testId];
1022
1048
  if(!t){drawerBodyEl.innerHTML='';return;}
1049
+ /* t.status is the verdict; _raw is what actually happened, which decides
1050
+ whether there is an error to show. */
1051
+ var _raw=t.rawStatus||t.status,_note=pwNote(_raw,t.expectedStatus);
1023
1052
  var h='<div class="test-detail">';
1024
1053
 
1025
1054
  /* \u2500\u2500 Top: Metadata \u2500\u2500 */
@@ -1031,7 +1060,8 @@ body{
1031
1060
  if(t.retryCount>0)h+='<span class="dm-badge dm-retry">'+t.retryCount+' retries</span>';
1032
1061
  if(t.retryStatus)h+='<span class="dm-badge dm-retry">'+esc(t.retryStatus)+'</span>';
1033
1062
  if(t.tags&&t.tags.length>0){for(var ti=0;ti<t.tags.length;ti++){if(t.tags[ti])h+='<span class="dm-badge dm-tag">'+esc(t.tags[ti])+'</span>';}}
1034
- if(t.expectedStatus&&t.actualStatus&&t.expectedStatus!==t.actualStatus)h+='<span class="dm-badge" style="background:rgba(239,68,68,0.12);color:#ef4444">expected: '+esc(t.expectedStatus)+' actual: '+esc(t.actualStatus)+'</span>';
1063
+ if(_note)h+='<span class="dm-badge '+(t.status==='passed'?'dm-xfail':'dm-xfail-bad')+'">'+esc(_note)+'</span>';
1064
+ else if(t.expectedStatus&&t.actualStatus&&t.expectedStatus!==t.actualStatus)h+='<span class="dm-badge" style="background:rgba(239,68,68,0.12);color:#ef4444">expected: '+esc(t.expectedStatus)+' actual: '+esc(t.actualStatus)+'</span>';
1035
1065
  h+='</div>';
1036
1066
  if(t.testId||t.filePath||t.suiteName){h+='<div class="detail-sub-meta">';if(t.testId)h+='<span><span class="meta-k">ID</span><span class="detail-id" title="'+esc(t.testId)+'">'+esc(t.testId.substring(0,12))+'</span></span>';if(t.filePath)h+='<span><span class="meta-k">File</span><span class="detail-file">'+esc(t.filePath)+'</span></span>';if(t.suiteName)h+='<span><span class="meta-k">Suite</span><span class="detail-suite">'+esc(t.suiteName)+'</span></span>';h+='</div>';}
1037
1067
  h+='</div><div class="detail-duration">'+fmtDur(t.duration)+'</div></div></div>';
@@ -1051,14 +1081,17 @@ body{
1051
1081
  if(hasVideo&&t.startedAt){baseTime=Date.parse(t.startedAt);}
1052
1082
  if(!baseTime&&hasVideo&&t.consoleLogs&&t.consoleLogs.length>0&&t.consoleLogs[0].timestamp){baseTime=Date.parse(t.consoleLogs[0].timestamp);}
1053
1083
 
1054
- var hasFailure=(t.status==='failed'||t.status==='flaky')&&t.failure;
1084
+ /* From the actual result: an expected failure keeps its error, as it does
1085
+ in Playwright's own report, under an 'Expected failure' rail entry. */
1086
+ var hasFailure=(_raw==='failed'||_raw==='flaky')&&t.failure;
1055
1087
  var hasDom=false;
1056
1088
  if(t.visual){for(var dv=0;dv<t.visual.length;dv++){if(t.visual[dv].domChangeCount)hasDom=true;}}
1057
1089
 
1058
1090
  /* What the rail is allowed to offer \u2014 built from what actually rendered,
1059
1091
  so a jump can never land on a section that is not there. */
1060
1092
  var present={};
1061
- if(hasFailure)present.failure={};
1093
+ if(hasFailure)present.failure={xfail:t.status==='passed'};
1094
+ else if(_note&&t.status==='failed')present.failure={};
1062
1095
  if(hasVisual)present.visual={n:t.visual.length};
1063
1096
  if(hasDom)present.dom={n:(function(){var n=0;for(var q=0;q<t.visual.length;q++)n+=t.visual[q].domChangeCount||0;return n;})()};
1064
1097
  if(hasArt)present.artifacts={};
@@ -1082,6 +1115,8 @@ body{
1082
1115
  h+='<div class="drawer-main">';
1083
1116
 
1084
1117
  if(hasFailure)h+='<div class="drawer-section" data-section="failure">'+renderFailure(t.failure,t.filePath,t.title,t.tags)+'</div>';
1118
+ /* A test.fail() that passed has no error of its own; the failure is the pass. */
1119
+ else if(_note&&t.status==='failed')h+='<div class="drawer-section" data-section="failure"><div class="failure-panel"><div class="failure-message">'+esc(_note)+'</div></div></div>';
1085
1120
  else if(t.status==='failed')h+='<div class="drawer-section" data-section="failure" style="padding:14px;background:var(--bg-2);border:1px solid var(--bd);border-radius:10px;font-size:12px;color:var(--fg-2);font-style:italic">No diagnostic information available</div>';
1086
1121
 
1087
1122
  if(anySection){
@@ -1211,7 +1246,7 @@ body{
1211
1246
  clearTimeout(_searchTimer);
1212
1247
  _searchTimer=setTimeout(function(){searchQuery=q;applyFilters();},150);
1213
1248
  }
1214
- `;var it=`
1249
+ `;var lt=`
1215
1250
  /* \u2500\u2500 Network Visualization Helpers \u2500\u2500 */
1216
1251
  var RES_COLORS={xhr:'#60a5fa',document:'#818cf8',script:'#fbbf24',stylesheet:'#a78bfa',image:'#34d399',font:'#f472b6',other:'#6b7280'};
1217
1252
  var RES_LABELS={xhr:'XHR',document:'Doc',script:'JS',stylesheet:'CSS',image:'Img',font:'Font',other:'Other'};
@@ -1946,7 +1981,7 @@ body{
1946
1981
  var countEl=ndt.querySelector('.ndt-count');
1947
1982
  if(countEl)countEl.textContent=visible+' / '+rows.length+' requests';
1948
1983
  }
1949
- `;var ot=`
1984
+ `;var dt=`
1950
1985
  var _filterState={status:{},type:{},specFile:{},visual:{},evidence:{}};
1951
1986
 
1952
1987
  /* Evidence filters: one predicate per chip, so API and mobile runs share the
@@ -2106,9 +2141,13 @@ function renderFilterBar(){
2106
2141
  function initFilters(){
2107
2142
  _filterState={status:{},type:{},specFile:{},visual:{},evidence:{}};
2108
2143
  _totalTests=tests.length;
2109
- _originalSummary={total:data.summary.total,passed:data.summary.passed,
2110
- failed:data.summary.failed,flaky:data.summary.flaky,
2111
- skipped:data.summary.skipped,timedout:data.summary.timedout||0};
2144
+ /* The presented counts (test.fail() read as Playwright reads it), so an
2145
+ unfiltered view agrees with the verdict band and with the chips, which
2146
+ count each test's presented status. */
2147
+ var _ps=data.presentedSummary||data.summary;
2148
+ _originalSummary={total:_ps.total,passed:_ps.passed,
2149
+ failed:_ps.failed,flaky:_ps.flaky,
2150
+ skipped:_ps.skipped,timedout:_ps.timedout||0};
2112
2151
  }
2113
2152
 
2114
2153
  function getFilteredTests(){
@@ -2201,7 +2240,7 @@ function _updateCard(cls,val){
2201
2240
  var el=document.querySelector('.'+cls+' .s-count');
2202
2241
  if(el)el.textContent=''+val;
2203
2242
  }
2204
- `;var lt=`
2243
+ `;var ct=`
2205
2244
  /* \u2500\u2500 Event Delegation \u2500\u2500 */
2206
2245
  document.addEventListener('click',function(e){
2207
2246
  var target=e.target;
@@ -2472,7 +2511,7 @@ function _updateCard(cls,val){
2472
2511
  var d=document.getElementById('filter-drawer');if(d)d.classList.remove('open');
2473
2512
  var b=document.getElementById('filter-drawer-backdrop');if(b)b.classList.remove('open');
2474
2513
  }
2475
- `;var dt=`
2514
+ `;var ut=`
2476
2515
  /* \u2500\u2500 Category badge helpers \u2500\u2500 */
2477
2516
  function actionBadgeClass(cat){
2478
2517
  if(cat==='assertion')return 'action-badge-assertion';
@@ -2518,7 +2557,7 @@ function _updateCard(cls,val){
2518
2557
  h+='</div>';
2519
2558
  return h;
2520
2559
  }
2521
- `;var ct=`
2560
+ `;var pt=`
2522
2561
  /* \u2500\u2500 Console Log Level Colors & Labels \u2500\u2500 */
2523
2562
  var LOG_COLORS={log:'#9ca3af',warn:'#fbbf24',error:'#f87171',info:'#60a5fa',debug:'#a78bfa',stdout:'#9ca3af',stderr:'#f87171'};
2524
2563
  var LOG_LABELS={log:'LOG',warn:'WARN',error:'ERR',info:'INFO',debug:'DBG',stdout:'OUT',stderr:'ERR'};
@@ -2705,7 +2744,7 @@ function _updateCard(cls,val){
2705
2744
  }
2706
2745
  return h;
2707
2746
  }
2708
- `;var ut=`
2747
+ `;var ft=`
2709
2748
  /* \u2500\u2500 Artifact Utilities \u2500\u2500 */
2710
2749
  function formatBytes(bytes){
2711
2750
  if(bytes===0)return '0 B';
@@ -2714,7 +2753,7 @@ function _updateCard(cls,val){
2714
2753
  if(i>=sizes.length)i=sizes.length-1;
2715
2754
  return parseFloat((bytes/Math.pow(k,i)).toFixed(1))+' '+sizes[i];
2716
2755
  }
2717
- `;var pt=`
2756
+ `;var gt=`
2718
2757
  /* \u2500\u2500 Visual Regression \u2500\u2500 */
2719
2758
 
2720
2759
  function visStatusLabel(status){
@@ -2871,7 +2910,7 @@ function _updateCard(cls,val){
2871
2910
  if(otop)otop.style.opacity=String(el.value/100);
2872
2911
  }
2873
2912
  });
2874
- `;var ft=`
2913
+ `;var ht=`
2875
2914
  /* \u2500\u2500 DOM comparison \u2500\u2500 */
2876
2915
 
2877
2916
  /* Rank-cycled so a row and its box always share a colour. */
@@ -3023,7 +3062,7 @@ function _updateCard(cls,val){
3023
3062
  var card=row.closest('.vis-card');
3024
3063
  if(card&&!row.classList.contains('pinned'))domSetActive(card,row.getAttribute('data-dom-row'),false);
3025
3064
  });
3026
- `;var gt=`
3065
+ `;var mt=`
3027
3066
  /* \u2500\u2500 Verdict band \u2500\u2500 */
3028
3067
 
3029
3068
  /* Both report modes hand us a summary; streaming's carries fewer fields. */
@@ -3067,19 +3106,24 @@ function _updateCard(cls,val){
3067
3106
  }
3068
3107
 
3069
3108
  function renderSummary(){
3070
- var s=data.summary||{};
3071
- var failed=vNum(s.failed),flaky=vNum(s.flaky);
3109
+ /* Two objects on purpose. data.summary counts by actual status and also
3110
+ carries the run's volume totals (the tiles below). presentedSummary has
3111
+ only the status counts, read the way Playwright reads test.fail(), so it
3112
+ drives the verdict and nothing else \u2014 reading the tiles from it would
3113
+ blank them. */
3114
+ var s=data.summary||{};var c=data.presentedSummary||s;
3115
+ var failed=vNum(c.failed),flaky=vNum(c.flaky);
3072
3116
  var cls=failed>0?'v-failed':(flaky>0?'':'v-passed');
3073
3117
 
3074
3118
  var h='<div class="verdict"><div class="verdict-main '+cls+'">';
3075
3119
 
3076
- h+='<div class="verdict-head"><div class="verdict-title">'+esc(renderVerdictHeadline(s))+'</div>';
3120
+ h+='<div class="verdict-head"><div class="verdict-title">'+esc(renderVerdictHeadline(c))+'</div>';
3077
3121
  var where=failed>0?failureLocation():null;
3078
3122
  if(where)h+='<div class="verdict-where">all in <code>'+esc(where.split('/').pop())+'</code></div>';
3079
3123
  h+='<div class="verdict-dur"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>'+fmtDur(data.totalDuration||0)+'</div>';
3080
3124
  h+='</div>';
3081
3125
 
3082
- h+=renderVerdictBar(s);
3126
+ h+=renderVerdictBar(c);
3083
3127
 
3084
3128
  /* Non-zero statuses get a real count; the rest collapse to one grey line
3085
3129
  rather than each taking a sixth of the width. */
@@ -3090,7 +3134,7 @@ function _updateCard(cls,val){
3090
3134
  ];
3091
3135
  var counts='',zeros=[];
3092
3136
  for(var m=0;m<kinds.length;m++){
3093
- var kk=kinds[m],n=vNum(s[kk.k]);
3137
+ var kk=kinds[m],n=vNum(c[kk.k]);
3094
3138
  if(n>0){
3095
3139
  counts+='<div class="vc"><span class="vc-dot" style="background:'+kk.c+'"></span><span class="vc-n">'+n+'</span><span class="vc-l">'+kk.l+'</span></div>';
3096
3140
  }else{
@@ -3099,6 +3143,16 @@ function _updateCard(cls,val){
3099
3143
  }
3100
3144
  h+='<div class="verdict-counts">'+counts;
3101
3145
  if(zeros.length>0)h+='<div class="verdict-zeros">'+esc(zeros.join(' \\u00b7 '))+'</div>';
3146
+ /* Say why these counts differ from report.json and summary.json. Its own
3147
+ line: a second margin-left:auto item would split the free space with
3148
+ the zeros and strand them mid-row. */
3149
+ var xf=vNum(c.expectedFailures),xp=vNum(c.unexpectedPasses);
3150
+ if(xf>0||xp>0){
3151
+ var notes=[];
3152
+ if(xf>0)notes.push(xf+' failed as expected');
3153
+ if(xp>0)notes.push(xp+' expected to fail, but passed');
3154
+ h+='<div class="verdict-xnote">'+esc(notes.join(' \\u00b7 ')+' (test.fail)')+'</div>';
3155
+ }
3102
3156
  h+='</div>';
3103
3157
 
3104
3158
  h+='</div>';
@@ -3139,7 +3193,8 @@ function _updateCard(cls,val){
3139
3193
  var px=t.errorMessage.match(/([\\d,]+) pixels \\(ratio ([\\d.]+)/);
3140
3194
  if(px)return '<em>'+esc(px[1])+' px differ</em>';
3141
3195
  }
3142
- if(!t.errorMessage)return '';
3196
+ /* A test.fail() that passed has no error; its note is the cause. */
3197
+ if(!t.errorMessage){var _n=pwNote(t.rawStatus||t.status,t.expectedStatus);return _n&&t.status!=='passed'?'<em>'+esc(_n)+'</em>':'';}
3143
3198
  var first=String(t.errorMessage).split('\\n')[0].trim();
3144
3199
  if(first.length>150)first=first.slice(0,150)+'\\u2026';
3145
3200
  return '<em>'+esc(first)+'</em>';
@@ -3261,9 +3316,10 @@ function _updateCard(cls,val){
3261
3316
  var sec=RAIL_SECTIONS[i];
3262
3317
  var info=present[sec.id];
3263
3318
  if(!info)continue;
3264
- h+='<button class="rail-item'+(sec.fail?' rail-fail':'')+(first?' active':'')+'" data-rail="'+sec.id+'">';
3319
+ /* An expected failure's error is shown, but it is not why anything failed. */
3320
+ h+='<button class="rail-item'+(sec.fail&&!info.xfail?' rail-fail':'')+(first?' active':'')+'" data-rail="'+sec.id+'">';
3265
3321
  h+=railIcon(sec.id);
3266
- h+='<span class="rail-name">'+esc(sec.label)+'</span>';
3322
+ h+='<span class="rail-name">'+esc(info.xfail?'Expected failure':sec.label)+'</span>';
3267
3323
  if(info.n)h+='<span class="rail-n'+(sec.dom?' rail-n-dom':'')+'">'+info.n+'</span>';
3268
3324
  h+='</button>';
3269
3325
  first=false;
@@ -3327,7 +3383,7 @@ function _updateCard(cls,val){
3327
3383
  if(!card)return;
3328
3384
  openTest(card.getAttribute('data-testid'));
3329
3385
  });
3330
- `,ht=`
3386
+ `,vt=`
3331
3387
  var overviewViewEl=document.getElementById('view-overview');
3332
3388
  var detailViewEl=document.getElementById('view-detail');
3333
3389
  var detailNavEl=document.getElementById('detail-nav');
@@ -3468,7 +3524,7 @@ function _updateCard(cls,val){
3468
3524
 
3469
3525
  window.addEventListener('hashchange',routeFromHash);
3470
3526
  window.addEventListener('popstate',routeFromHash);
3471
- `;var mt=`
3527
+ `;var yt=`
3472
3528
  var API_METHOD_COLOR={GET:'#60a5fa',POST:'#34d399',PUT:'#fbbf24',PATCH:'#a78bfa',DELETE:'#f87171',HEAD:'#6b7280',OPTIONS:'#6b7280'};
3473
3529
  var API_STATUS_ORDER=['2xx','3xx','4xx','5xx','error'];
3474
3530
  var API_STATUS_COLOR={'2xx':'#22c55e','3xx':'#60a5fa','4xx':'#fb923c','5xx':'#ef4444','error':'#ef4444'};
@@ -3694,7 +3750,7 @@ function _updateCard(cls,val){
3694
3750
  }
3695
3751
  return '';
3696
3752
  }
3697
- `;var vt=`
3753
+ `;var bt=`
3698
3754
  .vis-header{font-size:11px;font-weight:700;color:var(--fg-1);text-transform:uppercase;letter-spacing:.06em;margin-bottom:12px;display:flex;align-items:center;gap:6px}
3699
3755
  .vis-header svg{opacity:.6}
3700
3756
  .vis-count{font-weight:400;color:var(--fg-2);font-size:10px}
@@ -3727,7 +3783,7 @@ function _updateCard(cls,val){
3727
3783
 
3728
3784
  /* A checkerboard behind the diff so fully transparent regions stay legible. */
3729
3785
  .vis-diff-wrap{background-image:linear-gradient(45deg,var(--bd-xs) 25%,transparent 25%),linear-gradient(-45deg,var(--bd-xs) 25%,transparent 25%),linear-gradient(45deg,transparent 75%,var(--bd-xs) 75%),linear-gradient(-45deg,transparent 75%,var(--bd-xs) 75%);background-size:16px 16px;background-position:0 0,0 8px,8px -8px,-8px 0;border-radius:8px}
3730
- `,yt=`
3786
+ `,xt=`
3731
3787
  .dom-figure{position:relative;line-height:0;border:1px solid var(--bd);border-radius:8px;overflow:hidden;margin-bottom:12px}
3732
3788
  .dom-img{display:block;width:100%;height:auto}
3733
3789
  .dom-ov{position:absolute;top:0;left:0;right:0;bottom:0;pointer-events:none}
@@ -3759,7 +3815,7 @@ function _updateCard(cls,val){
3759
3815
  .dom-from{color:#ef4444;word-break:break-all}
3760
3816
  .dom-arrow{color:var(--fg-2)}
3761
3817
  .dom-to{color:#2dd4a8;word-break:break-all}
3762
- `;var bt=`
3818
+ `;var wt=`
3763
3819
  /* \u2500\u2500 Wider shell \u2500\u2500
3764
3820
  960px was sized for a list. The row now carries evidence and timing, and
3765
3821
  the detail panel shows two screenshots side by side; both were cramped. */
@@ -3790,6 +3846,8 @@ function _updateCard(cls,val){
3790
3846
  .vc-l{font-size:12px;color:var(--fg-1)}
3791
3847
  /* Statuses with nothing in them stop taking a sixth of the width. */
3792
3848
  .verdict-zeros{margin-left:auto;font-size:11px;color:var(--fg-2)}
3849
+ /* Why the counts above differ from report.json: test.fail() read as Playwright reads it. */
3850
+ .verdict-xnote{flex-basis:100%;font-size:11px;color:var(--fg-2)}
3793
3851
 
3794
3852
  .verdict-side{width:268px;flex-shrink:0;background:var(--bg-1);border:1px solid var(--bd);border-radius:12px;padding:18px 20px;display:flex;flex-direction:column;gap:12px}
3795
3853
  .verdict-side-label{font-size:10px;font-weight:600;color:var(--fg-2);letter-spacing:.06em;text-transform:uppercase}
@@ -3884,7 +3942,7 @@ function _updateCard(cls,val){
3884
3942
  .verdict{flex-direction:column}
3885
3943
  .verdict-side{width:100%}
3886
3944
  }
3887
- `,xt=`
3945
+ `,kt=`
3888
3946
  /* The overlay is gone. Anything still carrying .drawer must not float. */
3889
3947
  .drawer,.drawer-backdrop{display:none}
3890
3948
 
@@ -3905,7 +3963,7 @@ function _updateCard(cls,val){
3905
3963
  /* The page scrolls now, so the old panel body must not scroll inside it. */
3906
3964
  #view-detail .drawer-body{flex:none;overflow:visible;padding:0}
3907
3965
  .detail-page .detail-rail,.detail-page .drawer-rail{top:16px}
3908
- `;var wt=`
3966
+ `;var Ct=`
3909
3967
  /* \u2500\u2500 Run-level type band \u2500\u2500 */
3910
3968
  .tband{display:grid;gap:16px;margin-bottom:20px}
3911
3969
  .tband-3{grid-template-columns:1.1fr 1.1fr .9fr}
@@ -4003,21 +4061,21 @@ function _updateCard(cls,val){
4003
4061
  @media (max-width:1100px){
4004
4062
  .tband-3,.tband-2{grid-template-columns:1fr}
4005
4063
  }
4006
- `;var Ba=`
4064
+ `;var za=`
4007
4065
  (function(){
4008
4066
  var data=JSON.parse(document.getElementById('report-data').textContent);
4009
- ${at}
4010
- ${dt}
4011
- ${ct}
4012
- ${it}
4013
4067
  ${ot}
4014
4068
  ${ut}
4015
- ${ft}
4016
4069
  ${pt}
4017
4070
  ${lt}
4071
+ ${dt}
4072
+ ${ft}
4073
+ ${ht}
4018
4074
  ${gt}
4075
+ ${ct}
4019
4076
  ${mt}
4020
- ${ht}
4077
+ ${yt}
4078
+ ${vt}
4021
4079
  applyTheme();
4022
4080
  renderRunMeta();
4023
4081
  renderSummary();
@@ -4028,7 +4086,7 @@ function _updateCard(cls,val){
4028
4086
  renderNeedsAttention();
4029
4087
  routeFromHash();
4030
4088
  var _lo=document.getElementById('loading-overlay');if(_lo)_lo.remove();
4031
- })();`;function zr(t,e,r){let n=t.replace(/<\//g,"<\\/"),s=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
4089
+ })();`;function $r(t,e,r){let n=t.replace(/<\//g,"<\\/"),s=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
4032
4090
  <!DOCTYPE html>
4033
4091
  <html lang="en" data-theme="">
4034
4092
  <head>
@@ -4038,7 +4096,7 @@ function _updateCard(cls,val){
4038
4096
  <title>TestRelic AI Analytics Report</title>
4039
4097
  ${""}
4040
4098
  <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(nt).toString("base64")}">
4041
- <style>${rt}${vt}${yt}${bt}${xt}${wt}</style>
4099
+ <style>${rt}${bt}${xt}${wt}${kt}${Ct}</style>
4042
4100
  <script>(function(){var p=localStorage.getItem('tr-theme')||'system';var t=p==='system'?(window.matchMedia('(prefers-color-scheme:light)').matches?'light':'dark'):p;document.documentElement.setAttribute('data-theme',t);})()</script>
4043
4101
  </head>
4044
4102
  <body>
@@ -4082,23 +4140,24 @@ ${""}
4082
4140
  </aside>
4083
4141
  <script id="report-data" type="application/json">${n}</script>
4084
4142
  ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:""}
4085
- <script>${Ba}</script>
4143
+ <script>${za}</script>
4086
4144
  </body>
4087
- </html>`}function kt(t,e,r,n){let s=t.replace(/<\//g,"<\\/"),a=e.replace(/<\//g,"<\\/"),o=n?n.replace(/<\//g,"<\\/"):null,i={};try{i=JSON.parse(t);}catch{}let d=`{
4145
+ </html>`}function St(t,e,r,n,s){let a=t.replace(/<\//g,"<\\/"),o=s?s.replace(/<\//g,"<\\/"):"null",i=e.replace(/<\//g,"<\\/"),l=n?n.replace(/<\//g,"<\\/"):null,d={};try{d=JSON.parse(t);}catch{}let c=`{
4088
4146
  "schemaVersion":"2.0",
4089
4147
  "reportMode":"streaming",
4090
4148
  "serverPort":${r??"null"},
4091
- "summary":${s},
4092
- "index":${a},
4149
+ "summary":${a},
4150
+ "presentedSummary":${o},
4151
+ "index":${i},
4093
4152
  "timeline":[],
4094
- "testRunId":${JSON.stringify(String(i.testRunId??""))},
4095
- "startedAt":${JSON.stringify(String(i.startedAt??""))},
4096
- "completedAt":${JSON.stringify(String(i.completedAt??""))},
4097
- "totalDuration":${Number(i.totalDuration)||0},
4098
- "ci":${i.ci?JSON.stringify(i.ci).replace(/<\//g,"<\\/"):"null"},
4099
- "metadata":${i.metadata?JSON.stringify(i.metadata).replace(/<\//g,"<\\/"):"null"},
4100
- "shardRunIds":${i.shardRunIds?JSON.stringify(i.shardRunIds).replace(/<\//g,"<\\/"):"null"}
4101
- }`,l=`
4153
+ "testRunId":${JSON.stringify(String(d.testRunId??""))},
4154
+ "startedAt":${JSON.stringify(String(d.startedAt??""))},
4155
+ "completedAt":${JSON.stringify(String(d.completedAt??""))},
4156
+ "totalDuration":${Number(d.totalDuration)||0},
4157
+ "ci":${d.ci?JSON.stringify(d.ci).replace(/<\//g,"<\\/"):"null"},
4158
+ "metadata":${d.metadata?JSON.stringify(d.metadata).replace(/<\//g,"<\\/"):"null"},
4159
+ "shardRunIds":${d.shardRunIds?JSON.stringify(d.shardRunIds).replace(/<\//g,"<\\/"):"null"}
4160
+ }`,u=`
4102
4161
  (function(){
4103
4162
  var data=JSON.parse(document.getElementById('report-data').textContent);
4104
4163
  var _serverPort=data.serverPort||null;
@@ -4168,18 +4227,18 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:
4168
4227
  window.__trServerPort=_serverPort;
4169
4228
  window.__trIsStreaming=true;
4170
4229
 
4171
- ${at}
4172
- ${dt}
4173
- ${ct}
4174
- ${it}
4175
4230
  ${ot}
4176
4231
  ${ut}
4177
- ${ft}
4178
4232
  ${pt}
4179
4233
  ${lt}
4234
+ ${dt}
4235
+ ${ft}
4236
+ ${ht}
4180
4237
  ${gt}
4238
+ ${ct}
4181
4239
  ${mt}
4182
- ${ht}
4240
+ ${yt}
4241
+ ${vt}
4183
4242
  applyTheme();
4184
4243
  renderRunMeta();
4185
4244
  renderSummary();
@@ -4204,7 +4263,7 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:
4204
4263
  ${r?`<meta name="report-server-port" content="${r}">`:""}
4205
4264
  ${r?`<meta name="artifact-server-port" content="${r}">`:""}
4206
4265
  <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(nt).toString("base64")}">
4207
- <style>${rt}${vt}${yt}${bt}${xt}${wt}</style>
4266
+ <style>${rt}${bt}${xt}${wt}${kt}${Ct}</style>
4208
4267
  <script>(function(){var p=localStorage.getItem('tr-theme')||'system';var t=p==='system'?(window.matchMedia('(prefers-color-scheme:light)').matches?'light':'dark'):p;document.documentElement.setAttribute('data-theme',t);})()</script>
4209
4268
  </head>
4210
4269
  <body>
@@ -4246,62 +4305,62 @@ ${r?`<meta name="artifact-server-port" content="${r}">`:""}
4246
4305
  </div>
4247
4306
  <div class="filter-drawer-body" id="filter-drawer-body"></div>
4248
4307
  </aside>
4249
- <script id="report-data" type="application/json">${d}</script>
4250
- ${o?`<script id="artifact-manifest-data" type="application/json">${o}</script>`:""}
4251
- <script>${l}</script>
4308
+ <script id="report-data" type="application/json">${c}</script>
4309
+ ${l?`<script id="artifact-manifest-data" type="application/json">${l}</script>`:""}
4310
+ <script>${u}</script>
4252
4311
  </body>
4253
- </html>`}function Ct(t){try{let e=process.platform,r,n;e==="darwin"?(r="open",n=[t]):e==="win32"?(r="cmd",n=["/c","start","",t]):(r="xdg-open",n=[t]),child_process.execFile(r,n,s=>{s&&process.stderr.write(`[testrelic] Failed to open browser: ${s.message}
4254
- `);});}catch{}}var jr=path.join(os$1.tmpdir(),"testrelic-data"),H=class{constructor(e){this.count=0;this.closed=false;fs$1.mkdirSync(jr,{recursive:true}),this.filePath=path.join(jr,`${e}-${crypto.randomUUID().substring(0,8)}.jsonl`),this.fd=fs$1.openSync(this.filePath,"w");}append(e){if(this.closed)return;let r=JSON.stringify(e)+`
4255
- `;fs$1.writeSync(this.fd,r),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{fs$1.closeSync(this.fd);}catch{}}}cleanup(){try{fs$1.unlinkSync(this.filePath);}catch{}}};async function $r(t,e,r,n){let s=(e-1)*r,a=[],o=0,i=readline.createInterface({input:fs$1.createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of i)if(c.length!==0){if(o>=s&&a.length<r)try{a.push(JSON.parse(c));}catch{}if(o++,a.length>=r&&n!==void 0)break}let d=n??o,l=Math.max(1,Math.ceil(d/r));return {items:a,total:d,page:e,pageSize:r,totalPages:l}}var Jr=/^[a-f0-9]{12}$/,Rt=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Yr=500;function R(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function Xr(t){t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type");}function Te(t){try{return fs$1.existsSync(t)?JSON.parse(fs$1.readFileSync(t,"utf-8")):null}catch{return null}}function Re(t){let e=0;try{let r=fs$1.readdirSync(t,{withFileTypes:!0});for(let n of r){let s=path.join(t,n.name);n.isFile()?e+=fs$1.statSync(s).size:n.isDirectory()&&(e+=Re(s));}}catch{}return e}function Zr(t,e,r,n){let s=Te(path.join(r,"index.json"));R(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function Qr(t,e,r){let n=Te(path.join(r,"summary.json"));if(!n){R(e,404,{error:"Summary not found"});return}R(e,200,n);}function en(t,e,r){let n=Te(path.join(r,"index.json"));if(!n){R(e,404,{error:"Test index not found"});return}let a=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,o=Math.max(1,parseInt(a.get("page")??"1",10)||1),i=Math.min(Yr,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),d=a.get("status")?.split(",").filter(Boolean)??null,l=a.get("file")??null,c=a.get("search")?.toLowerCase()??null,u=a.get("tag")?.split(",").filter(Boolean)??null,h=a.get("sort")??"file",f=a.get("order")==="desc"?-1:1,p=n;d&&d.length>0&&(p=p.filter(b=>d.includes(b.status))),l&&(p=p.filter(b=>b.filePath===l||b.filePath.startsWith(l+"/"))),c&&(p=p.filter(b=>b.title.toLowerCase().includes(c)||b.filePath.toLowerCase().includes(c))),u&&u.length>0&&(p=p.filter(b=>u.some(k=>b.tags.includes(k)))),p=[...p].sort((b,k)=>{let T=0;switch(h){case "duration":T=b.duration-k.duration;break;case "status":T=b.status.localeCompare(k.status);break;case "title":T=b.title.localeCompare(k.title);break;default:T=b.filePath.localeCompare(k.filePath);break}return T*f});let m=p.length,g=Math.max(1,Math.ceil(m/i)),v=(o-1)*i,y=p.slice(v,v+i);R(e,200,{tests:y,pagination:{page:o,pageSize:i,totalItems:m,totalPages:g},filters:{status:d,file:l,search:c,tag:u}});}function tn(t,e,r,n){if(!Jr.test(n)){R(e,400,{error:"Invalid test ID format"});return}let s=path.join(r,"tests",n,"meta.json"),a=path.join(r,"tests",`${n}.json`),o=fs$1.existsSync(s)?s:fs$1.existsSync(a)?a:null;if(!o){R(e,404,{error:`Test not found: ${n}`});return}try{let i=fs$1.readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){R(e,500,{error:i instanceof Error?i.message:String(i)});}}async function rn(t,e,r,n,s){if(!Jr.test(n)){R(e,400,{error:"Invalid test ID format"});return}let o=path.join(r,"tests",n,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!fs$1.existsSync(o)){R(e,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let d=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,l=Math.max(1,parseInt(d.get("page")??"1",10)||1),c=Math.min(Yr,Math.max(1,parseInt(d.get("pageSize")??"50",10)||50)),u,h=path.join(r,"tests",n,"meta.json");if(fs$1.existsSync(h))try{let p=JSON.parse(fs$1.readFileSync(h,"utf-8"));switch(s){case "network":u=p.networkRequestsCount;break;case "console":u=p.consoleLogsCount;break;case "api-calls":u=p.apiCallsCount;break}}catch{}let f=await $r(o,l,c,u);R(e,200,f);}catch(i){R(e,500,{error:i instanceof Error?i.message:String(i)});}}function nn(t,e,r){let n=Te(path.join(r,"index.json"));if(!n){R(e,404,{error:"Test index not found"});return}let s=new Map;for(let o of n){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 a=Array.from(s.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));R(e,200,{files:a});}function sn(t,e,r){if(!fs$1.existsSync(r)){R(e,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Rt.test(o.name))continue;let i=path.join(r,o.name),d=Re(i),l=fs$1.readdirSync(i,{withFileTypes:!0}).filter(c=>c.isDirectory());n.push({folderName:o.name,totalSizeBytes:d,testCount:l.length}),s+=d;}n.sort((o,i)=>i.folderName.localeCompare(o.folderName)),R(e,200,{runs:n,totalSizeBytes:s});}catch(n){R(e,500,{error:n instanceof Error?n.message:String(n)});}}function an(t,e,r){try{let n=0,s=0;if(fs$1.existsSync(r)){let a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Rt.test(o.name))continue;let i=path.join(r,o.name),d=Re(i);fs$1.rmSync(i,{recursive:!0,force:!0}),s+=d,n++;}}R(e,200,{deletedCount:n,freedBytes:s});}catch(n){R(e,500,{error:n instanceof Error?n.message:String(n)});}}function on(t,e,r,n){if(!Rt.test(n)){R(e,400,{error:"Invalid folder name"});return}let s=path.join(r,n);try{if(!fs$1.statSync(s).isDirectory()){R(e,404,{error:"Not found"});return}}catch{R(e,404,{error:"Not found"});return}try{let a=Re(s);fs$1.rmSync(s,{recursive:!0,force:!0}),R(e,200,{deleted:n,freedBytes:a});}catch(a){R(e,500,{error:a instanceof Error?a.message:String(a)});}}function ln(t,e,r){R(e,200,{status:"shutting_down"}),r.close();}function At(t,e,r){if(!fs$1.existsSync(r)){R(e,404,{error:"File not found"});return}try{let n=fs$1.statSync(r).size,s=path.extname(r).toLowerCase(),a=Ya[s]??"application/octet-stream",o=Ja(t.headers.range,n);if(o==="unsatisfiable"){e.writeHead(416,{"Content-Range":`bytes */${n}`,"Accept-Ranges":"bytes"}),e.end();return}if(o){e.writeHead(206,{"Content-Type":a,"Content-Length":o.end-o.start+1,"Content-Range":`bytes ${o.start}-${o.end}/${n}`,"Accept-Ranges":"bytes"}),Gr(fs$1.createReadStream(r,{start:o.start,end:o.end}),e);return}e.writeHead(200,{"Content-Type":a,"Content-Length":n,"Accept-Ranges":"bytes"}),Gr(fs$1.createReadStream(r),e);}catch(n){R(e,500,{error:n instanceof Error?n.message:String(n)});}}function Gr(t,e){t.on("error",()=>{t.destroy(),e.destroy();}),e.on("close",()=>{t.destroy();}),t.pipe(e);}function Ja(t,e){if(!t)return null;let r=/^bytes=(\d*)-(\d*)$/.exec(t.trim());if(!r)return null;let[,n,s]=r;if(n===""&&s==="")return null;let a,o;if(n===""){let i=Number(s);if(i<=0)return "unsatisfiable";a=Math.max(0,e-i),o=e-1;}else a=Number(n),o=s===""?e-1:Math.min(Number(s),e-1);return !Number.isFinite(a)||!Number.isFinite(o)?null:e===0||a>=e||a>o?"unsatisfiable":{start:a,end:o}}var Ya={".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 ei=9323,ti=10,ri=1800*1e3;function me(t,e){return new Promise((r,n)=>{let s=e?.port??ei,a=Date.now(),o,i=0,d=fs$1.existsSync(path.join(t,"artifacts"))?path.join(t,"artifacts"):fs$1.existsSync(path.join(t,"..","artifacts"))?path.join(t,"..","artifacts"):path.join(t,"artifacts");function l(){clearTimeout(o),o=setTimeout(()=>{u.close();},ri);}let c=e?.htmlPath??null;if(!c){let f=path.dirname(t);try{let p=fs$1.readdirSync(f).find(m=>m.endsWith(".html"));p&&(c=path.join(f,p));}catch{}}let u=http.createServer((f,p)=>{if(l(),Xr(p),f.method==="OPTIONS"){p.writeHead(204),p.end();return}let m;try{m=new URL(f.url??"/",`http://${f.headers.host??"localhost"}`).pathname;}catch{R(p,400,{error:"Invalid URL"});return}if(f.method==="GET"&&(m==="/"||m==="/index.html")){if(c&&fs$1.existsSync(c)){At(f,p,c);return}R(p,404,{error:"HTML report not found"});return}if(f.method==="GET"&&m==="/api/health"){Zr(f,p,t,a);return}if(f.method==="GET"&&m==="/api/summary"){Qr(f,p,t);return}if(f.method==="GET"&&m==="/api/tests"){en(f,p,t);return}if(f.method==="GET"&&m==="/api/files"){nn(f,p,t);return}let g=m.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(f.method==="GET"&&g){rn(f,p,t,g[1],g[2]);return}let v=m.match(/^\/api\/tests\/([a-f0-9]+)$/);if(f.method==="GET"&&v){tn(f,p,t,v[1]);return}if(f.method==="GET"&&m==="/api/artifacts"){sn(f,p,d);return}if(f.method==="DELETE"&&m==="/api/artifacts"){an(f,p,d);return}let y=m.match(/^\/api\/artifacts\/(.+)$/);if(f.method==="DELETE"&&y){on(f,p,d,decodeURIComponent(y[1]));return}if(f.method==="GET"&&m.startsWith("/artifacts/")){let b=decodeURIComponent(m.slice(11));if(b.includes("..")||b.includes("\0")){R(p,400,{error:"Invalid path"});return}At(f,p,path.join(d,b));return}if(f.method==="POST"&&m==="/api/shutdown"){ln(f,p,u);return}R(p,404,{error:"Not found"});});function h(f){let p=m=>{m.code==="EADDRINUSE"&&i<ti?(i++,h(f+1)):n(m);};u.once("error",p),u.listen(f,"127.0.0.1",()=>{u.removeListener("error",p);let m=u.address();if(!m||typeof m=="string"){n(new Error("Failed to get server address"));return}l(),r({port:m.port,dispose:()=>new Promise(g=>{clearTimeout(o),u.close(()=>g());})});});}h(s);})}async function dn(t){let e=await me(t);return {port:e.port,dispose:e.dispose}}function ai(t,e,r){let n=JSON.stringify(t),s=r?JSON.stringify(r):null;return zr(n,e,s)}async function It(t,e,r){try{let n=null,s=null,a=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,i=e.htmlReportPath,d=path.dirname(i);fs$1.mkdirSync(d,{recursive:!0});let l="",c="[]",u=null;if(a){l=JSON.stringify({...t.summary,testRunId:t.testRunId,startedAt:t.startedAt,completedAt:t.completedAt,totalDuration:t.totalDuration,ci:t.ci,metadata:t.metadata,shardRunIds:t.shardRunIds});let f=path.dirname(e.outputPath),p=path.join(f,".testrelic-report");try{let m=path.join(p,"index-compact.json"),g=path.join(p,"index.json");fs$1.existsSync(m)?c=fs$1.readFileSync(m,"utf-8"):fs$1.existsSync(g)&&(c=fs$1.readFileSync(g,"utf-8"));}catch{}u=r?JSON.stringify(r):null,o=kt(l,c,null,u);}else o=ai(t,null,r);let h=i+".tmp";if(fs$1.writeFileSync(h,o,"utf-8"),fs$1.renameSync(h,i),a){if(t.ci===null){let f=path.dirname(e.outputPath),p=path.join(f,".testrelic-report"),m=path.resolve(i);try{if(await oi(),n=await li(p),!n){s=await me(p,{htmlPath:m}),n=s.port;let g=setInterval(()=>{},6e4),v=()=>{clearInterval(g),s?.dispose();};process.on("SIGINT",v),process.on("SIGTERM",v),setTimeout(v,1800*1e3).unref();}if(n){process.stderr.write(`
4256
- Report server: http://127.0.0.1:${n}
4257
- `);try{let g=kt(l,c,n,u),v=i+".tmp";fs$1.writeFileSync(v,g,"utf-8"),fs$1.renameSync(v,i);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let f=path.dirname(e.outputPath),p=path.join(f,"artifacts");if(fs$1.existsSync(p))try{let m=await dn(p);n=m.port,process.on("exit",()=>{m.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(a&&n)Ct(`http://127.0.0.1:${n}`);else {let f=path.resolve(i);Ct(f);}}catch(n){process.stderr.write(`[testrelic] Failed to write HTML report: ${n instanceof Error?n.message:String(n)}
4258
- `);}}var Ie=9323,gn=10;async function ii(){for(let t=Ie;t<Ie+gn;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),n.ok)return t}catch{}return null}async function oi(){for(let t=Ie;t<Ie+gn;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),1e3);await fetch(`http://127.0.0.1:${t}/api/shutdown`,{method:"POST",signal:e.signal}),clearTimeout(r);}catch{}await new Promise(t=>setTimeout(t,300));}async function li(t){let r=[path.join(__dirname,"cli.cjs"),path.join(__dirname,"cli.js"),path.join(__dirname,"..","dist","cli.cjs"),path.join(__dirname,"..","dist","cli.js")].find(n=>fs$1.existsSync(n));if(!r){let n=await me(t);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=child_process.spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",o=false,i=setTimeout(()=>{o||(o=true,s.stderr?.removeAllListeners(),ii().then(n));},5e3);s.stderr?.on("data",d=>{a+=d.toString();let l=a.match(/127\.0\.0\.1:(\d+)/);l&&!o&&(o=true,clearTimeout(i),s.stderr?.removeAllListeners(),s.unref(),n(Number(l[1])));}),s.on("error",()=>{o||(o=true,clearTimeout(i),n(null));}),s.on("exit",()=>{o||(o=true,clearTimeout(i),n(null));}),s.unref();})}var hn=Buffer.from([137,80,78,71,13,10,26,10]),di=16,ci=20,Me=24;function mn(t){if(t.length<Me||!t.subarray(0,hn.length).equals(hn))return null;let e=t.readUInt32BE(di),r=t.readUInt32BE(ci);return e===0||r===0?null:{width:e,height:r}}var ui=/(\d+) pixels \(ratio [\d.]+ of all image pixels\) are different/,vn=/Expected an image (\d+)px by (\d+)px, received (\d+)px by (\d+)px/;function yn(t){return t?vn.test(t):false}var pi=/^\s*Snapshot:\s*(.+?)\s*$/m;function bn(t){if(!t)return {};let e={},r=ui.exec(t);if(r){let a=Number.parseInt(r[1],10);Number.isFinite(a)&&(e.diffPixels=a);}let n=vn.exec(t);if(n){let[,a,o,i,d]=n,l=[a,o,i,d].map(c=>Number.parseInt(c,10));l.every(c=>Number.isFinite(c))&&(e.expectedWidth=l[0],e.expectedHeight=l[1],e.actualWidth=l[2],e.actualHeight=l[3]);}let s=pi.exec(t);return s&&(e.snapshotName=s[1]),e}function xn(t,e){if(t===void 0||!e)return;let r=e.width*e.height;if(!(r<=0))return t/r}var bi=20,Mt=0,Pt=[];async function ve(t,e){Mt>=bi&&await new Promise(r=>Pt.push(r)),Mt++;try{return await promises.copyFile(t,e),!0}catch{return false}finally{Mt--,Pt.length>0&&Pt.shift()();}}var W=[];async function Cn(){W.length!==0&&(await Promise.allSettled(W),W.length=0);}function Sn(t){let e=new Date,r=a=>String(a).padStart(2,"0"),n=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!fs$1.existsSync(path.join(t,n)))return n;let s=1;for(;fs$1.existsSync(path.join(t,`${n}-${s}`));)s++;return `${n}-${s}`}function Et(t){let e=t.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return e.length>100&&(e=e.substring(0,100).replace(/-+$/,"")),e||"unnamed-test"}var xi=8;function Tn(t,e,r){let n=Et(t),s=r?Et(r).substring(0,xi):"";return s&&(n+=`--${s}`),e>0&&(n+=`--retry-${e}`),n}function Rn(t,e,r,n,s,a){let o=t.find(p=>p.name==="screenshot"&&p.path),i=t.find(p=>p.name==="video"&&p.path),d=t.find(p=>p.name==="trace"&&p.path);if(!o&&!i&&!d)return null;let l=Tn(e,r,a),c=s?["artifacts",s,l]:["artifacts",l],u=path.join(n,...c),h=c,f={};try{fs$1.mkdirSync(u,{recursive:!0});}catch{return null}if(o?.path&&fs$1.existsSync(o.path)){let m=`screenshot${path.extname(o.path)||".png"}`,g=path.join(u,m);W.push(ve(o.path,g).then(()=>{})),f.screenshot=`${h.join("/")}/${m}`;}if(i?.path&&fs$1.existsSync(i.path)){let m=`video${path.extname(i.path)||".webm"}`,g=path.join(u,m);W.push(ve(i.path,g).then(()=>{})),f.video=`${h.join("/")}/${m}`;}if(d?.path&&fs$1.existsSync(d.path)){let m=`trace${path.extname(d.path)||".zip"}`,g=path.join(u,m);W.push(ve(d.path,g).then(()=>{})),f.trace=`${h.join("/")}/${m}`;}return !f.screenshot&&!f.video&&!f.trace?null:f}var Lt="visual",wi=6;function ki(t){let e=crypto.createHash("sha256").update(t).digest("hex").substring(0,wi);return `${Et(t)}--${e}`}function wn(t){let e=null;try{e=fs$1.openSync(t,"r");let r=Buffer.alloc(Me),n=fs$1.readSync(e,r,0,Me,0);return mn(r.subarray(0,n))}catch{return null}finally{if(e!==null)try{fs$1.closeSync(e);}catch{}}}var kn=[{key:"expectedPath",dest:"baseline",field:"baseline"},{key:"actualPath",dest:"actual",field:"actual"},{key:"diffPath",dest:"diff",field:"diff"},{key:"previousPath",dest:"previous",field:"previous"}],Ci=[{key:"baselineDomPath",dest:"baseline.dom.json",field:"baselineDom"},{key:"actualDomPath",dest:"actual.dom.json",field:"actualDom"}];function Si(t,e,r,n){let s=ki(t.name),a=path.join(e,s),o=kn.some(p=>t[p.key]);if(o||t.dom)try{fs$1.mkdirSync(a,{recursive:!0});}catch{return null}let i={},d=false;for(let p of kn){let m=t[p.key];if(!m||!fs$1.existsSync(m))continue;let g=path.extname(m)||".png",v=`${p.dest}${g}`;W.push(ve(m,path.join(a,v)).then(()=>{})),i[p.field]=`${r}/${Lt}/${s}/${v}`,d=true;}let l=t.dom;if(l)for(let p of Ci){let m=l[p.key];!m||!fs$1.existsSync(m)||(W.push(ve(m,path.join(a,p.dest)).then(()=>{})),i[p.field]=`${r}/${Lt}/${s}/${p.dest}`);}if(!d&&o)return null;let c=t.expectedPath?wn(t.expectedPath):t.actualPath?wn(t.actualPath):null,u=xn(t.diffPixels,c),h=t.committedPath??t.expectedPath,f=h?path.relative(n,h).replace(/\\/g,"/"):void 0;return {name:t.name,status:t.status,source:t.source,...i,...f?{baselinePath:f}:{},...c?{width:c.width,height:c.height}:{},...t.actualWidth!==void 0?{actualWidth:t.actualWidth}:{},...t.actualHeight!==void 0?{actualHeight:t.actualHeight}:{},...t.diffPixels!==void 0?{diffPixels:t.diffPixels}:{},...u!==void 0?{diffPixelRatio:u}:{},...l?{domChanges:l.changes,domChangeCount:l.total,domRootCauses:l.rootCauses,domTruncated:l.truncated,domCaptureBox:l.captureBox}:{}}}function An(t,e,r,n,s,a,o=process.cwd()){if(t.length===0)return null;let i=Tn(e,r,a),d=s?["artifacts",s,i]:["artifacts",i],l=path.join(n,...d,Lt),c=d.join("/");try{fs$1.mkdirSync(l,{recursive:!0});}catch{return null}let u=[];for(let h of t){let f=Si(h,l,c,o);f&&u.push(f);}return u.length>0?u:null}function _n(t){let{styleProps:e,defaults:r,inherited:n,maxNodes:s,maxText:a,maskBoxes:o,viewportBox:i,fullPage:d}=t,l={};for(let S=0;S<n.length;S++)l[n[S]]=true;let c=window.scrollX||window.pageXOffset||0,u=window.scrollY||window.pageYOffset||0,h=[],f=0,p=[];for(let S=0;S<o.length;S++){let w=o[S];p.push([w[0]+c,w[1]+u,w[2],w[3]]);}function m(S,w,A,x){for(let C=0;C<p.length;C++){let _=p[C];if(S<_[0]+_[2]&&S+A>_[0]&&w<_[1]+_[3]&&w+x>_[1])return true}return false}function g(S){let w=S.parentElement;if(!w)return 0;let A=w.children,x=0;for(let C=0;C<A.length;C++){let _=A[C];if(_===S)break;_.tagName===S.tagName&&x++;}return x}function v(S){let w="",A=S.childNodes;for(let x=0;x<A.length;x++){let C=A[x];C.nodeType===3&&(w+=C.nodeValue??"");}return w=w.replace(/\s+/g," ").trim(),w.length>a?w.slice(0,a):w}function y(S,w){let A;for(let x=0;x<e.length;x++){let C=e[x],_=S.getPropertyValue(C);if(_){if(l[C]){if(w&&w.getPropertyValue(C)===_)continue}else if(r[C]===_)continue;A||(A={}),A[C]=_;}}return A}let b=[{el:document.body,parentPath:"",parentComputed:null}];for(;b.length>0;){let S=b.pop(),w=S.el,A=window.getComputedStyle(w);if(A.display==="none")continue;let x=w.tagName.toLowerCase(),C=w.id?"#"+w.id:S.parentPath?S.parentPath+">"+x+"["+g(w)+"]":x,_=w.children;for(let E=_.length-1;E>=0;E--)b.push({el:_[E],parentPath:C,parentComputed:A});if(A.visibility==="hidden")continue;let L=w.getBoundingClientRect();if(L.width<=0||L.height<=0)continue;if(h.length>=s){f++;continue}let z=Math.round(L.left+c),ce=Math.round(L.top+u),ue=Math.round(L.width),pe=Math.round(L.height),I={p:C,t:x,r:[z,ce,ue,pe]};w.id&&(I.i=w.id);let M=w.getAttribute("class");M&&(I.c=M.replace(/\s+/g," ").trim());let N=v(w);N&&(I.x=N);let j=y(A,S.parentComputed);j&&(I.s=j),m(z,ce,ue,pe)&&(I.m=1),h.push(I);}let k=Math.max(document.documentElement.scrollWidth,window.innerWidth),T=Math.max(document.documentElement.scrollHeight,window.innerHeight),P;return i?P=[Math.round(i[0]+c),Math.round(i[1]+u),Math.round(i[2]),Math.round(i[3])]:d?P=[0,0,k,T]:P=[Math.round(c),Math.round(u),window.innerWidth,window.innerHeight],{version:"1.0",url:location.href,viewport:{width:window.innerWidth,height:window.innerHeight},content:{width:k,height:T},captureBox:P,nodes:h,truncatedNodes:f}}var Mi=["display","position","color","background-color","background-image","border-top-width","border-right-width","border-bottom-width","border-left-width","border-color","border-style","border-radius","box-shadow","opacity","transform","margin-top","margin-right","margin-bottom","margin-left","padding-top","padding-right","padding-bottom","padding-left","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-decoration-line","text-transform","flex-direction","justify-content","align-items","gap","z-index","overflow"],Pi={position:"static","background-color":"rgba(0, 0, 0, 0)","background-image":"none","border-top-width":"0px","border-right-width":"0px","border-bottom-width":"0px","border-left-width":"0px","border-style":"none","border-radius":"0px","box-shadow":"none",opacity:"1",transform:"none","margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px","padding-top":"0px","padding-right":"0px","padding-bottom":"0px","padding-left":"0px","text-decoration-line":"none","flex-direction":"row","justify-content":"normal","align-items":"normal",gap:"normal","z-index":"auto",overflow:"visible"},Ei=["color","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-transform"],Li=1024*1024,Ni=1500,Di=200;async function Fi(t){let e=[];for(let r of t)try{let n=await r.boundingBox();n&&e.push([n.x,n.y,n.width,n.height]);}catch{}return e}async function In(t){let e=t.config??{};try{let r=t.maskLocators?.length?await Fi(t.maskLocators):[],n=null;if(t.bounded){let a=await t.bounded.boundingBox();a&&(n=[a.x,a.y,a.width,a.height]);}let s={styleProps:Mi,defaults:Pi,inherited:Ei,maxNodes:e.maxNodes??Ni,maxText:e.maxText??Di,maskBoxes:r,viewportBox:n,fullPage:t.fullPage===!0};return await t.target.evaluate(_n,s)}catch{return null}}function Mn(t,e=Li){let r=JSON.stringify(t);if(Buffer.byteLength(r,"utf-8")<=e)return {json:r,truncatedBytes:false};let n=t.nodes.slice(),s=0;for(;n.length>0&&Buffer.byteLength(r,"utf-8")>e;){let a=Math.max(1,Math.floor(n.length*.1));n.splice(-a,a),s+=a,r=JSON.stringify({...t,nodes:n,truncatedNodes:t.truncatedNodes+s});}return {json:r,truncatedBytes:true}}function Pn(t){return t.replace(/\.[A-Za-z0-9]+$/,"")+".dom.json"}function En(t){try{if(!fs$1.existsSync(t))return null;let e=JSON.parse(fs$1.readFileSync(t,"utf-8"));return Bi(e)?e:null}catch{return null}}function Ln(t,e){try{return fs$1.mkdirSync(path.dirname(t),{recursive:!0}),fs$1.writeFileSync(t,e,"utf-8"),!0}catch{return false}}function Bi(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.version=="string"&&Array.isArray(e.nodes)&&Array.isArray(e.captureBox)&&e.captureBox.length===4}var Oi=new Set(["moved","resized"]);function Ee(t){return t.some(e=>!Oi.has(e))}function Dt(t){let e=t.t;if(t.i&&(e+="#"+t.i),t.c){let r=t.c.split(" ").filter(Boolean).slice(0,3);r.length>0&&(e+="."+r.join("."));}return e}function qi(t,e){let r=[],n=Math.abs(t.r[0]-e.r[0]),s=Math.abs(t.r[1]-e.r[1]),a=Math.abs(t.r[2]-e.r[2]),o=Math.abs(t.r[3]-e.r[3]);return (n>1||s>1)&&r.push("moved"),(a>1||o>1)&&r.push("resized"),r}function Hi(t,e){let r=t.s??{},n=e.s??{},s=new Set([...Object.keys(r),...Object.keys(n)]),a=[];for(let o of s){let i=r[o],d=n[o];i!==d&&a.push({prop:o,from:i??"(initial)",to:d??"(initial)"});}return a.sort((o,i)=>o.prop.localeCompare(i.prop)),a}function Nn(t){return t.i?"i:"+t.t+"#"+t.i:t.c?"c:"+t.t+"."+t.c:null}function Ui(t,e){let r=new Map;for(let u of t)r.set(u.p,u);let n=[],s=[],a=new Set;for(let u of e){let h=r.get(u.p);if(h&&h.t!==u.t){s.push(u);continue}h&&!a.has(h)?(a.add(h),n.push({before:h,after:u})):s.push(u);}let o=t.filter(u=>!a.has(u)),i=new Map;for(let u of o){let h=Nn(u);if(!h)continue;let f=i.get(h);f?f.push(u):i.set(h,[u]);}let d=[],l=new Set;for(let u of s){let h=Nn(u),p=(h?i.get(h):void 0)?.find(m=>!l.has(m));p?(l.add(p),n.push({before:p,after:u})):d.push(u);}let c=o.filter(u=>!l.has(u));return {pairs:n,removed:c,added:d}}function zi(t,e){let r=[];return (t.i??"")!==(e.i??"")&&r.push({prop:"id",from:t.i??"(none)",to:e.i??"(none)"}),(t.c??"")!==(e.c??"")&&r.push({prop:"class",from:t.c??"(none)",to:e.c??"(none)"}),r}function Ft(t,e){let r=(e[2]??0)*(e[3]??0);return r<=0?0:Math.min(1,t.r[2]*t.r[3]/r)}function Dn(t,e,r={}){let n=r.maxChanges??50,s=r.includeText!==false,a=r.includeStyles!==false,o=t.nodes.filter(p=>p.m!==1),i=e.nodes.filter(p=>p.m!==1),{pairs:d,removed:l,added:c}=Ui(o,i),u=[];for(let{before:p,after:m}of d){let g=qi(p,m),v=a?Hi(p,m):[];v.length>0&&g.push("restyled");let y=zi(p,m);y.length>0&&g.push("attrs");let b=s&&(p.x??"")!==(m.x??"");if(b&&g.push("text"),g.length===0)continue;let k=Ft(m,e.captureBox);u.push({score:k,change:{path:m.p,label:Dt(m),kinds:g,rect:m.r,baselineRect:p.r,areaPct:k,...y.length>0?{attrs:y}:{},...v.length>0?{styles:v}:{},...b?{text:{from:p.x??"",to:m.x??""}}:{}}});}for(let p of c){let m=Ft(p,e.captureBox);u.push({score:m,change:{path:p.p,label:Dt(p),kinds:["added"],rect:p.r,areaPct:m}});}for(let p of l){let m=Ft(p,t.captureBox);u.push({score:m,change:{path:p.p,label:Dt(p),kinds:["removed"],baselineRect:p.r,areaPct:m}});}let h=u.filter(p=>Ee(p.change.kinds)).length;return u.sort((p,m)=>{if(h>0){let g=Ee(p.change.kinds)?1:0,v=Ee(m.change.kinds)?1:0;if(g!==v)return v-g}return m.score-p.score}),{changes:u.slice(0,n).map((p,m)=>({rank:m+1,...p.change,...h>0&&!Ee(p.change.kinds)?{consequence:true}:{}})),total:u.length,rootCauses:h}}var ji="__testrelic_snapshot_path_probe__.png",Fn=Symbol.for("testrelic.snapshotPathWarned");function Vi(){let t=globalThis,e=t[Fn];return e||(e={warned:false},t[Fn]=e),e}function Le(t){try{let e=t.snapshotPath(ji,{kind:"screenshot"});return typeof e=="string"&&!e.includes("[object Object]")}catch{return false}}function Ne(t){let e=Vi();e.warned||(e.warned=true,process.stderr.write(`[testrelic] ${t} needs Playwright >= 1.51 for testInfo.snapshotPath(name, { kind }); this project's Playwright resolves that call the older way. Everything else in the reporter is unaffected \u2014 upgrade Playwright to enable it.
4259
- `));}var Bt="testrelic-visual-dom",Ji=new Set(["toHaveScreenshot","toMatchVisualBaseline"]);function Bn(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.boundingBox=="function"&&typeof e.page=="function"}function Yi(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.evaluate=="function"&&typeof e.screenshot=="function"}function Xi(t){let e=t[0];if(typeof e=="string")return e;if(Array.isArray(e))return e.join("/");if(typeof e=="object"&&e!==null){let r=e.name;if(typeof r=="string")return r}return null}function Zi(t){for(let e of t)if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e;return {}}function Qi(t){let e=t.mask;return Array.isArray(e)?e.filter(r=>typeof r=="object"&&r!==null&&typeof r.boundingBox=="function"):[]}function eo(t){return /\.(png|jpg|jpeg)$/i.test(t)?t:`${t}.png`}var to=/^(.+)-(expected|actual|diff|previous)\.[A-Za-z0-9]+$/;function ro(t,e,r){let n=t.attachments;for(let s=e;s<n.length;s++){let a=to.exec(n[s]?.name??"");if(a)return a[1]}return r}async function no(t){let e=Zi(t.args),r=Bn(t.received)?t.received:null,n=r?r.page():t.received;return In({target:n,bounded:r,maskLocators:Qi(e),fullPage:e.fullPage===true})}function so(t){let e=t.config?.updateSnapshots;return e==="all"||e==="changed"}async function ao(t,e){let r=Xi(t.args);if(!r)return;if(!Le(t.testInfo)){Ne("DOM comparison");return}let n=t.testInfo.snapshotPath(eo(r),{kind:"screenshot"}),s=Pn(n),a=ro(t.testInfo,t.attachedBefore,path.basename(n,path.extname(n))),o=Mn(e),d=so(t.testInfo)?null:En(s);if(!d){Ln(s,o.json);return}let{changes:l,total:c,rootCauses:u}=Dn(d,e),h;try{h=t.testInfo.outputPath(`${a}.actual.dom.json`),fs$1.writeFileSync(h,o.json,"utf-8");}catch{h=void 0;}let f={stem:a,changes:l,total:c,rootCauses:u,truncated:o.truncatedBytes||e.truncatedNodes>0,captureBox:e.captureBox,...fs$1.existsSync(s)?{baselineDomPath:s}:{},...h?{actualDomPath:h}:{}};await t.testInfo.attach(Bt,{body:Buffer.from(JSON.stringify([f])),contentType:"application/json"});}function On(t,e){let r=function(o,...i){let d=t(o,...i);return !(Bn(o)||Yi(o))||typeof d!="object"||d===null?d:new Proxy(d,{get(c,u,h){let f=Reflect.get(c,u,h);if(typeof u!="string"||!Ji.has(u)||typeof f!="function")return f;let p=f;return async function(...g){let v=e(),y=null,b=v?.attachments.length??0;if(v)try{y=await no({received:o,args:g,testInfo:v,attachedBefore:b});}catch{}try{return await p.apply(c,g)}finally{if(v&&y)try{await ao({received:o,args:g,testInfo:v,attachedBefore:b},y);}catch{}}}}})},n=t,s=r;for(let a of Object.keys(n))s[a]=n[a];return r}var Ot="testrelic-visual",io=/^(.+)-(expected|actual|diff|previous)(\.[A-Za-z0-9]+)$/;function oo(t){let e=new Map;for(let r of t)if(!(r.name!==Ot||!r.body))try{let n=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(n))continue;for(let s of n){let a=co(s);a&&e.set(a.stem,a);}}catch{}return e}var lo=["passed","failed","new","updated"];function co(t){if(typeof t!="object"||t===null)return null;let e=t;return typeof e.stem!="string"||!e.stem||typeof e.name!="string"||!e.name||typeof e.status!="string"||!lo.includes(e.status)?null:{stem:e.stem,name:e.name,status:e.status,...typeof e.committedPath=="string"&&e.committedPath?{committedPath:e.committedPath}:{}}}function uo(t){let e=new Map;for(let r of t)if(!(r.name!==Bt||!r.body))try{let n=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(n))continue;for(let s of n){if(typeof s!="object"||s===null)continue;let a=s;typeof a.stem!="string"||!Array.isArray(a.changes)||e.set(a.stem,s);}}catch{}return e}function po(t){let e=new Map;for(let r of t){if(!r.path)continue;let n=io.exec(r.name);if(!n)continue;let[,s,a]=n,o=e.get(s)??{};o[a]=r.path,e.set(s,o);}return e}function fo(t){return !!(t.actual&&(t.expected||t.diff))}function go(t,e,r){return t.diff||yn(r)?"failed":e?"updated":"new"}function ho(t,e){if(t.length===0)return null;if(t.length===1)return t[0];if(!e)return null;let r=e.replace(/\.[A-Za-z0-9]+$/,""),n=t.filter(s=>s===r||s.endsWith(`/${r}`));return n.length===1?n[0]:null}function Un(t,e={}){if(t.length===0)return [];let r=oo(t),n=uo(t),s=po(t);if(s.size===0&&r.size===0)return [];let a=e.updatingSnapshots===true,o=[];for(let[i,d]of s){let l=r.get(i);!l&&!fo(d)||o.push({name:l?.name??i,status:l?.status??go(d,a,e.failureMessage),source:l?"toMatchVisualBaseline":"toHaveScreenshot",...d.expected?{expectedPath:d.expected}:{},...l?.committedPath?{committedPath:l.committedPath}:{},...d.actual?{actualPath:d.actual}:{},...d.diff?{diffPath:d.diff}:{},...d.previous?{previousPath:d.previous}:{},...n.has(i)?{dom:n.get(i)}:{}});}for(let[i,d]of r)s.has(i)||o.push({name:d.name,status:d.status,source:"toMatchVisualBaseline",...d.committedPath?{committedPath:d.committedPath}:{},...n.has(i)?{dom:n.get(i)}:{}});return mo(o,s,e.failureMessage)}function mo(t,e,r){let n=bn(r);if(n.diffPixels===void 0&&n.actualWidth===void 0)return [...t];let s=t.filter(o=>o.status==="failed"&&qn(o)).map(o=>Hn(o,e)),a=ho(s,n.snapshotName);return a===null?[...t]:t.map(o=>qn(o)&&Hn(o,e)===a?{...o,...n.diffPixels!==void 0?{diffPixels:n.diffPixels}:{},...n.actualWidth!==void 0?{actualWidth:n.actualWidth}:{},...n.actualHeight!==void 0?{actualHeight:n.actualHeight}:{}}:o)}function qn(t){return !!(t.expectedPath||t.actualPath||t.diffPath||t.previousPath)}function Hn(t,e){if(e.has(t.name))return t.name;for(let[r,n]of e)if(n.actual===t.actualPath&&n.expected===t.expectedPath&&n.diff===t.diffPath)return r;return t.name}var vo=new RegExp("[\x1B\x9B][[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[0-9A-PR-TZcf-nqry=><]","g");function se(t){return !t||t.indexOf("\x1B")===-1&&t.indexOf("\x9B")===-1?t:t.replace(vo,"")}function zn(t){return t==null?null:se(t)}var yo=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,bo="1.0",qt="visual";function Wn(t){let e=path.extname(t).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(e)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(e)?"video":e===".zip"&&path.basename(t,e)==="trace"?"trace":"other"}function xo(t){if(t.endsWith(".dom.json"))return "dom";let e=path.basename(t,path.extname(t));return e==="baseline"?"baseline":e==="diff"?"diff":Wn(t)}function wo(t,e,r){let n=[];try{for(let s of fs$1.readdirSync(t,{withFileTypes:!0})){if(!s.isFile())continue;let a=fs$1.statSync(path.join(t,s.name));n.push({name:`${qt}/${r}/${s.name}`,type:xo(s.name),relativePath:`${e}/${qt}/${r}/${s.name}`,sizeBytes:a.size});}}catch{}return n}function Gn(t,e,r){let n=[],s=`artifacts/${e}/${r}`;try{let a=fs$1.readdirSync(t,{withFileTypes:!0});for(let o of a){if(o.isDirectory()&&o.name===qt){let l=path.join(t,o.name);for(let c of fs$1.readdirSync(l,{withFileTypes:!0}))c.isDirectory()&&n.push(...wo(path.join(l,c.name),s,c.name));continue}if(!o.isFile())continue;let i=path.join(t,o.name),d=fs$1.statSync(i);n.push({name:o.name,type:Wn(o.name),relativePath:`${s}/${o.name}`,sizeBytes:d.size});}}catch{}return {testName:r,files:n}}function ko(t,e){let r=path.join(t,e),n=[],s=0;try{let o=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let d=Gn(path.join(r,i.name),e,i.name);n.push(d);for(let l of d.files)s+=l.sizeBytes;}}catch{}let a=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return n.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function Kn(t,e){let r=path.join(t,"artifacts"),n=[],s=[],a=0;try{let i=fs$1.readdirSync(r,{withFileTypes:!0});for(let d of i)if(d.isDirectory())if(yo.test(d.name)){let l=ko(r,d.name);n.push({...l,isCurrentRun:d.name===e});}else {let l=Gn(path.join(r,d.name),d.name,d.name);s.push(l);for(let c of l.files)a+=c.sizeBytes;}}catch{}n.sort((i,d)=>d.timestamp.localeCompare(i.timestamp)),s.length>0&&(s.sort((i,d)=>i.testName.localeCompare(d.testName)),n.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:a,testCount:s.length,tests:s,isCurrentRun:false}));let o=n.reduce((i,d)=>i+d.totalSizeBytes,0);return {schemaVersion:bo,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:n,serverPort:null}}var _o=256;function Io(t){let e=path.resolve(t);for(let r=0;r<_o;r++){if(fs$1.existsSync(path.join(e,".git")))return e;let n=path.dirname(e);if(n===e)return null;e=n;}return null}function Xn(t){try{let e=Io(t);if(!e)return;let r=path.join(e,".gitignore"),n=path.relative(e,t).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(fs$1.existsSync(r)&&fs$1.readFileSync(r,"utf-8").split(`
4260
- `).map(d=>d.trim()).some(d=>d===s||d===n))return;let a=`
4312
+ </html>`}function Tt(t){try{let e=process.platform,r,n;e==="darwin"?(r="open",n=[t]):e==="win32"?(r="cmd",n=["/c","start","",t]):(r="xdg-open",n=[t]),child_process.execFile(r,n,s=>{s&&process.stderr.write(`[testrelic] Failed to open browser: ${s.message}
4313
+ `);});}catch{}}var Wr=path.join(os$1.tmpdir(),"testrelic-data"),H=class{constructor(e){this.count=0;this.closed=false;fs$1.mkdirSync(Wr,{recursive:true}),this.filePath=path.join(Wr,`${e}-${crypto.randomUUID().substring(0,8)}.jsonl`),this.fd=fs$1.openSync(this.filePath,"w");}append(e){if(this.closed)return;let r=JSON.stringify(e)+`
4314
+ `;fs$1.writeSync(this.fd,r),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{fs$1.closeSync(this.fd);}catch{}}}cleanup(){try{fs$1.unlinkSync(this.filePath);}catch{}}};async function Kr(t,e,r,n){let s=(e-1)*r,a=[],o=0,i=readline.createInterface({input:fs$1.createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of i)if(c.length!==0){if(o>=s&&a.length<r)try{a.push(JSON.parse(c));}catch{}if(o++,a.length>=r&&n!==void 0)break}let l=n??o,d=Math.max(1,Math.ceil(l/r));return {items:a,total:l,page:e,pageSize:r,totalPages:d}}var Zr=/^[a-f0-9]{12}$/,_t=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Qr=500;function R(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function en(t){t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type");}function Te(t){try{return fs$1.existsSync(t)?JSON.parse(fs$1.readFileSync(t,"utf-8")):null}catch{return null}}function Re(t){let e=0;try{let r=fs$1.readdirSync(t,{withFileTypes:!0});for(let n of r){let s=path.join(t,n.name);n.isFile()?e+=fs$1.statSync(s).size:n.isDirectory()&&(e+=Re(s));}}catch{}return e}function tn(t,e,r,n){let s=Te(path.join(r,"index.json"));R(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function rn(t,e,r){let n=Te(path.join(r,"summary.json"));if(!n){R(e,404,{error:"Summary not found"});return}R(e,200,n);}function nn(t,e,r){let n=Te(path.join(r,"index.json"));if(!n){R(e,404,{error:"Test index not found"});return}let a=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,o=Math.max(1,parseInt(a.get("page")??"1",10)||1),i=Math.min(Qr,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),l=a.get("status")?.split(",").filter(Boolean)??null,d=a.get("file")??null,c=a.get("search")?.toLowerCase()??null,u=a.get("tag")?.split(",").filter(Boolean)??null,f=a.get("sort")??"file",g=a.get("order")==="desc"?-1:1,p=n;l&&l.length>0&&(p=p.filter(b=>l.includes(b.status))),d&&(p=p.filter(b=>b.filePath===d||b.filePath.startsWith(d+"/"))),c&&(p=p.filter(b=>b.title.toLowerCase().includes(c)||b.filePath.toLowerCase().includes(c))),u&&u.length>0&&(p=p.filter(b=>u.some(w=>b.tags.includes(w)))),p=[...p].sort((b,w)=>{let C=0;switch(f){case "duration":C=b.duration-w.duration;break;case "status":C=b.status.localeCompare(w.status);break;case "title":C=b.title.localeCompare(w.title);break;default:C=b.filePath.localeCompare(w.filePath);break}return C*g});let h=p.length,v=Math.max(1,Math.ceil(h/i)),y=(o-1)*i,m=p.slice(y,y+i);R(e,200,{tests:m,pagination:{page:o,pageSize:i,totalItems:h,totalPages:v},filters:{status:l,file:d,search:c,tag:u}});}function sn(t,e,r,n){if(!Zr.test(n)){R(e,400,{error:"Invalid test ID format"});return}let s=path.join(r,"tests",n,"meta.json"),a=path.join(r,"tests",`${n}.json`),o=fs$1.existsSync(s)?s:fs$1.existsSync(a)?a:null;if(!o){R(e,404,{error:`Test not found: ${n}`});return}try{let i=fs$1.readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){R(e,500,{error:i instanceof Error?i.message:String(i)});}}async function an(t,e,r,n,s){if(!Zr.test(n)){R(e,400,{error:"Invalid test ID format"});return}let o=path.join(r,"tests",n,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!fs$1.existsSync(o)){R(e,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),c=Math.min(Qr,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),u,f=path.join(r,"tests",n,"meta.json");if(fs$1.existsSync(f))try{let p=JSON.parse(fs$1.readFileSync(f,"utf-8"));switch(s){case "network":u=p.networkRequestsCount;break;case "console":u=p.consoleLogsCount;break;case "api-calls":u=p.apiCallsCount;break}}catch{}let g=await Kr(o,d,c,u);R(e,200,g);}catch(i){R(e,500,{error:i instanceof Error?i.message:String(i)});}}function on(t,e,r){let n=Te(path.join(r,"index.json"));if(!n){R(e,404,{error:"Test index not found"});return}let s=new Map;for(let o of n){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 a=Array.from(s.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));R(e,200,{files:a});}function ln(t,e,r){if(!fs$1.existsSync(r)){R(e,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!_t.test(o.name))continue;let i=path.join(r,o.name),l=Re(i),d=fs$1.readdirSync(i,{withFileTypes:!0}).filter(c=>c.isDirectory());n.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),s+=l;}n.sort((o,i)=>i.folderName.localeCompare(o.folderName)),R(e,200,{runs:n,totalSizeBytes:s});}catch(n){R(e,500,{error:n instanceof Error?n.message:String(n)});}}function dn(t,e,r){try{let n=0,s=0;if(fs$1.existsSync(r)){let a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!_t.test(o.name))continue;let i=path.join(r,o.name),l=Re(i);fs$1.rmSync(i,{recursive:!0,force:!0}),s+=l,n++;}}R(e,200,{deletedCount:n,freedBytes:s});}catch(n){R(e,500,{error:n instanceof Error?n.message:String(n)});}}function cn(t,e,r,n){if(!_t.test(n)){R(e,400,{error:"Invalid folder name"});return}let s=path.join(r,n);try{if(!fs$1.statSync(s).isDirectory()){R(e,404,{error:"Not found"});return}}catch{R(e,404,{error:"Not found"});return}try{let a=Re(s);fs$1.rmSync(s,{recursive:!0,force:!0}),R(e,200,{deleted:n,freedBytes:a});}catch(a){R(e,500,{error:a instanceof Error?a.message:String(a)});}}function un(t,e,r){R(e,200,{status:"shutting_down"}),r.close();}function It(t,e,r){if(!fs$1.existsSync(r)){R(e,404,{error:"File not found"});return}try{let n=fs$1.statSync(r).size,s=path.extname(r).toLowerCase(),a=ti[s]??"application/octet-stream",o=ei(t.headers.range,n);if(o==="unsatisfiable"){e.writeHead(416,{"Content-Range":`bytes */${n}`,"Accept-Ranges":"bytes"}),e.end();return}if(o){e.writeHead(206,{"Content-Type":a,"Content-Length":o.end-o.start+1,"Content-Range":`bytes ${o.start}-${o.end}/${n}`,"Accept-Ranges":"bytes"}),Yr(fs$1.createReadStream(r,{start:o.start,end:o.end}),e);return}e.writeHead(200,{"Content-Type":a,"Content-Length":n,"Accept-Ranges":"bytes"}),Yr(fs$1.createReadStream(r),e);}catch(n){R(e,500,{error:n instanceof Error?n.message:String(n)});}}function Yr(t,e){t.on("error",()=>{t.destroy(),e.destroy();}),e.on("close",()=>{t.destroy();}),t.pipe(e);}function ei(t,e){if(!t)return null;let r=/^bytes=(\d*)-(\d*)$/.exec(t.trim());if(!r)return null;let[,n,s]=r;if(n===""&&s==="")return null;let a,o;if(n===""){let i=Number(s);if(i<=0)return "unsatisfiable";a=Math.max(0,e-i),o=e-1;}else a=Number(n),o=s===""?e-1:Math.min(Number(s),e-1);return !Number.isFinite(a)||!Number.isFinite(o)?null:e===0||a>=e||a>o?"unsatisfiable":{start:a,end:o}}var ti={".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 ai=9323,ii=10,oi=1800*1e3;function me(t,e){return new Promise((r,n)=>{let s=e?.port??ai,a=Date.now(),o,i=0,l=fs$1.existsSync(path.join(t,"artifacts"))?path.join(t,"artifacts"):fs$1.existsSync(path.join(t,"..","artifacts"))?path.join(t,"..","artifacts"):path.join(t,"artifacts");function d(){clearTimeout(o),o=setTimeout(()=>{u.close();},oi);}let c=e?.htmlPath??null;if(!c){let g=path.dirname(t);try{let p=fs$1.readdirSync(g).find(h=>h.endsWith(".html"));p&&(c=path.join(g,p));}catch{}}let u=http.createServer((g,p)=>{if(d(),en(p),g.method==="OPTIONS"){p.writeHead(204),p.end();return}let h;try{h=new URL(g.url??"/",`http://${g.headers.host??"localhost"}`).pathname;}catch{R(p,400,{error:"Invalid URL"});return}if(g.method==="GET"&&(h==="/"||h==="/index.html")){if(c&&fs$1.existsSync(c)){It(g,p,c);return}R(p,404,{error:"HTML report not found"});return}if(g.method==="GET"&&h==="/api/health"){tn(g,p,t,a);return}if(g.method==="GET"&&h==="/api/summary"){rn(g,p,t);return}if(g.method==="GET"&&h==="/api/tests"){nn(g,p,t);return}if(g.method==="GET"&&h==="/api/files"){on(g,p,t);return}let v=h.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(g.method==="GET"&&v){an(g,p,t,v[1],v[2]);return}let y=h.match(/^\/api\/tests\/([a-f0-9]+)$/);if(g.method==="GET"&&y){sn(g,p,t,y[1]);return}if(g.method==="GET"&&h==="/api/artifacts"){ln(g,p,l);return}if(g.method==="DELETE"&&h==="/api/artifacts"){dn(g,p,l);return}let m=h.match(/^\/api\/artifacts\/(.+)$/);if(g.method==="DELETE"&&m){cn(g,p,l,decodeURIComponent(m[1]));return}if(g.method==="GET"&&h.startsWith("/artifacts/")){let b=decodeURIComponent(h.slice(11));if(b.includes("..")||b.includes("\0")){R(p,400,{error:"Invalid path"});return}It(g,p,path.join(l,b));return}if(g.method==="POST"&&h==="/api/shutdown"){un(g,p,u);return}R(p,404,{error:"Not found"});});function f(g){let p=h=>{h.code==="EADDRINUSE"&&i<ii?(i++,f(g+1)):n(h);};u.once("error",p),u.listen(g,"127.0.0.1",()=>{u.removeListener("error",p);let h=u.address();if(!h||typeof h=="string"){n(new Error("Failed to get server address"));return}d(),r({port:h.port,dispose:()=>new Promise(v=>{clearTimeout(o),u.close(()=>v());})});});}f(s);})}async function pn(t){let e=await me(t);return {port:e.port,dispose:e.dispose}}function ci(t,e,r,n){let s=JSON.stringify(n?{...t,presentedSummary:n}:t),a=r?JSON.stringify(r):null;return $r(s,e,a)}async function Pt(t,e,r,n){try{let s=null,a=null,o=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,i,l=e.htmlReportPath,d=path.dirname(l);fs$1.mkdirSync(d,{recursive:!0});let c="",u="[]",f=null,g=n?JSON.stringify(n):null;if(o){c=JSON.stringify({...t.summary,testRunId:t.testRunId,startedAt:t.startedAt,completedAt:t.completedAt,totalDuration:t.totalDuration,ci:t.ci,metadata:t.metadata,shardRunIds:t.shardRunIds});let h=path.dirname(e.outputPath),v=path.join(h,".testrelic-report");try{let y=path.join(v,"index-compact.json"),m=path.join(v,"index.json");fs$1.existsSync(y)?u=fs$1.readFileSync(y,"utf-8"):fs$1.existsSync(m)&&(u=fs$1.readFileSync(m,"utf-8"));}catch{}f=r?JSON.stringify(r):null,i=St(c,u,null,f,g);}else i=ci(t,null,r,n);let p=l+".tmp";if(fs$1.writeFileSync(p,i,"utf-8"),fs$1.renameSync(p,l),o){if(t.ci===null){let h=path.dirname(e.outputPath),v=path.join(h,".testrelic-report"),y=path.resolve(l);try{if(await pi(),s=await fi(v),!s){a=await me(v,{htmlPath:y}),s=a.port;let m=setInterval(()=>{},6e4),b=()=>{clearInterval(m),a?.dispose();};process.on("SIGINT",b),process.on("SIGTERM",b),setTimeout(b,1800*1e3).unref();}if(s){process.stderr.write(`
4315
+ Report server: http://127.0.0.1:${s}
4316
+ `);try{let m=St(c,u,s,f,g),b=l+".tmp";fs$1.writeFileSync(b,m,"utf-8"),fs$1.renameSync(b,l);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let h=path.dirname(e.outputPath),v=path.join(h,"artifacts");if(fs$1.existsSync(v))try{let y=await pn(v);s=y.port,process.on("exit",()=>{y.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(o&&s)Tt(`http://127.0.0.1:${s}`);else {let h=path.resolve(l);Tt(h);}}catch(s){process.stderr.write(`[testrelic] Failed to write HTML report: ${s instanceof Error?s.message:String(s)}
4317
+ `);}}var Ie=9323,vn=10;async function ui(){for(let t=Ie;t<Ie+vn;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),n.ok)return t}catch{}return null}async function pi(){for(let t=Ie;t<Ie+vn;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),1e3);await fetch(`http://127.0.0.1:${t}/api/shutdown`,{method:"POST",signal:e.signal}),clearTimeout(r);}catch{}await new Promise(t=>setTimeout(t,300));}async function fi(t){let r=[path.join(__dirname,"cli.cjs"),path.join(__dirname,"cli.js"),path.join(__dirname,"..","dist","cli.cjs"),path.join(__dirname,"..","dist","cli.js")].find(n=>fs$1.existsSync(n));if(!r){let n=await me(t);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=child_process.spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",o=false,i=setTimeout(()=>{o||(o=true,s.stderr?.removeAllListeners(),ui().then(n));},5e3);s.stderr?.on("data",l=>{a+=l.toString();let d=a.match(/127\.0\.0\.1:(\d+)/);d&&!o&&(o=true,clearTimeout(i),s.stderr?.removeAllListeners(),s.unref(),n(Number(d[1])));}),s.on("error",()=>{o||(o=true,clearTimeout(i),n(null));}),s.on("exit",()=>{o||(o=true,clearTimeout(i),n(null));}),s.unref();})}var yn=Buffer.from([137,80,78,71,13,10,26,10]),gi=16,hi=20,Me=24;function bn(t){if(t.length<Me||!t.subarray(0,yn.length).equals(yn))return null;let e=t.readUInt32BE(gi),r=t.readUInt32BE(hi);return e===0||r===0?null:{width:e,height:r}}var mi=/(\d+) pixels \(ratio [\d.]+ of all image pixels\) are different/,xn=/Expected an image (\d+)px by (\d+)px, received (\d+)px by (\d+)px/;function wn(t){return t?xn.test(t):false}var vi=/^\s*Snapshot:\s*(.+?)\s*$/m;function kn(t){if(!t)return {};let e={},r=mi.exec(t);if(r){let a=Number.parseInt(r[1],10);Number.isFinite(a)&&(e.diffPixels=a);}let n=xn.exec(t);if(n){let[,a,o,i,l]=n,d=[a,o,i,l].map(c=>Number.parseInt(c,10));d.every(c=>Number.isFinite(c))&&(e.expectedWidth=d[0],e.expectedHeight=d[1],e.actualWidth=d[2],e.actualHeight=d[3]);}let s=vi.exec(t);return s&&(e.snapshotName=s[1]),e}function Cn(t,e){if(t===void 0||!e)return;let r=e.width*e.height;if(!(r<=0))return t/r}var Si=20,Et=0,Nt=[];async function ve(t,e){Et>=Si&&await new Promise(r=>Nt.push(r)),Et++;try{return await promises.copyFile(t,e),!0}catch{return false}finally{Et--,Nt.length>0&&Nt.shift()();}}var W=[];async function Rn(){W.length!==0&&(await Promise.allSettled(W),W.length=0);}function An(t){let e=new Date,r=a=>String(a).padStart(2,"0"),n=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!fs$1.existsSync(path.join(t,n)))return n;let s=1;for(;fs$1.existsSync(path.join(t,`${n}-${s}`));)s++;return `${n}-${s}`}function Lt(t){let e=t.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return e.length>100&&(e=e.substring(0,100).replace(/-+$/,"")),e||"unnamed-test"}var Ti=8;function _n(t,e,r){let n=Lt(t),s=r?Lt(r).substring(0,Ti):"";return s&&(n+=`--${s}`),e>0&&(n+=`--retry-${e}`),n}function In(t,e,r,n,s,a){let o=t.find(p=>p.name==="screenshot"&&p.path),i=t.find(p=>p.name==="video"&&p.path),l=t.find(p=>p.name==="trace"&&p.path);if(!o&&!i&&!l)return null;let d=_n(e,r,a),c=s?["artifacts",s,d]:["artifacts",d],u=path.join(n,...c),f=c,g={};try{fs$1.mkdirSync(u,{recursive:!0});}catch{return null}if(o?.path&&fs$1.existsSync(o.path)){let h=`screenshot${path.extname(o.path)||".png"}`,v=path.join(u,h);W.push(ve(o.path,v).then(()=>{})),g.screenshot=`${f.join("/")}/${h}`;}if(i?.path&&fs$1.existsSync(i.path)){let h=`video${path.extname(i.path)||".webm"}`,v=path.join(u,h);W.push(ve(i.path,v).then(()=>{})),g.video=`${f.join("/")}/${h}`;}if(l?.path&&fs$1.existsSync(l.path)){let h=`trace${path.extname(l.path)||".zip"}`,v=path.join(u,h);W.push(ve(l.path,v).then(()=>{})),g.trace=`${f.join("/")}/${h}`;}return !g.screenshot&&!g.video&&!g.trace?null:g}var Dt="visual",Ri=6;function Ai(t){let e=crypto.createHash("sha256").update(t).digest("hex").substring(0,Ri);return `${Lt(t)}--${e}`}function Sn(t){let e=null;try{e=fs$1.openSync(t,"r");let r=Buffer.alloc(Me),n=fs$1.readSync(e,r,0,Me,0);return bn(r.subarray(0,n))}catch{return null}finally{if(e!==null)try{fs$1.closeSync(e);}catch{}}}var Tn=[{key:"expectedPath",dest:"baseline",field:"baseline"},{key:"actualPath",dest:"actual",field:"actual"},{key:"diffPath",dest:"diff",field:"diff"},{key:"previousPath",dest:"previous",field:"previous"}],_i=[{key:"baselineDomPath",dest:"baseline.dom.json",field:"baselineDom"},{key:"actualDomPath",dest:"actual.dom.json",field:"actualDom"}];function Ii(t,e,r,n){let s=Ai(t.name),a=path.join(e,s),o=Tn.some(p=>t[p.key]);if(o||t.dom)try{fs$1.mkdirSync(a,{recursive:!0});}catch{return null}let i={},l=false;for(let p of Tn){let h=t[p.key];if(!h||!fs$1.existsSync(h))continue;let v=path.extname(h)||".png",y=`${p.dest}${v}`;W.push(ve(h,path.join(a,y)).then(()=>{})),i[p.field]=`${r}/${Dt}/${s}/${y}`,l=true;}let d=t.dom;if(d)for(let p of _i){let h=d[p.key];!h||!fs$1.existsSync(h)||(W.push(ve(h,path.join(a,p.dest)).then(()=>{})),i[p.field]=`${r}/${Dt}/${s}/${p.dest}`);}if(!l&&o)return null;let c=t.expectedPath?Sn(t.expectedPath):t.actualPath?Sn(t.actualPath):null,u=Cn(t.diffPixels,c),f=t.committedPath??t.expectedPath,g=f?path.relative(n,f).replace(/\\/g,"/"):void 0;return {name:t.name,status:t.status,source:t.source,...i,...g?{baselinePath:g}:{},...c?{width:c.width,height:c.height}:{},...t.actualWidth!==void 0?{actualWidth:t.actualWidth}:{},...t.actualHeight!==void 0?{actualHeight:t.actualHeight}:{},...t.diffPixels!==void 0?{diffPixels:t.diffPixels}:{},...u!==void 0?{diffPixelRatio:u}:{},...d?{domChanges:d.changes,domChangeCount:d.total,domRootCauses:d.rootCauses,domTruncated:d.truncated,domCaptureBox:d.captureBox}:{}}}function Mn(t,e,r,n,s,a,o=process.cwd()){if(t.length===0)return null;let i=_n(e,r,a),l=s?["artifacts",s,i]:["artifacts",i],d=path.join(n,...l,Dt),c=l.join("/");try{fs$1.mkdirSync(d,{recursive:!0});}catch{return null}let u=[];for(let f of t){let g=Ii(f,d,c,o);g&&u.push(g);}return u.length>0?u:null}function Pn(t){let{styleProps:e,defaults:r,inherited:n,maxNodes:s,maxText:a,maskBoxes:o,viewportBox:i,fullPage:l}=t,d={};for(let T=0;T<n.length;T++)d[n[T]]=true;let c=window.scrollX||window.pageXOffset||0,u=window.scrollY||window.pageYOffset||0,f=[],g=0,p=[];for(let T=0;T<o.length;T++){let k=o[T];p.push([k[0]+c,k[1]+u,k[2],k[3]]);}function h(T,k,A,x){for(let S=0;S<p.length;S++){let _=p[S];if(T<_[0]+_[2]&&T+A>_[0]&&k<_[1]+_[3]&&k+x>_[1])return true}return false}function v(T){let k=T.parentElement;if(!k)return 0;let A=k.children,x=0;for(let S=0;S<A.length;S++){let _=A[S];if(_===T)break;_.tagName===T.tagName&&x++;}return x}function y(T){let k="",A=T.childNodes;for(let x=0;x<A.length;x++){let S=A[x];S.nodeType===3&&(k+=S.nodeValue??"");}return k=k.replace(/\s+/g," ").trim(),k.length>a?k.slice(0,a):k}function m(T,k){let A;for(let x=0;x<e.length;x++){let S=e[x],_=T.getPropertyValue(S);if(_){if(d[S]){if(k&&k.getPropertyValue(S)===_)continue}else if(r[S]===_)continue;A||(A={}),A[S]=_;}}return A}let b=[{el:document.body,parentPath:"",parentComputed:null}];for(;b.length>0;){let T=b.pop(),k=T.el,A=window.getComputedStyle(k);if(A.display==="none")continue;let x=k.tagName.toLowerCase(),S=k.id?"#"+k.id:T.parentPath?T.parentPath+">"+x+"["+v(k)+"]":x,_=k.children;for(let E=_.length-1;E>=0;E--)b.push({el:_[E],parentPath:S,parentComputed:A});if(A.visibility==="hidden")continue;let N=k.getBoundingClientRect();if(N.width<=0||N.height<=0)continue;if(f.length>=s){g++;continue}let z=Math.round(N.left+c),ce=Math.round(N.top+u),ue=Math.round(N.width),pe=Math.round(N.height),I={p:S,t:x,r:[z,ce,ue,pe]};k.id&&(I.i=k.id);let P=k.getAttribute("class");P&&(I.c=P.replace(/\s+/g," ").trim());let D=y(k);D&&(I.x=D);let j=m(A,T.parentComputed);j&&(I.s=j),h(z,ce,ue,pe)&&(I.m=1),f.push(I);}let w=Math.max(document.documentElement.scrollWidth,window.innerWidth),C=Math.max(document.documentElement.scrollHeight,window.innerHeight),M;return i?M=[Math.round(i[0]+c),Math.round(i[1]+u),Math.round(i[2]),Math.round(i[3])]:l?M=[0,0,w,C]:M=[Math.round(c),Math.round(u),window.innerWidth,window.innerHeight],{version:"1.0",url:location.href,viewport:{width:window.innerWidth,height:window.innerHeight},content:{width:w,height:C},captureBox:M,nodes:f,truncatedNodes:g}}var Di=["display","position","color","background-color","background-image","border-top-width","border-right-width","border-bottom-width","border-left-width","border-color","border-style","border-radius","box-shadow","opacity","transform","margin-top","margin-right","margin-bottom","margin-left","padding-top","padding-right","padding-bottom","padding-left","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-decoration-line","text-transform","flex-direction","justify-content","align-items","gap","z-index","overflow"],Fi={position:"static","background-color":"rgba(0, 0, 0, 0)","background-image":"none","border-top-width":"0px","border-right-width":"0px","border-bottom-width":"0px","border-left-width":"0px","border-style":"none","border-radius":"0px","box-shadow":"none",opacity:"1",transform:"none","margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px","padding-top":"0px","padding-right":"0px","padding-bottom":"0px","padding-left":"0px","text-decoration-line":"none","flex-direction":"row","justify-content":"normal","align-items":"normal",gap:"normal","z-index":"auto",overflow:"visible"},Bi=["color","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-transform"],Oi=1024*1024,qi=1500,Hi=200;async function Ui(t){let e=[];for(let r of t)try{let n=await r.boundingBox();n&&e.push([n.x,n.y,n.width,n.height]);}catch{}return e}async function En(t){let e=t.config??{};try{let r=t.maskLocators?.length?await Ui(t.maskLocators):[],n=null;if(t.bounded){let a=await t.bounded.boundingBox();a&&(n=[a.x,a.y,a.width,a.height]);}let s={styleProps:Di,defaults:Fi,inherited:Bi,maxNodes:e.maxNodes??qi,maxText:e.maxText??Hi,maskBoxes:r,viewportBox:n,fullPage:t.fullPage===!0};return await t.target.evaluate(Pn,s)}catch{return null}}function Nn(t,e=Oi){let r=JSON.stringify(t);if(Buffer.byteLength(r,"utf-8")<=e)return {json:r,truncatedBytes:false};let n=t.nodes.slice(),s=0;for(;n.length>0&&Buffer.byteLength(r,"utf-8")>e;){let a=Math.max(1,Math.floor(n.length*.1));n.splice(-a,a),s+=a,r=JSON.stringify({...t,nodes:n,truncatedNodes:t.truncatedNodes+s});}return {json:r,truncatedBytes:true}}function Ln(t){return t.replace(/\.[A-Za-z0-9]+$/,"")+".dom.json"}function Dn(t){try{if(!fs$1.existsSync(t))return null;let e=JSON.parse(fs$1.readFileSync(t,"utf-8"));return zi(e)?e:null}catch{return null}}function Fn(t,e){try{return fs$1.mkdirSync(path.dirname(t),{recursive:!0}),fs$1.writeFileSync(t,e,"utf-8"),!0}catch{return false}}function zi(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.version=="string"&&Array.isArray(e.nodes)&&Array.isArray(e.captureBox)&&e.captureBox.length===4}var ji=new Set(["moved","resized"]);function Ee(t){return t.some(e=>!ji.has(e))}function Bt(t){let e=t.t;if(t.i&&(e+="#"+t.i),t.c){let r=t.c.split(" ").filter(Boolean).slice(0,3);r.length>0&&(e+="."+r.join("."));}return e}function Vi(t,e){let r=[],n=Math.abs(t.r[0]-e.r[0]),s=Math.abs(t.r[1]-e.r[1]),a=Math.abs(t.r[2]-e.r[2]),o=Math.abs(t.r[3]-e.r[3]);return (n>1||s>1)&&r.push("moved"),(a>1||o>1)&&r.push("resized"),r}function $i(t,e){let r=t.s??{},n=e.s??{},s=new Set([...Object.keys(r),...Object.keys(n)]),a=[];for(let o of s){let i=r[o],l=n[o];i!==l&&a.push({prop:o,from:i??"(initial)",to:l??"(initial)"});}return a.sort((o,i)=>o.prop.localeCompare(i.prop)),a}function Bn(t){return t.i?"i:"+t.t+"#"+t.i:t.c?"c:"+t.t+"."+t.c:null}function Wi(t,e){let r=new Map;for(let u of t)r.set(u.p,u);let n=[],s=[],a=new Set;for(let u of e){let f=r.get(u.p);if(f&&f.t!==u.t){s.push(u);continue}f&&!a.has(f)?(a.add(f),n.push({before:f,after:u})):s.push(u);}let o=t.filter(u=>!a.has(u)),i=new Map;for(let u of o){let f=Bn(u);if(!f)continue;let g=i.get(f);g?g.push(u):i.set(f,[u]);}let l=[],d=new Set;for(let u of s){let f=Bn(u),p=(f?i.get(f):void 0)?.find(h=>!d.has(h));p?(d.add(p),n.push({before:p,after:u})):l.push(u);}let c=o.filter(u=>!d.has(u));return {pairs:n,removed:c,added:l}}function Gi(t,e){let r=[];return (t.i??"")!==(e.i??"")&&r.push({prop:"id",from:t.i??"(none)",to:e.i??"(none)"}),(t.c??"")!==(e.c??"")&&r.push({prop:"class",from:t.c??"(none)",to:e.c??"(none)"}),r}function Ot(t,e){let r=(e[2]??0)*(e[3]??0);return r<=0?0:Math.min(1,t.r[2]*t.r[3]/r)}function On(t,e,r={}){let n=r.maxChanges??50,s=r.includeText!==false,a=r.includeStyles!==false,o=t.nodes.filter(p=>p.m!==1),i=e.nodes.filter(p=>p.m!==1),{pairs:l,removed:d,added:c}=Wi(o,i),u=[];for(let{before:p,after:h}of l){let v=Vi(p,h),y=a?$i(p,h):[];y.length>0&&v.push("restyled");let m=Gi(p,h);m.length>0&&v.push("attrs");let b=s&&(p.x??"")!==(h.x??"");if(b&&v.push("text"),v.length===0)continue;let w=Ot(h,e.captureBox);u.push({score:w,change:{path:h.p,label:Bt(h),kinds:v,rect:h.r,baselineRect:p.r,areaPct:w,...m.length>0?{attrs:m}:{},...y.length>0?{styles:y}:{},...b?{text:{from:p.x??"",to:h.x??""}}:{}}});}for(let p of c){let h=Ot(p,e.captureBox);u.push({score:h,change:{path:p.p,label:Bt(p),kinds:["added"],rect:p.r,areaPct:h}});}for(let p of d){let h=Ot(p,t.captureBox);u.push({score:h,change:{path:p.p,label:Bt(p),kinds:["removed"],baselineRect:p.r,areaPct:h}});}let f=u.filter(p=>Ee(p.change.kinds)).length;return u.sort((p,h)=>{if(f>0){let v=Ee(p.change.kinds)?1:0,y=Ee(h.change.kinds)?1:0;if(v!==y)return y-v}return h.score-p.score}),{changes:u.slice(0,n).map((p,h)=>({rank:h+1,...p.change,...f>0&&!Ee(p.change.kinds)?{consequence:true}:{}})),total:u.length,rootCauses:f}}var Ki="__testrelic_snapshot_path_probe__.png",qn=Symbol.for("testrelic.snapshotPathWarned");function Ji(){let t=globalThis,e=t[qn];return e||(e={warned:false},t[qn]=e),e}function Ne(t){try{let e=t.snapshotPath(Ki,{kind:"screenshot"});return typeof e=="string"&&!e.includes("[object Object]")}catch{return false}}function Le(t){let e=Ji();e.warned||(e.warned=true,process.stderr.write(`[testrelic] ${t} needs Playwright >= 1.51 for testInfo.snapshotPath(name, { kind }); this project's Playwright resolves that call the older way. Everything else in the reporter is unaffected \u2014 upgrade Playwright to enable it.
4318
+ `));}var qt="testrelic-visual-dom",eo=new Set(["toHaveScreenshot","toMatchVisualBaseline"]);function Hn(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.boundingBox=="function"&&typeof e.page=="function"}function to(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.evaluate=="function"&&typeof e.screenshot=="function"}function ro(t){let e=t[0];if(typeof e=="string")return e;if(Array.isArray(e))return e.join("/");if(typeof e=="object"&&e!==null){let r=e.name;if(typeof r=="string")return r}return null}function no(t){for(let e of t)if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e;return {}}function so(t){let e=t.mask;return Array.isArray(e)?e.filter(r=>typeof r=="object"&&r!==null&&typeof r.boundingBox=="function"):[]}function ao(t){return /\.(png|jpg|jpeg)$/i.test(t)?t:`${t}.png`}var io=/^(.+)-(expected|actual|diff|previous)\.[A-Za-z0-9]+$/;function oo(t,e,r){let n=t.attachments;for(let s=e;s<n.length;s++){let a=io.exec(n[s]?.name??"");if(a)return a[1]}return r}async function lo(t){let e=no(t.args),r=Hn(t.received)?t.received:null,n=r?r.page():t.received;return En({target:n,bounded:r,maskLocators:so(e),fullPage:e.fullPage===true})}function co(t){let e=t.config?.updateSnapshots;return e==="all"||e==="changed"}async function uo(t,e){let r=ro(t.args);if(!r)return;if(!Ne(t.testInfo)){Le("DOM comparison");return}let n=t.testInfo.snapshotPath(ao(r),{kind:"screenshot"}),s=Ln(n),a=oo(t.testInfo,t.attachedBefore,path.basename(n,path.extname(n))),o=Nn(e),l=co(t.testInfo)?null:Dn(s);if(!l){Fn(s,o.json);return}let{changes:d,total:c,rootCauses:u}=On(l,e),f;try{f=t.testInfo.outputPath(`${a}.actual.dom.json`),fs$1.writeFileSync(f,o.json,"utf-8");}catch{f=void 0;}let g={stem:a,changes:d,total:c,rootCauses:u,truncated:o.truncatedBytes||e.truncatedNodes>0,captureBox:e.captureBox,...fs$1.existsSync(s)?{baselineDomPath:s}:{},...f?{actualDomPath:f}:{}};await t.testInfo.attach(qt,{body:Buffer.from(JSON.stringify([g])),contentType:"application/json"});}function Un(t,e){let r=function(o,...i){let l=t(o,...i);return !(Hn(o)||to(o))||typeof l!="object"||l===null?l:new Proxy(l,{get(c,u,f){let g=Reflect.get(c,u,f);if(typeof u!="string"||!eo.has(u)||typeof g!="function")return g;let p=g;return async function(...v){let y=e(),m=null,b=y?.attachments.length??0;if(y)try{m=await lo({received:o,args:v,testInfo:y,attachedBefore:b});}catch{}try{return await p.apply(c,v)}finally{if(y&&m)try{await uo({received:o,args:v,testInfo:y,attachedBefore:b},m);}catch{}}}}})},n=t,s=r;for(let a of Object.keys(n))s[a]=n[a];return r}var Ht="testrelic-visual",po=/^(.+)-(expected|actual|diff|previous)(\.[A-Za-z0-9]+)$/;function fo(t){let e=new Map;for(let r of t)if(!(r.name!==Ht||!r.body))try{let n=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(n))continue;for(let s of n){let a=ho(s);a&&e.set(a.stem,a);}}catch{}return e}var go=["passed","failed","new","updated"];function ho(t){if(typeof t!="object"||t===null)return null;let e=t;return typeof e.stem!="string"||!e.stem||typeof e.name!="string"||!e.name||typeof e.status!="string"||!go.includes(e.status)?null:{stem:e.stem,name:e.name,status:e.status,...typeof e.committedPath=="string"&&e.committedPath?{committedPath:e.committedPath}:{}}}function mo(t){let e=new Map;for(let r of t)if(!(r.name!==qt||!r.body))try{let n=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(n))continue;for(let s of n){if(typeof s!="object"||s===null)continue;let a=s;typeof a.stem!="string"||!Array.isArray(a.changes)||e.set(a.stem,s);}}catch{}return e}function vo(t){let e=new Map;for(let r of t){if(!r.path)continue;let n=po.exec(r.name);if(!n)continue;let[,s,a]=n,o=e.get(s)??{};o[a]=r.path,e.set(s,o);}return e}function yo(t){return !!(t.actual&&(t.expected||t.diff))}function bo(t,e,r){return t.diff||wn(r)?"failed":e?"updated":"new"}function xo(t,e){if(t.length===0)return null;if(t.length===1)return t[0];if(!e)return null;let r=e.replace(/\.[A-Za-z0-9]+$/,""),n=t.filter(s=>s===r||s.endsWith(`/${r}`));return n.length===1?n[0]:null}function Vn(t,e={}){if(t.length===0)return [];let r=fo(t),n=mo(t),s=vo(t);if(s.size===0&&r.size===0)return [];let a=e.updatingSnapshots===true,o=[];for(let[i,l]of s){let d=r.get(i);!d&&!yo(l)||o.push({name:d?.name??i,status:d?.status??bo(l,a,e.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}:{},...n.has(i)?{dom:n.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}:{},...n.has(i)?{dom:n.get(i)}:{}});return wo(o,s,e.failureMessage)}function wo(t,e,r){let n=kn(r);if(n.diffPixels===void 0&&n.actualWidth===void 0)return [...t];let s=t.filter(o=>o.status==="failed"&&zn(o)).map(o=>jn(o,e)),a=xo(s,n.snapshotName);return a===null?[...t]:t.map(o=>zn(o)&&jn(o,e)===a?{...o,...n.diffPixels!==void 0?{diffPixels:n.diffPixels}:{},...n.actualWidth!==void 0?{actualWidth:n.actualWidth}:{},...n.actualHeight!==void 0?{actualHeight:n.actualHeight}:{}}:o)}function zn(t){return !!(t.expectedPath||t.actualPath||t.diffPath||t.previousPath)}function jn(t,e){if(e.has(t.name))return t.name;for(let[r,n]of e)if(n.actual===t.actualPath&&n.expected===t.expectedPath&&n.diff===t.diffPath)return r;return t.name}var ko=new RegExp("[\x1B\x9B][[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[0-9A-PR-TZcf-nqry=><]","g");function se(t){return !t||t.indexOf("\x1B")===-1&&t.indexOf("\x9B")===-1?t:t.replace(ko,"")}function $n(t){return t==null?null:se(t)}var Co=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,So="1.0",Ut="visual";function Jn(t){let e=path.extname(t).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(e)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(e)?"video":e===".zip"&&path.basename(t,e)==="trace"?"trace":"other"}function To(t){if(t.endsWith(".dom.json"))return "dom";let e=path.basename(t,path.extname(t));return e==="baseline"?"baseline":e==="diff"?"diff":Jn(t)}function Ro(t,e,r){let n=[];try{for(let s of fs$1.readdirSync(t,{withFileTypes:!0})){if(!s.isFile())continue;let a=fs$1.statSync(path.join(t,s.name));n.push({name:`${Ut}/${r}/${s.name}`,type:To(s.name),relativePath:`${e}/${Ut}/${r}/${s.name}`,sizeBytes:a.size});}}catch{}return n}function Yn(t,e,r){let n=[],s=`artifacts/${e}/${r}`;try{let a=fs$1.readdirSync(t,{withFileTypes:!0});for(let o of a){if(o.isDirectory()&&o.name===Ut){let d=path.join(t,o.name);for(let c of fs$1.readdirSync(d,{withFileTypes:!0}))c.isDirectory()&&n.push(...Ro(path.join(d,c.name),s,c.name));continue}if(!o.isFile())continue;let i=path.join(t,o.name),l=fs$1.statSync(i);n.push({name:o.name,type:Jn(o.name),relativePath:`${s}/${o.name}`,sizeBytes:l.size});}}catch{}return {testName:r,files:n}}function Ao(t,e){let r=path.join(t,e),n=[],s=0;try{let o=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=Yn(path.join(r,i.name),e,i.name);n.push(l);for(let d of l.files)s+=d.sizeBytes;}}catch{}let a=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return n.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function Xn(t,e){let r=path.join(t,"artifacts"),n=[],s=[],a=0;try{let i=fs$1.readdirSync(r,{withFileTypes:!0});for(let l of i)if(l.isDirectory())if(Co.test(l.name)){let d=Ao(r,l.name);n.push({...d,isCurrentRun:l.name===e});}else {let d=Yn(path.join(r,l.name),l.name,l.name);s.push(d);for(let c of d.files)a+=c.sizeBytes;}}catch{}n.sort((i,l)=>l.timestamp.localeCompare(i.timestamp)),s.length>0&&(s.sort((i,l)=>i.testName.localeCompare(l.testName)),n.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:a,testCount:s.length,tests:s,isCurrentRun:false}));let o=n.reduce((i,l)=>i+l.totalSizeBytes,0);return {schemaVersion:So,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:n,serverPort:null}}var No=256;function Lo(t){let e=path.resolve(t);for(let r=0;r<No;r++){if(fs$1.existsSync(path.join(e,".git")))return e;let n=path.dirname(e);if(n===e)return null;e=n;}return null}function es(t){try{let e=Lo(t);if(!e)return;let r=path.join(e,".gitignore"),n=path.relative(e,t).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(fs$1.existsSync(r)&&fs$1.readFileSync(r,"utf-8").split(`
4319
+ `).map(l=>l.trim()).some(l=>l===s||l===n))return;let a=`
4261
4320
  # TestRelic test artifacts
4262
4321
  ${s}
4263
- `;fs$1.appendFileSync(r,a,"utf-8");}catch{}}var Zn=Symbol("testrelic.timeout"),Qn=3e4,Ht=12e4,Ut=6e4,es=15e3;async function Q(t,e,r){let n,s=new Promise(a=>{n=setTimeout(()=>a(Zn),e),typeof n?.unref=="function"&&n.unref();});try{let a=await Promise.race([t(),s]);if(a===Zn){process.stderr.write(`[testrelic] ${r} timed out after ${Math.round(e/1e3)}s \u2014 continuing without it. Your tests are unaffected.
4322
+ `;fs$1.appendFileSync(r,a,"utf-8");}catch{}}var ts=Symbol("testrelic.timeout"),rs=3e4,zt=12e4,jt=6e4,ns=15e3;async function Q(t,e,r){let n,s=new Promise(a=>{n=setTimeout(()=>a(ts),e),typeof n?.unref=="function"&&n.unref();});try{let a=await Promise.race([t(),s]);if(a===ts){process.stderr.write(`[testrelic] ${r} timed out after ${Math.round(e/1e3)}s \u2014 continuing without it. Your tests are unaffected.
4264
4323
  `);return}return a}catch(a){process.stderr.write(`[testrelic] ${r} failed \u2014 continuing without it. Your tests are unaffected. (${a instanceof Error?a.message:String(a)})
4265
- `);return}finally{n&&clearTimeout(n);}}function ns(t,e){let r=[];for(let n of t){let s=Mo(n),a=Po(n),o=Eo(n,s,a,e),i=Lo(n,s,a);if(o.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:n.startedAt,durationOnUrl:n.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:n.specFile,test:s,tests:[a],_testTitle:n.title});continue}r.push(...o,...i);}return r.sort(No),Do(r,t),r.map((n,s)=>n.type==="navigation"?{...{index:s,type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:n.durationOnUrl??0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:n.specFile,test:n.test},tests:n.tests}:{...{index:s,type:"api_call",callId:n.callId,method:n.method,url:n.url,timestamp:n.timestamp,responseTime:n.responseTime??null,request:n.request,response:n.response??null,...n.error?{error:n.error}:{},assertions:n.assertions??[],specFile:n.specFile,test:n.test},tests:n.tests})}function Mo(t){return {title:t.title,fullTitle:t.titlePath,status:t.status,duration:t.duration,retries:t.retryCount,retry:t.retry,tags:t.tags,failure:t.failure}}function Po(t){return {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,networkRequests:t.networkRequests,apiCalls:t.apiCalls,apiAssertions:t.apiAssertions,actions:t.actions,consoleLogs:t.consoleLogs}}function Eo(t,e,r,n){let s=[];for(let a of t.navigations)n.navigationTypes!==null&&!n.navigationTypes.includes(a.navigationType)||s.push({type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title});return s}function Lo(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let n=t.apiAssertions??[];return t.apiCalls.map(s=>{let a=n.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:rs(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:rs(s.requestBody)},response:o,...s.error?{error:s.error}:{},assertions:a,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function No(t,e){let r=new Date(t.timestamp).getTime(),n=new Date(e.timestamp).getTime();if(r!==n)return r-n;let s={navigation:0,api_call:1},a=s[t.type],o=s[e.type];return a!==o?a-o:t.type==="api_call"&&e.type==="api_call"&&t.callId&&e.callId?ts(t.callId)-ts(e.callId):0}function ts(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function Do(t,e){for(let r=0;r<t.length;r++){let n=t[r];if(n.type!=="navigation")continue;let s=new Date(n.timestamp).getTime(),a=null;for(let o=r+1;o<t.length;o++)if(t[o]._testTitle===n._testTitle){a=new Date(t[o].timestamp).getTime();break}if(a!==null)n.durationOnUrl=Math.max(0,a-s);else {let o=e.find(i=>i.title===n._testTitle);if(o){let i=new Date(o.completedAt).getTime();n.durationOnUrl=Math.max(0,i-s);}}}}function rs(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function ee(t,e){let r=t.length,n=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,n)]}function zt(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function Fo(t){return t==null?"error":t>=200&&t<300?"2xx":t>=300&&t<400?"3xx":t>=400&&t<500?"4xx":t>=500&&t<600?"5xx":"error"}function ss(t,e){let r=0,n=0,s=0,a=0,o=0;for(let x of t)switch(x.status){case "passed":r++;break;case "failed":n++;break;case "flaky":s++;break;case "skipped":a++;break;case "timedout":o++;break}let i=[];for(let x of t)x.apiCalls&&i.push(...x.apiCalls);let d=i.length,l=new Set,c={},u={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},h=[];for(let x of i)l.add(zt(x.url)),c[x.method]=(c[x.method]??0)+1,u[Fo(x.responseStatusCode)]+=1,h.push(x.responseTimeMs);let f=null;if(h.length>0){let x=[...h].sort((_,L)=>_-L),C=x.reduce((_,L)=>_+L,0);f={avg:Math.round(C/x.length),min:x[0],max:x[x.length-1],p50:ee(x,50),p95:ee(x,95),p99:ee(x,99)};}let p=0,m=0,g=0;for(let x of t)if(x.apiAssertions)for(let C of x.apiAssertions)p++,C.status==="passed"?m++:g++;let v=0,y=new Set;for(let x of t){v+=x.navigations.length;for(let C of x.navigations)y.add(C.url);}let b=0,k={};function T(x){for(let C of x)b++,k[C.category]=(k[C.category]??0)+1,C.children.length>0&&T(C.children);}for(let x of t)x.actions&&T(x.actions);let P=0,S=0,w=0,A=0;for(let x of t)if(x.visual)for(let C of x.visual)P++,C.status==="failed"?S++:(C.status==="new"||C.status==="updated")&&w++,A+=C.domChangeCount??0;return {total:t.length,passed:r,failed:n,flaky:s,skipped:a,timedout:o,totalApiCalls:d,uniqueApiUrls:l.size,apiCallsByMethod:c,apiCallsByStatusRange:u,apiResponseTime:f,totalAssertions:p,passedAssertions:m,failedAssertions:g,totalNavigations:v,uniqueNavigationUrls:y.size,totalTimelineSteps:e,totalActionSteps:b,actionStepsByCategory:k,visualChecks:P,visualFailures:S,visualNew:w,visualDomChanges:A}}function Bo(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function F(t){return `\u2502 ${Bo(t)} \u2502
4266
- `}function jt(t,e,r,n){if(n||t.total===0)return;let s=`\u250C${"\u2500".repeat(58)}\u2510
4267
- `,a=`\u2514${"\u2500".repeat(58)}\u2518
4268
- `,o=F(""),i=s;i+=F("TestRelic AI - Playwright Test Report"),i+=o;let d=[];if(t.passed>0&&d.push(`${t.passed} \u2713`),t.failed>0&&d.push(`${t.failed} \u2717`),t.flaky>0&&d.push(`${t.flaky} \u26A0`),t.skipped>0&&d.push(`${t.skipped} skipped`),t.timedout>0&&d.push(`${t.timedout} timedout`),i+=F(`Tests: ${t.total} total (${d.join(" ")})`),t.totalNavigations>0&&(i+=F(`Navigations: ${t.totalNavigations} visits across ${t.uniqueNavigationUrls} unique URLs`)),t.totalApiCalls>0){i+=F(`API Calls: ${t.totalApiCalls} calls across ${t.uniqueApiUrls} unique endpoints`);let l=Object.entries(t.apiCallsByMethod).filter(([,u])=>u>0).map(([u,h])=>`${u}: ${h}`);l.length>0&&(i+=F(` ${l.join(" ")}`));let c=Object.entries(t.apiCallsByStatusRange).filter(([,u])=>u>0).map(([u,h])=>`${u}: ${h}`);c.length>0&&(i+=F(` ${c.join(" ")}`)),t.apiResponseTime&&(i+=F(` Avg response: ${t.apiResponseTime.avg}ms P95: ${t.apiResponseTime.p95}ms`));}if(t.totalAssertions>0&&(i+=F(`Assertions: ${t.totalAssertions} total (${t.passedAssertions} \u2713 ${t.failedAssertions} \u2717)`)),t.totalActionSteps>0){let l=[],c=t.actionStepsByCategory;c.ui_action&&l.push(`${c.ui_action} UI`),c.assertion&&l.push(`${c.assertion} assertions`),c.custom_step&&l.push(`${c.custom_step} custom`);let u=l.length>0?` (${l.join(" ")})`:"";i+=F(`Actions: ${t.totalActionSteps} steps${u}`);}i+=F(`Report: ${r}`),i+=F(`Data: ${e}`),i+=a,i+=`For more information visit us at https://docs.testrelic.ai
4269
- `,process.stderr.write(i);}var Oo=new Set(["pw:api","expect","test.step"]);function qo(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function Vt(t,e,r){if(Oo.has(t.category)){let n=[];for(let a of t.steps)Vt(a,e,n);let s=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:qo(t.category),timestamp:t.startTime.toISOString(),duration:t.duration,videoOffset:s>=0?s/1e3:null,status:t.error?"failed":"passed",error:zn(t.error?.message),children:n});}else for(let n of t.steps)Vt(n,e,r);}function as(t,e){let r=[];for(let n of t)Vt(n,e,r);return r}var zo=new Set(["localhost","127.0.0.1","0.0.0.0"]);function os(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&zo.has(e.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var jo=3e3;async function $t(t){let e=new AbortController,r=setTimeout(()=>e.abort(),jo);try{return (await fetch(`${t}/health`,{method:"GET",signal:e.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function ls(t){return new Promise(e=>setTimeout(e,t))}async function is(t){try{let r=(await t.json()).error;if(r&&typeof r.message=="string"){let n=r.details;if(Array.isArray(n)&&n.length>0){let s=n.map(a=>`${a.field}: ${a.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${t.status}`}async function Wt(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.signal});if(a.ok){let i=await a.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(a.status===429){let i=a.headers.get("Retry-After"),d=i?parseInt(i,10)*1e3:5e3;if(!isNaN(d)&&d>0){await ls(d);let l=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.signal});if(l.ok){let c=await l.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 a.status===400?{code:"validation_error",message:await is(a),statusCode:400}:a.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:a.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await is(a),statusCode:a.status}}catch(a){return a instanceof DOMException&&a.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 Gt(t){return "code"in t&&typeof t.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(t.code)}async function ds(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.signal});if(a.status===429){let i=a.headers.get("Retry-After"),d=i?parseInt(i,10)*1e3:5e3;!isNaN(d)&&d>0&&(await ls(d),a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.signal}));}if(!a.ok)return null;let o=await a.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn}}catch{return null}finally{clearTimeout(s);}}async function cs(t,e,r,n,s,a){let o=new AbortController,i=setTimeout(()=>o.abort(),s);try{let d={gitId:r,displayName:n};a&&(d.branch=a);let l=await fetch(`${t}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(d),signal:o.signal});if(!l.ok)return null;let c=await l.json();return {repoId:c.repoId,displayName:c.displayName}}catch{return null}finally{clearTimeout(i);}}var Ko=5e3;function K(t,e){try{return child_process.execSync(t,{cwd:e,timeout:Ko,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function us(t){let e=K("git rev-parse --abbrev-ref HEAD",t),r=K("git rev-parse --short HEAD",t),n=K("git log -1 --pretty=%s",t),s=K("git log -1 --format=%an",t)??K("git config user.name",t),a=Jo(t),o=a?be(a):null;return {branch:e,commitSha:r,commitMessage:n,commitAuthor:s,remoteUrl:o}}function Jo(t){let e=K("git remote get-url origin",t);if(e)return e;let r=K("git remote",t);if(!r)return null;let n=r.split(`
4270
- `)[0]?.trim();return n?K(`git remote get-url ${n}`,t):null}function be(t){let e=t.trim();return e=e.replace(/^[a-z+]+:\/\//,""),e=e.replace(/^[^@]+@/,""),e=e.replace(/:(?!\d)/,"/"),e=e.replace(/\.git$/,""),e=e.replace(/\/+$/,""),e=e.replace(/^[^@/]+@/,""),e.toLowerCase()}function ps(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??t}function Kt(t){try{let e=fs$1.readFileSync(path.join(t,"package.json"),"utf-8"),r=JSON.parse(e);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function xe(t){let e=Kt(t);return e||`local/${path.basename(t)}`}var Yo=new Set(["smoke","regression","nightly","ci"]);function De(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&Yo.has(t))return t}async function J(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),Math.max(1,r));try{return await fetch(t,{...e,signal:n.signal})}finally{clearTimeout(s);}}function fs(t,e){let r=e+Math.ceil(Math.max(0,t)/1e3);return Math.min(6e5,Math.max(3e4,r))}var Fe=class{constructor(e=12e4,r=Date.now()){this.deadline=r+Math.max(0,e);}remaining(e=Date.now()){return Math.max(0,this.deadline-e)}expired(e=Date.now()){return this.remaining(e)===0}slice(e,r=Date.now()){return Math.min(e,this.remaining(r))}};var Qo=1048576,Be=[1e3,3e3,9e3],Oe=3,hs=3e4,el=90*1048576,tl=new Set(["e2e","mobile","unit"]);function Yt(t){if(t&&t.length>0&&t.every(s=>s.testType==="api")){let s=new Map;for(let i of t){let d=i.apiProtocol??"rest";s.set(d,(s.get(d)??0)+1);}let a="rest",o=0;for(let[i,d]of s)d>o&&(o=d,a=i);return {testType:"api",apiProtocol:a,metadata:{testType:"api",primaryProtocol:a}}}let e=new Map;for(let s of t??[])tl.has(s.testType)&&e.set(s.testType,(e.get(s.testType)??0)+1);let r=null,n=0;for(let[s,a]of e)a>n&&(n=a,r=s);return {testType:r??"e2e"}}function Xt(t,e,r,n,s,a){let o=a?.cloudPlatform?a.cloudPlatform:n?.provider&&n.provider!=="unknown"?n.provider:"local",i=De(),d=Yt(s),l=d.testType==="api"?d:null,c=l&&s?s.map(h=>h.apiProtocol?h:{...h,apiProtocol:l.apiProtocol}):s;return {runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,environment:o,...i?{runType:i}:{},...l?{testType:l.testType,apiProtocol:l.apiProtocol,metadata:l.metadata}:{testType:d.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}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{},...a?.cloudPlatform?{cloudPlatform:a.cloudPlatform}:{},...a?.cloudBuildId?{cloudBuildId:a.cloudBuildId}:{},...a?.cloudSessionId?{cloudSessionId:a.cloudSessionId}:{}}}function Jt(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function Zt(t){return Array.isArray(t)?t.map(e=>{let r=e.statusCode??e.responseStatusCode??null;return {...e.id!=null?{id:e.id}:{},...e.protocol!=null?{protocol:e.protocol}:{},method:e.method??null,url:e.url??null,statusCode:r,statusText:e.statusText??e.responseStatusText??null,ok:typeof r=="number"?r<400:e.ok??null,durationMs:e.durationMs??e.responseTimeMs??null,bytesIn:typeof e.bytesIn=="number"?e.bytesIn:Jt(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:Jt(e.requestBody),requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,requestCookies:e.requestCookies??null,responseCookies:e.responseCookies??null}}):[]}function Qt(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,n=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:Jt(e.responseBody),duration:e.responseTimeMs??e.durationMs??0,responseTimeMs:e.responseTimeMs??e.durationMs??0,requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,timestamp:n,startedAt:n}}):[]}function er(t){if(!Array.isArray(t))return [];let e=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return t.map(r=>{let n=r.status==="failed"?"failed":"passed",s=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,a=r.kind??r.type??"assertion",o=n==="failed"?`expected ${e(r.expected)}, received ${e(r.actual)}`:r.expected!==void 0?`expected ${e(r.expected)}`:null;return {...r.callId!=null?{callId:r.callId}:{},kind:a,description:s??r.description??`${a} assertion`,status:n,detail:o}})}async function qe(t){return new Promise(e=>setTimeout(e,t))}function rl(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}async function ms(t,e,r,n=hs,s){for(let a=0;a<Oe;a++){if(s?.expired())return null;let o=s?s.slice(n):n;if(o<=0)return null;try{let i=await J(t,e,o);if(i.ok)return i;if(i.status===401&&r&&a===0){let d=await r();if(d){let l={...e,headers:{...e.headers,Authorization:`Bearer ${d}`}},c=await J(t,l,o);if(c.ok)return c}return null}if(i.status===429&&a<Oe-1){let d=i.headers.get("Retry-After"),l=d?parseInt(d,10)*1e3:Be[a];!isNaN(l)&&l>0?await qe(l):await qe(Be[a]);continue}if(i.status>=500&&a<Oe-1){await qe(Be[a]);continue}return i}catch{if(a<Oe-1){await qe(Be[a]);continue}return null}}return null}var nl=util.promisify(zlib.gzip);function gs(t,e){if(!Array.isArray(t.tests))return t;let r=t.tests.map(n=>{let{consoleLogs:s,networkRequests:a,apiCalls:o,...i}=n;return e?i:{...i,...o!==void 0?{apiCalls:o}:{}}});return {...t,tests:r}}var sl=["consoleLogs","networkRequests","apiCalls","actions","navigations","protocolAssertions","visual"];function al(t){if(!Array.isArray(t.tests))return t;let e=new Set(sl),r=t.tests.map(n=>{let s={};for(let a in n)if(!e.has(a))if(a==="failure"&&n[a]&&typeof n[a]=="object"){let o=n[a];s.failure={message:o.message??null,line:o.line??null};}else s[a]=n[a];return s});return {...t,tests:r}}function il(t){let e=new Set(["tests","timeline","unifiedTimeline","navigations"]),r={};for(let n in t)e.has(n)||(r[n]=t[n]);return r.tests=[],r}async function tr(t,e=el){let r={"Content-Type":"application/json"},n=JSON.stringify(t),s=t,a=Array.isArray(s?.tests)?s.tests.length:0,o=i=>Buffer.byteLength(i,"utf-8")>e;if(a>0&&o(n)){let i=Math.max(1,Math.round(e/1048576));process.stderr.write(`[testrelic] WARNING: batch payload exceeds ${i}MB \u2014 dropping consoleLogs/networkRequests from ${a} test(s) to avoid HTTP 413. Console/network detail will be missing in the cloud.
4271
- `),n=JSON.stringify(gs(s,false)),o(n)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB after dropping logs \u2014 also dropping apiCalls from ${a} test(s). API request/response detail will be missing in the cloud.
4272
- `),n=JSON.stringify(gs(s,true))),o(n)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB \u2014 shedding remaining per-test detail (actions/navigations/assertions) from ${a} test(s). Only test results + summary will reach the cloud.
4273
- `),n=JSON.stringify(al(s))),o(n)&&(process.stderr.write(`[testrelic] ERROR: batch still exceeds ${i}MB after shedding all per-test detail \u2014 uploading run summary only (${a} per-test result(s) omitted) to avoid losing the run to HTTP 413.
4274
- `),n=JSON.stringify(il(s)));}if(Buffer.byteLength(n,"utf-8")>Qo){r["Content-Encoding"]="gzip";let i=await nl(Buffer.from(n,"utf-8")),d=i.buffer;return {body:new Uint8Array(d,i.byteOffset,i.byteLength),headers:r}}return {body:n,headers:r}}async function vs(t,e,r,n,s,a){let o=`${t}/runs`,{body:i,headers:d}=await tr(r);d.Authorization=`Bearer ${e}`;let l=await ms(o,{method:"POST",headers:d,body:i},n,s,a);return l?.ok?{success:true,statusCode:l.status,error:null}:l?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:l?`Upload failed with status ${l.status}`:"Upload failed after retries",statusCode:l?.status??null,payload:r,targetEndpoint:o,method:"POST"}}async function ys(t,e,r,n){let s=`${t}/runs/init`;try{let a=await J(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(rl(r))},n??hs);return a.ok?{runId:(await a.json()).runId}:null}catch{return null}}function bs(t,e,r,n){let s=`${t}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}).catch(()=>{});}async function xs(t,e,r,n){let s=`${t}/runs/${r}/finalize`;return (await ms(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}))?.ok??false}function rr(t,e,r,n){let s=`${t}/runs/${r}/finalize`,a=new Date,o={finishedAt:a.toISOString(),duration:a.getTime()-new Date(n).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}var ul="1.0.0",ws=10;function ks(t){return t instanceof Error?t.message:String(t)}function pl(t){return t>=400&&t<500&&t!==408&&t!==429}function we(t,e,r,n,s,a,o,i){try{fs$1.mkdirSync(t,{recursive:!0});let d=Date.now(),l=`${d}-${e}-${r}.json`,c=path.join(t,l),u={version:ul,queuedAt:new Date(d).toISOString(),reason:n,retryCount:0,targetEndpoint:s,method:a,payload:o,headers:i},h=c+".tmp";fs$1.writeFileSync(h,JSON.stringify(u,null,2),"utf-8"),fs$1.renameSync(h,c);}catch(d){d.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
4324
+ `);return}finally{n&&clearTimeout(n);}}function is(t,e){let r=[];for(let n of t){let s=Do(n),a=Fo(n),o=Bo(n,s,a,e),i=Oo(n,s,a);if(o.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:n.startedAt,durationOnUrl:n.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:n.specFile,test:s,tests:[a],_testTitle:n.title});continue}r.push(...o,...i);}return r.sort(qo),Ho(r,t),r.map((n,s)=>n.type==="navigation"?{...{index:s,type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:n.durationOnUrl??0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:n.specFile,test:n.test},tests:n.tests}:{...{index:s,type:"api_call",callId:n.callId,method:n.method,url:n.url,timestamp:n.timestamp,responseTime:n.responseTime??null,request:n.request,response:n.response??null,...n.error?{error:n.error}:{},assertions:n.assertions??[],specFile:n.specFile,test:n.test},tests:n.tests})}function Do(t){return {title:t.title,fullTitle:t.titlePath,status:t.status,duration:t.duration,retries:t.retryCount,retry:t.retry,tags:t.tags,failure:t.failure}}function Fo(t){return {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,networkRequests:t.networkRequests,apiCalls:t.apiCalls,apiAssertions:t.apiAssertions,actions:t.actions,consoleLogs:t.consoleLogs}}function Bo(t,e,r,n){let s=[];for(let a of t.navigations)n.navigationTypes!==null&&!n.navigationTypes.includes(a.navigationType)||s.push({type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title});return s}function Oo(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let n=t.apiAssertions??[];return t.apiCalls.map(s=>{let a=n.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:as(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:as(s.requestBody)},response:o,...s.error?{error:s.error}:{},assertions:a,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function qo(t,e){let r=new Date(t.timestamp).getTime(),n=new Date(e.timestamp).getTime();if(r!==n)return r-n;let s={navigation:0,api_call:1},a=s[t.type],o=s[e.type];return a!==o?a-o:t.type==="api_call"&&e.type==="api_call"&&t.callId&&e.callId?ss(t.callId)-ss(e.callId):0}function ss(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function Ho(t,e){for(let r=0;r<t.length;r++){let n=t[r];if(n.type!=="navigation")continue;let s=new Date(n.timestamp).getTime(),a=null;for(let o=r+1;o<t.length;o++)if(t[o]._testTitle===n._testTitle){a=new Date(t[o].timestamp).getTime();break}if(a!==null)n.durationOnUrl=Math.max(0,a-s);else {let o=e.find(i=>i.title===n._testTitle);if(o){let i=new Date(o.completedAt).getTime();n.durationOnUrl=Math.max(0,i-s);}}}}function as(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function ee(t,e){let r=t.length,n=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,n)]}function Vt(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function Uo(t){return t==null?"error":t>=200&&t<300?"2xx":t>=300&&t<400?"3xx":t>=400&&t<500?"4xx":t>=500&&t<600?"5xx":"error"}function os(t,e){let r=0,n=0,s=0,a=0,o=0;for(let x of t)switch(x.status){case "passed":r++;break;case "failed":n++;break;case "flaky":s++;break;case "skipped":a++;break;case "timedout":o++;break}let i=[];for(let x of t)x.apiCalls&&i.push(...x.apiCalls);let l=i.length,d=new Set,c={},u={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},f=[];for(let x of i)d.add(Vt(x.url)),c[x.method]=(c[x.method]??0)+1,u[Uo(x.responseStatusCode)]+=1,f.push(x.responseTimeMs);let g=null;if(f.length>0){let x=[...f].sort((_,N)=>_-N),S=x.reduce((_,N)=>_+N,0);g={avg:Math.round(S/x.length),min:x[0],max:x[x.length-1],p50:ee(x,50),p95:ee(x,95),p99:ee(x,99)};}let p=0,h=0,v=0;for(let x of t)if(x.apiAssertions)for(let S of x.apiAssertions)p++,S.status==="passed"?h++:v++;let y=0,m=new Set;for(let x of t){y+=x.navigations.length;for(let S of x.navigations)m.add(S.url);}let b=0,w={};function C(x){for(let S of x)b++,w[S.category]=(w[S.category]??0)+1,S.children.length>0&&C(S.children);}for(let x of t)x.actions&&C(x.actions);let M=0,T=0,k=0,A=0;for(let x of t)if(x.visual)for(let S of x.visual)M++,S.status==="failed"?T++:(S.status==="new"||S.status==="updated")&&k++,A+=S.domChangeCount??0;return {total:t.length,passed:r,failed:n,flaky:s,skipped:a,timedout:o,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:c,apiCallsByStatusRange:u,apiResponseTime:g,totalAssertions:p,passedAssertions:h,failedAssertions:v,totalNavigations:y,uniqueNavigationUrls:m.size,totalTimelineSteps:e,totalActionSteps:b,actionStepsByCategory:w,visualChecks:M,visualFailures:T,visualNew:k,visualDomChanges:A}}function zo(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function L(t){return `\u2502 ${zo(t)} \u2502
4325
+ `}function $t(t,e,r,n,s){if(n||t.total===0)return;let a=`\u250C${"\u2500".repeat(58)}\u2510
4326
+ `,o=`\u2514${"\u2500".repeat(58)}\u2518
4327
+ `,i=L(""),l=a;l+=L("TestRelic AI - Playwright Test Report"),l+=i;let d=s??t,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+=L(`Tests: ${t.total} total (${c.join(" ")})`),s&&s.expectedFailures>0&&(l+=L(` ${s.expectedFailures} failed as expected (test.fail)`)),s&&s.unexpectedPasses>0&&(l+=L(` ${s.unexpectedPasses} expected to fail, but passed (test.fail)`)),t.totalNavigations>0&&(l+=L(`Navigations: ${t.totalNavigations} visits across ${t.uniqueNavigationUrls} unique URLs`)),t.totalApiCalls>0){l+=L(`API Calls: ${t.totalApiCalls} calls across ${t.uniqueApiUrls} unique endpoints`);let u=Object.entries(t.apiCallsByMethod).filter(([,g])=>g>0).map(([g,p])=>`${g}: ${p}`);u.length>0&&(l+=L(` ${u.join(" ")}`));let f=Object.entries(t.apiCallsByStatusRange).filter(([,g])=>g>0).map(([g,p])=>`${g}: ${p}`);f.length>0&&(l+=L(` ${f.join(" ")}`)),t.apiResponseTime&&(l+=L(` Avg response: ${t.apiResponseTime.avg}ms P95: ${t.apiResponseTime.p95}ms`));}if(t.totalAssertions>0&&(l+=L(`Assertions: ${t.totalAssertions} total (${t.passedAssertions} \u2713 ${t.failedAssertions} \u2717)`)),t.totalActionSteps>0){let u=[],f=t.actionStepsByCategory;f.ui_action&&u.push(`${f.ui_action} UI`),f.assertion&&u.push(`${f.assertion} assertions`),f.custom_step&&u.push(`${f.custom_step} custom`);let g=u.length>0?` (${u.join(" ")})`:"";l+=L(`Actions: ${t.totalActionSteps} steps${g}`);}l+=L(`Report: ${r}`),l+=L(`Data: ${e}`),l+=o,l+=`For more information visit us at https://docs.testrelic.ai
4328
+ `,process.stderr.write(l);}var jo=new Set(["pw:api","expect","test.step"]);function Vo(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function Wt(t,e,r){if(jo.has(t.category)){let n=[];for(let a of t.steps)Wt(a,e,n);let s=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:Vo(t.category),timestamp:t.startTime.toISOString(),duration:t.duration,videoOffset:s>=0?s/1e3:null,status:t.error?"failed":"passed",error:$n(t.error?.message),children:n});}else for(let n of t.steps)Wt(n,e,r);}function ls(t,e){let r=[];for(let n of t)Wt(n,e,r);return r}var Go=new Set(["localhost","127.0.0.1","0.0.0.0"]);function cs(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Go.has(e.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var Ko=3e3;async function Gt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Ko);try{return (await fetch(`${t}/health`,{method:"GET",signal:e.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function us(t){return new Promise(e=>setTimeout(e,t))}async function ds(t){try{let r=(await t.json()).error;if(r&&typeof r.message=="string"){let n=r.details;if(Array.isArray(n)&&n.length>0){let s=n.map(a=>`${a.field}: ${a.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${t.status}`}async function Kt(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.signal});if(a.ok){let i=await a.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(a.status===429){let i=a.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;if(!isNaN(l)&&l>0){await us(l);let d=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.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 a.status===400?{code:"validation_error",message:await ds(a),statusCode:400}:a.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:a.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await ds(a),statusCode:a.status}}catch(a){return a instanceof DOMException&&a.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 Jt(t){return "code"in t&&typeof t.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(t.code)}async function ps(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.signal});if(a.status===429){let i=a.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;!isNaN(l)&&l>0&&(await us(l),a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.signal}));}if(!a.ok)return null;let o=await a.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn}}catch{return null}finally{clearTimeout(s);}}async function fs(t,e,r,n,s,a){let o=new AbortController,i=setTimeout(()=>o.abort(),s);try{let l={gitId:r,displayName:n};a&&(l.branch=a);let d=await fetch(`${t}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},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 Qo=5e3;function K(t,e){try{return child_process.execSync(t,{cwd:e,timeout:Qo,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function gs(t){let e=K("git rev-parse --abbrev-ref HEAD",t),r=K("git rev-parse --short HEAD",t),n=K("git log -1 --pretty=%s",t),s=K("git log -1 --format=%an",t)??K("git config user.name",t),a=el(t),o=a?be(a):null;return {branch:e,commitSha:r,commitMessage:n,commitAuthor:s,remoteUrl:o}}function el(t){let e=K("git remote get-url origin",t);if(e)return e;let r=K("git remote",t);if(!r)return null;let n=r.split(`
4329
+ `)[0]?.trim();return n?K(`git remote get-url ${n}`,t):null}function be(t){let e=t.trim();return e=e.replace(/^[a-z+]+:\/\//,""),e=e.replace(/^[^@]+@/,""),e=e.replace(/:(?!\d)/,"/"),e=e.replace(/\.git$/,""),e=e.replace(/\/+$/,""),e=e.replace(/^[^@/]+@/,""),e.toLowerCase()}function hs(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??t}function Yt(t){try{let e=fs$1.readFileSync(path.join(t,"package.json"),"utf-8"),r=JSON.parse(e);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function xe(t){let e=Yt(t);return e||`local/${path.basename(t)}`}var tl=new Set(["smoke","regression","nightly","ci"]);function De(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&tl.has(t))return t}async function J(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),Math.max(1,r));try{return await fetch(t,{...e,signal:n.signal})}finally{clearTimeout(s);}}function ms(t,e){let r=e+Math.ceil(Math.max(0,t)/1e3);return Math.min(6e5,Math.max(3e4,r))}var Fe=class{constructor(e=12e4,r=Date.now()){this.deadline=r+Math.max(0,e);}remaining(e=Date.now()){return Math.max(0,this.deadline-e)}expired(e=Date.now()){return this.remaining(e)===0}slice(e,r=Date.now()){return Math.min(e,this.remaining(r))}};var sl=1048576,Be=[1e3,3e3,9e3],Oe=3,ys=3e4,al=90*1048576,il=new Set(["e2e","mobile","unit"]);function Zt(t){if(t&&t.length>0&&t.every(s=>s.testType==="api")){let s=new Map;for(let i of t){let l=i.apiProtocol??"rest";s.set(l,(s.get(l)??0)+1);}let a="rest",o=0;for(let[i,l]of s)l>o&&(o=l,a=i);return {testType:"api",apiProtocol:a,metadata:{testType:"api",primaryProtocol:a}}}let e=new Map;for(let s of t??[])il.has(s.testType)&&e.set(s.testType,(e.get(s.testType)??0)+1);let r=null,n=0;for(let[s,a]of e)a>n&&(n=a,r=s);return {testType:r??"e2e"}}function Qt(t,e,r,n,s,a){let o=a?.cloudPlatform?a.cloudPlatform:n?.provider&&n.provider!=="unknown"?n.provider:"local",i=De(),l=Zt(s),d=l.testType==="api"?l:null,c=d&&s?s.map(f=>f.apiProtocol?f:{...f,apiProtocol:d.apiProtocol}):s;return {runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.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}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{},...a?.cloudPlatform?{cloudPlatform:a.cloudPlatform}:{},...a?.cloudBuildId?{cloudBuildId:a.cloudBuildId}:{},...a?.cloudSessionId?{cloudSessionId:a.cloudSessionId}:{}}}function Xt(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function er(t){return Array.isArray(t)?t.map(e=>{let r=e.statusCode??e.responseStatusCode??null;return {...e.id!=null?{id:e.id}:{},...e.protocol!=null?{protocol:e.protocol}:{},method:e.method??null,url:e.url??null,statusCode:r,statusText:e.statusText??e.responseStatusText??null,ok:typeof r=="number"?r<400:e.ok??null,durationMs:e.durationMs??e.responseTimeMs??null,bytesIn:typeof e.bytesIn=="number"?e.bytesIn:Xt(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:Xt(e.requestBody),requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,requestCookies:e.requestCookies??null,responseCookies:e.responseCookies??null}}):[]}function tr(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,n=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:Xt(e.responseBody),duration:e.responseTimeMs??e.durationMs??0,responseTimeMs:e.responseTimeMs??e.durationMs??0,requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,timestamp:n,startedAt:n}}):[]}function rr(t){if(!Array.isArray(t))return [];let e=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return t.map(r=>{let n=r.status==="failed"?"failed":"passed",s=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,a=r.kind??r.type??"assertion",o=n==="failed"?`expected ${e(r.expected)}, received ${e(r.actual)}`:r.expected!==void 0?`expected ${e(r.expected)}`:null;return {...r.callId!=null?{callId:r.callId}:{},kind:a,description:s??r.description??`${a} assertion`,status:n,detail:o}})}async function qe(t){return new Promise(e=>setTimeout(e,t))}function ol(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}async function bs(t,e,r,n=ys,s){for(let a=0;a<Oe;a++){if(s?.expired())return null;let o=s?s.slice(n):n;if(o<=0)return null;try{let i=await J(t,e,o);if(i.ok)return i;if(i.status===401&&r&&a===0){let l=await r();if(l){let d={...e,headers:{...e.headers,Authorization:`Bearer ${l}`}},c=await J(t,d,o);if(c.ok)return c}return null}if(i.status===429&&a<Oe-1){let l=i.headers.get("Retry-After"),d=l?parseInt(l,10)*1e3:Be[a];!isNaN(d)&&d>0?await qe(d):await qe(Be[a]);continue}if(i.status>=500&&a<Oe-1){await qe(Be[a]);continue}return i}catch{if(a<Oe-1){await qe(Be[a]);continue}return null}}return null}var ll=util.promisify(zlib.gzip);function vs(t,e){if(!Array.isArray(t.tests))return t;let r=t.tests.map(n=>{let{consoleLogs:s,networkRequests:a,apiCalls:o,...i}=n;return e?i:{...i,...o!==void 0?{apiCalls:o}:{}}});return {...t,tests:r}}var dl=["consoleLogs","networkRequests","apiCalls","actions","navigations","protocolAssertions","visual"];function cl(t){if(!Array.isArray(t.tests))return t;let e=new Set(dl),r=t.tests.map(n=>{let s={};for(let a in n)if(!e.has(a))if(a==="failure"&&n[a]&&typeof n[a]=="object"){let o=n[a];s.failure={message:o.message??null,line:o.line??null};}else s[a]=n[a];return s});return {...t,tests:r}}function ul(t){let e=new Set(["tests","timeline","unifiedTimeline","navigations"]),r={};for(let n in t)e.has(n)||(r[n]=t[n]);return r.tests=[],r}async function nr(t,e=al){let r={"Content-Type":"application/json"},n=JSON.stringify(t),s=t,a=Array.isArray(s?.tests)?s.tests.length:0,o=i=>Buffer.byteLength(i,"utf-8")>e;if(a>0&&o(n)){let i=Math.max(1,Math.round(e/1048576));process.stderr.write(`[testrelic] WARNING: batch payload exceeds ${i}MB \u2014 dropping consoleLogs/networkRequests from ${a} test(s) to avoid HTTP 413. Console/network detail will be missing in the cloud.
4330
+ `),n=JSON.stringify(vs(s,false)),o(n)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB after dropping logs \u2014 also dropping apiCalls from ${a} test(s). API request/response detail will be missing in the cloud.
4331
+ `),n=JSON.stringify(vs(s,true))),o(n)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB \u2014 shedding remaining per-test detail (actions/navigations/assertions) from ${a} test(s). Only test results + summary will reach the cloud.
4332
+ `),n=JSON.stringify(cl(s))),o(n)&&(process.stderr.write(`[testrelic] ERROR: batch still exceeds ${i}MB after shedding all per-test detail \u2014 uploading run summary only (${a} per-test result(s) omitted) to avoid losing the run to HTTP 413.
4333
+ `),n=JSON.stringify(ul(s)));}if(Buffer.byteLength(n,"utf-8")>sl){r["Content-Encoding"]="gzip";let i=await ll(Buffer.from(n,"utf-8")),l=i.buffer;return {body:new Uint8Array(l,i.byteOffset,i.byteLength),headers:r}}return {body:n,headers:r}}async function xs(t,e,r,n,s,a){let o=`${t}/runs`,{body:i,headers:l}=await nr(r);l.Authorization=`Bearer ${e}`;let d=await bs(o,{method:"POST",headers:l,body:i},n,s,a);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 ws(t,e,r,n){let s=`${t}/runs/init`;try{let a=await J(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(ol(r))},n??ys);return a.ok?{runId:(await a.json()).runId}:null}catch{return null}}function ks(t,e,r,n){let s=`${t}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}).catch(()=>{});}async function Cs(t,e,r,n){let s=`${t}/runs/${r}/finalize`;return (await bs(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}))?.ok??false}function sr(t,e,r,n){let s=`${t}/runs/${r}/finalize`,a=new Date,o={finishedAt:a.toISOString(),duration:a.getTime()-new Date(n).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}var ml="1.0.0",Ss=10;function Ts(t){return t instanceof Error?t.message:String(t)}function vl(t){return t>=400&&t<500&&t!==408&&t!==429}function we(t,e,r,n,s,a,o,i){try{fs$1.mkdirSync(t,{recursive:!0});let l=Date.now(),d=`${l}-${e}-${r}.json`,c=path.join(t,d),u={version:ml,queuedAt:new Date(l).toISOString(),reason:n,retryCount:0,targetEndpoint:s,method:a,payload:o,headers:i},f=c+".tmp";fs$1.writeFileSync(f,JSON.stringify(u,null,2),"utf-8"),fs$1.renameSync(f,c);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
4275
4334
  `):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
4276
- `);}}async function Rs(t,e,r){let n;try{n=fs$1.readdirSync(t).filter(a=>a.endsWith(".json")&&!a.endsWith(".tmp")).sort();}catch{return}if(n.length===0)return;let s=[];for(let a=0;a<n.length;a+=ws)s.push(n.slice(a,a+ws));for(let a of s)for(let o of a){let i=path.join(t,o),d;try{if(!fs$1.statSync(i).isFile())continue;let c=JSON.parse(fs$1.readFileSync(i,"utf-8"));if(!core.isValidQueueEntry(c)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
4277
- `),fs$1.unlinkSync(i);continue}d=c;}catch(l){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${o}: ${ks(l)}
4278
- `);try{fs$1.unlinkSync(i);}catch{}continue}try{let{body:l,headers:c}=await tr(d.payload),u={...d.headers,...c,Authorization:`Bearer ${r}`},h=await fetch(d.targetEndpoint,{method:d.method,headers:u,body:l});if(h.ok)fs$1.unlinkSync(i);else if(pl(h.status)){process.stderr.write(`\u26A0 TestRelic: Queue entry ${o} rejected (HTTP ${h.status}) \u2014 moving aside; it will not be retried.
4279
- `);try{fs$1.renameSync(i,`${i}.failed`);}catch{try{fs$1.unlinkSync(i);}catch{}}}else {process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 server returned HTTP ${h.status} for ${o}; will retry later.
4280
- `);return}}catch(l){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${ks(l)}; will retry later.
4281
- `);return}}}function As(t,e){try{let r=fs$1.readdirSync(t).filter(s=>(s.endsWith(".json")||s.endsWith(".failed"))&&!s.endsWith(".tmp")),n=Date.now();for(let s of r){let a=path.join(t,s);try{let o=fs$1.readFileSync(a,"utf-8"),d=JSON.parse(o).queuedAt;if(typeof d=="string"){let l=new Date(d).getTime();n-l>e&&fs$1.unlinkSync(a);}}catch{try{fs$1.unlinkSync(a);}catch{}}}}catch{}}var bl=3e5,xl=864e5,wl=6e4,_s=3e4,ar="https://platform.testrelic.ai/settings/api-keys";function Is(t){return new Promise(e=>{let r=setTimeout(e,t);typeof r?.unref=="function"&&r.unref();})}var He=class{constructor(e){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=e,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.
4282
- `);return}try{if(os(this.config.endpoint),this.gitMetadata=us(),!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.
4283
- `);return}let r=await Wt(this.config.endpoint,this.config.apiKey,this.config.timeout);if(Gt(r)){this.handleAuthError(r.code,r.statusCode);return}let n=r;this.authState={mode:"cloud",accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:Date.now()+n.expiresIn*1e3,orgId:n.orgId,orgName:n.orgName,userId:n.userId,userName:n.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${n.orgName} / ${n.userName})
4284
- `),await this.resolveRepoId(),this.config.queueDirectory&&(As(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(e){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode. ${e instanceof Error?e.message:String(e)}
4285
- `);}}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 e=this.authState.expiresAt??0;if(Date.now()+bl<e)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await ds(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(e){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=e,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${e}).
4286
- `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,Is(_s)]);}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(e){this.authState.mode="local",this.failureReason=e;}handleAuthError(e,r){switch(e){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
4287
- \u2192 Manage keys: ${ar}
4335
+ `);}}async function Is(t,e,r){let n;try{n=fs$1.readdirSync(t).filter(a=>a.endsWith(".json")&&!a.endsWith(".tmp")).sort();}catch{return}if(n.length===0)return;let s=[];for(let a=0;a<n.length;a+=Ss)s.push(n.slice(a,a+Ss));for(let a of s)for(let o of a){let i=path.join(t,o),l;try{if(!fs$1.statSync(i).isFile())continue;let c=JSON.parse(fs$1.readFileSync(i,"utf-8"));if(!core.isValidQueueEntry(c)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
4336
+ `),fs$1.unlinkSync(i);continue}l=c;}catch(d){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${o}: ${Ts(d)}
4337
+ `);try{fs$1.unlinkSync(i);}catch{}continue}try{let{body:d,headers:c}=await nr(l.payload),u={...l.headers,...c,Authorization:`Bearer ${r}`},f=await fetch(l.targetEndpoint,{method:l.method,headers:u,body:d});if(f.ok)fs$1.unlinkSync(i);else if(vl(f.status)){process.stderr.write(`\u26A0 TestRelic: Queue entry ${o} rejected (HTTP ${f.status}) \u2014 moving aside; it will not be retried.
4338
+ `);try{fs$1.renameSync(i,`${i}.failed`);}catch{try{fs$1.unlinkSync(i);}catch{}}}else {process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 server returned HTTP ${f.status} for ${o}; will retry later.
4339
+ `);return}}catch(d){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${Ts(d)}; will retry later.
4340
+ `);return}}}function Ms(t,e){try{let r=fs$1.readdirSync(t).filter(s=>(s.endsWith(".json")||s.endsWith(".failed"))&&!s.endsWith(".tmp")),n=Date.now();for(let s of r){let a=path.join(t,s);try{let o=fs$1.readFileSync(a,"utf-8"),l=JSON.parse(o).queuedAt;if(typeof l=="string"){let d=new Date(l).getTime();n-d>e&&fs$1.unlinkSync(a);}}catch{try{fs$1.unlinkSync(a);}catch{}}}}catch{}}var Sl=3e5,Tl=864e5,Rl=6e4,Ps=3e4,or="https://platform.testrelic.ai/settings/api-keys";function Es(t){return new Promise(e=>{let r=setTimeout(e,t);typeof r?.unref=="function"&&r.unref();})}var He=class{constructor(e){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=e,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.
4341
+ `);return}try{if(cs(this.config.endpoint),this.gitMetadata=gs(),!await Gt(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.
4342
+ `);return}let r=await Kt(this.config.endpoint,this.config.apiKey,this.config.timeout);if(Jt(r)){this.handleAuthError(r.code,r.statusCode);return}let n=r;this.authState={mode:"cloud",accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:Date.now()+n.expiresIn*1e3,orgId:n.orgId,orgName:n.orgName,userId:n.userId,userName:n.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${n.orgName} / ${n.userName})
4343
+ `),await this.resolveRepoId(),this.config.queueDirectory&&(Ms(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(e){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode. ${e instanceof Error?e.message:String(e)}
4344
+ `);}}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 e=this.authState.expiresAt??0;if(Date.now()+Sl<e)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await ps(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(e){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=e,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${e}).
4345
+ `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,Es(Ps)]);}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(e){this.authState.mode="local",this.failureReason=e;}handleAuthError(e,r){switch(e){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
4346
+ \u2192 Manage keys: ${or}
4288
4347
  `);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
4289
- \u2192 Generate a new key: ${ar}
4348
+ \u2192 Generate a new key: ${or}
4290
4349
  `);break;case "validation_error":this.setLocalMode("validation_error"),process.stderr.write(`\u26A0 TestRelic: API key format invalid. Running in local mode.
4291
- \u2192 Manage keys: ${ar}
4350
+ \u2192 Manage keys: ${or}
4292
4351
  `);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
4293
4352
  `);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
4294
4353
  `);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
4295
- `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?be(this.gitMetadata.remoteUrl):null,r=e?ps(e):this.config.projectName??xe(process.cwd()),n=e??this.config.projectName??xe(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await cs(this.config.endpoint,this.authState.accessToken,n,r,this.config.timeout,this.gitMetadata?.branch);a&&(this.repoId=a.repoId,this.writeRepoCache(n,a.repoId,a.displayName));}catch{}!e&&!this.config.projectName&&!Kt(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
4296
- `);}readRepoCache(e){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs$1.existsSync(r))return null;let n=fs$1.readFileSync(r,"utf-8"),s=JSON.parse(n);if(s.gitId!==e||Date.now()-s.resolvedAt>xl)return null;let a=this.hashApiKey();return a&&s.apiKeyHash!==a?null:s}catch{return null}}writeRepoCache(e,r,n){if(!this.config)return;let s=path.join(this.config.queueDirectory,"..","cache"),a=path.join(s,"repo.json");try{fs$1.mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:e,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=a+".tmp";fs$1.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),fs$1.renameSync(i,a);}catch{}}hashApiKey(){return this.config?.apiKey?crypto.createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let e=this.authState.accessToken,r=this.config.queueDirectory,n=this.config.endpoint;this.flushPromise=Promise.race([Rs(r,n,e),Is(_s)]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let e=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(e))return;if(this.config?.apiKey){let n=await Wt(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Gt(n)){let s=n;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.
4297
- `),this.startBackgroundFlush();}}}catch{}},wl),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};function Tl(t,e){return e?t?{"2xx":t["2xx"]+e["2xx"],"3xx":t["3xx"]+e["3xx"],"4xx":t["4xx"]+e["4xx"],"5xx":t["5xx"]+e["5xx"],error:t.error+e.error}:{...e}:t}function Ms(t,e,r,n){let s=[],a=[],o=null,i=0,d=null,l=0,c=null,u=0,h=null,f=t.filter(g=>g.name===core.ATTACHMENT_NAME&&g.body),p=false;if(f.length>0)for(let g of f)try{let v=JSON.parse(g.body.toString());if(core.isTestRelicFilePayload(v)){s=s.concat(v.navigations),a=a.concat(v.apiAssertions),v.networkRequestsFile&&(o=v.networkRequestsFile,i+=v.networkRequestsCount),v.consoleLogsFile&&(d=v.consoleLogsFile,l+=v.consoleLogsCount),v.apiCallsFile&&(c=v.apiCallsFile,u+=v.apiCallsCount),h=Tl(h,v.apiStatusMix),p=!0;continue}if(core.isTestRelicDataPayload(v)){s=s.concat(v.navigations),Array.isArray(v.apiAssertions)&&(a=a.concat(v.apiAssertions)),i+=v.networkRequests?.length??0,u+=v.apiCalls?.length??0;let y=v.consoleLogs;Array.isArray(y)&&(l+=y.length),p=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
4298
- `);}return p||(s=e.filter(g=>g.type==="lambdatest-navigation"&&g.description).map(g=>{try{return JSON.parse(g.description)}catch{return null}}).filter(g=>g!==null)),s.length===0&&i===0&&u===0&&!n&&!p&&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.
4299
- `),{navigations:s,apiAssertions:a,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:d,consoleLogsCount:l,apiCallsFile:c,apiCallsCount:u,apiStatusMix:h}}function Ue(t=process.env){let e=Rl(t.TESTRELIC_CLOUD_PLATFORM);if(e)return {cloudPlatform:e,cloudBuildId:t.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:t.TESTRELIC_CLOUD_SESSION_ID||void 0};if(t.BROWSERSTACK_USERNAME||t.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:t.BROWSERSTACK_BUILD_NAME||t.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:t.BROWSERSTACK_SESSION_ID||void 0};if(t.LT_USERNAME||t.LAMBDATEST_USERNAME||t.LT_ACCESS_KEY||t.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:t.LT_BUILD||t.LAMBDATEST_BUILD||void 0,cloudSessionId:t.LT_SESSION_ID||t.LAMBDATEST_SESSION_ID||void 0};let r=t.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 Rl(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var Pl=5,ze=[1e3,3e3,9e3],ie=3,lr=3e4,El={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip",".json":"application/json"},ir=0,or=[];async function Ll(){ir>=Pl&&await new Promise(t=>or.push(t)),ir++;}function Nl(){ir--,or.length>0&&or.shift()();}async function je(t){return new Promise(e=>setTimeout(e,t))}function Dl(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return El[e]??"application/octet-stream"}function Fl(t){try{return fs$1.statSync(t).size}catch{return 0}}async function Bl(t,e,r,n,s){let a=`${t}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:s,type:r.type,sizeBytes:n});for(let i=0;i<ie;i++)try{let d=await J(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:o},lr);if(d.ok)return await d.json();if(d.status>=500&&i<ie-1){await je(ze[i]);continue}return null}catch{if(i<ie-1){await je(ze[i]);continue}return null}return null}async function Ol(t,e,r,n){let s=fs(n,lr);for(let a=0;a<ie;a++)try{let o=fs$1.createReadStream(e),i=stream.Readable.toWeb(o),d=await J(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(n)},body:i,duplex:"half"},s);if(d.ok)return !0;if(d.status>=500&&a<ie-1){await je(ze[a]);continue}return !1}catch{if(a<ie-1){await je(ze[a]);continue}return false}return false}async function ql(t,e,r){let n=`${t}/artifacts/confirm`;try{return (await J(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})},lr)).ok}catch{return false}}async function Hl(t,e,r,n){let s=Fl(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>n*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let a=Dl(r.filePath);await Ll();try{let o=await Bl(t,e,r,s,a);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await Ol(o.uploadUrl,r.filePath,a,s))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let d=await ql(t,e,o.artifactId);return {success:d,storageKey:o.storageKey,artifactId:o.artifactId,error:d?null:"confirm_failed"}}finally{Nl();}}async function Ps(t,e,r,n,s){let a=new Map,o=r.map(async i=>{if(s?.expired()){a.set(i.filePath,{success:false,storageKey:null,artifactId:null,error:"upload_budget_exhausted"});return}let d=await Hl(t,e,i,n);a.set(i.filePath,d);});return await Promise.allSettled(o),a}function cr(t){let r=t.getGitMetadata()?.remoteUrl;return r?be(r):t.getConfig()?.projectName??xe(process.cwd())}async function Es(t,e,r,n,s){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let o=t.getGitMetadata(),i=V(),d=Ue(),l=De();return (await ys(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:cr(t),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:n,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:s??d.cloudPlatform??null,cloudPlatform:d.cloudPlatform??null,cloudBuildId:d.cloudBuildId??null,cloudSessionId:d.cloudSessionId??null,...l?{runType:l}:{},testType:"e2e"}))?.runId??null}var zl=[{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"}],jl=true,Vl=50,dr={keyMap:new Map,visualKeyMap:new Map,total:0,uploaded:0};async function $l(t,e,r,n,s){let a=new Map,o=new Map;if(!(e?.uploadArtifacts??jl)||!await t.ensureValidToken())return dr;let l=[],c=new Map,u=new Map;for(let g of n){if(g.artifacts.screenshot){let y=path.join(g.outputDir,g.artifacts.screenshot);l.push({filePath:y,runId:r,testId:g.testId,type:"screenshot"}),c.set(y,{testId:g.testId,field:"screenshot"});}if(g.artifacts.video){let y=path.join(g.outputDir,g.artifacts.video);l.push({filePath:y,runId:r,testId:g.testId,type:"video"}),c.set(y,{testId:g.testId,field:"video"});}if(g.artifacts.trace){let y=path.join(g.outputDir,g.artifacts.trace);l.push({filePath:y,runId:r,testId:g.testId,type:"trace"}),c.set(y,{testId:g.testId,field:"trace"});}let v=g.visual??[];for(let y=0;y<v.length;y++){let b=v[y];if(b)for(let k of zl){let T=b[k.field];if(!T)continue;let P=path.join(g.outputDir,T);l.push({filePath:P,runId:r,testId:g.testId,type:k.type}),c.set(P,{testId:g.testId,field:"visual",visualIndex:y,visualKey:k.keyField});}}}if(l.length===0)return dr;let h=e?.artifactMaxSizeMb??Vl,f=await Ps(t.getEndpoint(),t.getAccessToken(),l,h,s),p=new Map;for(let[g,v]of f){if(!v.success||!v.storageKey)continue;let y=c.get(g);if(!y)continue;let b=p.get(y.testId)??{};if(y.field==="screenshot"&&(b.screenshotKey=v.storageKey),y.field==="video"&&(b.videoKey=v.storageKey),y.field==="trace"&&(b.traceKey=v.storageKey),y.field==="visual"&&y.visualIndex!==void 0&&y.visualKey){let k=u.get(y.testId)??new Map,T=k.get(y.visualIndex)??{};T[y.visualKey]=v.storageKey,k.set(y.visualIndex,T),u.set(y.testId,k);}p.set(y.testId,b);}for(let g of n){if(g.visual&&g.visual.length>0){let y=u.get(g.testId);o.set(g.testId,g.visual.map((b,k)=>({...b,...y?.get(k)??{}})));}let v=p.get(g.testId);a.set(g.testId,{...g.artifacts,...v?.screenshotKey?{screenshotKey:v.screenshotKey}:{},...v?.videoKey?{videoKey:v.videoKey}:{},...v?.traceKey?{traceKey:v.traceKey}:{}});}let m=Array.from(f.values()).filter(g=>g.success).length;return m>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${m} artifact(s) to cloud storage.
4300
- `),{keyMap:a,visualKeyMap:o,total:l.length,uploaded:m}}async function ur(t,e,r,n,s,a,o,i,d,l,c){let u={realtimeFinalizeAttempted:false,realtimeFinalized:false,batchAttempted:false,batchAcknowledged:false,artifactsTotal:0,artifactsUploaded:0,failureReason:null},h=new Fe(e?.uploadBudgetMs??12e4),f=p=>{u.failureReason||(u.failureReason=p);};try{if(t.isCloudMode()&&s&&(r==="realtime"||r==="both")){u.realtimeFinalizeAttempted=!0;let g=await t.ensureValidToken(),v=t.getGitMetadata(),y=Yt(c),b={finishedAt:o,duration:i,summary:d,...v?.commitMessage?{commitMessage:v.commitMessage}:{},testType:y.testType,...y.testType==="api"?{apiProtocol:y.apiProtocol,metadata:y.metadata}:{}};if(g){let k=await xs(t.getEndpoint(),t.getAccessToken(),s,b);if(u.realtimeFinalized=k,!k){f("finalize_failed_after_retries");let T=e?.queueDirectory??".testrelic/queue";we(T,n,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",b,{"Content-Type":"application/json"});}}else {f(t.getFailureReason()??"token_invalid");let k=e?.queueDirectory??".testrelic/queue";we(k,n,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",b,{"Content-Type":"application/json"});}}let p=new Map,m=new Map;if(t.isCloudMode()&&l&&l.length>0){let g=await $l(t,e,n,l,h);p=g.keyMap,m=g.visualKeyMap,u.artifactsTotal=g.total,u.artifactsUploaded=g.uploaded;}if(t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(u.batchAttempted=!0,await t.ensureValidToken()){let v=t.getGitMetadata(),y=V(),b=cr(t),k=Gl(Kl(a,p),m),T=Xt(k,b,v,y,Wl(c,m),Ue()),P=await vs(t.getEndpoint(),t.getAccessToken(),T,async()=>await t.ensureValidToken()?t.getAccessToken():null,e?.timeout,h);if(u.batchAcknowledged=P.success,!P.success){let S=P;f(S.reason);let w=e?.queueDirectory??".testrelic/queue";we(w,n,"batch",S.reason,S.targetEndpoint,S.method,S.payload,{"Content-Type":"application/json"});}}else {f(t.getFailureReason()??"token_invalid");let v=e?.queueDirectory??".testrelic/queue",y=t.getGitMetadata(),b=V(),k=cr(t),T=Xt(a,k,y,b,void 0,Ue());we(v,n,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",T,{"Content-Type":"application/json"});}await t.dispose();}catch(p){f(p instanceof Error?p.message:"unexpected_upload_error");try{await t.dispose();}catch{}}return u}function Wl(t,e){return !t||e.size===0?t:t.map(r=>{let n=e.get(r.testId);return n?{...r,visual:n}:r})}function Gl(t,e){if(e.size===0)return t;let r=t.timeline.map(n=>{let s=n.tests;if(!Array.isArray(s))return n;let a=false,o=s.map(i=>{let d=i.testId;if(!d)return i;let l=e.get(d);return l?(a=true,{...i,visual:l}):i});return a?{...n,tests:o}:n});return {...t,timeline:r}}function Kl(t,e){if(e.size===0)return t;let r=t.timeline.map(n=>{let s=n.testId;if(!s)return n;let a=e.get(s);return a?{...n,...a.screenshotKey?{screenshotKey:a.screenshotKey}:{},...a.videoKey?{videoKey:a.videoKey}:{}}:n});return {...t,timeline:r}}var Jl=new Set(["batch","realtime","both"]),ke=Object.freeze({attempted:false,acknowledged:false,runId:null,endpoint:null,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:"cloud reporting was never initialised"});function Yl(t){switch(t){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 t?`cloud mode off (${t}) \u2014 the run stayed local`:"cloud mode off \u2014 the run stayed local"}}function Ls(t,e,r){if(!t)return ke;if(!t.isCloudMode())return {...ke,detail:Yl(t.getFailureReason())};let n=e??"batch";if(!Jl.has(n))return {...ke,detail:`upload strategy '${n}' is not recognised \u2014 nothing was sent`};let s=t.getEndpoint(),a=n==="realtime"||n==="both";return a&&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:a?"run init failed \u2014 the platform did not acknowledge this run":`upload runs at the end of the run under the '${n}' strategy \u2014 not sent yet`}}function pr(t,e,r){if(!t.attempted)return t;if(!e)return {...t,detail:t.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:t.acknowledged};let n=t.acknowledged||e.batchAcknowledged,s=t.runId??(e.batchAcknowledged?r:null),a=e.realtimeFinalizeAttempted?e.realtimeFinalized:e.batchAcknowledged,o=null;return n?a||(o="run acknowledged but not closed out \u2014 finalize failed and was queued for retry"):o=e.failureReason?`upload failed (${e.failureReason}) \u2014 queued locally for retry`:"upload failed \u2014 the platform did not acknowledge this run",{attempted:true,acknowledged:n,runId:s,endpoint:t.endpoint,finalized:a,artifactsUploaded:e.artifactsUploaded,artifactsTotal:e.artifactsTotal,detail:o}}function Y(t){try{return fs$1.readFileSync(t,"utf-8").split(`
4301
- `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function nd(t){if(!t)return null;let e=t.split(`
4302
- `).map(a=>a.trim()).filter(Boolean);if(e.length===0)return null;let r=e.filter(a=>!/^Error:\s*expect\(/.test(a));if(r.length===0)return e[0]??null;let n=r[0],s=r[1];return s!==void 0&&/^Received:/.test(s)&&/^Expected:/.test(n)?`${n} \xB7 ${s}`:n}function gr(t){switch(t){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function sd(t,e,r){let n=`${t}::${e}::${r}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,16)}function ad(t){return t.length<=3?"":t[t.length-2]}function id(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function Hs(t){return t===null?"error":t>=200&&t<300?"2xx":t>=300&&t<400?"3xx":t>=400&&t<500?"4xx":t>=500&&t<600?"5xx":"error"}function od(t){let e={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},r=e;for(let n of t){let s=typeof n.responseStatusCode=="number"?n.responseStatusCode:null;r[Hs(s)]++;}return e}function Bs(t){if(t){for(let e of t)if(e.status==="failed")return {type:e.type,expected:Os(e.expected),actual:Os(e.actual),...e.expression?{expression:e.expression}:{}}}}function Os(t){if(t===void 0)return "undefined";if(t===null)return "null";let e;if(typeof t=="string")e=t;else try{e=JSON.stringify(t)??String(t);}catch{e=String(t);}return e.length>200?e.slice(0,200)+"\u2026":e}function $e(t,e){if(!t)return 0;let r=0;for(let n of t)n.status===e&&r++;return r}function Us(t,e){for(let r of t)e[r.category]=(e[r.category]??0)+1,r.children.length>0&&Us(r.children,e);}function ld(t){if(t.length===0)return null;let e=[...t].sort((n,s)=>n-s),r=e.reduce((n,s)=>n+s,0);return {avg:Math.round(r/e.length),min:e[0],max:e[e.length-1],p50:ee(e,50),p95:ee(e,95),p99:ee(e,99)}}var zs=2e5,We=1e5;function qs(t,e,r,n,s,a,o){let i={retryIndex:t,apiCalls:e?.length??0,apiUrls:[],methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,assertions:r.length,navigations:n.length,navUrls:[],networkRequests:s,consoleLogs:a,actionSteps:o?.length??0,actionCategories:{}};if(e){let l=new Set;for(let c of e){let u=typeof c.method=="string"?c.method:"OTHER";i.methodCounts[u]=(i.methodCounts[u]??0)+1;let h=typeof c.url=="string"?c.url:null;h&&l.size<We&&l.add(zt(h));let f=typeof c.responseStatusCode=="number"?c.responseStatusCode:typeof c.statusCode=="number"?c.statusCode:null,p=f!==null&&Number.isFinite(f)?f:null;i.statusRanges[Hs(p)]++;let m=typeof c.responseTimeMs=="number"?c.responseTimeMs:typeof c.durationMs=="number"?c.durationMs:null;m!==null&&Number.isFinite(m)&&i.responseTimes.length<zs&&i.responseTimes.push(m);}i.apiUrls=Array.from(l);}for(let l of r)l.status==="passed"?i.passedAssertions++:i.failedAssertions++;let d=new Set;for(let l of n)l.url&&d.size<We&&d.add(l.url);return i.navUrls=Array.from(d),o&&Us(o,i.actionCategories),i}function dd(){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 cd(t){return process.env.BROWSERSTACK_USERNAME?"BrowserStack":t?{"github-actions":"GitHub Actions","gitlab-ci":"GitLab CI",jenkins:"Jenkins",circleci:"CircleCI","bitbucket-pipelines":"Bitbucket Pipelines"}[t.provider]??"CI":"Local"}function ud(){let t=os$1.platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function pd(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:n}=e;if(n){let a=n.toLowerCase();return a==="chrome"||a==="chrome-stable"?"Chrome":a.startsWith("chrome-beta")?"Chrome Beta":a.startsWith("chrome-dev")?"Chrome Dev":a.startsWith("chrome-canary")?"Chrome Canary":a==="msedge"||a==="msedge-stable"?"Microsoft Edge":a.startsWith("msedge-beta")?"Edge Beta":a.startsWith("msedge-dev")?"Edge Dev":a.startsWith("msedge-canary")?"Edge Canary":n}if(r){let a=r.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":r}let s=e.defaultBrowserType;if(s){let a=s.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":s}}function fd(t,e,r){let n=r.parent?.project?.(),s="unknown";n!==void 0&&(n.use.isMobile===true?s="mobile":s="e2e");let a=["e2e","api","unit","mobile"];for(let d of a)if(t.some(l=>l===`@${d}`||l===d))return d;let o=e.replace(/\\/g,"/"),i=["e2e","api","unit"];for(let d of i)if(o.includes(`/${d}/`))return d;return s}var gd="__testrelic_api_config";function hd(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var Ge=class{constructor(e){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=ke;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=qr(e),this.apiConfig=Or(e);}upsertAggContribution(e,r){let n=this.streamingTestAgg.get(e);(!n||r.retryIndex>n.retryIndex)&&this.streamingTestAgg.set(e,r);}async onBegin(e,r){try{this.rootDir=e.rootDir,this.configDir=e.configFile?path.dirname(e.configFile):"";let n=e.updateSnapshots;if(this.updatingSnapshots=n==="all"||n==="changed",this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??crypto.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)
4303
- `),this.activeReportMode==="streaming"){let i=path.dirname(this.config.outputPath);this.streamingWriter=new he(i);let d=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let l={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(l);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let l=this.cloudClient.getAccessToken();l&&rr(this.cloudClient.getEndpoint(),l,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",d),process.on("SIGINT",d);}if(this.config.includeArtifacts){let i=path.dirname(this.config.outputPath);this.runTimestamp=Sn(path.join(i,"artifacts"));try{Xn(path.join(i,"artifacts"));}catch{}}let a=V();this.detectedOs=ud(),this.detectedSource=cd(a);let o=await Q(async()=>(this.cloudClient=new He(this.config.cloud),await this.cloudClient.initialize(),Es(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),Qn,"Cloud initialization");if(this.cloudRunId=o??null,o===void 0&&this.cloudClient?.switchToLocalMode("init_error"),this.cloudReceipt=Ls(this.cloudClient,this.config.cloud?.uploadStrategy,this.cloudRunId),this.activeReportMode!=="streaming"){let i=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let d=this.cloudClient.getAccessToken();d&&rr(this.cloudClient.getEndpoint(),d,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",i),process.on("SIGINT",i);}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:gd,description:hd(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let n=r,s=e.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=gr(n.status);let o=n.startTime.toISOString(),i=new Date(n.startTime.getTime()+n.duration).toISOString(),d=e.tags?[...e.tags]:e.annotations.filter(I=>I.type==="tag").map(I=>I.description??""),l=Ms(n.attachments,e.annotations,e.title,a==="skipped");(l.navigations.length>0||l.networkRequestsCount>0||l.apiCallsCount>0)&&(this.fixtureDataReceived=!0),l.navigations.length>0&&(this.navigationsCaptured=!0),!this.config.captureNavigation&&l.navigations.length>0&&(l={...l,navigations:[]});let c=null;if(a==="failed"||a==="flaky"){let M=(a==="flaky"?e.results.find(N=>N.status!=="passed")?.errors??[]:n.errors)[0];if(M){let N=Ur(this.config.redactPatterns),j=M.location?.file??null,E=l.apiAssertions.find(ca=>ca.status==="failed")?.location??null,re=E!==null&&(j===null||path.resolve(j)!==path.resolve(e.location.file)),Sr=re?E.file:j,Ze=re?E.line:M.location?.line??null,fe=null;this.config.includeCodeSnippets&&Ze!==null&&Sr&&(fe=Hr(Sr,Ze,this.config.codeContextLines),fe&&(fe=N(fe))),c={message:N(se(M.message??"Unknown error")),line:Ze,code:fe,stack:this.config.includeStackTrace&&M.stack?N(se(M.stack)):null};}}let u=e.titlePath().filter(Boolean),h=path.relative(this.rootDir||".",e.location.file).replace(/\\/g,"/"),f=ad(u),p=u.join(" > "),m=h,g=sd(m,f,p),v=fd(d,m,e),y=v!=="mobile"&&l.apiCallsCount>0?"api":v,b=s==="flaky",k=id(e.results),T=gr(e.expectedStatus),P=gr(n.status),S=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let I=path.dirname(this.config.outputPath),M=u[u.length-1]??e.title;S=Rn(n.attachments,M,n.retry,I,this.runTimestamp||void 0,g);}let w=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments)try{let I=Un(n.attachments,{updatingSnapshots:this.updatingSnapshots,failureMessage:n.errors.map(M=>M.message??"").join(`
4304
- `)});if(I.length>0){let M=path.dirname(this.config.outputPath),N=u[u.length-1]??e.title;w=An(I,N,n.retry,M,this.runTimestamp||void 0,g,this.configDir||this.rootDir||process.cwd());}}catch{}let A=this.config.includeActionSteps&&n.steps?as(n.steps,n.startTime):null,x=pd(e),C={titlePath:u,title:p,status:a,duration:n.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:n.retry,tags:d,failure:c,specFile:h,navigations:l.navigations,testId:g,filePath:m,suiteName:f,testType:y,isFlaky:b,retryStatus:k,expectedStatus:T,actualStatus:P,artifacts:S,visual:w,apiAssertions:l.apiAssertions,actions:A,networkRequestsFile:l.networkRequestsFile,networkRequestsCount:l.networkRequestsCount,consoleLogsFile:l.consoleLogsFile,consoleLogsCount:l.consoleLogsCount,apiCallsFile:l.apiCallsFile,apiCallsCount:l.apiCallsCount,apiStatusMix:l.apiStatusMix,browser:x,os:this.detectedOs||void 0,source:this.detectedSource||void 0},_=l.consoleLogsFile&&l.consoleLogsCount>0?Y(l.consoleLogsFile):void 0,L=l.networkRequestsFile&&l.networkRequestsCount>0?Y(l.networkRequestsFile):void 0,z=l.apiCallsFile&&l.apiCallsCount>0?Y(l.apiCallsFile):void 0,ce=z?Zt(z):void 0,ue=!L&&z?Qt(z):void 0,pe=l.apiAssertions&&l.apiAssertions.length>0?er(l.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:g,title:p,status:a,duration:n.duration,suiteName:f,filePath:m,testType:y,isFlaky:b,startedAt:o,completedAt:i,tags:d,failure:c,retry:n.retry,retryCount:e.results.length-1,retryStatus:k,browser:x,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...A&&A.length>0?{actions:A}:{},...l.navigations&&l.navigations.length>0?{navigations:l.navigations}:{},..._?{consoleLogs:_}:{},...L?{networkRequests:L}:ue?{networkRequests:ue}:{},...ce?{apiCalls:ce}:{},...pe?{protocolAssertions:pe}:{},...w&&w.length>0?{visual:w}:{}});try{let I=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(I==="realtime"||I==="both")){let M=this.cloudClient.getAccessToken();M&&bs(this.cloudClient.getEndpoint(),M,this.cloudRunId,this.buildCloudTestPayload(C));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let I=Qe(m,u,e.id??"",n.retry),M=n.retry===e.results.length-1,N={id:I,navigations:l.navigations,apiAssertions:l.apiAssertions,actions:A??[],artifacts:S,visual:w,failureDiagnostic:c,hasNetworkFile:l.networkRequestsFile!==null,networkRequestsCount:l.networkRequestsCount,hasConsoleFile:l.consoleLogsFile!==null,consoleLogsCount:l.consoleLogsCount,hasApiCallsFile:l.apiCallsFile!==null,apiCallsCount:l.apiCallsCount,startedAt:o};this.streamingWriter.writeTestDetail(I,N,{networkRequestsFile:l.networkRequestsFile,consoleLogsFile:l.consoleLogsFile,apiCallsFile:l.apiCallsFile});let j={id:I,title:u[u.length-1]??e.title,titlePath:u,filePath:m,status:a,...T!=="passed"?{expectedStatus:T}:{},duration:n.duration,project:u[1]??"",retryIndex:n.retry,tags:d,hasNetworkData:l.networkRequestsCount>0,hasConsoleData:l.consoleLogsCount>0,hasArtifacts:S!==null,hasActionSteps:(A?.length??0)>0,visualCount:w?.length??0,visualFailedCount:w?.filter(E=>E.status==="failed").length??0,domChangeCount:w?.reduce((E,re)=>E+(re.domChangeCount??0),0)??0,...(()=>{let E=w?.find(re=>re.diff);return E?.diff?{visualDiffPath:E.diff}:{}})(),errorMessage:nd(c?.message),networkCount:l.networkRequestsCount,consoleCount:l.consoleLogsCount,actionCount:A?.length??0,testType:y,apiCallCount:l.apiCallsCount,...l.apiStatusMix?{apiStatusMix:l.apiStatusMix}:{},assertionsPassed:$e(l.apiAssertions,"passed"),assertionsFailed:$e(l.apiAssertions,"failed"),...(()=>{let E=Bs(l.apiAssertions);return E?{firstFailedAssertion:E}:{}})(),isRetry:!M,retryGroupKey:et(m,u,e.id??"")};if(this.testIndex.push(j),M)switch(this.summaryCounters.total++,a){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}::${u.join(" > ")}`,qs(n.retry,z,l.apiAssertions,l.navigations,l.networkRequestsCount,l.consoleLogsCount,A)),(S||w)&&this.pendingArtifactEntries.push({testId:g,artifacts:S??{},visual:w,outputDir:path.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(e){try{let r=new Date().toISOString(),n=new Date(this.startedAt).getTime(),a=new Date(r).getTime()-n,o=this.activeReportMode==="streaming"?this.testIndex.some(d=>d.status!=="skipped"):this.collectedTests.some(d=>d.status!=="skipped");!this.fixtureDataReceived&&o&&process.stderr.write(`
4354
+ `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?be(this.gitMetadata.remoteUrl):null,r=e?hs(e):this.config.projectName??xe(process.cwd()),n=e??this.config.projectName??xe(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await fs(this.config.endpoint,this.authState.accessToken,n,r,this.config.timeout,this.gitMetadata?.branch);a&&(this.repoId=a.repoId,this.writeRepoCache(n,a.repoId,a.displayName));}catch{}!e&&!this.config.projectName&&!Yt(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
4355
+ `);}readRepoCache(e){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs$1.existsSync(r))return null;let n=fs$1.readFileSync(r,"utf-8"),s=JSON.parse(n);if(s.gitId!==e||Date.now()-s.resolvedAt>Tl)return null;let a=this.hashApiKey();return a&&s.apiKeyHash!==a?null:s}catch{return null}}writeRepoCache(e,r,n){if(!this.config)return;let s=path.join(this.config.queueDirectory,"..","cache"),a=path.join(s,"repo.json");try{fs$1.mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:e,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=a+".tmp";fs$1.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),fs$1.renameSync(i,a);}catch{}}hashApiKey(){return this.config?.apiKey?crypto.createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let e=this.authState.accessToken,r=this.config.queueDirectory,n=this.config.endpoint;this.flushPromise=Promise.race([Is(r,n,e),Es(Ps)]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let e=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await Gt(e))return;if(this.config?.apiKey){let n=await Kt(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Jt(n)){let s=n;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.
4356
+ `),this.startBackgroundFlush();}}}catch{}},Rl),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};function Ml(t,e){return e?t?{"2xx":t["2xx"]+e["2xx"],"3xx":t["3xx"]+e["3xx"],"4xx":t["4xx"]+e["4xx"],"5xx":t["5xx"]+e["5xx"],error:t.error+e.error}:{...e}:t}function Ns(t,e,r,n){let s=[],a=[],o=null,i=0,l=null,d=0,c=null,u=0,f=null,g=t.filter(v=>v.name===core.ATTACHMENT_NAME&&v.body),p=false;if(g.length>0)for(let v of g)try{let y=JSON.parse(v.body.toString());if(core.isTestRelicFilePayload(y)){s=s.concat(y.navigations),a=a.concat(y.apiAssertions),y.networkRequestsFile&&(o=y.networkRequestsFile,i+=y.networkRequestsCount),y.consoleLogsFile&&(l=y.consoleLogsFile,d+=y.consoleLogsCount),y.apiCallsFile&&(c=y.apiCallsFile,u+=y.apiCallsCount),f=Ml(f,y.apiStatusMix),p=!0;continue}if(core.isTestRelicDataPayload(y)){s=s.concat(y.navigations),Array.isArray(y.apiAssertions)&&(a=a.concat(y.apiAssertions)),i+=y.networkRequests?.length??0,u+=y.apiCalls?.length??0;let m=y.consoleLogs;Array.isArray(m)&&(d+=m.length),p=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
4357
+ `);}return p||(s=e.filter(v=>v.type==="lambdatest-navigation"&&v.description).map(v=>{try{return JSON.parse(v.description)}catch{return null}}).filter(v=>v!==null)),s.length===0&&i===0&&u===0&&!n&&!p&&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.
4358
+ `),{navigations:s,apiAssertions:a,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:c,apiCallsCount:u,apiStatusMix:f}}function Ue(t=process.env){let e=Pl(t.TESTRELIC_CLOUD_PLATFORM);if(e)return {cloudPlatform:e,cloudBuildId:t.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:t.TESTRELIC_CLOUD_SESSION_ID||void 0};if(t.BROWSERSTACK_USERNAME||t.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:t.BROWSERSTACK_BUILD_NAME||t.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:t.BROWSERSTACK_SESSION_ID||void 0};if(t.LT_USERNAME||t.LAMBDATEST_USERNAME||t.LT_ACCESS_KEY||t.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:t.LT_BUILD||t.LAMBDATEST_BUILD||void 0,cloudSessionId:t.LT_SESSION_ID||t.LAMBDATEST_SESSION_ID||void 0};let r=t.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 Pl(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var Fl=5,ze=[1e3,3e3,9e3],ie=3,cr=3e4,Bl={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip",".json":"application/json"},lr=0,dr=[];async function Ol(){lr>=Fl&&await new Promise(t=>dr.push(t)),lr++;}function ql(){lr--,dr.length>0&&dr.shift()();}async function je(t){return new Promise(e=>setTimeout(e,t))}function Hl(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return Bl[e]??"application/octet-stream"}function Ul(t){try{return fs$1.statSync(t).size}catch{return 0}}async function zl(t,e,r,n,s){let a=`${t}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:s,type:r.type,sizeBytes:n});for(let i=0;i<ie;i++)try{let l=await J(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:o},cr);if(l.ok)return await l.json();if(l.status>=500&&i<ie-1){await je(ze[i]);continue}return null}catch{if(i<ie-1){await je(ze[i]);continue}return null}return null}async function jl(t,e,r,n){let s=ms(n,cr);for(let a=0;a<ie;a++)try{let o=fs$1.createReadStream(e),i=stream.Readable.toWeb(o),l=await J(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(n)},body:i,duplex:"half"},s);if(l.ok)return !0;if(l.status>=500&&a<ie-1){await je(ze[a]);continue}return !1}catch{if(a<ie-1){await je(ze[a]);continue}return false}return false}async function Vl(t,e,r){let n=`${t}/artifacts/confirm`;try{return (await J(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})},cr)).ok}catch{return false}}async function $l(t,e,r,n){let s=Ul(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>n*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let a=Hl(r.filePath);await Ol();try{let o=await zl(t,e,r,s,a);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await jl(o.uploadUrl,r.filePath,a,s))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let l=await Vl(t,e,o.artifactId);return {success:l,storageKey:o.storageKey,artifactId:o.artifactId,error:l?null:"confirm_failed"}}finally{ql();}}async function Ls(t,e,r,n,s){let a=new Map,o=r.map(async i=>{if(s?.expired()){a.set(i.filePath,{success:false,storageKey:null,artifactId:null,error:"upload_budget_exhausted"});return}let l=await $l(t,e,i,n);a.set(i.filePath,l);});return await Promise.allSettled(o),a}function pr(t){let r=t.getGitMetadata()?.remoteUrl;return r?be(r):t.getConfig()?.projectName??xe(process.cwd())}async function Ds(t,e,r,n,s){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let o=t.getGitMetadata(),i=V(),l=Ue(),d=De();return (await ws(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:pr(t),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:n,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 Gl=[{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"}],Kl=true,Jl=50,ur={keyMap:new Map,visualKeyMap:new Map,total:0,uploaded:0};async function Yl(t,e,r,n,s){let a=new Map,o=new Map;if(!(e?.uploadArtifacts??Kl)||!await t.ensureValidToken())return ur;let d=[],c=new Map,u=new Map;for(let v of n){if(v.artifacts.screenshot){let m=path.join(v.outputDir,v.artifacts.screenshot);d.push({filePath:m,runId:r,testId:v.testId,type:"screenshot"}),c.set(m,{testId:v.testId,field:"screenshot"});}if(v.artifacts.video){let m=path.join(v.outputDir,v.artifacts.video);d.push({filePath:m,runId:r,testId:v.testId,type:"video"}),c.set(m,{testId:v.testId,field:"video"});}if(v.artifacts.trace){let m=path.join(v.outputDir,v.artifacts.trace);d.push({filePath:m,runId:r,testId:v.testId,type:"trace"}),c.set(m,{testId:v.testId,field:"trace"});}let y=v.visual??[];for(let m=0;m<y.length;m++){let b=y[m];if(b)for(let w of Gl){let C=b[w.field];if(!C)continue;let M=path.join(v.outputDir,C);d.push({filePath:M,runId:r,testId:v.testId,type:w.type}),c.set(M,{testId:v.testId,field:"visual",visualIndex:m,visualKey:w.keyField});}}}if(d.length===0)return ur;let f=e?.artifactMaxSizeMb??Jl,g=await Ls(t.getEndpoint(),t.getAccessToken(),d,f,s),p=new Map;for(let[v,y]of g){if(!y.success||!y.storageKey)continue;let m=c.get(v);if(!m)continue;let b=p.get(m.testId)??{};if(m.field==="screenshot"&&(b.screenshotKey=y.storageKey),m.field==="video"&&(b.videoKey=y.storageKey),m.field==="trace"&&(b.traceKey=y.storageKey),m.field==="visual"&&m.visualIndex!==void 0&&m.visualKey){let w=u.get(m.testId)??new Map,C=w.get(m.visualIndex)??{};C[m.visualKey]=y.storageKey,w.set(m.visualIndex,C),u.set(m.testId,w);}p.set(m.testId,b);}for(let v of n){if(v.visual&&v.visual.length>0){let m=u.get(v.testId);o.set(v.testId,v.visual.map((b,w)=>({...b,...m?.get(w)??{}})));}let y=p.get(v.testId);a.set(v.testId,{...v.artifacts,...y?.screenshotKey?{screenshotKey:y.screenshotKey}:{},...y?.videoKey?{videoKey:y.videoKey}:{},...y?.traceKey?{traceKey:y.traceKey}:{}});}let h=Array.from(g.values()).filter(v=>v.success).length;return h>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${h} artifact(s) to cloud storage.
4359
+ `),{keyMap:a,visualKeyMap:o,total:d.length,uploaded:h}}async function fr(t,e,r,n,s,a,o,i,l,d,c){let u={realtimeFinalizeAttempted:false,realtimeFinalized:false,batchAttempted:false,batchAcknowledged:false,artifactsTotal:0,artifactsUploaded:0,failureReason:null},f=new Fe(e?.uploadBudgetMs??12e4),g=p=>{u.failureReason||(u.failureReason=p);};try{if(t.isCloudMode()&&s&&(r==="realtime"||r==="both")){u.realtimeFinalizeAttempted=!0;let v=await t.ensureValidToken(),y=t.getGitMetadata(),m=Zt(c),b={finishedAt:o,duration:i,summary:l,...y?.commitMessage?{commitMessage:y.commitMessage}:{},testType:m.testType,...m.testType==="api"?{apiProtocol:m.apiProtocol,metadata:m.metadata}:{}};if(v){let w=await Cs(t.getEndpoint(),t.getAccessToken(),s,b);if(u.realtimeFinalized=w,!w){g("finalize_failed_after_retries");let C=e?.queueDirectory??".testrelic/queue";we(C,n,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",b,{"Content-Type":"application/json"});}}else {g(t.getFailureReason()??"token_invalid");let w=e?.queueDirectory??".testrelic/queue";we(w,n,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",b,{"Content-Type":"application/json"});}}let p=new Map,h=new Map;if(t.isCloudMode()&&d&&d.length>0){let v=await Yl(t,e,n,d,f);p=v.keyMap,h=v.visualKeyMap,u.artifactsTotal=v.total,u.artifactsUploaded=v.uploaded;}if(t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(u.batchAttempted=!0,await t.ensureValidToken()){let y=t.getGitMetadata(),m=V(),b=pr(t),w=Zl(Ql(a,p),h),C=Qt(w,b,y,m,Xl(c,h),Ue()),M=await xs(t.getEndpoint(),t.getAccessToken(),C,async()=>await t.ensureValidToken()?t.getAccessToken():null,e?.timeout,f);if(u.batchAcknowledged=M.success,!M.success){let T=M;g(T.reason);let k=e?.queueDirectory??".testrelic/queue";we(k,n,"batch",T.reason,T.targetEndpoint,T.method,T.payload,{"Content-Type":"application/json"});}}else {g(t.getFailureReason()??"token_invalid");let y=e?.queueDirectory??".testrelic/queue",m=t.getGitMetadata(),b=V(),w=pr(t),C=Qt(a,w,m,b,void 0,Ue());we(y,n,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",C,{"Content-Type":"application/json"});}await t.dispose();}catch(p){g(p instanceof Error?p.message:"unexpected_upload_error");try{await t.dispose();}catch{}}return u}function Xl(t,e){return !t||e.size===0?t:t.map(r=>{let n=e.get(r.testId);return n?{...r,visual:n}:r})}function Zl(t,e){if(e.size===0)return t;let r=t.timeline.map(n=>{let s=n.tests;if(!Array.isArray(s))return n;let a=false,o=s.map(i=>{let l=i.testId;if(!l)return i;let d=e.get(l);return d?(a=true,{...i,visual:d}):i});return a?{...n,tests:o}:n});return {...t,timeline:r}}function Ql(t,e){if(e.size===0)return t;let r=t.timeline.map(n=>{let s=n.testId;if(!s)return n;let a=e.get(s);return a?{...n,...a.screenshotKey?{screenshotKey:a.screenshotKey}:{},...a.videoKey?{videoKey:a.videoKey}:{}}:n});return {...t,timeline:r}}var ed=new Set(["batch","realtime","both"]),ke=Object.freeze({attempted:false,acknowledged:false,runId:null,endpoint:null,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:"cloud reporting was never initialised"});function td(t){switch(t){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 t?`cloud mode off (${t}) \u2014 the run stayed local`:"cloud mode off \u2014 the run stayed local"}}function Fs(t,e,r){if(!t)return ke;if(!t.isCloudMode())return {...ke,detail:td(t.getFailureReason())};let n=e??"batch";if(!ed.has(n))return {...ke,detail:`upload strategy '${n}' is not recognised \u2014 nothing was sent`};let s=t.getEndpoint(),a=n==="realtime"||n==="both";return a&&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:a?"run init failed \u2014 the platform did not acknowledge this run":`upload runs at the end of the run under the '${n}' strategy \u2014 not sent yet`}}function gr(t,e,r){if(!t.attempted)return t;if(!e)return {...t,detail:t.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:t.acknowledged};let n=t.acknowledged||e.batchAcknowledged,s=t.runId??(e.batchAcknowledged?r:null),a=e.realtimeFinalizeAttempted?e.realtimeFinalized:e.batchAcknowledged,o=null;return n?a||(o="run acknowledged but not closed out \u2014 finalize failed and was queued for retry"):o=e.failureReason?`upload failed (${e.failureReason}) \u2014 queued locally for retry`:"upload failed \u2014 the platform did not acknowledge this run",{attempted:true,acknowledged:n,runId:s,endpoint:t.endpoint,finalized:a,artifactsUploaded:e.artifactsUploaded,artifactsTotal:e.artifactsTotal,detail:o}}function Y(t){try{return fs$1.readFileSync(t,"utf-8").split(`
4360
+ `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function ld(t){if(!t)return null;let e=t.split(`
4361
+ `).map(a=>a.trim()).filter(Boolean);if(e.length===0)return null;let r=e.filter(a=>!/^Error:\s*expect\(/.test(a));if(r.length===0)return e[0]??null;let n=r[0],s=r[1];return s!==void 0&&/^Received:/.test(s)&&/^Expected:/.test(n)?`${n} \xB7 ${s}`:n}function mr(t){switch(t){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function dd(t,e,r){let n=`${t}::${e}::${r}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,16)}function cd(t){return t.length<=3?"":t[t.length-2]}function ud(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function js(t){return t===null?"error":t>=200&&t<300?"2xx":t>=300&&t<400?"3xx":t>=400&&t<500?"4xx":t>=500&&t<600?"5xx":"error"}function pd(t){let e={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},r=e;for(let n of t){let s=typeof n.responseStatusCode=="number"?n.responseStatusCode:null;r[js(s)]++;}return e}function Hs(t){if(t){for(let e of t)if(e.status==="failed")return {type:e.type,expected:Us(e.expected),actual:Us(e.actual),...e.expression?{expression:e.expression}:{}}}}function Us(t){if(t===void 0)return "undefined";if(t===null)return "null";let e;if(typeof t=="string")e=t;else try{e=JSON.stringify(t)??String(t);}catch{e=String(t);}return e.length>200?e.slice(0,200)+"\u2026":e}function $e(t,e){if(!t)return 0;let r=0;for(let n of t)n.status===e&&r++;return r}function Vs(t,e){for(let r of t)e[r.category]=(e[r.category]??0)+1,r.children.length>0&&Vs(r.children,e);}function fd(t){if(t.length===0)return null;let e=[...t].sort((n,s)=>n-s),r=e.reduce((n,s)=>n+s,0);return {avg:Math.round(r/e.length),min:e[0],max:e[e.length-1],p50:ee(e,50),p95:ee(e,95),p99:ee(e,99)}}var $s=2e5,We=1e5;function zs(t,e,r,n,s,a,o){let i={retryIndex:t,apiCalls:e?.length??0,apiUrls:[],methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,assertions:r.length,navigations:n.length,navUrls:[],networkRequests:s,consoleLogs:a,actionSteps:o?.length??0,actionCategories:{}};if(e){let d=new Set;for(let c of e){let u=typeof c.method=="string"?c.method:"OTHER";i.methodCounts[u]=(i.methodCounts[u]??0)+1;let f=typeof c.url=="string"?c.url:null;f&&d.size<We&&d.add(Vt(f));let g=typeof c.responseStatusCode=="number"?c.responseStatusCode:typeof c.statusCode=="number"?c.statusCode:null,p=g!==null&&Number.isFinite(g)?g:null;i.statusRanges[js(p)]++;let h=typeof c.responseTimeMs=="number"?c.responseTimeMs:typeof c.durationMs=="number"?c.durationMs:null;h!==null&&Number.isFinite(h)&&i.responseTimes.length<$s&&i.responseTimes.push(h);}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 n)d.url&&l.size<We&&l.add(d.url);return i.navUrls=Array.from(l),o&&Vs(o,i.actionCategories),i}function gd(){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 hd(t){return process.env.BROWSERSTACK_USERNAME?"BrowserStack":t?{"github-actions":"GitHub Actions","gitlab-ci":"GitLab CI",jenkins:"Jenkins",circleci:"CircleCI","bitbucket-pipelines":"Bitbucket Pipelines"}[t.provider]??"CI":"Local"}function md(){let t=os$1.platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function vd(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:n}=e;if(n){let a=n.toLowerCase();return a==="chrome"||a==="chrome-stable"?"Chrome":a.startsWith("chrome-beta")?"Chrome Beta":a.startsWith("chrome-dev")?"Chrome Dev":a.startsWith("chrome-canary")?"Chrome Canary":a==="msedge"||a==="msedge-stable"?"Microsoft Edge":a.startsWith("msedge-beta")?"Edge Beta":a.startsWith("msedge-dev")?"Edge Dev":a.startsWith("msedge-canary")?"Edge Canary":n}if(r){let a=r.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":r}let s=e.defaultBrowserType;if(s){let a=s.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":s}}function yd(t,e,r){let n=r.parent?.project?.(),s="unknown";n!==void 0&&(n.use.isMobile===true?s="mobile":s="e2e");let a=["e2e","api","unit","mobile"];for(let l of a)if(t.some(d=>d===`@${l}`||d===l))return l;let o=e.replace(/\\/g,"/"),i=["e2e","api","unit"];for(let l of i)if(o.includes(`/${l}/`))return l;return s}var bd="__testrelic_api_config";function xd(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var Ge=class{constructor(e){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=ke;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=Ur(e),this.apiConfig=Hr(e);}upsertAggContribution(e,r){let n=this.streamingTestAgg.get(e);(!n||r.retryIndex>n.retryIndex)&&this.streamingTestAgg.set(e,r);}async onBegin(e,r){try{this.rootDir=e.rootDir,this.configDir=e.configFile?path.dirname(e.configFile):"";let n=e.updateSnapshots;if(this.updatingSnapshots=n==="all"||n==="changed",this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??crypto.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)
4362
+ `),this.activeReportMode==="streaming"){let i=path.dirname(this.config.outputPath);this.streamingWriter=new he(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&&sr(this.cloudClient.getEndpoint(),d,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",l),process.on("SIGINT",l);}if(this.config.includeArtifacts){let i=path.dirname(this.config.outputPath);this.runTimestamp=An(path.join(i,"artifacts"));try{es(path.join(i,"artifacts"));}catch{}}let a=V();this.detectedOs=md(),this.detectedSource=hd(a);let o=await Q(async()=>(this.cloudClient=new He(this.config.cloud),await this.cloudClient.initialize(),Ds(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),rs,"Cloud initialization");if(this.cloudRunId=o??null,o===void 0&&this.cloudClient?.switchToLocalMode("init_error"),this.cloudReceipt=Fs(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&&sr(this.cloudClient.getEndpoint(),l,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",i),process.on("SIGINT",i);}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:bd,description:xd(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let n=r,s=e.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=mr(n.status);let o=n.startTime.toISOString(),i=new Date(n.startTime.getTime()+n.duration).toISOString(),l=e.tags?[...e.tags]:e.annotations.filter(I=>I.type==="tag").map(I=>I.description??""),d=Ns(n.attachments,e.annotations,e.title,a==="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(a==="failed"||a==="flaky"){let P=(a==="flaky"?e.results.find(D=>D.status!=="passed")?.errors??[]:n.errors)[0];if(P){let D=jr(this.config.redactPatterns),j=P.location?.file??null,E=d.apiAssertions.find(fa=>fa.status==="failed")?.location??null,re=E!==null&&(j===null||path.resolve(j)!==path.resolve(e.location.file)),Rr=re?E.file:j,Ze=re?E.line:P.location?.line??null,fe=null;this.config.includeCodeSnippets&&Ze!==null&&Rr&&(fe=zr(Rr,Ze,this.config.codeContextLines),fe&&(fe=D(fe))),c={message:D(se(P.message??"Unknown error")),line:Ze,code:fe,stack:this.config.includeStackTrace&&P.stack?D(se(P.stack)):null};}}let u=e.titlePath().filter(Boolean),f=path.relative(this.rootDir||".",e.location.file).replace(/\\/g,"/"),g=cd(u),p=u.join(" > "),h=f,v=dd(h,g,p),y=yd(l,h,e),m=y!=="mobile"&&d.apiCallsCount>0?"api":y,b=s==="flaky",w=ud(e.results),C=mr(e.expectedStatus),M=mr(n.status),T=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let I=path.dirname(this.config.outputPath),P=u[u.length-1]??e.title;T=In(n.attachments,P,n.retry,I,this.runTimestamp||void 0,v);}let k=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments)try{let I=Vn(n.attachments,{updatingSnapshots:this.updatingSnapshots,failureMessage:n.errors.map(P=>P.message??"").join(`
4363
+ `)});if(I.length>0){let P=path.dirname(this.config.outputPath),D=u[u.length-1]??e.title;k=Mn(I,D,n.retry,P,this.runTimestamp||void 0,v,this.configDir||this.rootDir||process.cwd());}}catch{}let A=this.config.includeActionSteps&&n.steps?ls(n.steps,n.startTime):null,x=vd(e),S={titlePath:u,title:p,status:a,duration:n.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:n.retry,tags:l,failure:c,specFile:f,navigations:d.navigations,testId:v,filePath:h,suiteName:g,testType:m,isFlaky:b,retryStatus:w,expectedStatus:C,actualStatus:M,artifacts:T,visual:k,apiAssertions:d.apiAssertions,actions:A,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount,apiStatusMix:d.apiStatusMix,browser:x,os:this.detectedOs||void 0,source:this.detectedSource||void 0},_=d.consoleLogsFile&&d.consoleLogsCount>0?Y(d.consoleLogsFile):void 0,N=d.networkRequestsFile&&d.networkRequestsCount>0?Y(d.networkRequestsFile):void 0,z=d.apiCallsFile&&d.apiCallsCount>0?Y(d.apiCallsFile):void 0,ce=z?er(z):void 0,ue=!N&&z?tr(z):void 0,pe=d.apiAssertions&&d.apiAssertions.length>0?rr(d.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:v,title:p,status:a,duration:n.duration,suiteName:g,filePath:h,testType:m,isFlaky:b,startedAt:o,completedAt:i,tags:l,failure:c,retry:n.retry,retryCount:e.results.length-1,retryStatus:w,browser:x,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...A&&A.length>0?{actions:A}:{},...d.navigations&&d.navigations.length>0?{navigations:d.navigations}:{},..._?{consoleLogs:_}:{},...N?{networkRequests:N}:ue?{networkRequests:ue}:{},...ce?{apiCalls:ce}:{},...pe?{protocolAssertions:pe}:{},...k&&k.length>0?{visual:k}:{}});try{let I=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(I==="realtime"||I==="both")){let P=this.cloudClient.getAccessToken();P&&ks(this.cloudClient.getEndpoint(),P,this.cloudRunId,this.buildCloudTestPayload(S));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let I=Qe(h,u,e.id??"",n.retry),P=n.retry===e.results.length-1,D={id:I,...C!=="passed"?{expectedStatus:C}:{},navigations:d.navigations,apiAssertions:d.apiAssertions,actions:A??[],artifacts:T,visual:k,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(I,D,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let j={id:I,title:u[u.length-1]??e.title,titlePath:u,filePath:h,status:a,...C!=="passed"?{expectedStatus:C}:{},duration:n.duration,project:u[1]??"",retryIndex:n.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:T!==null,hasActionSteps:(A?.length??0)>0,visualCount:k?.length??0,visualFailedCount:k?.filter(E=>E.status==="failed").length??0,domChangeCount:k?.reduce((E,re)=>E+(re.domChangeCount??0),0)??0,...(()=>{let E=k?.find(re=>re.diff);return E?.diff?{visualDiffPath:E.diff}:{}})(),errorMessage:ld(c?.message),networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:A?.length??0,testType:m,apiCallCount:d.apiCallsCount,...d.apiStatusMix?{apiStatusMix:d.apiStatusMix}:{},assertionsPassed:$e(d.apiAssertions,"passed"),assertionsFailed:$e(d.apiAssertions,"failed"),...(()=>{let E=Hs(d.apiAssertions);return E?{firstFailedAssertion:E}:{}})(),isRetry:!P,retryGroupKey:et(h,u,e.id??"")};if(this.testIndex.push(j),P)switch(this.summaryCounters.total++,a){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(`${h}::${u.join(" > ")}`,zs(n.retry,z,d.apiAssertions,d.navigations,d.networkRequestsCount,d.consoleLogsCount,A)),(T||k)&&this.pendingArtifactEntries.push({testId:v,artifacts:T??{},visual:k,outputDir:path.dirname(this.config.outputPath)}),S.actions=null,S.apiAssertions=null,S.navigations=[],S.artifacts=null,S.failure=null,S.networkRequestsFile=null,S.consoleLogsFile=null,S.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(S),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(e){try{let r=new Date().toISOString(),n=new Date(this.startedAt).getTime(),a=new Date(r).getTime()-n,o=this.activeReportMode==="streaming"?this.testIndex.some(l=>l.status!=="skipped"):this.collectedTests.some(l=>l.status!=="skipped");!this.fixtureDataReceived&&o&&process.stderr.write(`
4305
4364
  \u26A0 TestRelic: No fixture data received from any test.
4306
4365
  To enable network logs, video sync, and Test Navigation tracking, import the TestRelic fixture:
4307
4366
  import { test, expect } from '@testrelic/playwright-analytics/fixture';
@@ -4310,19 +4369,19 @@ ${s}
4310
4369
 
4311
4370
  `),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).
4312
4371
  `):process.stderr.write(`[testrelic] Test Navigation capture is disabled (captureNavigation: false). Remove the option or set it to true to capture the navigation graph.
4313
- `),await Q(()=>Cn(),Ut,"Artifact flush");let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let d=path.dirname(this.config.outputPath);i=Kn(d,this.runTimestamp);let l=path.join(d,"artifact-manifest.json"),c=JSON.stringify(i),u=l+".tmp";fs$1.writeFileSync(u,c,"utf-8"),fs$1.renameSync(u,l);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await Q(()=>this.finalizeStreamingReport(r,a,e,i),Ht,"Report finalization");else {let d=this.buildTimeline(),l=new Map;for(let f of this.collectedTests){let p=l.get(f.testId);(!p||f.retry>p.retry)&&l.set(f.testId,f);}let c=Array.from(l.values()),u=ss(c,d.length),h={schemaVersion:Ce,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:u,ci:V(),metadata:this.config.metadata,timeline:d,shardRunIds:null};if(this.writeReport(h),await Q(()=>It(h,this.config,i),Ut,"HTML report write"),jt(u,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let f=this.collectArtifactEntries(),p=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0;let m=await Q(()=>ur(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,h,r,a,u,f,p),Ht,"Cloud upload");this.cloudReceipt=pr(this.cloudReceipt,m,this.testRunId);}}}catch{}finally{await this.disposeCloudClient();}}async disposeCloudClient(){let e=this.cloudClient;e&&(this.cloudClient=null,await Q(()=>e.dispose(),es,"Cloud client shutdown"));}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=path.dirname(this.config.outputPath),r=[];for(let n of this.collectedTests)(n.artifacts||n.visual)&&r.push({testId:n.testId,artifacts:n.artifacts??{},visual:n.visual,outputDir:e});return r}async finalizeStreamingReport(e,r,n,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 a=new Map,o=new Map;for(let g of this.testIndex){let v=`${g.filePath}::${g.titlePath.join(" > ")}`,y=a.get(v);(y===void 0||g.retryIndex>y)&&a.set(v,g.retryIndex);}let i=0;for(let g of this.testIndex){let v=`${g.filePath}::${g.titlePath.join(" > ")}`,y=a.get(v);if(g.isRetry=g.retryIndex<y,g.isRetry)continue;switch(i++,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 b=o.get(g.filePath);switch(b||(b={filePath:g.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},o.set(g.filePath,b)),b.total++,g.status){case "passed":b.passed++;break;case "failed":b.failed++;break;case "flaky":b.flaky++;break;case "skipped":b.skipped++;break;case "timedout":b.timedOut++;break}}let d=Array.from(o.values()),l=dd();for(let g of this.streamingTestAgg.values()){l.volApiCalls+=g.apiCalls,l.volAssertions+=g.assertions,l.volNavigations+=g.navigations,l.volNetworkRequests+=g.networkRequests,l.volConsoleLogs+=g.consoleLogs,l.volActionSteps+=g.actionSteps;for(let v in g.methodCounts)l.methodCounts[v]=(l.methodCounts[v]??0)+g.methodCounts[v];l.statusRanges["2xx"]+=g.statusRanges["2xx"],l.statusRanges["3xx"]+=g.statusRanges["3xx"],l.statusRanges["4xx"]+=g.statusRanges["4xx"],l.statusRanges["5xx"]+=g.statusRanges["5xx"],l.statusRanges.error+=g.statusRanges.error,l.passedAssertions+=g.passedAssertions,l.failedAssertions+=g.failedAssertions;for(let v in g.actionCategories)l.actionCategoryCounts[v]=(l.actionCategoryCounts[v]??0)+g.actionCategories[v];for(let v of g.apiUrls){if(l.apiUrlSet.size>=We)break;l.apiUrlSet.add(v);}for(let v of g.navUrls){if(l.navUrlSet.size>=We)break;l.navUrlSet.add(v);}for(let v of g.responseTimes){if(l.responseTimes.length>=zs)break;l.responseTimes.push(v);}}this.summaryCounters.totalApiCalls=l.volApiCalls,this.summaryCounters.totalAssertions=l.volAssertions,this.summaryCounters.totalNavigations=l.volNavigations,this.summaryCounters.totalNetworkRequests=l.volNetworkRequests,this.summaryCounters.totalConsoleLogs=l.volConsoleLogs,this.summaryCounters.totalActionSteps=l.volActionSteps,this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let c={reporterTotal:this.summaryCounters.total,indexTotal:i,playwrightStatus:n.status,isValid:this.summaryCounters.total===i};c.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${c.reporterTotal}, index: ${c.indexTotal}
4314
- `);let u={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:l.apiUrlSet.size,apiCallsByMethod:{...l.methodCounts},apiCallsByStatusRange:{"2xx":l.statusRanges["2xx"],"3xx":l.statusRanges["3xx"],"4xx":l.statusRanges["4xx"],"5xx":l.statusRanges["5xx"],error:l.statusRanges.error},apiResponseTime:ld(l.responseTimes),totalAssertions:this.summaryCounters.totalAssertions,passedAssertions:l.passedAssertions,failedAssertions:l.failedAssertions,totalNavigations:this.summaryCounters.totalNavigations,uniqueNavigationUrls:l.navUrlSet.size,totalTimelineSteps:i,totalActionSteps:this.summaryCounters.totalActionSteps,actionStepsByCategory:{...l.actionCategoryCounts},visualChecks:this.summaryCounters.visualChecks,visualFailures:this.summaryCounters.visualFailures,visualDomChanges:this.summaryCounters.visualDomChanges},h={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:d,enrichedSummary:u,validation:c,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(h);let f={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(f),await It(this.buildStreamingReport(h,u,e,r),this.config,s),jt(u,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let p=this.streamingWriter.getReportDir();process.stderr.write(`[testrelic] Streaming report written to ${p}
4372
+ `),await Q(()=>Rn(),jt,"Artifact flush");let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let l=path.dirname(this.config.outputPath);i=Xn(l,this.runTimestamp);let d=path.join(l,"artifact-manifest.json"),c=JSON.stringify(i),u=d+".tmp";fs$1.writeFileSync(u,c,"utf-8"),fs$1.renameSync(u,d);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await Q(()=>this.finalizeStreamingReport(r,a,e,i),zt,"Report finalization");else {let l=this.buildTimeline(),d=new Map;for(let p of this.collectedTests){let h=d.get(p.testId);(!h||p.retry>h.retry)&&d.set(p.testId,p);}let c=Array.from(d.values()),u=os(c,l.length),f={schemaVersion:Ce,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:u,ci:V(),metadata:this.config.metadata,timeline:l,shardRunIds:null},g=it(u,c);if(this.writeReport(f),await Q(()=>Pt(f,this.config,i,g),jt,"HTML report write"),$t(u,this.config.outputPath,this.config.htmlReportPath,this.config.quiet,g),this.cloudClient){let p=this.collectArtifactEntries(),h=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0;let v=await Q(()=>fr(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,f,r,a,u,p,h),zt,"Cloud upload");this.cloudReceipt=gr(this.cloudReceipt,v,this.testRunId);}}}catch{}finally{await this.disposeCloudClient();}}async disposeCloudClient(){let e=this.cloudClient;e&&(this.cloudClient=null,await Q(()=>e.dispose(),ns,"Cloud client shutdown"));}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=path.dirname(this.config.outputPath),r=[];for(let n of this.collectedTests)(n.artifacts||n.visual)&&r.push({testId:n.testId,artifacts:n.artifacts??{},visual:n.visual,outputDir:e});return r}async finalizeStreamingReport(e,r,n,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 a=new Map,o=new Map;for(let m of this.testIndex){let b=`${m.filePath}::${m.titlePath.join(" > ")}`,w=a.get(b);(w===void 0||m.retryIndex>w)&&a.set(b,m.retryIndex);}let i=0,l=[];for(let m of this.testIndex){let b=`${m.filePath}::${m.titlePath.join(" > ")}`,w=a.get(b);if(m.isRetry=m.retryIndex<w,m.isRetry)continue;switch(l.push(m),i++,this.summaryCounters.total++,m.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+=m.visualCount??0,this.summaryCounters.visualFailures+=m.visualFailedCount??0,this.summaryCounters.visualDomChanges+=m.domChangeCount??0;let C=o.get(m.filePath);switch(C||(C={filePath:m.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},o.set(m.filePath,C)),C.total++,m.status){case "passed":C.passed++;break;case "failed":C.failed++;break;case "flaky":C.flaky++;break;case "skipped":C.skipped++;break;case "timedout":C.timedOut++;break}}let d=Array.from(o.values()),c=gd();for(let m of this.streamingTestAgg.values()){c.volApiCalls+=m.apiCalls,c.volAssertions+=m.assertions,c.volNavigations+=m.navigations,c.volNetworkRequests+=m.networkRequests,c.volConsoleLogs+=m.consoleLogs,c.volActionSteps+=m.actionSteps;for(let b in m.methodCounts)c.methodCounts[b]=(c.methodCounts[b]??0)+m.methodCounts[b];c.statusRanges["2xx"]+=m.statusRanges["2xx"],c.statusRanges["3xx"]+=m.statusRanges["3xx"],c.statusRanges["4xx"]+=m.statusRanges["4xx"],c.statusRanges["5xx"]+=m.statusRanges["5xx"],c.statusRanges.error+=m.statusRanges.error,c.passedAssertions+=m.passedAssertions,c.failedAssertions+=m.failedAssertions;for(let b in m.actionCategories)c.actionCategoryCounts[b]=(c.actionCategoryCounts[b]??0)+m.actionCategories[b];for(let b of m.apiUrls){if(c.apiUrlSet.size>=We)break;c.apiUrlSet.add(b);}for(let b of m.navUrls){if(c.navUrlSet.size>=We)break;c.navUrlSet.add(b);}for(let b of m.responseTimes){if(c.responseTimes.length>=$s)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 u={reporterTotal:this.summaryCounters.total,indexTotal:i,playwrightStatus:n.status,isValid:this.summaryCounters.total===i};u.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${u.reporterTotal}, index: ${u.indexTotal}
4373
+ `);let f={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:fd(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:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:d,enrichedSummary:f,validation:u,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(g);let p={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(p);let h=it(f,l);await Pt(this.buildStreamingReport(g,f,e,r),this.config,s,h),$t(f,this.config.outputPath,this.config.htmlReportPath,this.config.quiet,h);let v=this.streamingWriter.getReportDir();process.stderr.write(`[testrelic] Streaming report written to ${v}
4315
4374
  [testrelic] ${this.testIndex.length} test detail files on disk
4316
- [testrelic] View report: npx testrelic serve ${p}
4375
+ [testrelic] View report: npx testrelic serve ${v}
4317
4376
  `),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
4318
- `);let m=this.streamingWriter;try{if(this.cloudClient){let g=this.buildStreamingReport(h,u,e,r),v=this.collectArtifactEntries(),y=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0;let b=await ur(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,g,e,r,u,v,y);this.cloudReceipt=pr(this.cloudReceipt,b,this.testRunId);let k={...h,cloudUpload:this.cloudReceipt};try{m.writeSummary(k);}catch{}}}finally{m.dispose();}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(e,r,n,s){return {schemaVersion:Ce,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:n,totalDuration:s,summary:r,ci:V(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let e=process.memoryUsage(),r=e.heapUsed/1024/1024;if(r<200)return;let n=e.heapUsed/e.heapTotal;n>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
4377
+ `);let y=this.streamingWriter;try{if(this.cloudClient){let m=this.buildStreamingReport(g,f,e,r),b=this.collectArtifactEntries(),w=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0;let C=await fr(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,m,e,r,f,b,w);this.cloudReceipt=gr(this.cloudReceipt,C,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(e,r,n,s){return {schemaVersion:Ce,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:n,totalDuration:s,summary:r,ci:V(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let e=process.memoryUsage(),r=e.heapUsed/1024/1024;if(r<200)return;let n=e.heapUsed/e.heapTotal;n>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
4319
4378
  `),this.switchToStreamingMode()):n>.8&&r>=500&&!this.memoryPressureWarned&&(this.memoryPressureWarned=!0,process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
4320
- `));}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=path.dirname(this.config.outputPath);this.streamingWriter=new he(e);for(let r of this.collectedTests){let n=Qe(r.filePath,r.titlePath,r.testId,r.retry),s=r.apiCallsFile&&r.apiCallsCount>0?Y(r.apiCallsFile):void 0,a={id:n,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(n,a,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let o={id:n,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(`
4321
- `)[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:od(s)}:{},assertionsPassed:$e(r.apiAssertions,"passed"),assertionsFailed:$e(r.apiAssertions,"failed"),...(()=>{let i=Bs(r.apiAssertions);return i?{firstFailedAssertion:i}:{}})(),isRetry:!1,retryGroupKey:et(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(" > ")}`,qs(r.retry,s,r.apiAssertions??[],r.navigations??[],r.networkRequestsCount,r.consoleLogsCount,r.actions??null));}this.collectedTests.length=0;}catch{}}buildTimeline(){let e=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 ns(e,{navigationTypes:this.config.navigationTypes})}readJsonlFile(e){if(!e)return null;let r=Y(e);return r.length>0?r:null}toTestResult(e,r){let n=null,s=null,a=null;return r?.loadFiles&&(n=this.readJsonlFile(e.networkRequestsFile),s=this.readJsonlFile(e.consoleLogsFile),a=this.readJsonlFile(e.apiCallsFile)),{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,visual:e.visual,networkRequests:n,apiCalls:a,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:s}}buildCloudTestPayload(e){let r={title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retry:e.retry,retryCount:e.retryCount,retryStatus:e.retryStatus,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,visual:e.visual??[],actions:e.actions??[],navigations:e.navigations??[],steps:e.actions??[],browser:e.browser,os:e.os,source:e.source};if(e.apiAssertions&&e.apiAssertions.length>0&&(r.protocolAssertions=er(e.apiAssertions)),e.consoleLogsFile&&(r.consoleLogs=Y(e.consoleLogsFile)),e.networkRequestsFile&&(r.networkRequests=Y(e.networkRequestsFile)),e.apiCallsFile){let n=Y(e.apiCallsFile);r.apiCalls=Zt(n),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=Qt(n));}return r}writeReport(e){try{let r=JSON.stringify(e),n=this.config.outputPath,s=path.dirname(n);fs$1.mkdirSync(s,{recursive:!0});let a=n+".tmp";fs$1.writeFileSync(a,r,"utf-8"),fs$1.renameSync(a,n);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
4322
- `);}}};var xd=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function wd(t){let e=t.toLowerCase();return xd.some(r=>e.includes(r))}var Ke=class t{constructor(e,r){this.page=e;this.records=[];this.listeners=[];this.navCounters=[];this.pendingRequests=new Map;this.networkWriter=null;this.consoleWriter=null;this.pendingBodyReads=[];this.requestIdCounter=0;this.networkRequestCount=0;this.consoleLogCount=0;this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=e.goto.bind(e),this.origGoBack=e.goBack.bind(e),this.origGoForward=e.goForward.bind(e),this.origReload=e.reload.bind(e);try{this.includeNetworkStats&&(this.networkWriter=new H("network")),this.consoleWriter=new H("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,e]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:e.url,method:e.method,resourceType:e.resourceType,statusCode:0,responseTimeMs:Date.now()-e.startTimeMs,startedAt:e.startedAt,requestHeaders:e.headers,requestBody:e.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:e.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(e){switch(e){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.assembleNetworkStats();let e=this.records.map(r=>({url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:e,networkRequestsFile:this.networkWriter?.getCount()?this.networkWriter.getPath():null,networkRequestsCount:this.networkWriter?.getCount()??0,consoleLogsFile:this.consoleWriter?.getCount()?this.consoleWriter.getPath():null,consoleLogsCount:this.consoleWriter?.getCount()??0}}async flushLegacyAnnotations(e){}dispose(){let e=t.asPatchable(this.page);e.goto=this.origGoto,e.goBack=this.origGoBack,e.goForward=this.origGoForward,e.reload=this.origReload;for(let{event:r,handler:n}of this.listeners)this.page.off(r,n);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.assembleNetworkStats(),this.records}static asPatchable(e){return e}interceptMethods(){let e=this.page,r=t.asPatchable(e);r.goto=async(n,s)=>(this.recordNavigation(n,"goto"),this.origGoto(n,s)),r.goBack=async n=>{let s=await this.origGoBack(n);return this.recordNavigation(e.url(),"back"),s},r.goForward=async n=>{let s=await this.origGoForward(n);return this.recordNavigation(e.url(),"forward"),s},r.reload=async n=>(this.recordNavigation(e.url(),"refresh"),this.origReload(n));}attachListeners(){let e=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",e),this.listeners.push({event:"domcontentloaded",handler:e});let r=s=>{try{let a=s;if(typeof a.parentFrame=="function"&&a.parentFrame()!==null)return;let o=a.url(),i=this.records[this.records.length-1];if(i&&Date.now()-new Date(i.timestamp).getTime()<50&&i.url===o)return;this.recordNavigation(o,"navigation");}catch{}};this.page.on("framenavigated",r),this.listeners.push({event:"framenavigated",handler:r});let n=s=>{try{let a=s,o=a.type(),i=a.text();if(o==="debug"&&i.startsWith("__testrelic_nav:")){try{let d=JSON.parse(i.slice(16));d.type&&d.url&&this.recordNavigation(d.url,d.type);}catch{}return}{let d=null;try{let c=a.location();c&&c.url&&(d=`${c.url}:${c.lineNumber}:${c.columnNumber}`);}catch{}let l=t.mapConsoleType(o);this.consoleWriter&&(this.consoleWriter.append({level:l,text:i,timestamp:new Date().toISOString(),location:d}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=i=>{let d=this.records.length-1,l=this.counterForNav(d);l&&l.totalRequests++;try{let c=i,u=String(this.requestIdCounter++),h=c.postData()??null,f={url:c.url(),method:c.method(),resourceType:this.mapResourceType(c.resourceType()),headers:c.headers(),postData:h,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now(),navIndex:d};this.pendingRequests.set(u,f),i.__testrelic_id=u;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=i=>{try{let d=i,l=d.request().__testrelic_id,c=l?this.pendingRequests.get(l):void 0,u=this.counterForNav(c?c.navIndex:this.records.length-1);if(u){let y=d.status();y>=400&&(u.failedRequests++,u.failedRequestUrls.push(y+" "+d.url()));let b=d.headers()["content-length"];b&&(u.totalBytes+=parseInt(b,10)||0);let k=d.request().resourceType(),T=this.mapResourceType(k);u.byType[T]++;}if(!l||!c)return;this.pendingRequests.delete(l);let h=Date.now()-c.startTimeMs,f=d.headers(),p=f["content-type"]??null,m=parseInt(f["content-length"]??"0",10)||0,g=p?!wd(p):!1,v=(async()=>{let y=null;if(!g)try{y=(await d.body()).toString("utf-8");}catch{}let b={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:d.status(),responseTimeMs:h,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:y,responseHeaders:f,contentType:p,responseSize:m,requestBodyTruncated:c.postDataTruncated,responseBodyTruncated:!1,isBinary:g,error:null};this.networkWriter&&(this.networkWriter.append(b),this.networkRequestCount++);})();this.pendingBodyReads.push(v);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});let o=i=>{let d=i.__testrelic_id,l=d?this.pendingRequests.get(d):void 0,c=this.counterForNav(l?l.navIndex:this.records.length-1);if(c){c.failedRequests++;try{let u=i;c.failedRequestUrls.push("ERR "+u.url());}catch{}}try{let u=i;if(!d||!l)return;this.pendingRequests.delete(d);let h={url:l.url,method:l.method,resourceType:l.resourceType,statusCode:0,responseTimeMs:Date.now()-l.startTimeMs,startedAt:l.startedAt,requestHeaders:l.headers,requestBody:l.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:l.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:u.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(h),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",o),this.listeners.push({event:"requestfailed",handler:o});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let e=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(e,r){this.records.push({url:e,navigationType:r,timestamp:new Date().toISOString()}),this.includeNetworkStats&&this.navCounters.push(this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}counterForNav(e){return e>=0?this.navCounters[e]:void 0}assembleNetworkStats(){if(this.includeNetworkStats)for(let e=0;e<this.records.length;e++){let r=this.navCounters[e];r&&(this.records[e].networkStats={totalRequests:r.totalRequests,failedRequests:r.failedRequests,failedRequestUrls:[...r.failedRequestUrls],totalBytes:r.totalBytes,byType:{...r.byType}});}}mapResourceType(e){switch(e){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var vr=Symbol.for("__testrelic_call_id"),Cd="__testrelic_api_assertions",te=new WeakMap,oe=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(e){this.assertions.push(e);}getAssertions(){return this.assertions}setCurrentCallId(e){this.currentCallId=e;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(e){this.assertions.length!==0&&e.annotations.push({type:Cd,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}},js=new Map;function Sd(t){let e=js.get(t);if(e)return e;try{let r=t.startsWith("file://")?url.fileURLToPath(t):t,s=fs$1.readFileSync(r,"utf-8").split(`
4323
- `);return js.set(t,s),s}catch{return null}}var Vs=(()=>{let t=new Error().stack;if(!t)return null;for(let e of t.split(`
4324
- `)){let r=e.match(/at\s+(?:.*?\s+\()?(.+?):\d+:\d+\)?$/);if(!r||r[1].startsWith("node:"))continue;let n=Math.max(r[1].lastIndexOf("/"),r[1].lastIndexOf("\\"));return n>0?r[1].slice(0,n+1):null}return null})();function Td(t){if(!t.startsWith("file:"))return t;try{return url.fileURLToPath(t)}catch{return t}}function Rd(){let e=new Error().stack;if(!e)return null;let r=e.split(`
4325
- `);return $s(r,true)??$s(r,false)}function $s(t,e){for(let r of t){if(e&&Vs!==null&&r.includes(Vs)||r.includes("node_modules")||r.includes("node:internal")||r.includes(" at new Error")||r.includes(" at captureAssertionLocation")||r.includes(" at findFrame")||r.includes(" at expectWrapper")||r.includes(" at wrappedMatcher"))continue;let n=r.match(/at\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?$/);if(n)return {file:Td(n[1]),line:parseInt(n[2],10),column:parseInt(n[3],10)}}return null}function Ad(t,e){if(!t)return "custom";let r=t.toLowerCase();return r.includes(".status()")&&!r.includes(".statustext()")?r.includes(".ok()")?"statusOk":"status":r.includes(".ok()")?"statusOk":r.includes(".headers()")||r.includes(".headersarray()")?"header":r.includes("tomatchobject")||r.includes("toequal")?"bodyMatch":r.includes("tocontain")||r.includes("tostringcontaining")?"bodyContains":r.includes(".json()")||r.includes(".text()")?"bodyField":"custom"}function _d(t,e,r){let n=function(i,...d){let l=t(),c=e();if(!l||!c)return r(i,...d);let u=null;if(i!=null&&typeof i=="object"){let m=i[vr];typeof m=="string"&&(u=m);}if(!u&&i!==null&&i!==void 0&&typeof i=="object"&&(u=te.get(i)??null),u||(u=c.getCallIdForValue(i)),u||(u=l.getCurrentCallId()),!u)return r(i,...d);let h=Rd(),f;if(h){let m=Sd(h.file);m&&h.line>0&&h.line<=m.length&&(f=m[h.line-1].trim());}let p=r(i,...d);return u?Js(p,{tracker:l,callId:u,received:i,location:h??{file:"unknown",line:0},expression:f}):p},s=r,a=n;for(let o of Object.keys(s))a[o]=s[o];return n}var Ws=Symbol.for("testrelic.activeAssertionContext");function mr(){let t=globalThis,e=t[Ws];return e||(e={tracker:null,apiTracker:null},t[Ws]=e),e}function le(t,e){let r=mr();r.tracker=t,r.apiTracker=e;}function Je(t){return _d(()=>mr().tracker,()=>mr().apiTracker,t)}function Js(t,e){return new Proxy(t,{get(r,n,s){let a=Reflect.get(r,n,s);return typeof a!="function"||typeof n=="symbol"?a:n==="not"?Js(a,e):function(...i){let d=i[0],l="passed",c=e.received,u=null;try{let h=a.apply(this??r,i);return h&&typeof h=="object"&&typeof h.then=="function"?h.then(()=>{hr(e,n,d,c,"passed");},f=>{throw hr(e,n,d,c,"failed"),f}):h}catch(h){if(l="failed",u=h,h instanceof Error&&h.message){let f=h.message.match(/Received:\s*(.+)/);f&&(c=f[1]);}throw h}finally{(u!==null||l==="passed")&&hr(e,n,d,c,l);}}}})}function hr(t,e,r,n,s){let a=Ad(t.expression,t.received),o={callId:t.callId,type:a,expected:Gs(r),actual:Gs(n),status:s,location:t.location,expression:t.expression};t.tracker.recordAssertion(o);}function Gs(t){if(t==null)return t;if(typeof t=="string")return se(t);if(typeof t=="number"||typeof t=="boolean")return t;try{return JSON.stringify(t),t}catch{return String(t)}}var Ys="[REDACTED]";function br(t,e){if(t===null||e.length===0)return t;let r=new Set(e.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(t))Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=r.has(s.toLowerCase())?Ys:t[s]);return n}function Ye(t,e){if(t===null||e.length===0)return t;let r;try{r=JSON.parse(t);}catch{return t}if(typeof r!="object"||r===null)return t;let n=new Set(e.map(a=>a.toLowerCase())),s=yr(r,n);return JSON.stringify(s)}function yr(t,e){if(Array.isArray(t))return t.map(r=>yr(r,e));if(typeof t=="object"&&t!==null){let r={};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n];e.has(n.toLowerCase())?r[n]=Ys:r[n]=yr(s,e);}return r}return t}var Id=new Set(["access_token","api_key","token","sig"]);function xr(t){if(!t)return t;let e;try{e=new URL(t);}catch{return t}let r=false;for(let n of [...e.searchParams.keys()])Id.has(n.toLowerCase())&&(e.searchParams.delete(n),r=true);return r?e.toString():t}function Zs(t,e,r){if(r.length>0){for(let n of r)if(Xs(t,n))return false}if(e.length>0){for(let n of e)if(Xs(t,n))return true;return false}return true}function Xs(t,e){try{return e instanceof RegExp?e.test(t):Md(e).test(t)}catch{return process.stderr.write(`[testrelic] Invalid URL filter pattern: ${String(e)}
4326
- `),false}}function Md(t){let e="",r=0;for(;r<t.length;){let n=t[r];n==="*"&&t[r+1]==="*"?(e+=".*",r+=2,t[r]==="/"&&r++):n==="*"?(e+="[^/]*",r++):n==="?"?(e+="[^/]",r++):".+^${}()|[]\\".includes(n)?(e+="\\"+n,r++):(e+=n,r++);}return new RegExp(e)}var Pd=["get","post","put","patch","delete","head","fetch"],Ed=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Ld(t){let e=t.toLowerCase();return Ed.some(r=>e.includes(r))}function Nd(t){if(!t)return null;if(t.data!==void 0&&t.data!==null){let e=t.data;return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):JSON.stringify(e)}if(t.form!==void 0&&t.form!==null)return JSON.stringify(t.form);if(t.multipart!==void 0&&t.multipart!==null){let e=t.multipart,r={};for(let[n,s]of Object.entries(e))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?r[n]=String(s):s&&typeof s=="object"&&"name"in s?r[n]=`[file: ${s.name}]`:r[n]="[binary]";return JSON.stringify(r)}return null}function Qs(t){return t?"\u2022\u2022\u2022\u2022":""}function Dd(t){if(!t)return [];let e;for(let[n,s]of Object.entries(t))if(n.toLowerCase()==="cookie"){e=s;break}if(!e)return [];let r=[];for(let n of e.split(";")){let s=n.trim();if(!s)continue;let a=s.indexOf("="),o=a===-1?s:s.slice(0,a).trim(),i=a===-1?"":s.slice(a+1).trim();o&&r.push({name:o,value:Qs(i)});}return r}function Fd(t){let e=[];for(let r of t)for(let n of r.split(/,(?=\s*[A-Za-z0-9_.-]+=)/)){let s=n.trim();if(!s)continue;let a=s.split(";"),o=a[0].indexOf("=");if(o===-1)continue;let i=a[0].slice(0,o).trim(),d=a[0].slice(o+1).trim(),l=a.slice(1).map(c=>c.trim()).filter(Boolean).join(" \xB7 ")||void 0;i&&e.push({name:i,value:Qs(d),attributes:l});}return e}var Xe=class Xe{constructor(e,r,n){this.originals=new Map;this.apiCallWriter=null;this.statusMix={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0};this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=e,this.assertionTracker=r??null,this.apiConfig=n??Xe.DEFAULT_API_CONFIG;try{this.apiCallWriter=new H("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?te.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let r of Pd){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let e=this.context.dispose.bind(this.context);this.originals.set("dispose",e),this.context.dispose=async r=>(this.disposed=true,e(r));}tallyStatus(e){if(e===null||e<=0){this.statusMix.error++;return}if(e>=500){this.statusMix["5xx"]++;return}if(e>=400){this.statusMix["4xx"]++;return}if(e>=300){this.statusMix["3xx"]++;return}if(e>=200){this.statusMix["2xx"]++;return}this.statusMix.error++;}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0,apiStatusMix:{...this.statusMix}}}flushLegacyAnnotations(e){}dispose(){for(let[e,r]of this.originals)this.context[e]=r;this.originals.clear(),this.apiCallWriter?.close(),this.callCounter=0,this.apiCallCount=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCallCount(){return this.apiCallCount}tagResponseMethods(e,r){let{primitiveCallIds:n}=this,s=e.headers.bind(e);e.headers=function(){let f=s();return te.set(f,r),f};let a=e.headersArray.bind(e);e.headersArray=function(){let f=a();return te.set(f,r),f};let o=e.json.bind(e);e.json=async function(){let f=await o();return f!=null&&typeof f=="object"&&te.set(f,r),f};let i=e.status.bind(e);e.status=function(){let f=i();return n.set(f,r),f};let d=e.statusText.bind(e);e.statusText=function(){let f=d();return n.set(f,r),f};let l=e.ok.bind(e);e.ok=function(){let f=l();return n.set(f,r),f};let c=e.text.bind(e);e.text=async function(){let f=await c();return n.set(f,r),f};let u=e.body.bind(e);e.body=async function(){let f=await u();return te.set(f,r),f};}createWrapper(e,r){return async(n,s)=>{if(!Zs(n,this.apiConfig.apiIncludeUrls,this.apiConfig.apiExcludeUrls))return r(n,s);let a=`api-call-${this.callCounter++}`,o=new Date().toISOString(),i=e==="fetch"?(s?.method??"GET").toUpperCase():e.toUpperCase(),d=Nd(s),l=perf_hooks.performance.now();this._lastCallId=a,this.assertionTracker&&this.assertionTracker.setCurrentCallId(a);let c;try{c=await r(n,s);}catch(u){let h=perf_hooks.performance.now();try{let f=this.apiConfig.captureRequestBody?Ye(d,this.apiConfig.redactBodyFields):null,p={id:a,timestamp:o,method:i,url:xr(n),requestHeaders:null,requestBody:f,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((h-l)*100)/100,isBinary:!1,error:u instanceof Error?u.message:String(u)};this.apiCallWriter&&(this.apiCallWriter.append(p),this.apiCallCount++,this.tallyStatus(null));}catch{}throw u}try{let u=perf_hooks.performance.now(),h=c.headers(),f=h["content-type"]??null,p=f?!Ld(f):!1,m=null;this.apiConfig.captureRequestHeaders&&s?.headers&&(m=s.headers);let g=null;this.apiConfig.captureResponseHeaders&&(g=h);let v=this.apiConfig.captureRequestBody?d:null,y=null;if(this.apiConfig.captureResponseBody)try{p?y=(await c.body()).toString("base64"):y=await c.text();}catch{}let b=[],k=[];try{if(this.apiConfig.captureRequestHeaders&&(b=Dd(s?.headers)),this.apiConfig.captureResponseHeaders){let P=c.headersArray().filter(S=>S.name.toLowerCase()==="set-cookie").map(S=>S.value);k=Fd(P);}}catch{}m=br(m,this.apiConfig.redactHeaders),g=br(g,this.apiConfig.redactHeaders),v=Ye(v,this.apiConfig.redactBodyFields),y=Ye(y,this.apiConfig.redactBodyFields);let T={id:a,timestamp:o,method:i,url:xr(c.url()),requestHeaders:m,requestBody:v,responseStatusCode:c.status(),responseStatusText:c.statusText(),responseHeaders:g,responseBody:y,requestCookies:b.length?b:null,responseCookies:k.length?k:null,responseTimeMs:Math.round((u-l)*100)/100,isBinary:p,error:null};this.apiCallWriter&&(this.apiCallWriter.append(T),this.apiCallCount++,this.tallyStatus(T.responseStatusCode));}catch{}try{c[vr]=a,this.tagResponseMethods(c,a);}catch{}return c}}};Xe.DEFAULT_API_CONFIG=Object.freeze({trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]});var de=Xe;var Hd=[".png",".jpg",".jpeg"],Ud=/A snapshot doesn't exist at /;function zd(t){return t.wrote?t.existedBefore?"updated":"new":t.pass?"passed":"failed"}function jd(t){return t.status==="failed"&&!t.hadBaseline}function ea(t){if(!t)return null;try{let e=fs$1.statSync(t);return {size:e.size,mtimeMs:e.mtimeMs}}catch{return null}}function Vd(t,e){if(!Le(t))return null;try{return t.snapshotPath(e,{kind:"screenshot"})}catch{return null}}function $d(t){let e=t.toLowerCase();return Hd.some(r=>e.endsWith(r))?t:`${t}.png`}function Wd(){try{return test.test.info()}catch{return null}}function Gd(t,e,r){let n=a=>/^(.+)-(expected|actual|diff|previous)\.[A-Za-z0-9]+$/.exec(a)?.[1]??null,s=t.slice(e);if(r){for(let a of s)if(a.path===r&&/-expected\.[A-Za-z0-9]+$/.test(a.name))return n(a.name)}for(let a of s){let o=n(a.name);if(o)return o}return null}function Kd(t,e){return e?path.basename(e,path.extname(e)||".png"):t.replace(/\.[A-Za-z0-9]+$/,"")}async function Jd(t,e){if(e===null)return Ne("Attaching the baseline of a passing comparison"),null;try{let r=path.extname(e)||".png",n=path.basename(e,r);return await t.attach(`${n}-expected${r}`,{path:e}),n}catch{return null}}async function Yd(t,e){try{await t.attach(Ot,{body:Buffer.from(JSON.stringify([e])),contentType:"application/json"});}catch{}}async function kr(t,e,r={}){let n={...r};delete n.tags;let s=$d(e),a=Wd(),o=a?.attachments.length??0,i=a?.errors?.length??0,d=a?Vd(a,s):null,l=ea(d),c=true,u="";try{await test.expect(t).toHaveScreenshot(s,n);}catch(h){c=false,u=h instanceof Error?h.message:String(h);}if(a){let h=ea(d),f=d!==null?h!==null&&(l===null||l.size!==h.size||l.mtimeMs!==h.mtimeMs):(a.errors??[]).slice(i).some(v=>Ud.test(v.message??"")),p=zd({pass:c,wrote:f,existedBefore:l!==null}),g=(p==="passed"||p==="updated"?await Jd(a,d):Gd(a.attachments,o,d))??(jd({status:p,hadBaseline:l!==null})?Kd(s,d):null);g&&await Yd(a,{stem:g,name:e,status:p,...d?{committedPath:d}:{}});}return {pass:c,name:"toMatchVisualBaseline",message:()=>c?`Expected "${e}" to differ from its visual baseline, but it matched.`:u}}test.expect.extend({toMatchVisualBaseline:kr});function Qd(){try{return test.test.info()}catch{return null}}On(Je(test.expect),Qd);var ec="__testrelic_api_config",tc="__testrelic_config_trackApiCalls";function Cr(t){let e=t.annotations.find(n=>n.type===ec&&n.description!==void 0);if(e)try{return JSON.parse(e.description,rc)}catch{}let r=t.annotations.find(n=>n.type===tc&&n.description!==void 0);return r?{trackApiCalls:r.description!=="false",captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}:{trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}}function rc(t,e){if(typeof e=="object"&&e!==null&&e.__regexp===true&&typeof e.source=="string"){let{source:r,flags:n}=e;return new RegExp(r,n)}return e}var oa={page:async({page:t},e,r)=>{let n=new Ke(t);try{await n.init();}catch{}await e(t);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:d}=await n.getFileData(),l={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:d,apiCallsFile:null,apiCallsCount:0};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(l)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:t},e,r)=>{let n=Cr(r);if(!n.trackApiCalls){await e(t);return}let s=new oe,a=new de(t,s,n);a.intercept(),le(s,a);try{await e(t);}finally{le(null,null);}try{let{apiCallsFile:o,apiCallsCount:i,apiStatusMix:d}=a.getFileData(),l=n.captureAssertions?s.getData():[],c={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:l,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:o,apiCallsCount:i,apiStatusMix:d};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};test.test.extend(oa);Je(test.expect);var oc={request:async({request:t},e,r)=>{let n=Cr(r);if(!n.trackApiCalls){await e(t);return}let s=new oe,a=new de(t,s,n);a.intercept(),le(s,a);let o=null;try{o=new H("api-console");}catch{}let i=0,d=process.stdout.write,l=process.stderr.write;process.stdout.write=function(c,...u){try{let h=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!h.startsWith("[testrelic]")&&!h.startsWith("\u2139 TestRelic")&&!h.startsWith("\u2713 TestRelic")&&!h.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stdout",text:h.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return d.apply(process.stdout,[c,...u])},process.stderr.write=function(c,...u){try{let h=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!h.startsWith("[testrelic]")&&!h.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stderr",text:h.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return l.apply(process.stderr,[c,...u])};try{await e(t);}finally{process.stdout.write=d,process.stderr.write=l,le(null,null);}try{o?.close();let{apiCallsFile:c,apiCallsCount:u,apiStatusMix:h}=a.getFileData(),f=n.captureAssertions?s.getData():[],p={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:f,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:i>0?o?.getPath()??null:null,consoleLogsCount:i,apiCallsFile:c,apiCallsCount:u,apiStatusMix:h};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(p)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};var la="@testrelic/playwright-analytics";function dc(t){return Array.isArray(t)?t.some(e=>Array.isArray(e)&&typeof e[0]=="string"&&e[0]===la):false}function cc(t,e){let n={video:"on",screenshot:"on",trace:"on",...t.use??{}},s;Array.isArray(t.reporter)?s=t.reporter:typeof t.reporter=="string"?s=[[t.reporter]]:s=[["list"]];let a=dc(s)?s:[...s,[la,e??{}]];return test.defineConfig({...t,use:n,reporter:a})}var da=false;function _g(t,e,r="manual_record"){if(!t||!t.annotations){da||(da=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
4327
- `));return}let n={url:e,navigationType:r,timestamp:new Date().toISOString()};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}Object.defineProperty(exports,"ATTACHMENT_CONTENT_TYPE",{enumerable:true,get:function(){return core.ATTACHMENT_CONTENT_TYPE}});Object.defineProperty(exports,"ATTACHMENT_NAME",{enumerable:true,get:function(){return core.ATTACHMENT_NAME}});Object.defineProperty(exports,"PAYLOAD_VERSION",{enumerable:true,get:function(){return core.PAYLOAD_VERSION}});Object.defineProperty(exports,"isTestRelicDataPayload",{enumerable:true,get:function(){return core.isTestRelicDataPayload}});exports.SCHEMA_VERSION=Ce;exports.default=Ge;exports.defineConfig=cc;exports.recordNavigation=_g;exports.testRelicApiFixture=oc;exports.testRelicFixture=oa;//# sourceMappingURL=index.cjs.map
4379
+ `));}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=path.dirname(this.config.outputPath);this.streamingWriter=new he(e);for(let r of this.collectedTests){let n=Qe(r.filePath,r.titlePath,r.testId,r.retry),s=r.apiCallsFile&&r.apiCallsCount>0?Y(r.apiCallsFile):void 0,a={id:n,...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(n,a,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let o={id:n,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(`
4380
+ `)[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:pd(s)}:{},assertionsPassed:$e(r.apiAssertions,"passed"),assertionsFailed:$e(r.apiAssertions,"failed"),...(()=>{let i=Hs(r.apiAssertions);return i?{firstFailedAssertion:i}:{}})(),isRetry:!1,retryGroupKey:et(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(" > ")}`,zs(r.retry,s,r.apiAssertions??[],r.navigations??[],r.networkRequestsCount,r.consoleLogsCount,r.actions??null));}this.collectedTests.length=0;}catch{}}buildTimeline(){let e=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 is(e,{navigationTypes:this.config.navigationTypes})}readJsonlFile(e){if(!e)return null;let r=Y(e);return r.length>0?r:null}toTestResult(e,r){let n=null,s=null,a=null;return r?.loadFiles&&(n=this.readJsonlFile(e.networkRequestsFile),s=this.readJsonlFile(e.consoleLogsFile),a=this.readJsonlFile(e.apiCallsFile)),{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,visual:e.visual,networkRequests:n,apiCalls:a,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:s}}buildCloudTestPayload(e){let r={title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retry:e.retry,retryCount:e.retryCount,retryStatus:e.retryStatus,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,visual:e.visual??[],actions:e.actions??[],navigations:e.navigations??[],steps:e.actions??[],browser:e.browser,os:e.os,source:e.source};if(e.apiAssertions&&e.apiAssertions.length>0&&(r.protocolAssertions=rr(e.apiAssertions)),e.consoleLogsFile&&(r.consoleLogs=Y(e.consoleLogsFile)),e.networkRequestsFile&&(r.networkRequests=Y(e.networkRequestsFile)),e.apiCallsFile){let n=Y(e.apiCallsFile);r.apiCalls=er(n),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=tr(n));}return r}writeReport(e){try{let r=JSON.stringify(e),n=this.config.outputPath,s=path.dirname(n);fs$1.mkdirSync(s,{recursive:!0});let a=n+".tmp";fs$1.writeFileSync(a,r,"utf-8"),fs$1.renameSync(a,n);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
4381
+ `);}}};var Td=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Rd(t){let e=t.toLowerCase();return Td.some(r=>e.includes(r))}var Ke=class t{constructor(e,r){this.page=e;this.records=[];this.listeners=[];this.navCounters=[];this.pendingRequests=new Map;this.networkWriter=null;this.consoleWriter=null;this.pendingBodyReads=[];this.requestIdCounter=0;this.networkRequestCount=0;this.consoleLogCount=0;this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=e.goto.bind(e),this.origGoBack=e.goBack.bind(e),this.origGoForward=e.goForward.bind(e),this.origReload=e.reload.bind(e);try{this.includeNetworkStats&&(this.networkWriter=new H("network")),this.consoleWriter=new H("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,e]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:e.url,method:e.method,resourceType:e.resourceType,statusCode:0,responseTimeMs:Date.now()-e.startTimeMs,startedAt:e.startedAt,requestHeaders:e.headers,requestBody:e.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:e.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(e){switch(e){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.assembleNetworkStats();let e=this.records.map(r=>({url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:e,networkRequestsFile:this.networkWriter?.getCount()?this.networkWriter.getPath():null,networkRequestsCount:this.networkWriter?.getCount()??0,consoleLogsFile:this.consoleWriter?.getCount()?this.consoleWriter.getPath():null,consoleLogsCount:this.consoleWriter?.getCount()??0}}async flushLegacyAnnotations(e){}dispose(){let e=t.asPatchable(this.page);e.goto=this.origGoto,e.goBack=this.origGoBack,e.goForward=this.origGoForward,e.reload=this.origReload;for(let{event:r,handler:n}of this.listeners)this.page.off(r,n);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.assembleNetworkStats(),this.records}static asPatchable(e){return e}interceptMethods(){let e=this.page,r=t.asPatchable(e);r.goto=async(n,s)=>(this.recordNavigation(n,"goto"),this.origGoto(n,s)),r.goBack=async n=>{let s=await this.origGoBack(n);return this.recordNavigation(e.url(),"back"),s},r.goForward=async n=>{let s=await this.origGoForward(n);return this.recordNavigation(e.url(),"forward"),s},r.reload=async n=>(this.recordNavigation(e.url(),"refresh"),this.origReload(n));}attachListeners(){let e=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",e),this.listeners.push({event:"domcontentloaded",handler:e});let r=s=>{try{let a=s;if(typeof a.parentFrame=="function"&&a.parentFrame()!==null)return;let o=a.url(),i=this.records[this.records.length-1];if(i&&Date.now()-new Date(i.timestamp).getTime()<50&&i.url===o)return;this.recordNavigation(o,"navigation");}catch{}};this.page.on("framenavigated",r),this.listeners.push({event:"framenavigated",handler:r});let n=s=>{try{let a=s,o=a.type(),i=a.text();if(o==="debug"&&i.startsWith("__testrelic_nav:")){try{let l=JSON.parse(i.slice(16));l.type&&l.url&&this.recordNavigation(l.url,l.type);}catch{}return}{let l=null;try{let c=a.location();c&&c.url&&(l=`${c.url}:${c.lineNumber}:${c.columnNumber}`);}catch{}let d=t.mapConsoleType(o);this.consoleWriter&&(this.consoleWriter.append({level:d,text:i,timestamp:new Date().toISOString(),location:l}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=i=>{let l=this.records.length-1,d=this.counterForNav(l);d&&d.totalRequests++;try{let c=i,u=String(this.requestIdCounter++),f=c.postData()??null,g={url:c.url(),method:c.method(),resourceType:this.mapResourceType(c.resourceType()),headers:c.headers(),postData:f,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now(),navIndex:l};this.pendingRequests.set(u,g),i.__testrelic_id=u;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=i=>{try{let l=i,d=l.request().__testrelic_id,c=d?this.pendingRequests.get(d):void 0,u=this.counterForNav(c?c.navIndex:this.records.length-1);if(u){let m=l.status();m>=400&&(u.failedRequests++,u.failedRequestUrls.push(m+" "+l.url()));let b=l.headers()["content-length"];b&&(u.totalBytes+=parseInt(b,10)||0);let w=l.request().resourceType(),C=this.mapResourceType(w);u.byType[C]++;}if(!d||!c)return;this.pendingRequests.delete(d);let f=Date.now()-c.startTimeMs,g=l.headers(),p=g["content-type"]??null,h=parseInt(g["content-length"]??"0",10)||0,v=p?!Rd(p):!1,y=(async()=>{let m=null;if(!v)try{m=(await l.body()).toString("utf-8");}catch{}let b={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:l.status(),responseTimeMs:f,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:m,responseHeaders:g,contentType:p,responseSize:h,requestBodyTruncated:c.postDataTruncated,responseBodyTruncated:!1,isBinary:v,error:null};this.networkWriter&&(this.networkWriter.append(b),this.networkRequestCount++);})();this.pendingBodyReads.push(y);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});let o=i=>{let l=i.__testrelic_id,d=l?this.pendingRequests.get(l):void 0,c=this.counterForNav(d?d.navIndex:this.records.length-1);if(c){c.failedRequests++;try{let u=i;c.failedRequestUrls.push("ERR "+u.url());}catch{}}try{let u=i;if(!l||!d)return;this.pendingRequests.delete(l);let f={url:d.url,method:d.method,resourceType:d.resourceType,statusCode:0,responseTimeMs:Date.now()-d.startTimeMs,startedAt:d.startedAt,requestHeaders:d.headers,requestBody:d.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:d.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:u.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(f),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",o),this.listeners.push({event:"requestfailed",handler:o});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let e=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(e,r){this.records.push({url:e,navigationType:r,timestamp:new Date().toISOString()}),this.includeNetworkStats&&this.navCounters.push(this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}counterForNav(e){return e>=0?this.navCounters[e]:void 0}assembleNetworkStats(){if(this.includeNetworkStats)for(let e=0;e<this.records.length;e++){let r=this.navCounters[e];r&&(this.records[e].networkStats={totalRequests:r.totalRequests,failedRequests:r.failedRequests,failedRequestUrls:[...r.failedRequestUrls],totalBytes:r.totalBytes,byType:{...r.byType}});}}mapResourceType(e){switch(e){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var br=Symbol.for("__testrelic_call_id"),_d="__testrelic_api_assertions",te=new WeakMap,oe=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(e){this.assertions.push(e);}getAssertions(){return this.assertions}setCurrentCallId(e){this.currentCallId=e;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(e){this.assertions.length!==0&&e.annotations.push({type:_d,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}},Ws=new Map;function Id(t){let e=Ws.get(t);if(e)return e;try{let r=t.startsWith("file://")?url.fileURLToPath(t):t,s=fs$1.readFileSync(r,"utf-8").split(`
4382
+ `);return Ws.set(t,s),s}catch{return null}}var Gs=(()=>{let t=new Error().stack;if(!t)return null;for(let e of t.split(`
4383
+ `)){let r=e.match(/at\s+(?:.*?\s+\()?(.+?):\d+:\d+\)?$/);if(!r||r[1].startsWith("node:"))continue;let n=Math.max(r[1].lastIndexOf("/"),r[1].lastIndexOf("\\"));return n>0?r[1].slice(0,n+1):null}return null})();function Md(t){if(!t.startsWith("file:"))return t;try{return url.fileURLToPath(t)}catch{return t}}function Pd(){let e=new Error().stack;if(!e)return null;let r=e.split(`
4384
+ `);return Ks(r,true)??Ks(r,false)}function Ks(t,e){for(let r of t){if(e&&Gs!==null&&r.includes(Gs)||r.includes("node_modules")||r.includes("node:internal")||r.includes(" at new Error")||r.includes(" at captureAssertionLocation")||r.includes(" at findFrame")||r.includes(" at expectWrapper")||r.includes(" at wrappedMatcher"))continue;let n=r.match(/at\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?$/);if(n)return {file:Md(n[1]),line:parseInt(n[2],10),column:parseInt(n[3],10)}}return null}function Ed(t,e){if(!t)return "custom";let r=t.toLowerCase();return r.includes(".status()")&&!r.includes(".statustext()")?r.includes(".ok()")?"statusOk":"status":r.includes(".ok()")?"statusOk":r.includes(".headers()")||r.includes(".headersarray()")?"header":r.includes("tomatchobject")||r.includes("toequal")?"bodyMatch":r.includes("tocontain")||r.includes("tostringcontaining")?"bodyContains":r.includes(".json()")||r.includes(".text()")?"bodyField":"custom"}function Nd(t,e,r){let n=function(i,...l){let d=t(),c=e();if(!d||!c)return r(i,...l);let u=null;if(i!=null&&typeof i=="object"){let h=i[br];typeof h=="string"&&(u=h);}if(!u&&i!==null&&i!==void 0&&typeof i=="object"&&(u=te.get(i)??null),u||(u=c.getCallIdForValue(i)),u||(u=d.getCurrentCallId()),!u)return r(i,...l);let f=Pd(),g;if(f){let h=Id(f.file);h&&f.line>0&&f.line<=h.length&&(g=h[f.line-1].trim());}let p=r(i,...l);return u?Zs(p,{tracker:d,callId:u,received:i,location:f??{file:"unknown",line:0},expression:g}):p},s=r,a=n;for(let o of Object.keys(s))a[o]=s[o];return n}var Js=Symbol.for("testrelic.activeAssertionContext");function yr(){let t=globalThis,e=t[Js];return e||(e={tracker:null,apiTracker:null},t[Js]=e),e}function le(t,e){let r=yr();r.tracker=t,r.apiTracker=e;}function Je(t){return Nd(()=>yr().tracker,()=>yr().apiTracker,t)}function Zs(t,e){return new Proxy(t,{get(r,n,s){let a=Reflect.get(r,n,s);return typeof a!="function"||typeof n=="symbol"?a:n==="not"?Zs(a,e):function(...i){let l=i[0],d="passed",c=e.received,u=null;try{let f=a.apply(this??r,i);return f&&typeof f=="object"&&typeof f.then=="function"?f.then(()=>{vr(e,n,l,c,"passed");},g=>{throw vr(e,n,l,c,"failed"),g}):f}catch(f){if(d="failed",u=f,f instanceof Error&&f.message){let g=f.message.match(/Received:\s*(.+)/);g&&(c=g[1]);}throw f}finally{(u!==null||d==="passed")&&vr(e,n,l,c,d);}}}})}function vr(t,e,r,n,s){let a=Ed(t.expression,t.received),o={callId:t.callId,type:a,expected:Ys(r),actual:Ys(n),status:s,location:t.location,expression:t.expression};t.tracker.recordAssertion(o);}function Ys(t){if(t==null)return t;if(typeof t=="string")return se(t);if(typeof t=="number"||typeof t=="boolean")return t;try{return JSON.stringify(t),t}catch{return String(t)}}var Qs="[REDACTED]";function wr(t,e){if(t===null||e.length===0)return t;let r=new Set(e.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(t))Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=r.has(s.toLowerCase())?Qs:t[s]);return n}function Ye(t,e){if(t===null||e.length===0)return t;let r;try{r=JSON.parse(t);}catch{return t}if(typeof r!="object"||r===null)return t;let n=new Set(e.map(a=>a.toLowerCase())),s=xr(r,n);return JSON.stringify(s)}function xr(t,e){if(Array.isArray(t))return t.map(r=>xr(r,e));if(typeof t=="object"&&t!==null){let r={};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n];e.has(n.toLowerCase())?r[n]=Qs:r[n]=xr(s,e);}return r}return t}var Ld=new Set(["access_token","api_key","token","sig"]);function kr(t){if(!t)return t;let e;try{e=new URL(t);}catch{return t}let r=false;for(let n of [...e.searchParams.keys()])Ld.has(n.toLowerCase())&&(e.searchParams.delete(n),r=true);return r?e.toString():t}function ta(t,e,r){if(r.length>0){for(let n of r)if(ea(t,n))return false}if(e.length>0){for(let n of e)if(ea(t,n))return true;return false}return true}function ea(t,e){try{return e instanceof RegExp?e.test(t):Dd(e).test(t)}catch{return process.stderr.write(`[testrelic] Invalid URL filter pattern: ${String(e)}
4385
+ `),false}}function Dd(t){let e="",r=0;for(;r<t.length;){let n=t[r];n==="*"&&t[r+1]==="*"?(e+=".*",r+=2,t[r]==="/"&&r++):n==="*"?(e+="[^/]*",r++):n==="?"?(e+="[^/]",r++):".+^${}()|[]\\".includes(n)?(e+="\\"+n,r++):(e+=n,r++);}return new RegExp(e)}var Fd=["get","post","put","patch","delete","head","fetch"],Bd=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Od(t){let e=t.toLowerCase();return Bd.some(r=>e.includes(r))}function qd(t){if(!t)return null;if(t.data!==void 0&&t.data!==null){let e=t.data;return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):JSON.stringify(e)}if(t.form!==void 0&&t.form!==null)return JSON.stringify(t.form);if(t.multipart!==void 0&&t.multipart!==null){let e=t.multipart,r={};for(let[n,s]of Object.entries(e))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?r[n]=String(s):s&&typeof s=="object"&&"name"in s?r[n]=`[file: ${s.name}]`:r[n]="[binary]";return JSON.stringify(r)}return null}function ra(t){return t?"\u2022\u2022\u2022\u2022":""}function Hd(t){if(!t)return [];let e;for(let[n,s]of Object.entries(t))if(n.toLowerCase()==="cookie"){e=s;break}if(!e)return [];let r=[];for(let n of e.split(";")){let s=n.trim();if(!s)continue;let a=s.indexOf("="),o=a===-1?s:s.slice(0,a).trim(),i=a===-1?"":s.slice(a+1).trim();o&&r.push({name:o,value:ra(i)});}return r}function Ud(t){let e=[];for(let r of t)for(let n of r.split(/,(?=\s*[A-Za-z0-9_.-]+=)/)){let s=n.trim();if(!s)continue;let a=s.split(";"),o=a[0].indexOf("=");if(o===-1)continue;let i=a[0].slice(0,o).trim(),l=a[0].slice(o+1).trim(),d=a.slice(1).map(c=>c.trim()).filter(Boolean).join(" \xB7 ")||void 0;i&&e.push({name:i,value:ra(l),attributes:d});}return e}var Xe=class Xe{constructor(e,r,n){this.originals=new Map;this.apiCallWriter=null;this.statusMix={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0};this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=e,this.assertionTracker=r??null,this.apiConfig=n??Xe.DEFAULT_API_CONFIG;try{this.apiCallWriter=new H("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?te.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let r of Fd){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let e=this.context.dispose.bind(this.context);this.originals.set("dispose",e),this.context.dispose=async r=>(this.disposed=true,e(r));}tallyStatus(e){if(e===null||e<=0){this.statusMix.error++;return}if(e>=500){this.statusMix["5xx"]++;return}if(e>=400){this.statusMix["4xx"]++;return}if(e>=300){this.statusMix["3xx"]++;return}if(e>=200){this.statusMix["2xx"]++;return}this.statusMix.error++;}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0,apiStatusMix:{...this.statusMix}}}flushLegacyAnnotations(e){}dispose(){for(let[e,r]of this.originals)this.context[e]=r;this.originals.clear(),this.apiCallWriter?.close(),this.callCounter=0,this.apiCallCount=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCallCount(){return this.apiCallCount}tagResponseMethods(e,r){let{primitiveCallIds:n}=this,s=e.headers.bind(e);e.headers=function(){let g=s();return te.set(g,r),g};let a=e.headersArray.bind(e);e.headersArray=function(){let g=a();return te.set(g,r),g};let o=e.json.bind(e);e.json=async function(){let g=await o();return g!=null&&typeof g=="object"&&te.set(g,r),g};let i=e.status.bind(e);e.status=function(){let g=i();return n.set(g,r),g};let l=e.statusText.bind(e);e.statusText=function(){let g=l();return n.set(g,r),g};let d=e.ok.bind(e);e.ok=function(){let g=d();return n.set(g,r),g};let c=e.text.bind(e);e.text=async function(){let g=await c();return n.set(g,r),g};let u=e.body.bind(e);e.body=async function(){let g=await u();return te.set(g,r),g};}createWrapper(e,r){return async(n,s)=>{if(!ta(n,this.apiConfig.apiIncludeUrls,this.apiConfig.apiExcludeUrls))return r(n,s);let a=`api-call-${this.callCounter++}`,o=new Date().toISOString(),i=e==="fetch"?(s?.method??"GET").toUpperCase():e.toUpperCase(),l=qd(s),d=perf_hooks.performance.now();this._lastCallId=a,this.assertionTracker&&this.assertionTracker.setCurrentCallId(a);let c;try{c=await r(n,s);}catch(u){let f=perf_hooks.performance.now();try{let g=this.apiConfig.captureRequestBody?Ye(l,this.apiConfig.redactBodyFields):null,p={id:a,timestamp:o,method:i,url:kr(n),requestHeaders:null,requestBody:g,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((f-d)*100)/100,isBinary:!1,error:u instanceof Error?u.message:String(u)};this.apiCallWriter&&(this.apiCallWriter.append(p),this.apiCallCount++,this.tallyStatus(null));}catch{}throw u}try{let u=perf_hooks.performance.now(),f=c.headers(),g=f["content-type"]??null,p=g?!Od(g):!1,h=null;this.apiConfig.captureRequestHeaders&&s?.headers&&(h=s.headers);let v=null;this.apiConfig.captureResponseHeaders&&(v=f);let y=this.apiConfig.captureRequestBody?l:null,m=null;if(this.apiConfig.captureResponseBody)try{p?m=(await c.body()).toString("base64"):m=await c.text();}catch{}let b=[],w=[];try{if(this.apiConfig.captureRequestHeaders&&(b=Hd(s?.headers)),this.apiConfig.captureResponseHeaders){let M=c.headersArray().filter(T=>T.name.toLowerCase()==="set-cookie").map(T=>T.value);w=Ud(M);}}catch{}h=wr(h,this.apiConfig.redactHeaders),v=wr(v,this.apiConfig.redactHeaders),y=Ye(y,this.apiConfig.redactBodyFields),m=Ye(m,this.apiConfig.redactBodyFields);let C={id:a,timestamp:o,method:i,url:kr(c.url()),requestHeaders:h,requestBody:y,responseStatusCode:c.status(),responseStatusText:c.statusText(),responseHeaders:v,responseBody:m,requestCookies:b.length?b:null,responseCookies:w.length?w:null,responseTimeMs:Math.round((u-d)*100)/100,isBinary:p,error:null};this.apiCallWriter&&(this.apiCallWriter.append(C),this.apiCallCount++,this.tallyStatus(C.responseStatusCode));}catch{}try{c[br]=a,this.tagResponseMethods(c,a);}catch{}return c}}};Xe.DEFAULT_API_CONFIG=Object.freeze({trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]});var de=Xe;var $d=[".png",".jpg",".jpeg"],Wd=/A snapshot doesn't exist at /;function Gd(t){return t.wrote?t.existedBefore?"updated":"new":t.pass?"passed":"failed"}function Kd(t){return t.status==="failed"&&!t.hadBaseline}function na(t){if(!t)return null;try{let e=fs$1.statSync(t);return {size:e.size,mtimeMs:e.mtimeMs}}catch{return null}}function Jd(t,e){if(!Ne(t))return null;try{return t.snapshotPath(e,{kind:"screenshot"})}catch{return null}}function Yd(t){let e=t.toLowerCase();return $d.some(r=>e.endsWith(r))?t:`${t}.png`}function Xd(){try{return test.test.info()}catch{return null}}function Zd(t,e,r){let n=a=>/^(.+)-(expected|actual|diff|previous)\.[A-Za-z0-9]+$/.exec(a)?.[1]??null,s=t.slice(e);if(r){for(let a of s)if(a.path===r&&/-expected\.[A-Za-z0-9]+$/.test(a.name))return n(a.name)}for(let a of s){let o=n(a.name);if(o)return o}return null}function Qd(t,e){return e?path.basename(e,path.extname(e)||".png"):t.replace(/\.[A-Za-z0-9]+$/,"")}async function ec(t,e){if(e===null)return Le("Attaching the baseline of a passing comparison"),null;try{let r=path.extname(e)||".png",n=path.basename(e,r);return await t.attach(`${n}-expected${r}`,{path:e}),n}catch{return null}}async function tc(t,e){try{await t.attach(Ht,{body:Buffer.from(JSON.stringify([e])),contentType:"application/json"});}catch{}}async function Sr(t,e,r={}){let n={...r};delete n.tags;let s=Yd(e),a=Xd(),o=a?.attachments.length??0,i=a?.errors?.length??0,l=a?Jd(a,s):null,d=na(l),c=true,u="";try{await test.expect(t).toHaveScreenshot(s,n);}catch(f){c=false,u=f instanceof Error?f.message:String(f);}if(a){let f=na(l),g=l!==null?f!==null&&(d===null||d.size!==f.size||d.mtimeMs!==f.mtimeMs):(a.errors??[]).slice(i).some(y=>Wd.test(y.message??"")),p=Gd({pass:c,wrote:g,existedBefore:d!==null}),v=(p==="passed"||p==="updated"?await ec(a,l):Zd(a.attachments,o,l))??(Kd({status:p,hadBaseline:d!==null})?Qd(s,l):null);v&&await tc(a,{stem:v,name:e,status:p,...l?{committedPath:l}:{}});}return {pass:c,name:"toMatchVisualBaseline",message:()=>c?`Expected "${e}" to differ from its visual baseline, but it matched.`:u}}test.expect.extend({toMatchVisualBaseline:Sr});function sc(){try{return test.test.info()}catch{return null}}Un(Je(test.expect),sc);var ac="__testrelic_api_config",ic="__testrelic_config_trackApiCalls";function Tr(t){let e=t.annotations.find(n=>n.type===ac&&n.description!==void 0);if(e)try{return JSON.parse(e.description,oc)}catch{}let r=t.annotations.find(n=>n.type===ic&&n.description!==void 0);return r?{trackApiCalls:r.description!=="false",captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}:{trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}}function oc(t,e){if(typeof e=="object"&&e!==null&&e.__regexp===true&&typeof e.source=="string"){let{source:r,flags:n}=e;return new RegExp(r,n)}return e}var ca={page:async({page:t},e,r)=>{let n=new Ke(t);try{await n.init();}catch{}await e(t);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l}=await n.getFileData(),d={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l,apiCallsFile:null,apiCallsCount:0};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:t},e,r)=>{let n=Tr(r);if(!n.trackApiCalls){await e(t);return}let s=new oe,a=new de(t,s,n);a.intercept(),le(s,a);try{await e(t);}finally{le(null,null);}try{let{apiCallsFile:o,apiCallsCount:i,apiStatusMix:l}=a.getFileData(),d=n.captureAssertions?s.getData():[],c={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:d,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:o,apiCallsCount:i,apiStatusMix:l};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};test.test.extend(ca);Je(test.expect);var pc={request:async({request:t},e,r)=>{let n=Tr(r);if(!n.trackApiCalls){await e(t);return}let s=new oe,a=new de(t,s,n);a.intercept(),le(s,a);let o=null;try{o=new H("api-console");}catch{}let i=0,l=process.stdout.write,d=process.stderr.write;process.stdout.write=function(c,...u){try{let f=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!f.startsWith("[testrelic]")&&!f.startsWith("\u2139 TestRelic")&&!f.startsWith("\u2713 TestRelic")&&!f.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stdout",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return l.apply(process.stdout,[c,...u])},process.stderr.write=function(c,...u){try{let f=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!f.startsWith("[testrelic]")&&!f.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stderr",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return d.apply(process.stderr,[c,...u])};try{await e(t);}finally{process.stdout.write=l,process.stderr.write=d,le(null,null);}try{o?.close();let{apiCallsFile:c,apiCallsCount:u,apiStatusMix:f}=a.getFileData(),g=n.captureAssertions?s.getData():[],p={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:g,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:i>0?o?.getPath()??null:null,consoleLogsCount:i,apiCallsFile:c,apiCallsCount:u,apiStatusMix:f};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(p)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};var ua="@testrelic/playwright-analytics";function gc(t){return Array.isArray(t)?t.some(e=>Array.isArray(e)&&typeof e[0]=="string"&&e[0]===ua):false}function hc(t,e){let n={video:"on",screenshot:"on",trace:"on",...t.use??{}},s;Array.isArray(t.reporter)?s=t.reporter:typeof t.reporter=="string"?s=[[t.reporter]]:s=[["list"]];let a=gc(s)?s:[...s,[ua,e??{}]];return test.defineConfig({...t,use:n,reporter:a})}var pa=false;function Fg(t,e,r="manual_record"){if(!t||!t.annotations){pa||(pa=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
4386
+ `));return}let n={url:e,navigationType:r,timestamp:new Date().toISOString()};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}Object.defineProperty(exports,"ATTACHMENT_CONTENT_TYPE",{enumerable:true,get:function(){return core.ATTACHMENT_CONTENT_TYPE}});Object.defineProperty(exports,"ATTACHMENT_NAME",{enumerable:true,get:function(){return core.ATTACHMENT_NAME}});Object.defineProperty(exports,"PAYLOAD_VERSION",{enumerable:true,get:function(){return core.PAYLOAD_VERSION}});Object.defineProperty(exports,"isTestRelicDataPayload",{enumerable:true,get:function(){return core.isTestRelicDataPayload}});exports.SCHEMA_VERSION=Ce;exports.default=Ge;exports.defineConfig=hc;exports.recordNavigation=Fg;exports.testRelicApiFixture=pc;exports.testRelicFixture=ca;//# sourceMappingURL=index.cjs.map
4328
4387
  //# sourceMappingURL=index.cjs.map