@testrelic/playwright-analytics 2.16.4-next.193 → 2.16.4-next.230
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/api-fixture.cjs +7 -7
- package/dist/api-fixture.cjs.map +1 -1
- package/dist/api-fixture.d.cts +4 -1
- package/dist/api-fixture.d.ts +4 -1
- package/dist/api-fixture.js +7 -7
- package/dist/api-fixture.js.map +1 -1
- package/dist/cli.cjs +7 -2
- package/dist/fixture-marker-Buz_DCfv.d.cts +34 -0
- package/dist/fixture-marker-Buz_DCfv.d.ts +34 -0
- package/dist/fixture.cjs +6 -6
- package/dist/fixture.cjs.map +1 -1
- package/dist/fixture.d.cts +6 -1
- package/dist/fixture.d.ts +6 -1
- package/dist/fixture.js +6 -6
- package/dist/fixture.js.map +1 -1
- package/dist/index.cjs +112 -112
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +112 -112
- package/dist/index.js.map +1 -1
- package/dist/reporter-entry.cjs +107 -107
- package/dist/reporter-entry.cjs.map +1 -1
- package/dist/reporter-entry.d.cts +10 -0
- package/dist/reporter-entry.d.ts +10 -0
- package/dist/reporter-entry.js +107 -107
- package/dist/reporter-entry.js.map +1 -1
- package/package.json +3 -3
package/dist/reporter-entry.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {randomUUID,createHash}from'crypto';import {writeFileSync,renameSync,mkdirSync,copyFileSync,unlinkSync,existsSync,readFileSync,appendFileSync,readdirSync,statSync,openSync,readSync,closeSync,createReadStream,rmSync}from'fs';import {join,dirname,resolve,relative,extname,basename}from'path';import {tmpdir,platform}from'os';import {isValidConfig,createError,ErrorCode,ATTACHMENT_NAME,isTestRelicFilePayload,isTestRelicDataPayload,isValidEndpointUrl,isValidCloudConfig,isValidQueueEntry}from'@testrelic/core';import {spawn,execFile,execSync}from'child_process';import {createServer}from'http';import {createInterface}from'readline';import {copyFile}from'fs/promises';import {gzip}from'zlib';import {promisify}from'util';import {Readable}from'stream';var
|
|
2
|
-
`),false}}moveFile(
|
|
3
|
-
`);}}}writeIndex(
|
|
4
|
-
`),s}catch{}let n=dirname(
|
|
5
|
-
`);let c=
|
|
6
|
-
`);if(
|
|
7
|
-
`)}catch{return null}}function
|
|
1
|
+
import {randomUUID,createHash}from'crypto';import {writeFileSync,renameSync,mkdirSync,copyFileSync,unlinkSync,existsSync,readFileSync,appendFileSync,readdirSync,statSync,openSync,readSync,closeSync,createReadStream,rmSync}from'fs';import {join,dirname,resolve,relative,extname,basename}from'path';import {tmpdir,platform}from'os';import {isValidConfig,createError,ErrorCode,ATTACHMENT_NAME,isTestRelicFilePayload,isTestRelicDataPayload,isValidEndpointUrl,isValidCloudConfig,isValidQueueEntry}from'@testrelic/core';import {spawn,execFile,execSync}from'child_process';import {createServer}from'http';import {createInterface}from'readline';import {copyFile}from'fs/promises';import {gzip}from'zlib';import {promisify}from'util';import {Readable}from'stream';var Ss=".testrelic-report";function We(t,e,r,a){let s=`${t}|${e.join("|")}|${r}|${a}`;return createHash("sha256").update(s).digest("hex").substring(0,12)}function Ke(t,e,r){let a=`${t}|${e.join("|")}|${r}`;return createHash("sha256").update(a).digest("hex").substring(0,12)}var le=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=join(e,Ss),this.testsDir=join(this.reportDir,"tests"),mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}getTestDetailPaths(e){let r=join(this.testsDir,e);return {meta:join(r,"meta.json"),networkRequests:join(r,"network.jsonl"),consoleLogs:join(r,"console.jsonl"),apiCalls:join(r,"api-calls.jsonl")}}writeTestDetail(e,r,a){try{let s=join(this.testsDir,e);mkdirSync(s,{recursive:!0});let n=this.getTestDetailPaths(e),i=n.meta,o=i+".tmp",l=JSON.stringify(r);return writeFileSync(o,l,"utf-8"),renameSync(o,i),this.totalBytesWritten+=Buffer.byteLength(l,"utf-8"),a?.networkRequestsFile&&this.moveFile(a.networkRequestsFile,n.networkRequests),a?.consoleLogsFile&&this.moveFile(a.consoleLogsFile,n.consoleLogs),a?.apiCallsFile&&this.moveFile(a.apiCallsFile,n.apiCalls),!0}catch(s){let n=s instanceof Error?s.message:String(s);return this.writeErrors.push({testId:e,error:n,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${e}: ${n}
|
|
2
|
+
`),false}}moveFile(e,r){try{renameSync(e,r);}catch{try{copyFileSync(e,r);try{unlinkSync(e);}catch{}}catch(a){process.stderr.write(`[testrelic] Failed to move file ${e} \u2192 ${r}: ${a instanceof Error?a.message:String(a)}
|
|
3
|
+
`);}}}writeIndex(e){let r=join(this.reportDir,"index.json"),a=r+".tmp",s=JSON.stringify(e);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(e){let r=join(this.reportDir,"index-compact.json"),a=r+".tmp",s=e.map(({titlePath:i,project:o,...l})=>l),n=JSON.stringify(s);writeFileSync(a,n,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeSummary(e){let r=join(this.reportDir,"summary.json"),a=r+".tmp",s=JSON.stringify(e);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(e){let r=join(this.reportDir,"manifest.json"),a=r+".tmp",s=JSON.stringify(e);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var yr=".testrelic",Is="testrelic-config.json",Ms=".testrelic",Es=5,Ps=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:`${yr}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),Ls={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function br(t){let e=resolve(t);for(let r=0;r<=Es;r++){let a=join(e,yr,Is);if(existsSync(a))try{if(statSync(a).isFile())return a}catch{}let s=join(e,Ms);if(existsSync(s))try{if(statSync(s).isFile())return process.stderr.write(`[testrelic] Deprecation: config file ".testrelic" has moved to ".testrelic/testrelic-config.json". Please migrate your config file to the new location.
|
|
4
|
+
`),s}catch{}let n=dirname(e);if(n===e)break;e=n;}return null}function xr(t){try{let e=readFileSync(t,"utf-8"),r=JSON.parse(e);return typeof r!="object"||r===null||Array.isArray(r)||!wr(r)?null:r}catch{return null}}function wr(t){for(let e of Object.keys(t)){if(Ps.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!wr(r))return false}return true}function kr(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 Je(t){let e=Object.create(null);for(let r of Object.keys(t)){let a=t[r];typeof a=="string"&&a.startsWith("$")?e[r]=kr(a):typeof a=="object"&&a!==null&&!Array.isArray(a)?e[r]=Je(a):e[r]=a;}return e}function vr(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),a=e[2],s=Ls[a];return !s||r<=0?null:r*s}function Sr(t,e){let r=Object.create(null);if(Object.assign(r,mr),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 v=vr(c.maxAge);v!==null&&(r.queueMaxAge=v);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let l=e.apiKey.startsWith("$")?kr(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=vr(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 a=process.env.TESTRELIC_API_KEY;a&&a.length>0&&(r.apiKey=a);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&isValidEndpointUrl(s)&&(r.endpoint=s);let n=process.env.TESTRELIC_UPLOAD_STRATEGY;n&&["batch","realtime","both"].includes(n)&&(r.uploadStrategy=n);let i=process.env.TESTRELIC_CLOUD_TIMEOUT;if(i){let l=parseInt(i,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let o=Object.freeze(r);return isValidCloudConfig(o)?o:mr}var Bs=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],Os=["authorization","cookie","set-cookie","x-api-key"],Us=["password","secret","token","apiKey","api_key"];function Tr(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??[...Os],e.redactBodyFields=t?.redactBodyFields??[...Us],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function Cr(t){if(t!==void 0&&!isValidConfig(t))throw createError(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=[...Bs,...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 a=br(process.cwd()),s=a?xr(a):null,n=s?Je(s):null,i=Sr(n,t?.cloud);return e.cloud=i.apiKey?i:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var Ye="1.10.0";function Rr(t,e,r){try{let s=readFileSync(t,"utf-8").split(`
|
|
6
|
+
`);if(e<1||e>s.length)return null;let n=Math.max(1,e-r),i=Math.min(s.length,e+r),o=[];for(let l=n;l<=i;l++){let d=l===e?">":" ",c=String(l).padStart(String(i).length," ");o.push(`${d} ${c} | ${s[l-1]}`);}return o.join(`
|
|
7
|
+
`)}catch{return null}}function Ar(t){return e=>{let r=e;for(let a of t)if(typeof a=="string"){let s=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=a.flags.includes("g")?a.flags:a.flags+"g",n=new RegExp(a.source,s);r=r.replace(n,"[REDACTED]");}return r}}function zs(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 qs(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 $s(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 Vs(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 js(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 Gs=[zs,qs,$s,Vs,js];function $(t){let e=process.env;for(let r of Gs){let a=r(e);if(a)return a}return null}var Xe=`
|
|
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;
|
|
@@ -570,15 +570,15 @@ body{
|
|
|
570
570
|
.detail-error .failure-message{margin-bottom:16px;padding:12px;background:rgba(239,68,68,0.06);border:1px solid rgba(239,68,68,0.15);border-radius:8px;font-size:12px;color:#f87171;text-align:left;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap;word-break:break-word}
|
|
571
571
|
.detail-error code{font-size:11px;padding:2px 6px;background:var(--bg-2);border-radius:4px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
|
|
572
572
|
.server-offline-banner{padding:8px 14px;background:rgba(251,191,36,0.08);border:1px solid rgba(251,191,36,0.2);border-radius:6px;font-size:11px;color:#fbbf24;text-align:center;margin-bottom:12px}
|
|
573
|
-
`;var
|
|
573
|
+
`;var Ze=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 247" fill="none">
|
|
574
574
|
<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)"/>
|
|
575
575
|
<defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
|
|
576
576
|
<stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
|
|
577
|
-
</linearGradient></defs></svg>`,
|
|
577
|
+
</linearGradient></defs></svg>`,Qe=`<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
578
578
|
<path fill-rule="evenodd" clip-rule="evenodd" d="M4.75 1.08009C2.034 2.66209 -0.130999 7.63009 0.610001 10.5821C0.969001 12.0121 3.021 15.2131 5.17 17.6971C14.375 28.3321 18 39.7791 18 58.2101V71.0001H12.434C1.16501 71.0001 0 73.4641 0 97.3051C0 106.858 0.298003 128.922 0.662003 146.337L1.323 178H33.606C65.786 178 65.897 178.007 68.544 180.284C72.228 183.453 72.244 189.21 68.579 192.877L65.957 195.5L33.479 195.801L1 196.103V204.551V213H24.577H48.154L51.077 215.923C55.007 219.853 55.007 224.147 51.077 228.077L48.154 231H26.469H4.783L5.41901 233.534C5.76901 234.927 7.143 238.527 8.472 241.534L10.89 247H40.945H71L71.006 241.75C71.017 230.748 76.027 221.606 84.697 216.767C97.854 209.424 114.086 213.895 121.323 226.857C123.659 231.041 124.418 233.833 124.789 239.607L125.263 247H155.187H185.11L187.528 241.534C188.857 238.527 190.231 234.927 190.581 233.534L191.217 231H169.531H147.846L144.923 228.077C142.928 226.082 142 224.152 142 222C142 219.848 142.928 217.918 144.923 215.923L147.846 213H171.423H195V204.551V196.103L162.521 195.801L130.043 195.5L127.421 192.877C123.991 189.445 123.835 183.869 127.074 180.421L129.349 178H162.013H194.677L195.338 146.337C195.702 128.922 196 106.858 196 97.3051C196 73.4641 194.835 71.0001 183.566 71.0001H178V58.2101C178 39.6501 181.397 28.7731 190.538 18.0651C195.631 12.0971 196.572 9.00809 194.511 5.02109C192.672 1.46509 190.197 9.12233e-05 186.028 9.12233e-05C179.761 9.12233e-05 168.713 14.8831 163.388 30.5001C160.975 37.5771 160.608 40.3751 160.213 54.7501L159.765 71.0001H150.732H141.7L142.286 53.2501C142.904 34.5511 144.727 24.3761 148.938 16.1211C151.823 10.4671 151.628 5.90109 148.364 2.63609C145 -0.726907 140.105 -0.887909 136.596 2.25009C133.481 5.03609 128.686 17.0811 126.507 27.5921C125.569 32.1191 124.617 43.0901 124.28 53.2501L123.69 71.0001H115.345H107V38.4231V5.84609L104.077 2.92309C102.082 0.928088 100.152 9.12233e-05 98 9.12233e-05C95.848 9.12233e-05 93.918 0.928088 91.923 2.92309L89 5.84609V38.4231V71.0001H80.655H72.31L71.72 53.2501C71.383 43.0901 70.431 32.1191 69.493 27.5921C67.314 17.0811 62.519 5.03609 59.404 2.25009C55.998 -0.795909 51.059 -0.710905 47.646 2.45209C44.221 5.62609 44.191 9.92109 47.539 17.4911C51.71 26.9241 53.007 34.4791 53.676 53.2501L54.31 71.0001H45.272H36.235L35.787 54.7501C35.392 40.3751 35.025 37.5771 32.612 30.5001C27.194 14.6091 16.228 -0.02891 9.787 0.03009C7.979 0.04709 5.712 0.519093 4.75 1.08009ZM42.687 108.974C33.431 112.591 20.036 125.024 18.408 131.512C17.476 135.223 20.677 140.453 28.253 147.599C37.495 156.319 44.191 159.471 53.5 159.485C59.317 159.494 61.645 158.953 67.274 156.289C77.634 151.385 88.987 139.161 88.996 132.9C89.004 127.304 76.787 114.707 66.745 109.956C59.16 106.368 50.285 106.006 42.687 108.974ZM129.255 109.904C119.151 114.768 106.996 127.33 107.004 132.9C107.013 139.108 118.562 151.475 128.939 156.389C134.338 158.945 136.744 159.496 142.521 159.498C152.526 159.501 160.369 155.502 169.771 145.605C180.444 134.368 180.278 130.975 168.486 119.388C160.043 111.094 152.727 107.595 143 107.201C136.364 106.933 134.78 107.244 129.255 109.904ZM48.5 125.922C46.3 126.969 43.152 128.945 41.505 130.314L38.511 132.802L40.504 135.005C41.601 136.216 44.434 138.342 46.8 139.728C52.577 143.114 57.36 142.466 64.009 137.395L68.978 133.606L66.756 131.24C60.944 125.054 54.357 123.135 48.5 125.922ZM138.386 125.063C136.674 125.571 133.375 127.677 131.057 129.743L126.841 133.5L131.901 137.343C138.65 142.468 143.407 143.124 149.2 139.728C151.566 138.342 154.351 136.269 155.389 135.122C157.684 132.587 156.742 131.097 150.58 127.511C145.438 124.519 142.329 123.895 138.386 125.063ZM91.923 162.923C89.043 165.804 89 166.008 89 176.973C89 184.805 89.435 188.941 90.47 190.941C92.356 194.589 96.918 196.273 101.03 194.84C105.82 193.17 107 189.638 107 176.973C107 166.008 106.957 165.804 104.077 162.923C102.082 160.928 100.152 160 98 160C95.848 160 93.918 160.928 91.923 162.923ZM94.5 232.155C91.026 234.055 90 236.229 90 241.691V247H98H106V242.082C106 235.732 105.37 234.242 101.928 232.463C98.591 230.737 97.197 230.679 94.5 232.155Z" fill="url(#paint0_linear_55_11)"/>
|
|
579
579
|
<defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
|
|
580
580
|
<stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
|
|
581
|
-
</linearGradient></defs></svg>`;var
|
|
581
|
+
</linearGradient></defs></svg>`;var et={"failed|failed":"passed","failed|passed":"failed"},_r={"failed|failed":"Failed as expected","failed|passed":"Expected to fail, but passed."};function Ws(t,e){return `${e??"passed"}|${t}`}function Ks(t,e){return et[Ws(t,e)]??t}function tt(t,e){let r={passed:t.passed,failed:t.failed,flaky:t.flaky,skipped:t.skipped,timedout:t.timedout},a=0,s=0;for(let n of e){let i=Ks(n.status,n.expectedStatus);i!==n.status&&(r[n.status]--,r[i]++,i==="passed"?a++:s++);}return {total:t.total,...r,expectedFailures:a,unexpectedPasses:s}}var rt=`
|
|
582
582
|
/* \u2500\u2500 Utilities \u2500\u2500 */
|
|
583
583
|
function esc(s){if(!s)return '';return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''')}
|
|
584
584
|
function stripAnsi(s){return s?s.replace(/\\u001b\\[[0-9;]*m/g,'').replace(/\\x1b\\[[0-9;]*m/g,''):''}
|
|
@@ -595,7 +595,7 @@ body{
|
|
|
595
595
|
interpolated as JSON data (not code), so the report and the terminal box
|
|
596
596
|
cannot disagree about a pair. Defined before the data transformation
|
|
597
597
|
below, which is their first caller. */
|
|
598
|
-
var PW_VERDICT=${JSON.stringify(
|
|
598
|
+
var PW_VERDICT=${JSON.stringify(et)};var PW_NOTE=${JSON.stringify(_r)};
|
|
599
599
|
function pwKey(s,e){return (e||'passed')+'|'+s;}
|
|
600
600
|
function pwVerdict(s,e){return PW_VERDICT[pwKey(s,e)]||s;}
|
|
601
601
|
function pwNote(s,e){return PW_NOTE[pwKey(s,e)]||null;}
|
|
@@ -1279,7 +1279,7 @@ body{
|
|
|
1279
1279
|
clearTimeout(_searchTimer);
|
|
1280
1280
|
_searchTimer=setTimeout(function(){searchQuery=q;applyFilters();},150);
|
|
1281
1281
|
}
|
|
1282
|
-
`;var
|
|
1282
|
+
`;var at=`
|
|
1283
1283
|
/* \u2500\u2500 Network Visualization Helpers \u2500\u2500 */
|
|
1284
1284
|
var RES_COLORS={xhr:'#60a5fa',document:'#818cf8',script:'#fbbf24',stylesheet:'#a78bfa',image:'#34d399',font:'#f472b6',other:'#6b7280'};
|
|
1285
1285
|
var RES_LABELS={xhr:'XHR',document:'Doc',script:'JS',stylesheet:'CSS',image:'Img',font:'Font',other:'Other'};
|
|
@@ -2014,7 +2014,7 @@ body{
|
|
|
2014
2014
|
var countEl=ndt.querySelector('.ndt-count');
|
|
2015
2015
|
if(countEl)countEl.textContent=visible+' / '+rows.length+' requests';
|
|
2016
2016
|
}
|
|
2017
|
-
`;var
|
|
2017
|
+
`;var st=`
|
|
2018
2018
|
var _filterState={status:{},type:{},specFile:{},visual:{},evidence:{}};
|
|
2019
2019
|
|
|
2020
2020
|
/* Evidence filters: one predicate per chip, so API and mobile runs share the
|
|
@@ -2273,7 +2273,7 @@ function _updateCard(cls,val){
|
|
|
2273
2273
|
var el=document.querySelector('.'+cls+' .s-count');
|
|
2274
2274
|
if(el)el.textContent=''+val;
|
|
2275
2275
|
}
|
|
2276
|
-
`;var
|
|
2276
|
+
`;var nt=`
|
|
2277
2277
|
/* \u2500\u2500 Event Delegation \u2500\u2500 */
|
|
2278
2278
|
document.addEventListener('click',function(e){
|
|
2279
2279
|
var target=e.target;
|
|
@@ -2544,7 +2544,7 @@ function _updateCard(cls,val){
|
|
|
2544
2544
|
var d=document.getElementById('filter-drawer');if(d)d.classList.remove('open');
|
|
2545
2545
|
var b=document.getElementById('filter-drawer-backdrop');if(b)b.classList.remove('open');
|
|
2546
2546
|
}
|
|
2547
|
-
`;var
|
|
2547
|
+
`;var it=`
|
|
2548
2548
|
/* \u2500\u2500 Category badge helpers \u2500\u2500 */
|
|
2549
2549
|
function actionBadgeClass(cat){
|
|
2550
2550
|
if(cat==='assertion')return 'action-badge-assertion';
|
|
@@ -2590,7 +2590,7 @@ function _updateCard(cls,val){
|
|
|
2590
2590
|
h+='</div>';
|
|
2591
2591
|
return h;
|
|
2592
2592
|
}
|
|
2593
|
-
`;var
|
|
2593
|
+
`;var ot=`
|
|
2594
2594
|
/* \u2500\u2500 Console Log Level Colors & Labels \u2500\u2500 */
|
|
2595
2595
|
var LOG_COLORS={log:'#9ca3af',warn:'#fbbf24',error:'#f87171',info:'#60a5fa',debug:'#a78bfa',stdout:'#9ca3af',stderr:'#f87171'};
|
|
2596
2596
|
var LOG_LABELS={log:'LOG',warn:'WARN',error:'ERR',info:'INFO',debug:'DBG',stdout:'OUT',stderr:'ERR'};
|
|
@@ -2777,7 +2777,7 @@ function _updateCard(cls,val){
|
|
|
2777
2777
|
}
|
|
2778
2778
|
return h;
|
|
2779
2779
|
}
|
|
2780
|
-
`;var
|
|
2780
|
+
`;var lt=`
|
|
2781
2781
|
/* \u2500\u2500 Artifact Utilities \u2500\u2500 */
|
|
2782
2782
|
function formatBytes(bytes){
|
|
2783
2783
|
if(bytes===0)return '0 B';
|
|
@@ -2786,7 +2786,7 @@ function _updateCard(cls,val){
|
|
|
2786
2786
|
if(i>=sizes.length)i=sizes.length-1;
|
|
2787
2787
|
return parseFloat((bytes/Math.pow(k,i)).toFixed(1))+' '+sizes[i];
|
|
2788
2788
|
}
|
|
2789
|
-
`;var
|
|
2789
|
+
`;var dt=`
|
|
2790
2790
|
/* \u2500\u2500 Visual Regression \u2500\u2500 */
|
|
2791
2791
|
|
|
2792
2792
|
function visStatusLabel(status){
|
|
@@ -2943,7 +2943,7 @@ function _updateCard(cls,val){
|
|
|
2943
2943
|
if(otop)otop.style.opacity=String(el.value/100);
|
|
2944
2944
|
}
|
|
2945
2945
|
});
|
|
2946
|
-
`;var
|
|
2946
|
+
`;var ct=`
|
|
2947
2947
|
/* \u2500\u2500 DOM comparison \u2500\u2500 */
|
|
2948
2948
|
|
|
2949
2949
|
/* Rank-cycled so a row and its box always share a colour. */
|
|
@@ -3095,7 +3095,7 @@ function _updateCard(cls,val){
|
|
|
3095
3095
|
var card=row.closest('.vis-card');
|
|
3096
3096
|
if(card&&!row.classList.contains('pinned'))domSetActive(card,row.getAttribute('data-dom-row'),false);
|
|
3097
3097
|
});
|
|
3098
|
-
`;var
|
|
3098
|
+
`;var ut=`
|
|
3099
3099
|
/* \u2500\u2500 Verdict band \u2500\u2500 */
|
|
3100
3100
|
|
|
3101
3101
|
/* Both report modes hand us a summary; streaming's carries fewer fields. */
|
|
@@ -3416,7 +3416,7 @@ function _updateCard(cls,val){
|
|
|
3416
3416
|
if(!card)return;
|
|
3417
3417
|
openTest(card.getAttribute('data-testid'));
|
|
3418
3418
|
});
|
|
3419
|
-
`,
|
|
3419
|
+
`,pt=`
|
|
3420
3420
|
var overviewViewEl=document.getElementById('view-overview');
|
|
3421
3421
|
var detailViewEl=document.getElementById('view-detail');
|
|
3422
3422
|
var detailNavEl=document.getElementById('detail-nav');
|
|
@@ -3557,7 +3557,7 @@ function _updateCard(cls,val){
|
|
|
3557
3557
|
|
|
3558
3558
|
window.addEventListener('hashchange',routeFromHash);
|
|
3559
3559
|
window.addEventListener('popstate',routeFromHash);
|
|
3560
|
-
`;var
|
|
3560
|
+
`;var ft=`
|
|
3561
3561
|
var API_METHOD_COLOR={GET:'#60a5fa',POST:'#34d399',PUT:'#fbbf24',PATCH:'#a78bfa',DELETE:'#f87171',HEAD:'#6b7280',OPTIONS:'#6b7280'};
|
|
3562
3562
|
var API_STATUS_ORDER=['2xx','3xx','4xx','5xx','error'];
|
|
3563
3563
|
var API_STATUS_COLOR={'2xx':'#22c55e','3xx':'#60a5fa','4xx':'#fb923c','5xx':'#ef4444','error':'#ef4444'};
|
|
@@ -3783,7 +3783,7 @@ function _updateCard(cls,val){
|
|
|
3783
3783
|
}
|
|
3784
3784
|
return '';
|
|
3785
3785
|
}
|
|
3786
|
-
`;var
|
|
3786
|
+
`;var gt=`
|
|
3787
3787
|
.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}
|
|
3788
3788
|
.vis-header svg{opacity:.6}
|
|
3789
3789
|
.vis-count{font-weight:400;color:var(--fg-2);font-size:10px}
|
|
@@ -3816,7 +3816,7 @@ function _updateCard(cls,val){
|
|
|
3816
3816
|
|
|
3817
3817
|
/* A checkerboard behind the diff so fully transparent regions stay legible. */
|
|
3818
3818
|
.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}
|
|
3819
|
-
`,
|
|
3819
|
+
`,ht=`
|
|
3820
3820
|
.dom-figure{position:relative;line-height:0;border:1px solid var(--bd);border-radius:8px;overflow:hidden;margin-bottom:12px}
|
|
3821
3821
|
.dom-img{display:block;width:100%;height:auto}
|
|
3822
3822
|
.dom-ov{position:absolute;top:0;left:0;right:0;bottom:0;pointer-events:none}
|
|
@@ -3848,7 +3848,7 @@ function _updateCard(cls,val){
|
|
|
3848
3848
|
.dom-from{color:#ef4444;word-break:break-all}
|
|
3849
3849
|
.dom-arrow{color:var(--fg-2)}
|
|
3850
3850
|
.dom-to{color:#2dd4a8;word-break:break-all}
|
|
3851
|
-
`;var
|
|
3851
|
+
`;var mt=`
|
|
3852
3852
|
/* \u2500\u2500 Wider shell \u2500\u2500
|
|
3853
3853
|
960px was sized for a list. The row now carries evidence and timing, and
|
|
3854
3854
|
the detail panel shows two screenshots side by side; both were cramped. */
|
|
@@ -3975,7 +3975,7 @@ function _updateCard(cls,val){
|
|
|
3975
3975
|
.verdict{flex-direction:column}
|
|
3976
3976
|
.verdict-side{width:100%}
|
|
3977
3977
|
}
|
|
3978
|
-
`,
|
|
3978
|
+
`,vt=`
|
|
3979
3979
|
/* The overlay is gone. Anything still carrying .drawer must not float. */
|
|
3980
3980
|
.drawer,.drawer-backdrop{display:none}
|
|
3981
3981
|
|
|
@@ -3996,7 +3996,7 @@ function _updateCard(cls,val){
|
|
|
3996
3996
|
/* The page scrolls now, so the old panel body must not scroll inside it. */
|
|
3997
3997
|
#view-detail .drawer-body{flex:none;overflow:visible;padding:0}
|
|
3998
3998
|
.detail-page .detail-rail,.detail-page .drawer-rail{top:16px}
|
|
3999
|
-
`;var
|
|
3999
|
+
`;var yt=`
|
|
4000
4000
|
/* \u2500\u2500 Run-level type band \u2500\u2500 */
|
|
4001
4001
|
.tband{display:grid;gap:16px;margin-bottom:20px}
|
|
4002
4002
|
.tband-3{grid-template-columns:1.1fr 1.1fr .9fr}
|
|
@@ -4094,21 +4094,21 @@ function _updateCard(cls,val){
|
|
|
4094
4094
|
@media (max-width:1100px){
|
|
4095
4095
|
.tband-3,.tband-2{grid-template-columns:1fr}
|
|
4096
4096
|
}
|
|
4097
|
-
`;var
|
|
4097
|
+
`;var Js=`
|
|
4098
4098
|
(function(){
|
|
4099
4099
|
var data=JSON.parse(document.getElementById('report-data').textContent);
|
|
4100
|
-
${Ge}
|
|
4101
|
-
${Ye}
|
|
4102
|
-
${Xe}
|
|
4103
|
-
${We}
|
|
4104
|
-
${Ke}
|
|
4105
|
-
${Ze}
|
|
4106
|
-
${et}
|
|
4107
|
-
${Qe}
|
|
4108
|
-
${Je}
|
|
4109
|
-
${tt}
|
|
4110
|
-
${at}
|
|
4111
4100
|
${rt}
|
|
4101
|
+
${it}
|
|
4102
|
+
${ot}
|
|
4103
|
+
${at}
|
|
4104
|
+
${st}
|
|
4105
|
+
${lt}
|
|
4106
|
+
${ct}
|
|
4107
|
+
${dt}
|
|
4108
|
+
${nt}
|
|
4109
|
+
${ut}
|
|
4110
|
+
${ft}
|
|
4111
|
+
${pt}
|
|
4112
4112
|
applyTheme();
|
|
4113
4113
|
renderRunMeta();
|
|
4114
4114
|
renderSummary();
|
|
@@ -4119,7 +4119,7 @@ function _updateCard(cls,val){
|
|
|
4119
4119
|
renderNeedsAttention();
|
|
4120
4120
|
routeFromHash();
|
|
4121
4121
|
var _lo=document.getElementById('loading-overlay');if(_lo)_lo.remove();
|
|
4122
|
-
})();`;function
|
|
4122
|
+
})();`;function Ir(t,e,r){let a=t.replace(/<\//g,"<\\/"),s=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
|
|
4123
4123
|
<!DOCTYPE html>
|
|
4124
4124
|
<html lang="en" data-theme="">
|
|
4125
4125
|
<head>
|
|
@@ -4128,15 +4128,15 @@ function _updateCard(cls,val){
|
|
|
4128
4128
|
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: blob: file: 'self'; media-src blob: data: file: 'self'; connect-src 'self' http://127.0.0.1:*;">
|
|
4129
4129
|
<title>TestRelic AI Analytics Report</title>
|
|
4130
4130
|
${""}
|
|
4131
|
-
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(
|
|
4132
|
-
<style>${
|
|
4131
|
+
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Ze).toString("base64")}">
|
|
4132
|
+
<style>${Xe}${gt}${ht}${mt}${vt}${yt}</style>
|
|
4133
4133
|
<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>
|
|
4134
4134
|
</head>
|
|
4135
4135
|
<body>
|
|
4136
4136
|
<div class="wrap">
|
|
4137
4137
|
<div class="top-bar">
|
|
4138
4138
|
<div class="brand">
|
|
4139
|
-
${
|
|
4139
|
+
${Qe}
|
|
4140
4140
|
<div class="brand-text">
|
|
4141
4141
|
<span class="brand-title">TestRelic AI</span>
|
|
4142
4142
|
<span class="brand-sub">Analytics Report</span>
|
|
@@ -4173,9 +4173,9 @@ ${""}
|
|
|
4173
4173
|
</aside>
|
|
4174
4174
|
<script id="report-data" type="application/json">${a}</script>
|
|
4175
4175
|
${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:""}
|
|
4176
|
-
<script>${
|
|
4176
|
+
<script>${Js}</script>
|
|
4177
4177
|
</body>
|
|
4178
|
-
</html>`}function
|
|
4178
|
+
</html>`}function bt(t,e,r,a,s){let n=t.replace(/<\//g,"<\\/"),i=s?s.replace(/<\//g,"<\\/"):"null",o=e.replace(/<\//g,"<\\/"),l=a?a.replace(/<\//g,"<\\/"):null,d={};try{d=JSON.parse(t);}catch{}let c=`{
|
|
4179
4179
|
"schemaVersion":"2.0",
|
|
4180
4180
|
"reportMode":"streaming",
|
|
4181
4181
|
"serverPort":${r??"null"},
|
|
@@ -4190,7 +4190,7 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:
|
|
|
4190
4190
|
"ci":${d.ci?JSON.stringify(d.ci).replace(/<\//g,"<\\/"):"null"},
|
|
4191
4191
|
"metadata":${d.metadata?JSON.stringify(d.metadata).replace(/<\//g,"<\\/"):"null"},
|
|
4192
4192
|
"shardRunIds":${d.shardRunIds?JSON.stringify(d.shardRunIds).replace(/<\//g,"<\\/"):"null"}
|
|
4193
|
-
}`,
|
|
4193
|
+
}`,v=`
|
|
4194
4194
|
(function(){
|
|
4195
4195
|
var data=JSON.parse(document.getElementById('report-data').textContent);
|
|
4196
4196
|
var _serverPort=data.serverPort||null;
|
|
@@ -4260,18 +4260,18 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:
|
|
|
4260
4260
|
window.__trServerPort=_serverPort;
|
|
4261
4261
|
window.__trIsStreaming=true;
|
|
4262
4262
|
|
|
4263
|
-
${Ge}
|
|
4264
|
-
${Ye}
|
|
4265
|
-
${Xe}
|
|
4266
|
-
${We}
|
|
4267
|
-
${Ke}
|
|
4268
|
-
${Ze}
|
|
4269
|
-
${et}
|
|
4270
|
-
${Qe}
|
|
4271
|
-
${Je}
|
|
4272
|
-
${tt}
|
|
4273
|
-
${at}
|
|
4274
4263
|
${rt}
|
|
4264
|
+
${it}
|
|
4265
|
+
${ot}
|
|
4266
|
+
${at}
|
|
4267
|
+
${st}
|
|
4268
|
+
${lt}
|
|
4269
|
+
${ct}
|
|
4270
|
+
${dt}
|
|
4271
|
+
${nt}
|
|
4272
|
+
${ut}
|
|
4273
|
+
${ft}
|
|
4274
|
+
${pt}
|
|
4275
4275
|
applyTheme();
|
|
4276
4276
|
renderRunMeta();
|
|
4277
4277
|
renderSummary();
|
|
@@ -4295,15 +4295,15 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:
|
|
|
4295
4295
|
<title>TestRelic AI Analytics Report</title>
|
|
4296
4296
|
${r?`<meta name="report-server-port" content="${r}">`:""}
|
|
4297
4297
|
${r?`<meta name="artifact-server-port" content="${r}">`:""}
|
|
4298
|
-
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(
|
|
4299
|
-
<style>${
|
|
4298
|
+
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Ze).toString("base64")}">
|
|
4299
|
+
<style>${Xe}${gt}${ht}${mt}${vt}${yt}</style>
|
|
4300
4300
|
<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>
|
|
4301
4301
|
</head>
|
|
4302
4302
|
<body>
|
|
4303
4303
|
<div class="wrap">
|
|
4304
4304
|
<div class="top-bar">
|
|
4305
4305
|
<div class="brand">
|
|
4306
|
-
${
|
|
4306
|
+
${Qe}
|
|
4307
4307
|
<div class="brand-text">
|
|
4308
4308
|
<span class="brand-title">TestRelic AI</span>
|
|
4309
4309
|
<span class="brand-sub">Analytics Report</span>
|
|
@@ -4340,74 +4340,74 @@ ${r?`<meta name="artifact-server-port" content="${r}">`:""}
|
|
|
4340
4340
|
</aside>
|
|
4341
4341
|
<script id="report-data" type="application/json">${c}</script>
|
|
4342
4342
|
${l?`<script id="artifact-manifest-data" type="application/json">${l}</script>`:""}
|
|
4343
|
-
<script>${
|
|
4343
|
+
<script>${v}</script>
|
|
4344
4344
|
</body>
|
|
4345
|
-
</html>`}function
|
|
4346
|
-
`);});}catch{}}join(tmpdir(),"testrelic-data");async function Sr(e,t,r,a){let s=(t-1)*r,n=[],i=0,o=createInterface({input:createReadStream(e,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of o)if(c.length!==0){if(i>=s&&n.length<r)try{n.push(JSON.parse(c));}catch{}if(i++,n.length>=r&&a!==void 0)break}let l=a??i,d=Math.max(1,Math.ceil(l/r));return {items:n,total:l,page:t,pageSize:r,totalPages:d}}var Ar=/^[a-f0-9]{12}$/,ft=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,_r=500;function S(e,t,r){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(r));}function Ir(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type");}function he(e){try{return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):null}catch{return null}}function me(e){let t=0;try{let r=readdirSync(e,{withFileTypes:!0});for(let a of r){let s=join(e,a.name);a.isFile()?t+=statSync(s).size:a.isDirectory()&&(t+=me(s));}}catch{}return t}function Mr(e,t,r,a){let s=he(join(r,"index.json"));S(t,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-a)/1e3)});}function Er(e,t,r){let a=he(join(r,"summary.json"));if(!a){S(t,404,{error:"Summary not found"});return}S(t,200,a);}function Pr(e,t,r){let a=he(join(r,"index.json"));if(!a){S(t,404,{error:"Test index not found"});return}let n=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,i=Math.max(1,parseInt(n.get("page")??"1",10)||1),o=Math.min(_r,Math.max(1,parseInt(n.get("pageSize")??"100",10)||100)),l=n.get("status")?.split(",").filter(Boolean)??null,d=n.get("file")??null,c=n.get("search")?.toLowerCase()??null,p=n.get("tag")?.split(",").filter(Boolean)??null,y=n.get("sort")??"file",f=n.get("order")==="desc"?-1:1,u=a;l&&l.length>0&&(u=u.filter(v=>l.includes(v.status))),d&&(u=u.filter(v=>v.filePath===d||v.filePath.startsWith(d+"/"))),c&&(u=u.filter(v=>v.title.toLowerCase().includes(c)||v.filePath.toLowerCase().includes(c))),p&&p.length>0&&(u=u.filter(v=>p.some(w=>v.tags.includes(w)))),u=[...u].sort((v,w)=>{let x=0;switch(y){case "duration":x=v.duration-w.duration;break;case "status":x=v.status.localeCompare(w.status);break;case "title":x=v.title.localeCompare(w.title);break;default:x=v.filePath.localeCompare(w.filePath);break}return x*f});let m=u.length,b=Math.max(1,Math.ceil(m/o)),h=(i-1)*o,g=u.slice(h,h+o);S(t,200,{tests:g,pagination:{page:i,pageSize:o,totalItems:m,totalPages:b},filters:{status:l,file:d,search:c,tag:p}});}function Dr(e,t,r,a){if(!Ar.test(a)){S(t,400,{error:"Invalid test ID format"});return}let s=join(r,"tests",a,"meta.json"),n=join(r,"tests",`${a}.json`),i=existsSync(s)?s:existsSync(n)?n:null;if(!i){S(t,404,{error:`Test not found: ${a}`});return}try{let o=readFileSync(i,"utf-8");t.writeHead(200,{"Content-Type":"application/json"}),t.end(o);}catch{S(t,500,{error:"Failed to read the test data file"});}}async function Lr(e,t,r,a,s){if(!Ar.test(a)){S(t,400,{error:"Invalid test ID format"});return}let i=join(r,"tests",a,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!existsSync(i)){S(t,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),c=Math.min(_r,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),p,y=join(r,"tests",a,"meta.json");if(existsSync(y))try{let u=JSON.parse(readFileSync(y,"utf-8"));switch(s){case "network":p=u.networkRequestsCount;break;case "console":p=u.consoleLogsCount;break;case "api-calls":p=u.apiCallsCount;break}}catch{}let f=await Sr(i,d,c,p);S(t,200,f);}catch{S(t,500,{error:"Failed to read the report data"});}}function Nr(e,t,r){let a=he(join(r,"index.json"));if(!a){S(t,404,{error:"Test index not found"});return}let s=new Map;for(let i of a){if(i.isRetry)continue;let o=s.get(i.filePath);switch(o||(o={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.set(i.filePath,o)),o.total++,i.status){case "passed":o.passed++;break;case "failed":o.failed++;break;case "flaky":o.flaky++;break;case "skipped":o.skipped++;break;case "timedout":o.timedOut++;break}}let n=Array.from(s.entries()).map(([i,o])=>({filePath:i,...o})).sort((i,o)=>i.filePath.localeCompare(o.filePath));S(t,200,{files:n});}function Fr(e,t,r){if(!existsSync(r)){S(t,200,{runs:[],totalSizeBytes:0});return}try{let a=[],s=0,n=readdirSync(r,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||!ft.test(i.name))continue;let o=join(r,i.name),l=me(o),d=readdirSync(o,{withFileTypes:!0}).filter(c=>c.isDirectory());a.push({folderName:i.name,totalSizeBytes:l,testCount:d.length}),s+=l;}a.sort((i,o)=>o.folderName.localeCompare(i.folderName)),S(t,200,{runs:a,totalSizeBytes:s});}catch{S(t,500,{error:"Failed to read the report data"});}}function Br(e,t,r){try{let a=0,s=0;if(existsSync(r)){let n=readdirSync(r,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||!ft.test(i.name))continue;let o=join(r,i.name),l=me(o);rmSync(o,{recursive:!0,force:!0}),s+=l,a++;}}S(t,200,{deletedCount:a,freedBytes:s});}catch{S(t,500,{error:"Failed to read the report data"});}}function Or(e,t,r,a){if(!ft.test(a)){S(t,400,{error:"Invalid folder name"});return}let s=join(r,a);try{if(!statSync(s).isDirectory()){S(t,404,{error:"Not found"});return}}catch{S(t,404,{error:"Not found"});return}try{let n=me(s);rmSync(s,{recursive:!0,force:!0}),S(t,200,{deleted:a,freedBytes:n});}catch{S(t,500,{error:"Failed to read the report data"});}}function Ur(e,t,r){S(t,200,{status:"shutting_down"}),r.close();}function gt(e,t,r){if(!existsSync(r)){S(t,404,{error:"File not found"});return}try{let a=statSync(r).size,s=extname(r).toLowerCase(),n=Ws[s]??"application/octet-stream",i=Gs(e.headers.range,a);if(i==="unsatisfiable"){t.writeHead(416,{"Content-Range":`bytes */${a}`,"Accept-Ranges":"bytes"}),t.end();return}if(i){t.writeHead(206,{"Content-Type":n,"Content-Length":i.end-i.start+1,"Content-Range":`bytes ${i.start}-${i.end}/${a}`,"Accept-Ranges":"bytes"}),Tr(createReadStream(r,{start:i.start,end:i.end}),t);return}t.writeHead(200,{"Content-Type":n,"Content-Length":a,"Accept-Ranges":"bytes"}),Tr(createReadStream(r),t);}catch{S(t,500,{error:"Failed to read the report data"});}}function Tr(e,t){e.on("error",()=>{e.destroy(),t.destroy();}),t.on("close",()=>{e.destroy();}),e.pipe(t);}function Gs(e,t){if(!e)return null;let r=/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!r)return null;let[,a,s]=r;if(a===""&&s==="")return null;let n,i;if(a===""){let o=Number(s);if(o<=0)return "unsatisfiable";n=Math.max(0,t-o),i=t-1;}else n=Number(a),i=s===""?t-1:Math.min(Number(s),t-1);return !Number.isFinite(n)||!Number.isFinite(i)?null:t===0||n>=t||n>i?"unsatisfiable":{start:n,end:i}}var Ws={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".json":"application/json",".html":"text/html",".css":"text/css",".js":"text/javascript",".svg":"image/svg+xml"};var Xs=9323,Zs=10,Qs=1800*1e3;function oe(e,t){return new Promise((r,a)=>{let s=t?.port??Xs,n=Date.now(),i,o=0,l=existsSync(join(e,"artifacts"))?join(e,"artifacts"):existsSync(join(e,"..","artifacts"))?join(e,"..","artifacts"):join(e,"artifacts");function d(){clearTimeout(i),i=setTimeout(()=>{p.close();},Qs);}let c=t?.htmlPath??null;if(!c){let f=dirname(e);try{let u=readdirSync(f).find(m=>m.endsWith(".html"));u&&(c=join(f,u));}catch{}}let p=createServer((f,u)=>{if(d(),Ir(u),f.method==="OPTIONS"){u.writeHead(204),u.end();return}let m;try{m=new URL(f.url??"/",`http://${f.headers.host??"localhost"}`).pathname;}catch{S(u,400,{error:"Invalid URL"});return}if(f.method==="GET"&&(m==="/"||m==="/index.html")){if(c&&existsSync(c)){gt(f,u,c);return}S(u,404,{error:"HTML report not found"});return}if(f.method==="GET"&&m==="/api/health"){Mr(f,u,e,n);return}if(f.method==="GET"&&m==="/api/summary"){Er(f,u,e);return}if(f.method==="GET"&&m==="/api/tests"){Pr(f,u,e);return}if(f.method==="GET"&&m==="/api/files"){Nr(f,u,e);return}let b=m.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(f.method==="GET"&&b){Lr(f,u,e,b[1],b[2]);return}let h=m.match(/^\/api\/tests\/([a-f0-9]+)$/);if(f.method==="GET"&&h){Dr(f,u,e,h[1]);return}if(f.method==="GET"&&m==="/api/artifacts"){Fr(f,u,l);return}if(f.method==="DELETE"&&m==="/api/artifacts"){Br(f,u,l);return}let g=m.match(/^\/api\/artifacts\/(.+)$/);if(f.method==="DELETE"&&g){Or(f,u,l,decodeURIComponent(g[1]));return}if(f.method==="GET"&&m.startsWith("/artifacts/")){let v=decodeURIComponent(m.slice(11));if(v.includes("..")||v.includes("\0")){S(u,400,{error:"Invalid path"});return}gt(f,u,join(l,v));return}if(f.method==="POST"&&m==="/api/shutdown"){Ur(f,u,p);return}S(u,404,{error:"Not found"});});function y(f){let u=m=>{m.code==="EADDRINUSE"&&o<Zs?(o++,y(f+1)):a(m);};p.once("error",u),p.listen(f,"127.0.0.1",()=>{p.removeListener("error",u);let m=p.address();if(!m||typeof m=="string"){a(new Error("Failed to get server address"));return}d(),r({port:m.port,dispose:()=>new Promise(b=>{clearTimeout(i),p.close(()=>b());})});});}y(s);})}async function zr(e){let t=await oe(e);return {port:t.port,dispose:t.dispose}}function rn(e,t,r,a){let s=JSON.stringify(a?{...e,presentedSummary:a}:e),n=r?JSON.stringify(r):null;return kr(s,t,n)}async function mt(e,t,r,a){try{let s=null,n=null,i=t.reportMode==="streaming"||t.reportMode==="auto"&&e.timeline.length===0&&e.summary.total>=t.streamingThreshold,o,l=t.htmlReportPath,d=dirname(l);mkdirSync(d,{recursive:!0});let c="",p="[]",y=null,f=a?JSON.stringify(a):null;if(i){c=JSON.stringify({...e.summary,testRunId:e.testRunId,startedAt:e.startedAt,completedAt:e.completedAt,totalDuration:e.totalDuration,ci:e.ci,metadata:e.metadata,shardRunIds:e.shardRunIds});let m=dirname(t.outputPath),b=join(m,".testrelic-report");try{let h=join(b,"index-compact.json"),g=join(b,"index.json");existsSync(h)?p=readFileSync(h,"utf-8"):existsSync(g)&&(p=readFileSync(g,"utf-8"));}catch{}y=r?JSON.stringify(r):null,o=dt(c,p,null,y,f);}else o=rn(e,null,r,a);let u=l+".tmp";if(writeFileSync(u,o,"utf-8"),renameSync(u,l),i){if(e.ci===null){let m=dirname(t.outputPath),b=join(m,".testrelic-report"),h=resolve(l);try{if(await sn(),s=await nn(b),!s){n=await oe(b,{htmlPath:h}),s=n.port;let g=setInterval(()=>{},6e4),v=()=>{clearInterval(g),n?.dispose();};process.on("SIGINT",v),process.on("SIGTERM",v),setTimeout(v,1800*1e3).unref();}if(s){process.stderr.write(`
|
|
4345
|
+
</html>`}function xt(t){try{let e=process.platform,r,a;e==="darwin"?(r="open",a=[t]):e==="win32"?(r="explorer.exe",a=[t]):(r="xdg-open",a=[t]),execFile(r,a,s=>{s&&process.stderr.write(`[testrelic] Failed to open browser: ${s.message}
|
|
4346
|
+
`);});}catch{}}join(tmpdir(),"testrelic-data");async function Mr(t,e,r,a){let s=(e-1)*r,n=[],i=0,o=createInterface({input:createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of o)if(c.length!==0){if(i>=s&&n.length<r)try{n.push(JSON.parse(c));}catch{}if(i++,n.length>=r&&a!==void 0)break}let l=a??i,d=Math.max(1,Math.ceil(l/r));return {items:n,total:l,page:e,pageSize:r,totalPages:d}}function z(t){try{return readFileSync(t,"utf-8").split(`
|
|
4347
|
+
`).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}var Dr=/^[a-f0-9]{12}$/,St=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Nr=500;function S(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function Fr(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 be(t){try{return existsSync(t)?JSON.parse(readFileSync(t,"utf-8")):null}catch{return null}}function xe(t){let e=0;try{let r=readdirSync(t,{withFileTypes:!0});for(let a of r){let s=join(t,a.name);a.isFile()?e+=statSync(s).size:a.isDirectory()&&(e+=xe(s));}}catch{}return e}function Br(t,e,r,a){let s=be(join(r,"index.json"));S(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-a)/1e3)});}function Or(t,e,r){let a=be(join(r,"summary.json"));if(!a){S(e,404,{error:"Summary not found"});return}S(e,200,a);}function Ur(t,e,r){let a=be(join(r,"index.json"));if(!a){S(e,404,{error:"Test index not found"});return}let n=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,i=Math.max(1,parseInt(n.get("page")??"1",10)||1),o=Math.min(Nr,Math.max(1,parseInt(n.get("pageSize")??"100",10)||100)),l=n.get("status")?.split(",").filter(Boolean)??null,d=n.get("file")??null,c=n.get("search")?.toLowerCase()??null,v=n.get("tag")?.split(",").filter(Boolean)??null,g=n.get("sort")??"file",h=n.get("order")==="desc"?-1:1,f=a;l&&l.length>0&&(f=f.filter(y=>l.includes(y.status))),d&&(f=f.filter(y=>y.filePath===d||y.filePath.startsWith(d+"/"))),c&&(f=f.filter(y=>y.title.toLowerCase().includes(c)||y.filePath.toLowerCase().includes(c))),v&&v.length>0&&(f=f.filter(y=>v.some(x=>y.tags.includes(x)))),f=[...f].sort((y,x)=>{let k=0;switch(g){case "duration":k=y.duration-x.duration;break;case "status":k=y.status.localeCompare(x.status);break;case "title":k=y.title.localeCompare(x.title);break;default:k=y.filePath.localeCompare(x.filePath);break}return k*h});let p=f.length,u=Math.max(1,Math.ceil(p/o)),b=(i-1)*o,m=f.slice(b,b+o);S(e,200,{tests:m,pagination:{page:i,pageSize:o,totalItems:p,totalPages:u},filters:{status:l,file:d,search:c,tag:v}});}function Hr(t,e,r,a){if(!Dr.test(a)){S(e,400,{error:"Invalid test ID format"});return}let s=join(r,"tests",a,"meta.json"),n=join(r,"tests",`${a}.json`),i=existsSync(s)?s:existsSync(n)?n:null;if(!i){S(e,404,{error:`Test not found: ${a}`});return}try{let o=readFileSync(i,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(o);}catch{S(e,500,{error:"Failed to read the test data file"});}}async function zr(t,e,r,a,s){if(!Dr.test(a)){S(e,400,{error:"Invalid test ID format"});return}let i=join(r,"tests",a,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!existsSync(i)){S(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(Nr,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),v,g=join(r,"tests",a,"meta.json");if(existsSync(g))try{let f=JSON.parse(readFileSync(g,"utf-8"));switch(s){case "network":v=f.networkRequestsCount;break;case "console":v=f.consoleLogsCount;break;case "api-calls":v=f.apiCallsCount;break}}catch{}let h=await Mr(i,d,c,v);S(e,200,h);}catch{S(e,500,{error:"Failed to read the report data"});}}function qr(t,e,r){let a=be(join(r,"index.json"));if(!a){S(e,404,{error:"Test index not found"});return}let s=new Map;for(let i of a){if(i.isRetry)continue;let o=s.get(i.filePath);switch(o||(o={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.set(i.filePath,o)),o.total++,i.status){case "passed":o.passed++;break;case "failed":o.failed++;break;case "flaky":o.flaky++;break;case "skipped":o.skipped++;break;case "timedout":o.timedOut++;break}}let n=Array.from(s.entries()).map(([i,o])=>({filePath:i,...o})).sort((i,o)=>i.filePath.localeCompare(o.filePath));S(e,200,{files:n});}function $r(t,e,r){if(!existsSync(r)){S(e,200,{runs:[],totalSizeBytes:0});return}try{let a=[],s=0,n=readdirSync(r,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||!St.test(i.name))continue;let o=join(r,i.name),l=xe(o),d=readdirSync(o,{withFileTypes:!0}).filter(c=>c.isDirectory());a.push({folderName:i.name,totalSizeBytes:l,testCount:d.length}),s+=l;}a.sort((i,o)=>o.folderName.localeCompare(i.folderName)),S(e,200,{runs:a,totalSizeBytes:s});}catch{S(e,500,{error:"Failed to read the report data"});}}function Vr(t,e,r){try{let a=0,s=0;if(existsSync(r)){let n=readdirSync(r,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||!St.test(i.name))continue;let o=join(r,i.name),l=xe(o);rmSync(o,{recursive:!0,force:!0}),s+=l,a++;}}S(e,200,{deletedCount:a,freedBytes:s});}catch{S(e,500,{error:"Failed to read the report data"});}}function jr(t,e,r,a){if(!St.test(a)){S(e,400,{error:"Invalid folder name"});return}let s=join(r,a);try{if(!statSync(s).isDirectory()){S(e,404,{error:"Not found"});return}}catch{S(e,404,{error:"Not found"});return}try{let n=xe(s);rmSync(s,{recursive:!0,force:!0}),S(e,200,{deleted:a,freedBytes:n});}catch{S(e,500,{error:"Failed to read the report data"});}}function Gr(t,e,r){S(e,200,{status:"shutting_down"}),r.close();}function Tt(t,e,r){if(!existsSync(r)){S(e,404,{error:"File not found"});return}try{let a=statSync(r).size,s=extname(r).toLowerCase(),n=sn[s]??"application/octet-stream",i=an(t.headers.range,a);if(i==="unsatisfiable"){e.writeHead(416,{"Content-Range":`bytes */${a}`,"Accept-Ranges":"bytes"}),e.end();return}if(i){e.writeHead(206,{"Content-Type":n,"Content-Length":i.end-i.start+1,"Content-Range":`bytes ${i.start}-${i.end}/${a}`,"Accept-Ranges":"bytes"}),Pr(createReadStream(r,{start:i.start,end:i.end}),e);return}e.writeHead(200,{"Content-Type":n,"Content-Length":a,"Accept-Ranges":"bytes"}),Pr(createReadStream(r),e);}catch{S(e,500,{error:"Failed to read the report data"});}}function Pr(t,e){t.on("error",()=>{t.destroy(),e.destroy();}),e.on("close",()=>{t.destroy();}),t.pipe(e);}function an(t,e){if(!t)return null;let r=/^bytes=(\d*)-(\d*)$/.exec(t.trim());if(!r)return null;let[,a,s]=r;if(a===""&&s==="")return null;let n,i;if(a===""){let o=Number(s);if(o<=0)return "unsatisfiable";n=Math.max(0,e-o),i=e-1;}else n=Number(a),i=s===""?e-1:Math.min(Number(s),e-1);return !Number.isFinite(n)||!Number.isFinite(i)?null:e===0||n>=e||n>i?"unsatisfiable":{start:n,end:i}}var sn={".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 dn=9323,cn=10,un=1800*1e3;function de(t,e){return new Promise((r,a)=>{let s=e?.port??dn,n=Date.now(),i,o=0,l=existsSync(join(t,"artifacts"))?join(t,"artifacts"):existsSync(join(t,"..","artifacts"))?join(t,"..","artifacts"):join(t,"artifacts");function d(){clearTimeout(i),i=setTimeout(()=>{v.close();},un);}let c=e?.htmlPath??null;if(!c){let h=dirname(t);try{let f=readdirSync(h).find(p=>p.endsWith(".html"));f&&(c=join(h,f));}catch{}}let v=createServer((h,f)=>{if(d(),Fr(f),h.method==="OPTIONS"){f.writeHead(204),f.end();return}let p;try{p=new URL(h.url??"/",`http://${h.headers.host??"localhost"}`).pathname;}catch{S(f,400,{error:"Invalid URL"});return}if(h.method==="GET"&&(p==="/"||p==="/index.html")){if(c&&existsSync(c)){Tt(h,f,c);return}S(f,404,{error:"HTML report not found"});return}if(h.method==="GET"&&p==="/api/health"){Br(h,f,t,n);return}if(h.method==="GET"&&p==="/api/summary"){Or(h,f,t);return}if(h.method==="GET"&&p==="/api/tests"){Ur(h,f,t);return}if(h.method==="GET"&&p==="/api/files"){qr(h,f,t);return}let u=p.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(h.method==="GET"&&u){zr(h,f,t,u[1],u[2]);return}let b=p.match(/^\/api\/tests\/([a-f0-9]+)$/);if(h.method==="GET"&&b){Hr(h,f,t,b[1]);return}if(h.method==="GET"&&p==="/api/artifacts"){$r(h,f,l);return}if(h.method==="DELETE"&&p==="/api/artifacts"){Vr(h,f,l);return}let m=p.match(/^\/api\/artifacts\/(.+)$/);if(h.method==="DELETE"&&m){jr(h,f,l,decodeURIComponent(m[1]));return}if(h.method==="GET"&&p.startsWith("/artifacts/")){let y=decodeURIComponent(p.slice(11));if(y.includes("..")||y.includes("\0")){S(f,400,{error:"Invalid path"});return}Tt(h,f,join(l,y));return}if(h.method==="POST"&&p==="/api/shutdown"){Gr(h,f,v);return}S(f,404,{error:"Not found"});});function g(h){let f=p=>{p.code==="EADDRINUSE"&&o<cn?(o++,g(h+1)):a(p);};v.once("error",f),v.listen(h,"127.0.0.1",()=>{v.removeListener("error",f);let p=v.address();if(!p||typeof p=="string"){a(new Error("Failed to get server address"));return}d(),r({port:p.port,dispose:()=>new Promise(u=>{clearTimeout(i),v.close(()=>u());})});});}g(s);})}async function Wr(t){let e=await de(t);return {port:e.port,dispose:e.dispose}}function gn(t,e,r,a){let s=JSON.stringify(a?{...t,presentedSummary:a}:t),n=r?JSON.stringify(r):null;return Ir(s,e,n)}async function Rt(t,e,r,a){try{let s=null,n=null,i=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,l=e.htmlReportPath,d=dirname(l);mkdirSync(d,{recursive:!0});let c="",v="[]",g=null,h=a?JSON.stringify(a):null;if(i){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 p=dirname(e.outputPath),u=join(p,".testrelic-report");try{let b=join(u,"index-compact.json"),m=join(u,"index.json");existsSync(b)?v=readFileSync(b,"utf-8"):existsSync(m)&&(v=readFileSync(m,"utf-8"));}catch{}g=r?JSON.stringify(r):null,o=bt(c,v,null,g,h);}else o=gn(t,null,r,a);let f=l+".tmp";if(writeFileSync(f,o,"utf-8"),renameSync(f,l),i){if(t.ci===null){let p=dirname(e.outputPath),u=join(p,".testrelic-report"),b=resolve(l);try{if(await mn(),s=await vn(u),!s){n=await de(u,{htmlPath:b}),s=n.port;let m=setInterval(()=>{},6e4),y=()=>{clearInterval(m),n?.dispose();};process.on("SIGINT",y),process.on("SIGTERM",y),setTimeout(y,1800*1e3).unref();}if(s){process.stderr.write(`
|
|
4347
4348
|
Report server: http://127.0.0.1:${s}
|
|
4348
|
-
`);try{let
|
|
4349
|
-
`);}}var be=9323,jr=10;async function an(){for(let e=be;e<be+jr;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),500),a=await fetch(`http://127.0.0.1:${e}/api/health`,{signal:t.signal});if(clearTimeout(r),a.ok)return e}catch{}return null}async function sn(){for(let e=be;e<be+jr;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),1e3);await fetch(`http://127.0.0.1:${e}/api/shutdown`,{method:"POST",signal:t.signal}),clearTimeout(r);}catch{}await new Promise(e=>setTimeout(e,300));}async function nn(e){let r=[join(__dirname,"cli.cjs"),join(__dirname,"cli.js"),join(__dirname,"..","dist","cli.cjs"),join(__dirname,"..","dist","cli.js")].find(a=>existsSync(a));if(!r){let a=await oe(e);return process.on("exit",()=>{a?.dispose();}),a.port}return new Promise(a=>{let s=spawn(process.execPath,[r,"serve",e],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),n="",i=false,o=setTimeout(()=>{i||(i=true,s.stderr?.removeAllListeners(),an().then(a));},5e3);s.stderr?.on("data",l=>{n+=l.toString();let d=n.match(/127\.0\.0\.1:(\d+)/);d&&!i&&(i=true,clearTimeout(o),s.stderr?.removeAllListeners(),s.unref(),a(Number(d[1])));}),s.on("error",()=>{i||(i=true,clearTimeout(o),a(null));}),s.on("exit",()=>{i||(i=true,clearTimeout(o),a(null));}),s.unref();})}var Gr=Buffer.from([137,80,78,71,13,10,26,10]),on=16,ln=20,xe=24;function Wr(e){if(e.length<xe||!e.subarray(0,Gr.length).equals(Gr))return null;let t=e.readUInt32BE(on),r=e.readUInt32BE(ln);return t===0||r===0?null:{width:t,height:r}}var dn=/(?:^|\D)(\d+) pixels \(ratio [\d.]+ of all image pixels\) are different/,Kr=/Expected an image (\d+)px by (\d+)px, received (\d+)px by (\d+)px/;function Jr(e){return e?Kr.test(e):false}var cn=/^[ \t]*Snapshot:[ \t]*(\S(?:.*\S)?)[ \t]*$/m;function Yr(e){if(!e)return {};let t={},r=dn.exec(e);if(r){let n=Number.parseInt(r[1],10);Number.isFinite(n)&&(t.diffPixels=n);}let a=Kr.exec(e);if(a){let[,n,i,o,l]=a,d=[n,i,o,l].map(c=>Number.parseInt(c,10));d.every(c=>Number.isFinite(c))&&(t.expectedWidth=d[0],t.expectedHeight=d[1],t.actualWidth=d[2],t.actualHeight=d[3]);}let s=cn.exec(e);return s&&(t.snapshotName=s[1]),t}function Xr(e,t){if(e===void 0||!t)return;let r=t.width*t.height;if(!(r<=0))return e/r}var vn=20,vt=0,yt=[];async function le(e,t){vt>=vn&&await new Promise(r=>yt.push(r)),vt++;try{return await copyFile(e,t),!0}catch{return false}finally{vt--,yt.length>0&&yt.shift()();}}var H=[];async function ea(){H.length!==0&&(await Promise.allSettled(H),H.length=0);}function ta(e){let t=new Date,r=n=>String(n).padStart(2,"0"),a=`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())}T${r(t.getHours())}-${r(t.getMinutes())}-${r(t.getSeconds())}`;if(!existsSync(join(e,a)))return a;let s=1;for(;existsSync(join(e,`${a}-${s}`));)s++;return `${a}-${s}`}function bt(e){let t=e.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"");return t.length>100&&(t=t.substring(0,100).replace(/-+$/,"")),t||"unnamed-test"}var yn=8;function ra(e,t,r){let a=bt(e),s=r?bt(r).substring(0,yn):"";return s&&(a+=`--${s}`),t>0&&(a+=`--retry-${t}`),a}function aa(e,t,r,a,s,n){let i=e.find(u=>u.name==="screenshot"&&u.path),o=e.find(u=>u.name==="video"&&u.path),l=e.find(u=>u.name==="trace"&&u.path);if(!i&&!o&&!l)return null;let d=ra(t,r,n),c=s?["artifacts",s,d]:["artifacts",d],p=join(a,...c),y=c,f={};try{mkdirSync(p,{recursive:!0});}catch{return null}if(i?.path&&existsSync(i.path)){let m=`screenshot${extname(i.path)||".png"}`,b=join(p,m);H.push(le(i.path,b).then(()=>{})),f.screenshot=`${y.join("/")}/${m}`;}if(o?.path&&existsSync(o.path)){let m=`video${extname(o.path)||".webm"}`,b=join(p,m);H.push(le(o.path,b).then(()=>{})),f.video=`${y.join("/")}/${m}`;}if(l?.path&&existsSync(l.path)){let m=`trace${extname(l.path)||".zip"}`,b=join(p,m);H.push(le(l.path,b).then(()=>{})),f.trace=`${y.join("/")}/${m}`;}return !f.screenshot&&!f.video&&!f.trace?null:f}var xt="visual",bn=6;function xn(e){let t=createHash("sha256").update(e).digest("hex").substring(0,bn);return `${bt(e)}--${t}`}function Zr(e){let t=null;try{t=openSync(e,"r");let r=Buffer.alloc(xe),a=readSync(t,r,0,xe,0);return Wr(r.subarray(0,a))}catch{return null}finally{if(t!==null)try{closeSync(t);}catch{}}}var Qr=[{key:"expectedPath",dest:"baseline",field:"baseline"},{key:"actualPath",dest:"actual",field:"actual"},{key:"diffPath",dest:"diff",field:"diff"},{key:"previousPath",dest:"previous",field:"previous"}],wn=[{key:"baselineDomPath",dest:"baseline.dom.json",field:"baselineDom"},{key:"actualDomPath",dest:"actual.dom.json",field:"actualDom"}];function kn(e,t,r,a){let s=xn(e.name),n=join(t,s),i=Qr.some(u=>e[u.key]);if(i||e.dom)try{mkdirSync(n,{recursive:!0});}catch{return null}let o={},l=false;for(let u of Qr){let m=e[u.key];if(!m||!existsSync(m))continue;let b=extname(m)||".png",h=`${u.dest}${b}`;H.push(le(m,join(n,h)).then(()=>{})),o[u.field]=`${r}/${xt}/${s}/${h}`,l=true;}let d=e.dom;if(d)for(let u of wn){let m=d[u.key];!m||!existsSync(m)||(H.push(le(m,join(n,u.dest)).then(()=>{})),o[u.field]=`${r}/${xt}/${s}/${u.dest}`);}if(!l&&i)return null;let c=e.expectedPath?Zr(e.expectedPath):e.actualPath?Zr(e.actualPath):null,p=Xr(e.diffPixels,c),y=e.committedPath??e.expectedPath,f=y?relative(a,y).replace(/\\/g,"/"):void 0;return {name:e.name,status:e.status,source:e.source,...o,...f?{baselinePath:f}:{},...c?{width:c.width,height:c.height}:{},...e.actualWidth!==void 0?{actualWidth:e.actualWidth}:{},...e.actualHeight!==void 0?{actualHeight:e.actualHeight}:{},...e.diffPixels!==void 0?{diffPixels:e.diffPixels}:{},...p!==void 0?{diffPixelRatio:p}:{},...d?{domChanges:d.changes,domChangeCount:d.total,domRootCauses:d.rootCauses,domTruncated:d.truncated,domCaptureBox:d.captureBox}:{}}}function sa(e,t,r,a,s,n,i=process.cwd()){if(e.length===0)return null;let o=ra(t,r,n),l=s?["artifacts",s,o]:["artifacts",o],d=join(a,...l,xt),c=l.join("/");try{mkdirSync(d,{recursive:!0});}catch{return null}let p=[];for(let y of e){let f=kn(y,d,c,i);f&&p.push(f);}return p.length>0?p:null}var na="testrelic-visual-dom";var Sn="testrelic-visual",Cn=/^(.+)-(expected|actual|diff|previous)(\.[A-Za-z0-9]+)$/;function Tn(e){let t=new Map;for(let r of e)if(!(r.name!==Sn||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let s of a){let n=An(s);n&&t.set(n.stem,n);}}catch{}return t}var Rn=["passed","failed","new","updated"];function An(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.stem!="string"||!t.stem||typeof t.name!="string"||!t.name||typeof t.status!="string"||!Rn.includes(t.status)?null:{stem:t.stem,name:t.name,status:t.status,...typeof t.committedPath=="string"&&t.committedPath?{committedPath:t.committedPath}:{}}}function _n(e){let t=new Map;for(let r of e)if(!(r.name!==na||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let s of a){if(typeof s!="object"||s===null)continue;let n=s;typeof n.stem!="string"||!Array.isArray(n.changes)||t.set(n.stem,s);}}catch{}return t}function In(e){let t=new Map;for(let r of e){if(!r.path)continue;let a=Cn.exec(r.name);if(!a)continue;let[,s,n]=a,i=t.get(s)??{};i[n]=r.path,t.set(s,i);}return t}function Mn(e){return !!(e.actual&&(e.expected||e.diff))}function En(e,t,r){return e.diff||Jr(r)?"failed":t?"updated":"new"}function Pn(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;let r=t.replace(/\.[A-Za-z0-9]+$/,""),a=e.filter(s=>s===r||s.endsWith(`/${r}`));return a.length===1?a[0]:null}function la(e,t={}){if(e.length===0)return [];let r=Tn(e),a=_n(e),s=In(e);if(s.size===0&&r.size===0)return [];let n=t.updatingSnapshots===true,i=[];for(let[o,l]of s){let d=r.get(o);!d&&!Mn(l)||i.push({name:d?.name??o,status:d?.status??En(l,n,t.failureMessage),source:d?"toMatchVisualBaseline":"toHaveScreenshot",...l.expected?{expectedPath:l.expected}:{},...d?.committedPath?{committedPath:d.committedPath}:{},...l.actual?{actualPath:l.actual}:{},...l.diff?{diffPath:l.diff}:{},...l.previous?{previousPath:l.previous}:{},...a.has(o)?{dom:a.get(o)}:{}});}for(let[o,l]of r)s.has(o)||i.push({name:l.name,status:l.status,source:"toMatchVisualBaseline",...l.committedPath?{committedPath:l.committedPath}:{},...a.has(o)?{dom:a.get(o)}:{}});return Dn(i,s,t.failureMessage)}function Dn(e,t,r){let a=Yr(r);if(a.diffPixels===void 0&&a.actualWidth===void 0)return [...e];let s=e.filter(i=>i.status==="failed"&&ia(i)).map(i=>oa(i,t)),n=Pn(s,a.snapshotName);return n===null?[...e]:e.map(i=>ia(i)&&oa(i,t)===n?{...i,...a.diffPixels!==void 0?{diffPixels:a.diffPixels}:{},...a.actualWidth!==void 0?{actualWidth:a.actualWidth}:{},...a.actualHeight!==void 0?{actualHeight:a.actualHeight}:{}}:i)}function ia(e){return !!(e.expectedPath||e.actualPath||e.diffPath||e.previousPath)}function oa(e,t){if(t.has(e.name))return e.name;for(let[r,a]of t)if(a.actual===e.actualPath&&a.expected===e.expectedPath&&a.diff===e.diffPath)return r;return e.name}var Ln=new RegExp("[\x1B\x9B][[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[0-9A-PR-TZcf-nqry=><]","g");function ke(e){return !e||e.indexOf("\x1B")===-1&&e.indexOf("\x9B")===-1?e:e.replace(Ln,"")}function da(e){return e==null?null:ke(e)}var Nn=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Fn="1.0",kt="visual";function fa(e){let t=extname(e).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(t)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(t)?"video":t===".zip"&&basename(e,t)==="trace"?"trace":"other"}function Bn(e){if(e.endsWith(".dom.json"))return "dom";let t=basename(e,extname(e));return t==="baseline"?"baseline":t==="diff"?"diff":fa(e)}function On(e,t,r){let a=[];try{for(let s of readdirSync(e,{withFileTypes:!0})){if(!s.isFile())continue;let n=statSync(join(e,s.name));a.push({name:`${kt}/${r}/${s.name}`,type:Bn(s.name),relativePath:`${t}/${kt}/${r}/${s.name}`,sizeBytes:n.size});}}catch{}return a}function ga(e,t,r){let a=[],s=`artifacts/${t}/${r}`;try{let n=readdirSync(e,{withFileTypes:!0});for(let i of n){if(i.isDirectory()&&i.name===kt){let d=join(e,i.name);for(let c of readdirSync(d,{withFileTypes:!0}))c.isDirectory()&&a.push(...On(join(d,c.name),s,c.name));continue}if(!i.isFile())continue;let o=join(e,i.name),l=statSync(o);a.push({name:i.name,type:fa(i.name),relativePath:`${s}/${i.name}`,sizeBytes:l.size});}}catch{}return {testName:r,files:a}}function Un(e,t){let r=join(e,t),a=[],s=0;try{let i=readdirSync(r,{withFileTypes:!0});for(let o of i){if(!o.isDirectory())continue;let l=ga(join(r,o.name),t,o.name);a.push(l);for(let d of l.files)s+=d.sizeBytes;}}catch{}let n=t.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return a.sort((i,o)=>i.testName.localeCompare(o.testName)),{folderName:t,timestamp:n,totalSizeBytes:s,testCount:a.length,tests:a,isCurrentRun:false}}function ha(e,t){let r=join(e,"artifacts"),a=[],s=[],n=0;try{let o=readdirSync(r,{withFileTypes:!0});for(let l of o)if(l.isDirectory())if(Nn.test(l.name)){let d=Un(r,l.name);a.push({...d,isCurrentRun:l.name===t});}else {let d=ga(join(r,l.name),l.name,l.name);s.push(d);for(let c of d.files)n+=c.sizeBytes;}}catch{}a.sort((o,l)=>l.timestamp.localeCompare(o.timestamp)),s.length>0&&(s.sort((o,l)=>o.testName.localeCompare(l.testName)),a.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:n,testCount:s.length,tests:s,isCurrentRun:false}));let i=a.reduce((o,l)=>o+l.totalSizeBytes,0);return {schemaVersion:Fn,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:i,runs:a,serverPort:null}}var jn=256;function Gn(e){let t=resolve(e);for(let r=0;r<jn;r++){if(existsSync(join(t,".git")))return t;let a=dirname(t);if(a===t)return null;t=a;}return null}function ya(e){try{let t=Gn(e);if(!t)return;let r=join(t,".gitignore"),a=relative(t,e).replace(/\\/g,"/"),s=a.endsWith("/")?a:`${a}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
|
|
4349
|
+
`);try{let m=bt(c,v,s,g,h),y=l+".tmp";writeFileSync(y,m,"utf-8"),renameSync(y,l);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let p=dirname(e.outputPath),u=join(p,"artifacts");if(existsSync(u))try{let b=await Wr(u);s=b.port,process.on("exit",()=>{b.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(i&&s)xt(`http://127.0.0.1:${s}`);else {let p=resolve(l);xt(p);}}catch(s){process.stderr.write(`[testrelic] Failed to write HTML report: ${s instanceof Error?s.message:String(s)}
|
|
4350
|
+
`);}}var Se=9323,Zr=10;async function hn(){for(let t=Se;t<Se+Zr;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),a=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),a.ok)return t}catch{}return null}async function mn(){for(let t=Se;t<Se+Zr;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 vn(t){let r=[join(__dirname,"cli.cjs"),join(__dirname,"cli.js"),join(__dirname,"..","dist","cli.cjs"),join(__dirname,"..","dist","cli.js")].find(a=>existsSync(a));if(!r){let a=await de(t);return process.on("exit",()=>{a?.dispose();}),a.port}return new Promise(a=>{let s=spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),n="",i=false,o=setTimeout(()=>{i||(i=true,s.stderr?.removeAllListeners(),hn().then(a));},5e3);s.stderr?.on("data",l=>{n+=l.toString();let d=n.match(/127\.0\.0\.1:(\d+)/);d&&!i&&(i=true,clearTimeout(o),s.stderr?.removeAllListeners(),s.unref(),a(Number(d[1])));}),s.on("error",()=>{i||(i=true,clearTimeout(o),a(null));}),s.on("exit",()=>{i||(i=true,clearTimeout(o),a(null));}),s.unref();})}var Qr=Buffer.from([137,80,78,71,13,10,26,10]),yn=16,bn=20,Te=24;function ea(t){if(t.length<Te||!t.subarray(0,Qr.length).equals(Qr))return null;let e=t.readUInt32BE(yn),r=t.readUInt32BE(bn);return e===0||r===0?null:{width:e,height:r}}var xn=/(?:^|\D)(\d+) pixels \(ratio [\d.]+ of all image pixels\) are different/,ta=/Expected an image (\d+)px by (\d+)px, received (\d+)px by (\d+)px/;function ra(t){return t?ta.test(t):false}var wn=/^[ \t]*Snapshot:[ \t]*(\S(?:.*\S)?)[ \t]*$/m;function aa(t){if(!t)return {};let e={},r=xn.exec(t);if(r){let n=Number.parseInt(r[1],10);Number.isFinite(n)&&(e.diffPixels=n);}let a=ta.exec(t);if(a){let[,n,i,o,l]=a,d=[n,i,o,l].map(c=>Number.parseInt(c,10));d.every(c=>Number.isFinite(c))&&(e.expectedWidth=d[0],e.expectedHeight=d[1],e.actualWidth=d[2],e.actualHeight=d[3]);}let s=wn.exec(t);return s&&(e.snapshotName=s[1]),e}function sa(t,e){if(t===void 0||!e)return;let r=e.width*e.height;if(!(r<=0))return t/r}var _n=20,At=0,_t=[];async function ce(t,e){At>=_n&&await new Promise(r=>_t.push(r)),At++;try{return await copyFile(t,e),!0}catch{return false}finally{At--,_t.length>0&&_t.shift()();}}var j=[];async function oa(){j.length!==0&&(await Promise.allSettled(j),j.length=0);}function la(t){let e=new Date,r=n=>String(n).padStart(2,"0"),a=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!existsSync(join(t,a)))return a;let s=1;for(;existsSync(join(t,`${a}-${s}`));)s++;return `${a}-${s}`}function It(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 In=8;function da(t,e,r){let a=It(t),s=r?It(r).substring(0,In):"";return s&&(a+=`--${s}`),e>0&&(a+=`--retry-${e}`),a}function ca(t,e,r,a,s,n){let i=t.find(f=>f.name==="screenshot"&&f.path),o=t.find(f=>f.name==="video"&&f.path),l=t.find(f=>f.name==="trace"&&f.path);if(!i&&!o&&!l)return null;let d=da(e,r,n),c=s?["artifacts",s,d]:["artifacts",d],v=join(a,...c),g=c,h={};try{mkdirSync(v,{recursive:!0});}catch{return null}if(i?.path&&existsSync(i.path)){let p=`screenshot${extname(i.path)||".png"}`,u=join(v,p);j.push(ce(i.path,u).then(()=>{})),h.screenshot=`${g.join("/")}/${p}`;}if(o?.path&&existsSync(o.path)){let p=`video${extname(o.path)||".webm"}`,u=join(v,p);j.push(ce(o.path,u).then(()=>{})),h.video=`${g.join("/")}/${p}`;}if(l?.path&&existsSync(l.path)){let p=`trace${extname(l.path)||".zip"}`,u=join(v,p);j.push(ce(l.path,u).then(()=>{})),h.trace=`${g.join("/")}/${p}`;}return !h.screenshot&&!h.video&&!h.trace?null:h}var Mt="visual",Mn=6;function En(t){let e=createHash("sha256").update(t).digest("hex").substring(0,Mn);return `${It(t)}--${e}`}function na(t){let e=null;try{e=openSync(t,"r");let r=Buffer.alloc(Te),a=readSync(e,r,0,Te,0);return ea(r.subarray(0,a))}catch{return null}finally{if(e!==null)try{closeSync(e);}catch{}}}var ia=[{key:"expectedPath",dest:"baseline",field:"baseline"},{key:"actualPath",dest:"actual",field:"actual"},{key:"diffPath",dest:"diff",field:"diff"},{key:"previousPath",dest:"previous",field:"previous"}],Pn=[{key:"baselineDomPath",dest:"baseline.dom.json",field:"baselineDom"},{key:"actualDomPath",dest:"actual.dom.json",field:"actualDom"}];function Ln(t,e,r,a){let s=En(t.name),n=join(e,s),i=ia.some(f=>t[f.key]);if(i||t.dom)try{mkdirSync(n,{recursive:!0});}catch{return null}let o={},l=false;for(let f of ia){let p=t[f.key];if(!p||!existsSync(p))continue;let u=extname(p)||".png",b=`${f.dest}${u}`;j.push(ce(p,join(n,b)).then(()=>{})),o[f.field]=`${r}/${Mt}/${s}/${b}`,l=true;}let d=t.dom;if(d)for(let f of Pn){let p=d[f.key];!p||!existsSync(p)||(j.push(ce(p,join(n,f.dest)).then(()=>{})),o[f.field]=`${r}/${Mt}/${s}/${f.dest}`);}if(!l&&i)return null;let c=t.expectedPath?na(t.expectedPath):t.actualPath?na(t.actualPath):null,v=sa(t.diffPixels,c),g=t.committedPath??t.expectedPath,h=g?relative(a,g).replace(/\\/g,"/"):void 0;return {name:t.name,status:t.status,source:t.source,...o,...h?{baselinePath:h}:{},...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}:{},...v!==void 0?{diffPixelRatio:v}:{},...d?{domChanges:d.changes,domChangeCount:d.total,domRootCauses:d.rootCauses,domTruncated:d.truncated,domCaptureBox:d.captureBox}:{}}}function ua(t,e,r,a,s,n,i=process.cwd()){if(t.length===0)return null;let o=da(e,r,n),l=s?["artifacts",s,o]:["artifacts",o],d=join(a,...l,Mt),c=l.join("/");try{mkdirSync(d,{recursive:!0});}catch{return null}let v=[];for(let g of t){let h=Ln(g,d,c,i);h&&v.push(h);}return v.length>0?v:null}var pa="testrelic-visual-dom";var Dn="testrelic-visual",Nn=/^(.+)-(expected|actual|diff|previous)(\.[A-Za-z0-9]+)$/;function Fn(t){let e=new Map;for(let r of t)if(!(r.name!==Dn||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let s of a){let n=On(s);n&&e.set(n.stem,n);}}catch{}return e}var Bn=["passed","failed","new","updated"];function On(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"||!Bn.includes(e.status)?null:{stem:e.stem,name:e.name,status:e.status,...typeof e.committedPath=="string"&&e.committedPath?{committedPath:e.committedPath}:{}}}function Un(t){let e=new Map;for(let r of t)if(!(r.name!==pa||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let s of a){if(typeof s!="object"||s===null)continue;let n=s;typeof n.stem!="string"||!Array.isArray(n.changes)||e.set(n.stem,s);}}catch{}return e}function Hn(t){let e=new Map;for(let r of t){if(!r.path)continue;let a=Nn.exec(r.name);if(!a)continue;let[,s,n]=a,i=e.get(s)??{};i[n]=r.path,e.set(s,i);}return e}function zn(t){return !!(t.actual&&(t.expected||t.diff))}function qn(t,e,r){return t.diff||ra(r)?"failed":e?"updated":"new"}function $n(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]+$/,""),a=t.filter(s=>s===r||s.endsWith(`/${r}`));return a.length===1?a[0]:null}function ha(t,e={}){if(t.length===0)return [];let r=Fn(t),a=Un(t),s=Hn(t);if(s.size===0&&r.size===0)return [];let n=e.updatingSnapshots===true,i=[];for(let[o,l]of s){let d=r.get(o);!d&&!zn(l)||i.push({name:d?.name??o,status:d?.status??qn(l,n,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}:{},...a.has(o)?{dom:a.get(o)}:{}});}for(let[o,l]of r)s.has(o)||i.push({name:l.name,status:l.status,source:"toMatchVisualBaseline",...l.committedPath?{committedPath:l.committedPath}:{},...a.has(o)?{dom:a.get(o)}:{}});return Vn(i,s,e.failureMessage)}function Vn(t,e,r){let a=aa(r);if(a.diffPixels===void 0&&a.actualWidth===void 0)return [...t];let s=t.filter(i=>i.status==="failed"&&fa(i)).map(i=>ga(i,e)),n=$n(s,a.snapshotName);return n===null?[...t]:t.map(i=>fa(i)&&ga(i,e)===n?{...i,...a.diffPixels!==void 0?{diffPixels:a.diffPixels}:{},...a.actualWidth!==void 0?{actualWidth:a.actualWidth}:{},...a.actualHeight!==void 0?{actualHeight:a.actualHeight}:{}}:i)}function fa(t){return !!(t.expectedPath||t.actualPath||t.diffPath||t.previousPath)}function ga(t,e){if(e.has(t.name))return t.name;for(let[r,a]of e)if(a.actual===t.actualPath&&a.expected===t.expectedPath&&a.diff===t.diffPath)return r;return t.name}var jn=new RegExp("[\x1B\x9B][[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[0-9A-PR-TZcf-nqry=><]","g");function Re(t){return !t||t.indexOf("\x1B")===-1&&t.indexOf("\x9B")===-1?t:t.replace(jn,"")}function ma(t){return t==null?null:Re(t)}var Gn=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Wn="1.0",Pt="visual";function xa(t){let e=extname(t).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(e)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(e)?"video":e===".zip"&&basename(t,e)==="trace"?"trace":"other"}function Kn(t){if(t.endsWith(".dom.json"))return "dom";let e=basename(t,extname(t));return e==="baseline"?"baseline":e==="diff"?"diff":xa(t)}function Jn(t,e,r){let a=[];try{for(let s of readdirSync(t,{withFileTypes:!0})){if(!s.isFile())continue;let n=statSync(join(t,s.name));a.push({name:`${Pt}/${r}/${s.name}`,type:Kn(s.name),relativePath:`${e}/${Pt}/${r}/${s.name}`,sizeBytes:n.size});}}catch{}return a}function wa(t,e,r){let a=[],s=`artifacts/${e}/${r}`;try{let n=readdirSync(t,{withFileTypes:!0});for(let i of n){if(i.isDirectory()&&i.name===Pt){let d=join(t,i.name);for(let c of readdirSync(d,{withFileTypes:!0}))c.isDirectory()&&a.push(...Jn(join(d,c.name),s,c.name));continue}if(!i.isFile())continue;let o=join(t,i.name),l=statSync(o);a.push({name:i.name,type:xa(i.name),relativePath:`${s}/${i.name}`,sizeBytes:l.size});}}catch{}return {testName:r,files:a}}function Yn(t,e){let r=join(t,e),a=[],s=0;try{let i=readdirSync(r,{withFileTypes:!0});for(let o of i){if(!o.isDirectory())continue;let l=wa(join(r,o.name),e,o.name);a.push(l);for(let d of l.files)s+=d.sizeBytes;}}catch{}let n=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return a.sort((i,o)=>i.testName.localeCompare(o.testName)),{folderName:e,timestamp:n,totalSizeBytes:s,testCount:a.length,tests:a,isCurrentRun:false}}function ka(t,e){let r=join(t,"artifacts"),a=[],s=[],n=0;try{let o=readdirSync(r,{withFileTypes:!0});for(let l of o)if(l.isDirectory())if(Gn.test(l.name)){let d=Yn(r,l.name);a.push({...d,isCurrentRun:l.name===e});}else {let d=wa(join(r,l.name),l.name,l.name);s.push(d);for(let c of d.files)n+=c.sizeBytes;}}catch{}a.sort((o,l)=>l.timestamp.localeCompare(o.timestamp)),s.length>0&&(s.sort((o,l)=>o.testName.localeCompare(l.testName)),a.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:n,testCount:s.length,tests:s,isCurrentRun:false}));let i=a.reduce((o,l)=>o+l.totalSizeBytes,0);return {schemaVersion:Wn,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:i,runs:a,serverPort:null}}var ri=256;function ai(t){let e=resolve(t);for(let r=0;r<ri;r++){if(existsSync(join(e,".git")))return e;let a=dirname(e);if(a===e)return null;e=a;}return null}function Ca(t){try{let e=ai(t);if(!e)return;let r=join(e,".gitignore"),a=relative(e,t).replace(/\\/g,"/"),s=a.endsWith("/")?a:`${a}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
|
|
4350
4351
|
`).map(l=>l.trim()).some(l=>l===s||l===a))return;let n=`
|
|
4351
4352
|
# TestRelic test artifacts
|
|
4352
4353
|
${s}
|
|
4353
|
-
`;appendFileSync(r,n,"utf-8");}catch{}}var
|
|
4354
|
+
`;appendFileSync(r,n,"utf-8");}catch{}}var Ra=Symbol("testrelic.timeout"),Aa=3e4,Lt=12e4,Dt=6e4,_a=15e3;async function Q(t,e,r){let a,s=new Promise(n=>{a=setTimeout(()=>n(Ra),e),typeof a?.unref=="function"&&a.unref();});try{let n=await Promise.race([t(),s]);if(n===Ra){process.stderr.write(`[testrelic] ${r} timed out after ${Math.round(e/1e3)}s \u2014 continuing without it. Your tests are unaffected.
|
|
4354
4355
|
`);return}return n}catch(n){process.stderr.write(`[testrelic] ${r} failed \u2014 continuing without it. Your tests are unaffected. (${n instanceof Error?n.message:String(n)})
|
|
4355
|
-
`);return}finally{a&&clearTimeout(a);}}function
|
|
4356
|
-
`}function
|
|
4356
|
+
`);return}finally{a&&clearTimeout(a);}}function Ea(t,e){let r=[];for(let a of t){let s=si(a),n=ni(a),i=ii(a,s,n,e),o=oi(a,s,n);if(i.length===0&&o.length===0){r.push({type:"navigation",url:"about:blank",timestamp:a.startedAt,durationOnUrl:a.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:a.specFile,test:s,tests:[n],_testTitle:a.title});continue}r.push(...i,...o);}return r.sort(li),di(r,t),r.map((a,s)=>a.type==="navigation"?{...{index:s,type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:a.durationOnUrl??0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:a.specFile,test:a.test},tests:a.tests}:{...{index:s,type:"api_call",callId:a.callId,method:a.method,url:a.url,timestamp:a.timestamp,responseTime:a.responseTime??null,request:a.request,response:a.response??null,...a.error?{error:a.error}:{},assertions:a.assertions??[],specFile:a.specFile,test:a.test},tests:a.tests})}function si(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 ni(t){return {title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,retry:t.retry,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,networkRequests:t.networkRequests,apiCalls:t.apiCalls,apiAssertions:t.apiAssertions,actions:t.actions,consoleLogs:t.consoleLogs}}function ii(t,e,r,a){let s=[];for(let n of t.navigations)a.navigationTypes!==null&&!a.navigationTypes.includes(n.navigationType)||s.push({type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title});return s}function oi(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let a=t.apiAssertions??[];return t.apiCalls.map(s=>{let n=a.filter(o=>o.callId===s.id).map(o=>({type:o.type,expected:o.expected,actual:o.actual,status:o.status,location:o.location,...o.expression!==void 0?{expression:o.expression}:{}})),i=null;return s.responseStatusCode!==null&&s.responseStatusText!==null&&(i={statusCode:s.responseStatusCode,statusText:s.responseStatusText,headers:s.responseHeaders,body:Ma(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:Ma(s.requestBody)},response:i,...s.error?{error:s.error}:{},assertions:n,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function li(t,e){let r=new Date(t.timestamp).getTime(),a=new Date(e.timestamp).getTime();if(r!==a)return r-a;let s={navigation:0,api_call:1},n=s[t.type],i=s[e.type];return n!==i?n-i:t.type==="api_call"&&e.type==="api_call"&&t.callId&&e.callId?Ia(t.callId)-Ia(e.callId):0}function Ia(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function di(t,e){for(let r=0;r<t.length;r++){let a=t[r];if(a.type!=="navigation")continue;let s=new Date(a.timestamp).getTime(),n=null;for(let i=r+1;i<t.length;i++)if(t[i]._testTitle===a._testTitle&&t[i].test.retry===a.test.retry){n=new Date(t[i].timestamp).getTime();break}if(n!==null)a.durationOnUrl=Math.max(0,n-s);else {let i=e.find(o=>o.title===a._testTitle&&o.retry===a.test.retry);if(i){let o=new Date(i.completedAt).getTime();a.durationOnUrl=Math.max(0,o-s);}}}}function Ma(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function ee(t,e){let r=t.length,a=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,a)]}function Nt(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function ci(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 Pa(t,e){let r=0,a=0,s=0,n=0,i=0;for(let w of t)switch(w.status){case "passed":r++;break;case "failed":a++;break;case "flaky":s++;break;case "skipped":n++;break;case "timedout":i++;break}let o=[];for(let w of t)w.apiCalls&&o.push(...w.apiCalls);let l=o.length,d=new Set,c={},v={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},g=[];for(let w of o)d.add(Nt(w.url)),c[w.method]=(c[w.method]??0)+1,v[ci(w.responseStatusCode)]+=1,g.push(w.responseTimeMs);let h=null;if(g.length>0){let w=[...g].sort((E,J)=>E-J),R=w.reduce((E,J)=>E+J,0);h={avg:Math.round(R/w.length),min:w[0],max:w[w.length-1],p50:ee(w,50),p95:ee(w,95),p99:ee(w,99)};}let f=0,p=0,u=0;for(let w of t)if(w.apiAssertions)for(let R of w.apiAssertions)f++,R.status==="passed"?p++:u++;let b=0,m=new Set;for(let w of t){b+=w.navigations.length;for(let R of w.navigations)m.add(R.url);}let y=0,x={};function k(w){for(let R of w)y++,x[R.category]=(x[R.category]??0)+1,R.children.length>0&&k(R.children);}for(let w of t)w.actions&&k(w.actions);let T=0,D=0,C=0,A=0;for(let w of t)if(w.visual)for(let R of w.visual)T++,R.status==="failed"?D++:(R.status==="new"||R.status==="updated")&&C++,A+=R.domChangeCount??0;return {total:t.length,passed:r,failed:a,flaky:s,skipped:n,timedout:i,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:c,apiCallsByStatusRange:v,apiResponseTime:h,totalAssertions:f,passedAssertions:p,failedAssertions:u,totalNavigations:b,uniqueNavigationUrls:m.size,totalTimelineSteps:e,totalActionSteps:y,actionStepsByCategory:x,visualChecks:T,visualFailures:D,visualNew:C,visualDomChanges:A}}function ui(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function L(t){return `\u2502 ${ui(t)} \u2502
|
|
4357
|
+
`}function Ft(t,e,r,a,s){if(a||t.total===0)return;let n=`\u250C${"\u2500".repeat(58)}\u2510
|
|
4357
4358
|
`,i=`\u2514${"\u2500".repeat(58)}\u2518
|
|
4358
|
-
`,o=
|
|
4359
|
-
`,process.stderr.write(l);}var
|
|
4360
|
-
`)[0]?.trim();return a?
|
|
4361
|
-
`),a=JSON.stringify(
|
|
4362
|
-
`),a=JSON.stringify(
|
|
4363
|
-
`),a=JSON.stringify(
|
|
4364
|
-
`),a=JSON.stringify(
|
|
4359
|
+
`,o=L(""),l=n;l+=L("TestRelic AI - Playwright Test Report"),l+=o;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 v=Object.entries(t.apiCallsByMethod).filter(([,h])=>h>0).map(([h,f])=>`${h}: ${f}`);v.length>0&&(l+=L(` ${v.join(" ")}`));let g=Object.entries(t.apiCallsByStatusRange).filter(([,h])=>h>0).map(([h,f])=>`${h}: ${f}`);g.length>0&&(l+=L(` ${g.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 v=[],g=t.actionStepsByCategory;g.ui_action&&v.push(`${g.ui_action} UI`),g.assertion&&v.push(`${g.assertion} assertions`),g.custom_step&&v.push(`${g.custom_step} custom`);let h=v.length>0?` (${v.join(" ")})`:"";l+=L(`Actions: ${t.totalActionSteps} steps${h}`);}l+=L(`Report: ${r}`),l+=L(`Data: ${e}`),l+=i,l+=`For more information visit us at https://docs.testrelic.ai
|
|
4360
|
+
`,process.stderr.write(l);}var pi=new Set(["pw:api","expect","test.step"]);function fi(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function Bt(t,e,r){if(pi.has(t.category)){let a=[];for(let n of t.steps)Bt(n,e,a);let s=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:fi(t.category),timestamp:t.startTime.toISOString(),duration:t.duration,videoOffset:s>=0?s/1e3:null,status:t.error?"failed":"passed",error:ma(t.error?.message),children:a});}else for(let a of t.steps)Bt(a,e,r);}function La(t,e){let r=[];for(let a of t)Bt(a,e,r);return r}var mi=new Set(["localhost","127.0.0.1","0.0.0.0"]);function Na(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&mi.has(e.hostname)))throw createError(ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var vi=3e3;async function Ot(t){let e=new AbortController,r=setTimeout(()=>e.abort(),vi);try{return (await fetch(`${t}/health`,{method:"GET",signal:e.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function Fa(t){return new Promise(e=>setTimeout(e,t))}async function Da(t){try{let r=(await t.json()).error;if(r&&typeof r.message=="string"){let a=r.details;if(Array.isArray(a)&&a.length>0){let s=a.map(n=>`${n.field}: ${n.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${t.status}`}async function Ut(t,e,r){let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let n=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:a.signal});if(n.ok){let o=await n.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn,orgId:o.orgId,orgName:o.orgName,userId:o.userId,userName:o.userName}}if(n.status===429){let o=n.headers.get("Retry-After"),l=o?parseInt(o,10)*1e3:5e3;if(!isNaN(l)&&l>0){await Fa(l);let d=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:a.signal});if(d.ok){let c=await d.json();return {accessToken:c.accessToken,refreshToken:c.refreshToken,expiresIn:c.expiresIn,orgId:c.orgId,orgName:c.orgName,userId:c.userId,userName:c.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return n.status===400?{code:"validation_error",message:await Da(n),statusCode:400}:n.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:n.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await Da(n),statusCode:n.status}}catch(n){return n instanceof DOMException&&n.name==="AbortError"?{code:"timeout",message:"Token exchange timed out.",statusCode:null}:{code:"network_error",message:"Failed to reach cloud for token exchange.",statusCode:null}}finally{clearTimeout(s);}}function Ht(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 Ba(t,e,r){let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let n=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:a.signal});if(n.status===429){let o=n.headers.get("Retry-After"),l=o?parseInt(o,10)*1e3:5e3;!isNaN(l)&&l>0&&(await Fa(l),n=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:a.signal}));}if(!n.ok)return null;let i=await n.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn}}catch{return null}finally{clearTimeout(s);}}async function Oa(t,e,r,a,s,n){let i=new AbortController,o=setTimeout(()=>i.abort(),s);try{let l={gitId:r,displayName:a};n&&(l.branch=n);let d=await fetch(`${t}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(l),signal:i.signal});if(!d.ok)return null;let c=await d.json();return {repoId:c.repoId,displayName:c.displayName}}catch{return null}finally{clearTimeout(o);}}var ki=5e3;function W(t,e){try{return execSync(t,{cwd:e,timeout:ki,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Ua(t){let e=W("git rev-parse --abbrev-ref HEAD",t),r=W("git rev-parse --short HEAD",t),a=W("git log -1 --pretty=%s",t),s=W("git log -1 --format=%an",t)??W("git config user.name",t),n=Si(t),i=n?pe(n):null;return {branch:e,commitSha:r,commitMessage:a,commitAuthor:s,remoteUrl:i}}function Si(t){let e=W("git remote get-url origin",t);if(e)return e;let r=W("git remote",t);if(!r)return null;let a=r.split(`
|
|
4361
|
+
`)[0]?.trim();return a?W(`git remote get-url ${a}`,t):null}function pe(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 Ha(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??t}function zt(t){try{let e=readFileSync(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 fe(t){let e=zt(t);return e||`local/${basename(t)}`}var Ti=new Set(["smoke","regression","nightly","ci"]);function Ae(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&Ti.has(t))return t}async function K(t,e,r){let a=new AbortController,s=setTimeout(()=>a.abort(),Math.max(1,r));try{return await fetch(t,{...e,signal:a.signal})}finally{clearTimeout(s);}}function za(t,e){let r=e+Math.ceil(Math.max(0,t)/1e3);return Math.min(6e5,Math.max(3e4,r))}var _e=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 Ai=1048576,Ie=[1e3,3e3,9e3],Me=3,$a=3e4,_i=90*1048576,Ii=new Set(["e2e","mobile","unit"]);function $t(t){let e=new ge;for(let r of t??[])e.add(r.testType,r.apiProtocol);return e.signal()}var ge=class{constructor(){this.total=0;this.apiProtocols=new Map;this.nonApi=new Map;}add(e,r){if(this.total++,e==="api"){let a=r??"rest";this.apiProtocols.set(a,(this.apiProtocols.get(a)??0)+1);}else Ii.has(e)&&this.nonApi.set(e,(this.nonApi.get(e)??0)+1);}signal(){let e=0;for(let s of this.apiProtocols.values())e+=s;if(this.total>0&&e===this.total){let s="rest",n=0;for(let[i,o]of this.apiProtocols)o>n&&(n=o,s=i);return {testType:"api",apiProtocol:s,metadata:{testType:"api",primaryProtocol:s}}}let r=null,a=0;for(let[s,n]of this.nonApi)n>a&&(a=n,r=s);return {testType:r??"e2e"}}};function Vt(t,e,r,a,s,n){let i=n?.cloudPlatform?n.cloudPlatform:a?.provider&&a.provider!=="unknown"?a.provider:"local",o=Ae(),l=$t(s),d=l.testType==="api"?l:null,c=d&&s?s.map(g=>g.apiProtocol?g:{...g,apiProtocol:d.apiProtocol}):s;return {runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,environment:i,...o?{runType:o}:{},...d?{testType:d.testType,apiProtocol:d.apiProtocol,metadata:d.metadata}:{testType:l.testType},...c&&c.length>0?{tests:c}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...a?.provider?{ciProvider:a.provider}:{},...a?.runUrl?{ciRunUrl:a.runUrl}:{},...n?.cloudPlatform?{cloudPlatform:n.cloudPlatform}:{},...n?.cloudBuildId?{cloudBuildId:n.cloudBuildId}:{},...n?.cloudSessionId?{cloudSessionId:n.cloudSessionId}:{}}}function qt(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function Pe(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:qt(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:qt(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 Le(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,a=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:qt(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:a,startedAt:a}}):[]}function De(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 a=r.status==="failed"?"failed":"passed",s=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,n=r.kind??r.type??"assertion",i=a==="failed"?`expected ${e(r.expected)}, received ${e(r.actual)}`:r.expected!==void 0?`expected ${e(r.expected)}`:null;return {...r.callId!=null?{callId:r.callId}:{},kind:n,description:s??r.description??`${n} assertion`,status:a,detail:i}})}async function Ee(t){return new Promise(e=>setTimeout(e,t))}function Mi(t){let e={};for(let[r,a]of Object.entries(t))a!=null&&(e[r]=a);return e}async function Va(t,e,r,a=$a,s){for(let n=0;n<Me;n++){if(s?.expired())return null;let i=s?s.slice(a):a;if(i<=0)return null;try{let o=await K(t,e,i);if(o.ok)return o;if(o.status===401&&r&&n===0){let l=await r();if(l){let d={...e,headers:{...e.headers,Authorization:`Bearer ${l}`}},c=await K(t,d,i);if(c.ok)return c}return null}if(o.status===429&&n<Me-1){let l=o.headers.get("Retry-After"),d=l?parseInt(l,10)*1e3:Ie[n];!isNaN(d)&&d>0?await Ee(d):await Ee(Ie[n]);continue}if(o.status>=500&&n<Me-1){await Ee(Ie[n]);continue}return o}catch{if(n<Me-1){await Ee(Ie[n]);continue}return null}}return null}var Ei=promisify(gzip);function qa(t,e){if(!Array.isArray(t.tests))return t;let r=t.tests.map(a=>{let{consoleLogs:s,networkRequests:n,apiCalls:i,...o}=a;return e?o:{...o,...i!==void 0?{apiCalls:i}:{}}});return {...t,tests:r}}var Pi=["consoleLogs","networkRequests","apiCalls","actions","navigations","protocolAssertions","visual"];function Li(t){if(!Array.isArray(t.tests))return t;let e=new Set(Pi),r=t.tests.map(a=>{let s={};for(let n in a)if(!e.has(n))if(n==="failure"&&a[n]&&typeof a[n]=="object"){let i=a[n];s.failure={message:i.message??null,line:i.line??null};}else s[n]=a[n];return s});return {...t,tests:r}}function Di(t){let e=new Set(["tests","timeline","unifiedTimeline","navigations"]),r={};for(let a in t)e.has(a)||(r[a]=t[a]);return r.tests=[],r}async function jt(t,e=_i){let r={"Content-Type":"application/json"},a=JSON.stringify(t),s=t,n=Array.isArray(s?.tests)?s.tests.length:0,i=o=>Buffer.byteLength(o,"utf-8")>e;if(n>0&&i(a)){let o=Math.max(1,Math.round(e/1048576));process.stderr.write(`[testrelic] WARNING: batch payload exceeds ${o}MB \u2014 dropping consoleLogs/networkRequests from ${n} test(s) to avoid HTTP 413. Console/network detail will be missing in the cloud.
|
|
4362
|
+
`),a=JSON.stringify(qa(s,false)),i(a)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${o}MB after dropping logs \u2014 also dropping apiCalls from ${n} test(s). API request/response detail will be missing in the cloud.
|
|
4363
|
+
`),a=JSON.stringify(qa(s,true))),i(a)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${o}MB \u2014 shedding remaining per-test detail (actions/navigations/assertions) from ${n} test(s). Only test results + summary will reach the cloud.
|
|
4364
|
+
`),a=JSON.stringify(Li(s))),i(a)&&(process.stderr.write(`[testrelic] ERROR: batch still exceeds ${o}MB after shedding all per-test detail \u2014 uploading run summary only (${n} per-test result(s) omitted) to avoid losing the run to HTTP 413.
|
|
4365
|
+
`),a=JSON.stringify(Di(s)));}if(Buffer.byteLength(a,"utf-8")>Ai){r["Content-Encoding"]="gzip";let o=await Ei(Buffer.from(a,"utf-8")),l=o.buffer;return {body:new Uint8Array(l,o.byteOffset,o.byteLength),headers:r}}return {body:a,headers:r}}async function ja(t,e,r,a,s,n){let i=`${t}/runs`,{body:o,headers:l}=await jt(r);l.Authorization=`Bearer ${e}`;let d=await Va(i,{method:"POST",headers:l,body:o},a,s,n);return d?.ok?{success:true,statusCode:d.status,error:null}:d?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:d?`Upload failed with status ${d.status}`:"Upload failed after retries",statusCode:d?.status??null,payload:r,targetEndpoint:i,method:"POST"}}async function Ga(t,e,r,a){let s=`${t}/runs/init`;try{let n=await K(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(Mi(r))},a??$a);return n.ok?{runId:(await n.json()).runId}:null}catch{return null}}function Wa(t,e,r,a){let s=`${t}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(a)}).catch(()=>{});}async function Ka(t,e,r,a){let s=`${t}/runs/${r}/finalize`;return (await Va(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(a)}))?.ok??false}function Gt(t,e,r,a){let s=`${t}/runs/${r}/finalize`,n=new Date,i={finishedAt:n.toISOString(),duration:n.getTime()-new Date(a).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(i)}).catch(()=>{});}var Ui="1.0.0",Ja=10;function Ya(t){return t instanceof Error?t.message:String(t)}function Hi(t){return t>=400&&t<500&&t!==408&&t!==429}function he(t,e,r,a,s,n,i,o){try{mkdirSync(t,{recursive:!0});let l=Date.now(),d=`${l}-${e}-${r}.json`,c=join(t,d),v={version:Ui,queuedAt:new Date(l).toISOString(),reason:a,retryCount:0,targetEndpoint:s,method:n,payload:i,headers:o},g=c+".tmp";writeFileSync(g,JSON.stringify(v,null,2),"utf-8"),renameSync(g,c);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
|
|
4365
4366
|
`):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
|
|
4366
|
-
`);}}async function
|
|
4367
|
-
`),unlinkSync(o);continue}l=c;}catch(d){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${i}: ${
|
|
4368
|
-
`);try{unlinkSync(o);}catch{}continue}try{let{body:d,headers:c}=await
|
|
4369
|
-
`);try{renameSync(o,`${o}.failed`);}catch{try{unlinkSync(o);}catch{}}}else {process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 server returned HTTP ${
|
|
4370
|
-
`);return}}catch(d){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${
|
|
4371
|
-
`);return}}}function
|
|
4372
|
-
`);return}try{if(
|
|
4373
|
-
`);return}let r=await
|
|
4374
|
-
`),await this.resolveRepoId(),this.config.queueDirectory&&(
|
|
4375
|
-
`);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}getRepoId(){return this.repoId}getGitMetadata(){return this.gitMetadata}getConfig(){return this.config}getFailureReason(){return this.failureReason}getEndpoint(){return this.config?.endpoint??"https://platform.testrelic.ai/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let
|
|
4376
|
-
`));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,
|
|
4377
|
-
\u2192 Manage keys: ${
|
|
4367
|
+
`);}}async function es(t,e,r){let a;try{a=readdirSync(t).filter(n=>n.endsWith(".json")&&!n.endsWith(".tmp")).sort();}catch{return}if(a.length===0)return;let s=[];for(let n=0;n<a.length;n+=Ja)s.push(a.slice(n,n+Ja));for(let n of s)for(let i of n){let o=join(t,i),l;try{if(!statSync(o).isFile())continue;let c=JSON.parse(readFileSync(o,"utf-8"));if(!isValidQueueEntry(c)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${i}
|
|
4368
|
+
`),unlinkSync(o);continue}l=c;}catch(d){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${i}: ${Ya(d)}
|
|
4369
|
+
`);try{unlinkSync(o);}catch{}continue}try{let{body:d,headers:c}=await jt(l.payload),v={...l.headers,...c,Authorization:`Bearer ${r}`},g=await fetch(l.targetEndpoint,{method:l.method,headers:v,body:d});if(g.ok)unlinkSync(o);else if(Hi(g.status)){process.stderr.write(`\u26A0 TestRelic: Queue entry ${i} rejected (HTTP ${g.status}) \u2014 moving aside; it will not be retried.
|
|
4370
|
+
`);try{renameSync(o,`${o}.failed`);}catch{try{unlinkSync(o);}catch{}}}else {process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 server returned HTTP ${g.status} for ${i}; will retry later.
|
|
4371
|
+
`);return}}catch(d){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${Ya(d)}; will retry later.
|
|
4372
|
+
`);return}}}function ts(t,e){try{let r=readdirSync(t).filter(s=>(s.endsWith(".json")||s.endsWith(".failed"))&&!s.endsWith(".tmp")),a=Date.now();for(let s of r){let n=join(t,s);try{let i=readFileSync(n,"utf-8"),l=JSON.parse(i).queuedAt;if(typeof l=="string"){let d=new Date(l).getTime();a-d>e&&unlinkSync(n);}}catch{try{unlinkSync(n);}catch{}}}}catch{}}var Wi=3e5,Ki=864e5,Ji=6e4,rs=3e4,Jt="https://platform.testrelic.ai/settings/api-keys";function as(t){return new Promise(e=>{let r=setTimeout(e,t);typeof r?.unref=="function"&&r.unref();})}var Ne=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.
|
|
4373
|
+
`);return}try{if(Na(this.config.endpoint),this.gitMetadata=Ua(),!await Ot(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.
|
|
4374
|
+
`);return}let r=await Ut(this.config.endpoint,this.config.apiKey,this.config.timeout);if(Ht(r)){this.handleAuthError(r.code,r.statusCode);return}let a=r;this.authState={mode:"cloud",accessToken:a.accessToken,refreshToken:a.refreshToken,expiresAt:Date.now()+a.expiresIn*1e3,orgId:a.orgId,orgName:a.orgName,userId:a.userId,userName:a.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${a.orgName} / ${a.userName})
|
|
4375
|
+
`),await this.resolveRepoId(),this.config.queueDirectory&&(ts(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)}
|
|
4376
|
+
`);}}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()+Wi<e)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Ba(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}).
|
|
4377
|
+
`));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,as(rs)]);}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.
|
|
4378
|
+
\u2192 Manage keys: ${Jt}
|
|
4378
4379
|
`);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
|
|
4379
|
-
\u2192 Generate a new key: ${
|
|
4380
|
+
\u2192 Generate a new key: ${Jt}
|
|
4380
4381
|
`);break;case "validation_error":this.setLocalMode("validation_error"),process.stderr.write(`\u26A0 TestRelic: API key format invalid. Running in local mode.
|
|
4381
|
-
\u2192 Manage keys: ${
|
|
4382
|
+
\u2192 Manage keys: ${Jt}
|
|
4382
4383
|
`);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
|
|
4383
4384
|
`);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
|
|
4384
4385
|
`);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
|
|
4385
|
-
`);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let
|
|
4386
|
-
`);}readRepoCache(
|
|
4387
|
-
`),this.startBackgroundFlush();}}}catch{}},
|
|
4388
|
-
`);}
|
|
4389
|
-
`),{navigations:s,apiAssertions:n,networkRequestsFile:i,networkRequestsCount:o,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:c,apiCallsCount:p,apiStatusMix:y}}function Ie(e=process.env){let t=Vi(e.TESTRELIC_CLOUD_PLATFORM);if(t)return {cloudPlatform:t,cloudBuildId:e.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:e.TESTRELIC_CLOUD_SESSION_ID||void 0};if(e.BROWSERSTACK_USERNAME||e.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:e.BROWSERSTACK_BUILD_NAME||e.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:e.BROWSERSTACK_SESSION_ID||void 0};if(e.LT_USERNAME||e.LAMBDATEST_USERNAME||e.LT_ACCESS_KEY||e.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:e.LT_BUILD||e.LAMBDATEST_BUILD||void 0,cloudSessionId:e.LT_SESSION_ID||e.LAMBDATEST_SESSION_ID||void 0};let r=e.PLAYWRIGHT_WS_ENDPOINT;if(r){if(/cdp\.lambdatest\.com/i.test(r))return {cloudPlatform:"lambdatest"};if(/cdp\.browserstack\.com/i.test(r))return {cloudPlatform:"browserstack"}}return {}}function Vi(e){if(!e)return;let t=e.toLowerCase().trim();if(t==="browserstack"||t==="bs")return "browserstack";if(t==="lambdatest"||t==="lt")return "lambdatest"}var Ki=5,Me=[1e3,3e3,9e3],te=3,jt=3e4,Ji={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip",".json":"application/json"},Vt=0,$t=[];async function Yi(){Vt>=Ki&&await new Promise(e=>$t.push(e)),Vt++;}function Xi(){Vt--,$t.length>0&&$t.shift()();}async function Ee(e){return new Promise(t=>setTimeout(t,e))}function Zi(e){let t=e.substring(e.lastIndexOf(".")).toLowerCase();return Ji[t]??"application/octet-stream"}function Qi(e){try{return statSync(e).size}catch{return 0}}async function eo(e,t,r,a,s){let n=`${e}/artifacts/upload-url`,i=JSON.stringify({runId:r.runId,testId:r.testId,...r.retry!==void 0?{retry:r.retry}:{},fileName:basename(r.filePath),contentType:s,type:r.type,sizeBytes:a});for(let o=0;o<te;o++)try{let l=await $(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:i},jt);if(l.ok)return await l.json();if(l.status>=500&&o<te-1){await Ee(Me[o]);continue}return null}catch{if(o<te-1){await Ee(Me[o]);continue}return null}return null}async function to(e,t,r,a){let s=La(a,jt);for(let n=0;n<te;n++)try{let i=createReadStream(t),o=Readable.toWeb(i),l=await $(e,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(a)},body:o,duplex:"half"},s);if(l.ok)return !0;if(l.status>=500&&n<te-1){await Ee(Me[n]);continue}return !1}catch{if(n<te-1){await Ee(Me[n]);continue}return false}return false}async function ro(e,t,r){let a=`${e}/artifacts/confirm`;try{return (await $(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({artifactId:r})},jt)).ok}catch{return false}}async function ao(e,t,r,a){let s=Qi(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>a*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let n=Zi(r.filePath);await Yi();try{let i=await eo(e,t,r,s,n);if(!i)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await to(i.uploadUrl,r.filePath,n,s))return {success:!1,storageKey:i.storageKey,artifactId:i.artifactId,error:"presigned_put_failed"};let l=await ro(e,t,i.artifactId);return {success:l,storageKey:i.storageKey,artifactId:i.artifactId,error:l?null:"confirm_failed"}}finally{Xi();}}async function Za(e,t,r,a,s){let n=new Map,i=r.map(async o=>{if(s?.expired()){n.set(o.filePath,{success:false,storageKey:null,artifactId:null,error:"upload_budget_exhausted"});return}let l=await ao(e,t,o,a);n.set(o.filePath,l);});return await Promise.allSettled(i),n}function Wt(e){let r=e.getGitMetadata()?.remoteUrl;return r?ce(r):e.getConfig()?.projectName??ue(process.cwd())}async function Qa(e,t,r,a,s){if(!e.isCloudMode()||t!=="realtime"&&t!=="both"||!await e.ensureValidToken())return null;let i=e.getGitMetadata(),o=U(),l=Ie(),d=Se();return (await Ua(e.getEndpoint(),e.getAccessToken(),{runId:r,repoGitId:Wt(e),branch:i?.branch??null,commit:i?.commitSha??null,commitMessage:i?.commitMessage??null,commitAuthor:i?.commitAuthor??null,startedAt:a,totalTests:null,ciProvider:o?.provider??null,ciRunUrl:o?.runUrl??null,environment:s??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{},testType:"e2e"}))?.runId??null}var no=[{field:"baseline",keyField:"baselineKey",type:"baseline"},{field:"actual",keyField:"actualKey",type:"screenshot"},{field:"diff",keyField:"diffKey",type:"diff"},{field:"baselineDom",keyField:"baselineDomKey",type:"dom"},{field:"actualDom",keyField:"actualDomKey",type:"dom"}];function Kt(e,t){return `${e}#${t??0}`}function Jt(e,t,r){return r===void 0?e.get(t):e.get(Kt(t,r))}var io=true,oo=50,Gt={keyMap:new Map,visualKeyMap:new Map,total:0,uploaded:0};async function lo(e,t,r,a,s){let n=new Map,i=new Map;if(!(t?.uploadArtifacts??io)||!await e.ensureValidToken())return Gt;let d=[],c=new Map,p=new Map;for(let h of a){let g=Kt(h.testId,h.retry),v={runId:r,testId:h.testId,...h.retry!==void 0?{retry:h.retry}:{}};if(h.artifacts.screenshot){let x=join(h.outputDir,h.artifacts.screenshot);d.push({filePath:x,...v,type:"screenshot"}),c.set(x,{attemptKey:g,field:"screenshot"});}if(h.artifacts.video){let x=join(h.outputDir,h.artifacts.video);d.push({filePath:x,...v,type:"video"}),c.set(x,{attemptKey:g,field:"video"});}if(h.artifacts.trace){let x=join(h.outputDir,h.artifacts.trace);d.push({filePath:x,...v,type:"trace"}),c.set(x,{attemptKey:g,field:"trace"});}let w=h.visual??[];for(let x=0;x<w.length;x++){let A=w[x];if(A)for(let T of no){let R=A[T.field];if(!R)continue;let I=join(h.outputDir,R);d.push({filePath:I,...v,type:T.type}),c.set(I,{attemptKey:g,field:"visual",visualIndex:x,visualKey:T.keyField});}}}if(d.length===0)return Gt;let y=t?.artifactMaxSizeMb??oo,f=await Za(e.getEndpoint(),e.getAccessToken(),d,y,s),u=new Map;for(let[h,g]of f){if(!g.success||!g.storageKey)continue;let v=c.get(h);if(!v)continue;let w=u.get(v.attemptKey)??{};if(v.field==="screenshot"&&(w.screenshotKey=g.storageKey),v.field==="video"&&(w.videoKey=g.storageKey),v.field==="trace"&&(w.traceKey=g.storageKey),v.field==="visual"&&v.visualIndex!==void 0&&v.visualKey){let x=p.get(v.attemptKey)??new Map,A=x.get(v.visualIndex)??{};A[v.visualKey]=g.storageKey,x.set(v.visualIndex,A),p.set(v.attemptKey,x);}u.set(v.attemptKey,w);}let m=new Map;for(let h of a){let g=h.retry??0;(m.get(h.testId)??-1)<g&&m.set(h.testId,g);}for(let h of a){let g=Kt(h.testId,h.retry),v=(h.retry??0)===m.get(h.testId);if(h.visual&&h.visual.length>0){let A=p.get(g),T=h.visual.map((R,I)=>({...R,...A?.get(I)??{}}));i.set(g,T),v&&i.set(h.testId,T);}let w=u.get(g),x={...h.artifacts,...w?.screenshotKey?{screenshotKey:w.screenshotKey}:{},...w?.videoKey?{videoKey:w.videoKey}:{},...w?.traceKey?{traceKey:w.traceKey}:{}};n.set(g,x),v&&n.set(h.testId,x);}let b=Array.from(f.values()).filter(h=>h.success).length;return b>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${b} artifact(s) to cloud storage.
|
|
4390
|
-
`),{keyMap:n,visualKeyMap:i,total:d.length,uploaded:b}}async function Yt(e,t,r,a,s,n,i,o,l,d,c){let p={realtimeFinalizeAttempted:false,realtimeFinalized:false,batchAttempted:false,batchAcknowledged:false,artifactsTotal:0,artifactsUploaded:0,failureReason:null},y=new Ce(t?.uploadBudgetMs??12e4),f=u=>{p.failureReason||(p.failureReason=u);};try{if(e.isCloudMode()&&s&&(r==="realtime"||r==="both")){p.realtimeFinalizeAttempted=!0;let b=await e.ensureValidToken(),h=e.getGitMetadata(),g=Dt(c),v={finishedAt:i,duration:o,summary:l,...h?.commitMessage?{commitMessage:h.commitMessage}:{},testType:g.testType,...g.testType==="api"?{apiProtocol:g.apiProtocol,metadata:g.metadata}:{}};if(b){let w=await Ha(e.getEndpoint(),e.getAccessToken(),s,v);if(p.realtimeFinalized=w,!w){f("finalize_failed_after_retries");let x=t?.queueDirectory??".testrelic/queue";pe(x,a,"finalize","finalize_failed_after_retries",`${e.getEndpoint()}/runs/${s}/finalize`,"POST",v,{"Content-Type":"application/json"});}}else {f(e.getFailureReason()??"token_invalid");let w=t?.queueDirectory??".testrelic/queue";pe(w,a,"finalize",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs/${s}/finalize`,"POST",v,{"Content-Type":"application/json"});}}let u=new Map,m=new Map;if(e.isCloudMode()&&d&&d.length>0){let b=await lo(e,t,a,d,y);u=b.keyMap,m=b.visualKeyMap,p.artifactsTotal=b.total,p.artifactsUploaded=b.uploaded;}if(e.isCloudMode()&&(!r||r==="batch"||r==="both"))if(p.batchAttempted=!0,await e.ensureValidToken()){let h=e.getGitMetadata(),g=U(),v=Wt(e),w=uo(po(n,u),m),x=Lt(w,v,h,g,co(c,m),Ie()),A=await Oa(e.getEndpoint(),e.getAccessToken(),x,async()=>await e.ensureValidToken()?e.getAccessToken():null,t?.timeout,y);if(p.batchAcknowledged=A.success,!A.success){let T=A;f(T.reason);let R=t?.queueDirectory??".testrelic/queue";pe(R,a,"batch",T.reason,T.targetEndpoint,T.method,T.payload,{"Content-Type":"application/json"});}}else {f(e.getFailureReason()??"token_invalid");let h=t?.queueDirectory??".testrelic/queue",g=e.getGitMetadata(),v=U(),w=Wt(e),x=Lt(n,w,g,v,void 0,Ie());pe(h,a,"batch",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs`,"POST",x,{"Content-Type":"application/json"});}await e.dispose();}catch(u){f(u instanceof Error?u.message:"unexpected_upload_error");try{await e.dispose();}catch{}}return p}function co(e,t){return !e||t.size===0?e:e.map(r=>{let a=Jt(t,r.testId,r.retry);return a?{...r,visual:a}:r})}function uo(e,t){if(t.size===0)return e;let r=e.timeline.map(a=>{let s=a.tests;if(!Array.isArray(s))return a;let n=false,i=s.map(o=>{let{testId:l,retry:d}=o;if(!l)return o;let c=Jt(t,l,d);return c?(n=true,{...o,visual:c}):o});return n?{...a,tests:i}:a});return {...e,timeline:r}}function po(e,t){if(t.size===0)return e;let r=e.timeline.map(a=>{let s=a,n=s.testId;if(!n)return a;let i=Jt(t,n,s.retry);return i?{...a,...i.screenshotKey?{screenshotKey:i.screenshotKey}:{},...i.videoKey?{videoKey:i.videoKey}:{}}:a});return {...e,timeline:r}}var fo=new Set(["batch","realtime","both"]),fe=Object.freeze({attempted:false,acknowledged:false,runId:null,endpoint:null,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:"cloud reporting was never initialised"});function go(e){switch(e){case "no_api_key":return "cloud mode off \u2014 no API key configured";case "cloud_unreachable":case "network_error":return "cloud endpoint unreachable \u2014 the run stayed local";case "invalid_api_key":return "API key rejected as invalid or revoked \u2014 the run stayed local";case "expired_api_key":return "API key has expired \u2014 the run stayed local";case "validation_error":return "API key format rejected \u2014 the run stayed local";case "rate_limited":return "rate limited during authentication \u2014 the run stayed local";case "auth_timeout":return "authentication timed out \u2014 the run stayed local";case "token_expired_no_refresh":case "token_refresh_failed":case "token_refresh_error":return "access token could not be refreshed \u2014 the run stayed local";case "init_error":return "cloud initialisation timed out \u2014 the run stayed local";case "unexpected_error":return "cloud initialisation failed \u2014 the run stayed local";default:return e?`cloud mode off (${e}) \u2014 the run stayed local`:"cloud mode off \u2014 the run stayed local"}}function es(e,t,r){if(!e)return fe;if(!e.isCloudMode())return {...fe,detail:go(e.getFailureReason())};let a=t??"batch";if(!fo.has(a))return {...fe,detail:`upload strategy '${a}' is not recognised \u2014 nothing was sent`};let s=e.getEndpoint(),n=a==="realtime"||a==="both";return n&&r?{attempted:true,acknowledged:true,runId:r,endpoint:s,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:null}:{attempted:true,acknowledged:false,runId:null,endpoint:s,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:n?"run init failed \u2014 the platform did not acknowledge this run":`upload runs at the end of the run under the '${a}' strategy \u2014 not sent yet`}}function Xt(e,t,r){if(!e.attempted)return e;if(!t)return {...e,detail:e.acknowledged?"upload timed out before it completed \u2014 the run may be incomplete on the platform":"upload timed out before the platform acknowledged this run",acknowledged:e.acknowledged};let a=e.acknowledged||t.batchAcknowledged,s=e.runId??(t.batchAcknowledged?r:null),n=t.realtimeFinalizeAttempted?t.realtimeFinalized:t.batchAcknowledged,i=null;return a?n||(i="run acknowledged but not closed out \u2014 finalize failed and was queued for retry"):i=t.failureReason?`upload failed (${t.failureReason}) \u2014 queued locally for retry`:"upload failed \u2014 the platform did not acknowledge this run",{attempted:true,acknowledged:a,runId:s,endpoint:e.endpoint,finalized:n,artifactsUploaded:t.artifactsUploaded,artifactsTotal:t.artifactsTotal,detail:i}}function j(e){try{return readFileSync(e,"utf-8").split(`
|
|
4391
|
-
`).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function wo(e){if(!e)return null;let t=e.split(`
|
|
4392
|
-
`).map(n=>n.trim()).filter(Boolean);if(t.length===0)return null;let r=t.filter(n=>!/^Error:\s*expect\(/.test(n));if(r.length===0)return t[0]??null;let a=r[0],s=r[1];return s!==void 0&&/^Received:/.test(s)&&/^Expected:/.test(a)?`${a} \xB7 ${s}`:a}function Qt(e){switch(e){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function ko(e,t,r){let a=`${e}::${t}::${r}`;return createHash("sha256").update(a).digest("hex").substring(0,16)}function So(e){return e.length<=3?"":e[e.length-2]}function Co(e){let t=e.findIndex(r=>r.status==="passed");return t>0?`passed on retry ${t}`:null}function os(e){return e===null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function To(e){let t={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},r=t;for(let a of e){let s=typeof a.responseStatusCode=="number"?a.responseStatusCode:null;r[os(s)]++;}return t}function ss(e){if(e){for(let t of e)if(t.status==="failed")return {type:t.type,expected:ns(t.expected),actual:ns(t.actual),...t.expression?{expression:t.expression}:{}}}}function ns(e){if(e===void 0)return "undefined";if(e===null)return "null";let t;if(typeof e=="string")t=e;else try{t=JSON.stringify(e)??String(e);}catch{t=String(e);}return t.length>200?t.slice(0,200)+"\u2026":t}function De(e,t){if(!e)return 0;let r=0;for(let a of e)a.status===t&&r++;return r}function ls(e,t){for(let r of e)t[r.category]=(t[r.category]??0)+1,r.children.length>0&&ls(r.children,t);}function Ro(e){if(e.length===0)return null;let t=[...e].sort((a,s)=>a-s),r=t.reduce((a,s)=>a+s,0);return {avg:Math.round(r/t.length),min:t[0],max:t[t.length-1],p50:Y(t,50),p95:Y(t,95),p99:Y(t,99)}}var ds=2e5,Le=1e5;function is(e,t,r,a,s,n,i){let o={retryIndex:e,apiCalls:t?.length??0,apiUrls:[],methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,assertions:r.length,navigations:a.length,navUrls:[],networkRequests:s,consoleLogs:n,actionSteps:i?.length??0,actionCategories:{}};if(t){let d=new Set;for(let c of t){let p=typeof c.method=="string"?c.method:"OTHER";o.methodCounts[p]=(o.methodCounts[p]??0)+1;let y=typeof c.url=="string"?c.url:null;y&&d.size<Le&&d.add(Tt(y));let f=typeof c.responseStatusCode=="number"?c.responseStatusCode:typeof c.statusCode=="number"?c.statusCode:null,u=f!==null&&Number.isFinite(f)?f:null;o.statusRanges[os(u)]++;let m=typeof c.responseTimeMs=="number"?c.responseTimeMs:typeof c.durationMs=="number"?c.durationMs:null;m!==null&&Number.isFinite(m)&&o.responseTimes.length<ds&&o.responseTimes.push(m);}o.apiUrls=Array.from(d);}for(let d of r)d.status==="passed"?o.passedAssertions++:o.failedAssertions++;let l=new Set;for(let d of a)d.url&&l.size<Le&&l.add(d.url);return o.navUrls=Array.from(l),i&&ls(i,o.actionCategories),o}function Ao(){return {apiUrlSet:new Set,methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,navUrlSet:new Set,actionCategoryCounts:{},volApiCalls:0,volAssertions:0,volNavigations:0,volNetworkRequests:0,volConsoleLogs:0,volActionSteps:0}}function _o(e){return process.env.BROWSERSTACK_USERNAME?"BrowserStack":e?{"github-actions":"GitHub Actions","gitlab-ci":"GitLab CI",jenkins:"Jenkins",circleci:"CircleCI","bitbucket-pipelines":"Bitbucket Pipelines"}[e.provider]??"CI":"Local"}function Io(){let e=platform();return e==="win32"?"Windows":e==="darwin"?"macOS":"Linux"}function Mo(e){let t=e.parent?.project?.()?.use;if(!t)return;let{browserName:r,channel:a}=t;if(a){let n=a.toLowerCase();return n==="chrome"||n==="chrome-stable"?"Chrome":n.startsWith("chrome-beta")?"Chrome Beta":n.startsWith("chrome-dev")?"Chrome Dev":n.startsWith("chrome-canary")?"Chrome Canary":n==="msedge"||n==="msedge-stable"?"Microsoft Edge":n.startsWith("msedge-beta")?"Edge Beta":n.startsWith("msedge-dev")?"Edge Dev":n.startsWith("msedge-canary")?"Edge Canary":a}if(r){let n=r.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":r}let s=t.defaultBrowserType;if(s){let n=s.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":s}}function Eo(e,t,r){let a=r.parent?.project?.(),s="unknown";a!==void 0&&(a.use.isMobile===true?s="mobile":s="e2e");let n=["e2e","api","unit","mobile"];for(let l of n)if(e.some(d=>d===`@${l}`||d===l))return l;let i=t.replace(/\\/g,"/"),o=["e2e","api","unit"];for(let l of o)if(i.includes(`/${l}/`))return l;return s}var Po="__testrelic_api_config";function Do(e){return JSON.stringify(e,(t,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var Ne=class{constructor(t){this.rootDir="";this.configDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.navigationsCaptured=false;this.memoryPressureWarned=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.updatingSnapshots=false;this.cloudReceipt=fe;this.pendingArtifactEntries=[];this.detectedOs="";this.detectedSource="";this.cloudTestsBuffer=[];this.activeReportMode="embedded";this.streamingWriter=null;this.testIndex=[];this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};this.streamingTestAgg=new Map;this.config=yr(t),this.apiConfig=vr(t);}upsertAggContribution(t,r){let a=this.streamingTestAgg.get(t);(!a||r.retryIndex>a.retryIndex)&&this.streamingTestAgg.set(t,r);}async onBegin(t,r){try{this.rootDir=t.rootDir,this.configDir=t.configFile?dirname(t.configFile):"";let a=t.updateSnapshots;if(this.updatingSnapshots=a==="all"||a==="changed",this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??randomUUID(),this.config.reportMode==="auto"){let o=r.allTests().length;this.activeReportMode=o>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let s=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${s} tests)
|
|
4393
|
-
`),this.activeReportMode==="streaming"){let o=dirname(this.config.outputPath);this.streamingWriter=new ie(o);let l=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let d={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(d);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let d=this.cloudClient.getAccessToken();d&&Ut(this.cloudClient.getEndpoint(),d,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",l),process.on("SIGINT",l);}if(this.config.includeArtifacts){let o=dirname(this.config.outputPath);this.runTimestamp=ta(join(o,"artifacts"));try{ya(join(o,"artifacts"));}catch{}}let n=U();this.detectedOs=Io(),this.detectedSource=_o(n);let i=await J(async()=>(this.cloudClient=new _e(this.config.cloud),await this.cloudClient.initialize(),Qa(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),xa,"Cloud initialization");if(this.cloudRunId=i??null,i===void 0&&this.cloudClient?.switchToLocalMode("init_error"),this.cloudReceipt=es(this.cloudClient,this.config.cloud?.uploadStrategy,this.cloudRunId),this.activeReportMode!=="streaming"){let o=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let l=this.cloudClient.getAccessToken();l&&Ut(this.cloudClient.getEndpoint(),l,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}}catch{}}onTestBegin(t,r){try{t.annotations.push({type:Po,description:Do(this.apiConfig)});}catch{}}onTestEnd(t,r){try{let a=r,s=t.outcome(),n;s==="flaky"?n="flaky":s==="skipped"?n="skipped":n=Qt(a.status);let i=a.startTime.toISOString(),o=new Date(a.startTime.getTime()+a.duration).toISOString(),l=t.tags?[...t.tags]:t.annotations.filter(M=>M.type==="tag").map(M=>M.description??""),d=Xa(a.attachments,t.annotations,t.title,n==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0),d.navigations.length>0&&(this.navigationsCaptured=!0),!this.config.captureNavigation&&d.navigations.length>0&&(d={...d,navigations:[]});let c=null;if(n==="failed"||n==="flaky"){let _=(n==="flaky"?t.results.find(B=>B.status!=="passed")?.errors??[]:a.errors)[0];if(_){let B=xr(this.config.redactPatterns),ae=_.location?.file??null,P=d.apiAssertions.find(cs=>cs.status==="failed")?.location??null,Z=P!==null&&(ae===null||resolve(ae)!==resolve(t.location.file)),ar=Z?P.file:ae,Fe=Z?P.line:_.location?.line??null,se=null;this.config.includeCodeSnippets&&Fe!==null&&ar&&(se=br(ar,Fe,this.config.codeContextLines),se&&(se=B(se))),c={message:B(ke(_.message??"Unknown error")),line:Fe,code:se,stack:this.config.includeStackTrace&&_.stack?B(ke(_.stack)):null};}}let p=t.titlePath().filter(Boolean),y=relative(this.rootDir||".",t.location.file).replace(/\\/g,"/"),f=So(p),u=p.join(" > "),m=y,b=ko(m,f,u),h=Eo(l,m,t),g=h!=="mobile"&&d.apiCallsCount>0?"api":h,v=s==="flaky",w=Co(t.results),x=Qt(t.expectedStatus),A=Qt(a.status),T=null;if(this.config.includeArtifacts&&n!=="skipped"&&a.attachments){let M=dirname(this.config.outputPath),_=p[p.length-1]??t.title;T=aa(a.attachments,_,a.retry,M,this.runTimestamp||void 0,b);}let R=null;if(this.config.includeArtifacts&&n!=="skipped"&&a.attachments)try{let M=la(a.attachments,{updatingSnapshots:this.updatingSnapshots,failureMessage:a.errors.map(_=>_.message??"").join(`
|
|
4394
|
-
`)});if(M.length>0){let _=dirname(this.config.outputPath),B=p[p.length-1]??t.title;R=sa(M,B,a.retry,_,this.runTimestamp||void 0,b,this.configDir||this.rootDir||process.cwd());}}catch{}let I=this.config.includeActionSteps&&a.steps?Ra(a.steps,a.startTime):null,k=Mo(t),C={titlePath:p,title:u,status:n,duration:a.duration,startedAt:i,completedAt:o,retryCount:t.results.length-1,retry:a.retry,tags:l,failure:c,specFile:y,navigations:d.navigations,testId:b,filePath:m,suiteName:f,testType:g,isFlaky:v,retryStatus:w,expectedStatus:x,actualStatus:A,artifacts:T,visual:R,apiAssertions:d.apiAssertions,actions:I,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount,apiStatusMix:d.apiStatusMix,browser:k,os:this.detectedOs||void 0,source:this.detectedSource||void 0},X=d.consoleLogsFile&&d.consoleLogsCount>0?j(d.consoleLogsFile):void 0,G=d.networkRequestsFile&&d.networkRequestsCount>0?j(d.networkRequestsFile):void 0,re=d.apiCallsFile&&d.apiCallsCount>0?j(d.apiCallsFile):void 0,er=re?Nt(re):void 0,tr=!G&&re?Ft(re):void 0,rr=d.apiAssertions&&d.apiAssertions.length>0?Bt(d.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:b,title:u,status:n,duration:a.duration,suiteName:f,filePath:m,testType:g,isFlaky:v,startedAt:i,completedAt:o,tags:l,failure:c,retry:a.retry,retryCount:t.results.length-1,retryStatus:w,browser:k,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...I&&I.length>0?{actions:I}:{},...d.navigations&&d.navigations.length>0?{navigations:d.navigations}:{},...X?{consoleLogs:X}:{},...G?{networkRequests:G}:tr?{networkRequests:tr}:{},...er?{apiCalls:er}:{},...rr?{protocolAssertions:rr}:{},...R&&R.length>0?{visual:R}:{}});try{let M=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(M==="realtime"||M==="both")){let _=this.cloudClient.getAccessToken();_&&za(this.cloudClient.getEndpoint(),_,this.cloudRunId,this.buildCloudTestPayload(C));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let M=Be(m,p,t.id??"",a.retry),_=a.retry===t.results.length-1,B={id:M,...x!=="passed"?{expectedStatus:x}:{},navigations:d.navigations,apiAssertions:d.apiAssertions,actions:I??[],artifacts:T,visual:R,failureDiagnostic:c,hasNetworkFile:d.networkRequestsFile!==null,networkRequestsCount:d.networkRequestsCount,hasConsoleFile:d.consoleLogsFile!==null,consoleLogsCount:d.consoleLogsCount,hasApiCallsFile:d.apiCallsFile!==null,apiCallsCount:d.apiCallsCount,startedAt:i};this.streamingWriter.writeTestDetail(M,B,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let ae={id:M,title:p[p.length-1]??t.title,titlePath:p,filePath:m,status:n,...x!=="passed"?{expectedStatus:x}:{},duration:a.duration,project:p[1]??"",retryIndex:a.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:T!==null,hasActionSteps:(I?.length??0)>0,visualCount:R?.length??0,visualFailedCount:R?.filter(P=>P.status==="failed").length??0,domChangeCount:R?.reduce((P,Z)=>P+(Z.domChangeCount??0),0)??0,...(()=>{let P=R?.find(Z=>Z.diff);return P?.diff?{visualDiffPath:P.diff}:{}})(),errorMessage:wo(c?.message),networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:I?.length??0,testType:g,apiCallCount:d.apiCallsCount,...d.apiStatusMix?{apiStatusMix:d.apiStatusMix}:{},assertionsPassed:De(d.apiAssertions,"passed"),assertionsFailed:De(d.apiAssertions,"failed"),...(()=>{let P=ss(d.apiAssertions);return P?{firstFailedAssertion:P}:{}})(),isRetry:!_,retryGroupKey:Oe(m,p,t.id??"")};if(this.testIndex.push(ae),_)switch(this.summaryCounters.total++,n){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${m}::${p.join(" > ")}`,is(a.retry,re,d.apiAssertions,d.navigations,d.networkRequestsCount,d.consoleLogsCount,I)),(T||R)&&this.pendingArtifactEntries.push({testId:b,retry:a.retry,artifacts:T??{},visual:R,outputDir:dirname(this.config.outputPath)}),C.actions=null,C.apiAssertions=null,C.navigations=[],C.artifacts=null,C.failure=null,C.networkRequestsFile=null,C.consoleLogsFile=null,C.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(C),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(t){try{let r=new Date().toISOString(),a=new Date(this.startedAt).getTime(),n=new Date(r).getTime()-a,i=this.activeReportMode==="streaming"?this.testIndex.some(l=>l.status!=="skipped"):this.collectedTests.some(l=>l.status!=="skipped");!this.fixtureDataReceived&&i&&process.stderr.write(`
|
|
4386
|
+
`);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?pe(this.gitMetadata.remoteUrl):null,r=e?Ha(e):this.config.projectName??fe(process.cwd()),a=e??this.config.projectName??fe(process.cwd()),s=this.readRepoCache(a);if(s){this.repoId=s.repoId;return}try{let n=await Oa(this.config.endpoint,this.authState.accessToken,a,r,this.config.timeout,this.gitMetadata?.branch);n&&(this.repoId=n.repoId,this.writeRepoCache(a,n.repoId,n.displayName));}catch{}!e&&!this.config.projectName&&!zt(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
|
|
4387
|
+
`);}readRepoCache(e){if(!this.config)return null;let r=join(this.config.queueDirectory,"..","cache","repo.json");try{if(!existsSync(r))return null;let a=readFileSync(r,"utf-8"),s=JSON.parse(a);if(s.gitId!==e||Date.now()-s.resolvedAt>Ki)return null;let n=this.hashApiKey();return n&&s.apiKeyHash!==n?null:s}catch{return null}}writeRepoCache(e,r,a){if(!this.config)return;let s=join(this.config.queueDirectory,"..","cache"),n=join(s,"repo.json");try{mkdirSync(s,{recursive:!0});let i={repoId:r,gitId:e,displayName:a,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},o=n+".tmp";writeFileSync(o,JSON.stringify(i,null,2),"utf-8"),renameSync(o,n);}catch{}}hashApiKey(){return this.config?.apiKey?createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let e=this.authState.accessToken,r=this.config.queueDirectory,a=this.config.endpoint;this.flushPromise=Promise.race([es(r,a,e),as(rs)]).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 Ot(e))return;if(this.config?.apiKey){let a=await Ut(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Ht(a)){let s=a;this.authState={mode:"cloud",accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:Date.now()+s.expiresIn*1e3,orgId:s.orgId,orgName:s.orgName,userId:s.userId,userName:s.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
|
|
4388
|
+
`),this.startBackgroundFlush();}}}catch{}},Ji),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};function ss(t){if(!t.cloudMode)return "none";let e=t.uploadStrategy;return !e||e==="batch"||e==="both"?e==="both"&&t.sentRealtime?"summary":t.streaming?"deferred":"inline":"none"}function Yt(t){for(let e of t)if(existsSync(e))return z(e);return []}function Fe(t){let e=t.consoleLogs?Yt(t.consoleLogs):void 0,r=t.networkRequests?Yt(t.networkRequests):void 0,a=t.apiCalls?Yt(t.apiCalls):void 0,s=!r&&a?Le(a):void 0;return {...e?{consoleLogs:e}:{},...r?{networkRequests:r}:s?{networkRequests:s}:{},...a?{apiCalls:Pe(a)}:{}}}function Be(t,e){return {...t&&t.length>0?{actions:t}:{},...e&&e.length>0?{protocolAssertions:De(e)}:{}}}function Zi(t){try{let e=JSON.parse(readFileSync(t,"utf-8"));return typeof e=="object"&&e!==null?e:null}catch{return null}}function ns(t){let{deferred:e}=t;if(!e)return t.test;let r=Zi(e.metaFile);return {...t.test,...Be(Array.isArray(r?.actions)?r.actions:null,Array.isArray(r?.apiAssertions)?r.apiAssertions:null),...Fe(e.heavy)}}var is="_testrelic-fixture";function ro(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 os(t,e,r){let a=[],s=[],n=null,i=0,o=null,l=0,d=null,c=0,v=null,g=t.filter(p=>p.name===ATTACHMENT_NAME&&p.body),h=false;if(g.length>0)for(let p of g)try{let u=JSON.parse(p.body.toString());if(isTestRelicFilePayload(u)){a=a.concat(u.navigations),s=s.concat(u.apiAssertions),u.networkRequestsFile&&(n=u.networkRequestsFile,i+=u.networkRequestsCount),u.consoleLogsFile&&(o=u.consoleLogsFile,l+=u.consoleLogsCount),u.apiCallsFile&&(d=u.apiCallsFile,c+=u.apiCallsCount),v=ro(v,u.apiStatusMix),h=!0;continue}if(isTestRelicDataPayload(u)){a=a.concat(u.navigations),Array.isArray(u.apiAssertions)&&(s=s.concat(u.apiAssertions)),i+=u.networkRequests?.length??0,c+=u.apiCalls?.length??0;let b=u.consoleLogs;Array.isArray(b)&&(l+=b.length),h=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
|
|
4389
|
+
`);}h||(a=e.filter(p=>p.type==="lambdatest-navigation"&&p.description).map(p=>{try{return JSON.parse(p.description)}catch{return null}}).filter(p=>p!==null));let f=t.some(p=>p.name===is);return {navigations:a,apiAssertions:s,networkRequestsFile:n,networkRequestsCount:i,consoleLogsFile:o,consoleLogsCount:l,apiCallsFile:d,apiCallsCount:c,apiStatusMix:v,payloadAttached:h,fixtureMarker:f}}var ao=`
|
|
4395
4390
|
\u26A0 TestRelic: No fixture data received from any test.
|
|
4396
4391
|
To enable network logs, video sync, and Test Navigation tracking, import the TestRelic fixture:
|
|
4397
4392
|
import { test, expect } from '@testrelic/playwright-analytics/fixture';
|
|
4398
4393
|
instead of:
|
|
4399
4394
|
import { test, expect } from '@playwright/test';
|
|
4400
4395
|
|
|
4401
|
-
|
|
4396
|
+
`,Oe=class{constructor(){this.tests=new Map;}record(e,r,a,s){let i=(this.tests.get(e)?.flags??0)|(a?1:0)|(s?2:0);this.tests.set(e,{flags:i,title:r});}message(){let e=this.tests.size;if(e===0)return null;let r=false,a=0,s=0,n=[];for(let{flags:d,title:c}of this.tests.values())d!==0&&(r=true),(d&1)===0&&((d&2)!==0?s++:a++,n.length<3&&n.push(`"${c}"`));if(!r)return ao;let i=a+s;if(i===0)return null;let o=[];a>0&&o.push(`${a} did not run through the TestRelic fixture (import { test, expect } from '@testrelic/playwright-analytics/fixture' in their spec files instead of '@playwright/test')`),s>0&&o.push(`${s} ran through the fixture without using its page or request fixture (for example a page from browser.newPage(), or trackApiCalls: false); pass such pages to trackPage(page, testInfo) to capture them`);let l=i>n.length?", \u2026":"";return `[testrelic] ${i} of ${e} tests captured no network, console or navigation data: ${o.join("; ")}. For example: ${n.join(", ")}${l}
|
|
4397
|
+
`}};function Ue(t=process.env){let e=so(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 so(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var co=5,He=[1e3,3e3,9e3],ae=3,Qt=3e4,uo={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip",".json":"application/json"},Xt=0,Zt=[];async function po(){Xt>=co&&await new Promise(t=>Zt.push(t)),Xt++;}function fo(){Xt--,Zt.length>0&&Zt.shift()();}async function ze(t){return new Promise(e=>setTimeout(e,t))}function go(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return uo[e]??"application/octet-stream"}function ho(t){try{return statSync(t).size}catch{return 0}}async function mo(t,e,r,a,s){let n=`${t}/artifacts/upload-url`,i=JSON.stringify({runId:r.runId,testId:r.testId,...r.retry!==void 0?{retry:r.retry}:{},fileName:basename(r.filePath),contentType:s,type:r.type,sizeBytes:a});for(let o=0;o<ae;o++)try{let l=await K(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:i},Qt);if(l.ok)return await l.json();if(l.status>=500&&o<ae-1){await ze(He[o]);continue}return null}catch{if(o<ae-1){await ze(He[o]);continue}return null}return null}async function vo(t,e,r,a){let s=za(a,Qt);for(let n=0;n<ae;n++)try{let i=createReadStream(e),o=Readable.toWeb(i),l=await K(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(a)},body:o,duplex:"half"},s);if(l.ok)return !0;if(l.status>=500&&n<ae-1){await ze(He[n]);continue}return !1}catch{if(n<ae-1){await ze(He[n]);continue}return false}return false}async function yo(t,e,r){let a=`${t}/artifacts/confirm`;try{return (await K(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})},Qt)).ok}catch{return false}}async function bo(t,e,r,a){let s=ho(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>a*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let n=go(r.filePath);await po();try{let i=await mo(t,e,r,s,n);if(!i)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await vo(i.uploadUrl,r.filePath,n,s))return {success:!1,storageKey:i.storageKey,artifactId:i.artifactId,error:"presigned_put_failed"};let l=await yo(t,e,i.artifactId);return {success:l,storageKey:i.storageKey,artifactId:i.artifactId,error:l?null:"confirm_failed"}}finally{fo();}}async function ls(t,e,r,a,s){let n=new Map,i=r.map(async o=>{if(s?.expired()){n.set(o.filePath,{success:false,storageKey:null,artifactId:null,error:"upload_budget_exhausted"});return}let l=await bo(t,e,o,a);n.set(o.filePath,l);});return await Promise.allSettled(i),n}function tr(t){let r=t.getGitMetadata()?.remoteUrl;return r?pe(r):t.getConfig()?.projectName??fe(process.cwd())}async function ds(t,e,r,a,s){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let i=t.getGitMetadata(),o=$(),l=Ue(),d=Ae();return (await Ga(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:tr(t),branch:i?.branch??null,commit:i?.commitSha??null,commitMessage:i?.commitMessage??null,commitAuthor:i?.commitAuthor??null,startedAt:a,totalTests:null,ciProvider:o?.provider??null,ciRunUrl:o?.runUrl??null,environment:s??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{},testType:"e2e"}))?.runId??null}var wo=[{field:"baseline",keyField:"baselineKey",type:"baseline"},{field:"actual",keyField:"actualKey",type:"screenshot"},{field:"diff",keyField:"diffKey",type:"diff"},{field:"baselineDom",keyField:"baselineDomKey",type:"dom"},{field:"actualDom",keyField:"actualDomKey",type:"dom"}];function rr(t,e){return `${t}#${e??0}`}function ar(t,e,r){return r===void 0?t.get(e):t.get(rr(e,r))}var ko=true,So=50;function sr(t){return t?.uploadArtifacts??ko}var er={keyMap:new Map,visualKeyMap:new Map,total:0,uploaded:0};async function To(t,e,r,a,s){let n=new Map,i=new Map;if(!sr(e)||!await t.ensureValidToken())return er;let l=[],d=new Map,c=new Map;for(let u of a){let b=rr(u.testId,u.retry),m={runId:r,testId:u.testId,...u.retry!==void 0?{retry:u.retry}:{}};if(u.artifacts.screenshot){let x=join(u.outputDir,u.artifacts.screenshot);l.push({filePath:x,...m,type:"screenshot"}),d.set(x,{attemptKey:b,field:"screenshot"});}if(u.artifacts.video){let x=join(u.outputDir,u.artifacts.video);l.push({filePath:x,...m,type:"video"}),d.set(x,{attemptKey:b,field:"video"});}if(u.artifacts.trace){let x=join(u.outputDir,u.artifacts.trace);l.push({filePath:x,...m,type:"trace"}),d.set(x,{attemptKey:b,field:"trace"});}let y=u.visual??[];for(let x=0;x<y.length;x++){let k=y[x];if(k)for(let T of wo){let D=k[T.field];if(!D)continue;let C=join(u.outputDir,D);l.push({filePath:C,...m,type:T.type}),d.set(C,{attemptKey:b,field:"visual",visualIndex:x,visualKey:T.keyField});}}}if(l.length===0)return er;let v=e?.artifactMaxSizeMb??So,g=await ls(t.getEndpoint(),t.getAccessToken(),l,v,s),h=new Map;for(let[u,b]of g){if(!b.success||!b.storageKey)continue;let m=d.get(u);if(!m)continue;let y=h.get(m.attemptKey)??{};if(m.field==="screenshot"&&(y.screenshotKey=b.storageKey),m.field==="video"&&(y.videoKey=b.storageKey),m.field==="trace"&&(y.traceKey=b.storageKey),m.field==="visual"&&m.visualIndex!==void 0&&m.visualKey){let x=c.get(m.attemptKey)??new Map,k=x.get(m.visualIndex)??{};k[m.visualKey]=b.storageKey,x.set(m.visualIndex,k),c.set(m.attemptKey,x);}h.set(m.attemptKey,y);}let f=new Map;for(let u of a){let b=u.retry??0;(f.get(u.testId)??-1)<b&&f.set(u.testId,b);}for(let u of a){let b=rr(u.testId,u.retry),m=(u.retry??0)===f.get(u.testId);if(u.visual&&u.visual.length>0){let k=c.get(b),T=u.visual.map((D,C)=>({...D,...k?.get(C)??{}}));i.set(b,T),m&&i.set(u.testId,T);}let y=h.get(b),x={...u.artifacts,...y?.screenshotKey?{screenshotKey:y.screenshotKey}:{},...y?.videoKey?{videoKey:y.videoKey}:{},...y?.traceKey?{traceKey:y.traceKey}:{}};n.set(b,x),m&&n.set(u.testId,x);}let p=Array.from(g.values()).filter(u=>u.success).length;return p>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${p} artifact(s) to cloud storage.
|
|
4398
|
+
`),{keyMap:n,visualKeyMap:i,total:l.length,uploaded:p}}async function nr(t,e,r,a,s,n,i,o,l,d,c,v){let g={realtimeFinalizeAttempted:false,realtimeFinalized:false,batchAttempted:false,batchAcknowledged:false,artifactsTotal:0,artifactsUploaded:0,failureReason:null},h=new _e(e?.uploadBudgetMs??12e4),f=p=>{g.failureReason||(g.failureReason=p);};try{if(t.isCloudMode()&&s&&(r==="realtime"||r==="both")){g.realtimeFinalizeAttempted=!0;let b=await t.ensureValidToken(),m=t.getGitMetadata(),y=v??$t(c),x={finishedAt:i,duration:o,summary:l,...m?.commitMessage?{commitMessage:m.commitMessage}:{},testType:y.testType,...y.testType==="api"?{apiProtocol:y.apiProtocol,metadata:y.metadata}:{}};if(b){let k=await Ka(t.getEndpoint(),t.getAccessToken(),s,x);if(g.realtimeFinalized=k,!k){f("finalize_failed_after_retries");let T=e?.queueDirectory??".testrelic/queue";he(T,a,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",x,{"Content-Type":"application/json"});}}else {f(t.getFailureReason()??"token_invalid");let k=e?.queueDirectory??".testrelic/queue";he(k,a,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",x,{"Content-Type":"application/json"});}}let p=new Map,u=new Map;if(t.isCloudMode()&&d&&d.length>0){let b=await To(t,e,a,d,h);p=b.keyMap,u=b.visualKeyMap,g.artifactsTotal=b.total,g.artifactsUploaded=b.uploaded;}if(t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(g.batchAttempted=!0,await t.ensureValidToken()){let m=t.getGitMetadata(),y=$(),x=tr(t),k=Ro(Ao(n,p),u),T=Vt(k,x,m,y,Co(c,u),Ue()),D=await ja(t.getEndpoint(),t.getAccessToken(),T,async()=>await t.ensureValidToken()?t.getAccessToken():null,e?.timeout,h);if(g.batchAcknowledged=D.success,!D.success){let C=D;f(C.reason);let A=e?.queueDirectory??".testrelic/queue";he(A,a,"batch",C.reason,C.targetEndpoint,C.method,C.payload,{"Content-Type":"application/json"});}}else {f(t.getFailureReason()??"token_invalid");let m=e?.queueDirectory??".testrelic/queue",y=t.getGitMetadata(),x=$(),k=tr(t),T=Vt(n,k,y,x,void 0,Ue());he(m,a,"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 g}function Co(t,e){return !t||e.size===0?t:t.map(r=>{let a=ar(e,r.testId,r.retry);return a?{...r,visual:a}:r})}function Ro(t,e){if(e.size===0)return t;let r=t.timeline.map(a=>{let s=a.tests;if(!Array.isArray(s))return a;let n=false,i=s.map(o=>{let{testId:l,retry:d}=o;if(!l)return o;let c=ar(e,l,d);return c?(n=true,{...o,visual:c}):o});return n?{...a,tests:i}:a});return {...t,timeline:r}}function Ao(t,e){if(e.size===0)return t;let r=t.timeline.map(a=>{let s=a,n=s.testId;if(!n)return a;let i=ar(e,n,s.retry);return i?{...a,...i.screenshotKey?{screenshotKey:i.screenshotKey}:{},...i.videoKey?{videoKey:i.videoKey}:{}}:a});return {...t,timeline:r}}var _o=new Set(["batch","realtime","both"]),me=Object.freeze({attempted:false,acknowledged:false,runId:null,endpoint:null,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:"cloud reporting was never initialised"});function Io(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 cs(t,e,r){if(!t)return me;if(!t.isCloudMode())return {...me,detail:Io(t.getFailureReason())};let a=e??"batch";if(!_o.has(a))return {...me,detail:`upload strategy '${a}' is not recognised \u2014 nothing was sent`};let s=t.getEndpoint(),n=a==="realtime"||a==="both";return n&&r?{attempted:true,acknowledged:true,runId:r,endpoint:s,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:null}:{attempted:true,acknowledged:false,runId:null,endpoint:s,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:n?"run init failed \u2014 the platform did not acknowledge this run":`upload runs at the end of the run under the '${a}' strategy \u2014 not sent yet`}}function ir(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 a=t.acknowledged||e.batchAcknowledged,s=t.runId??(e.batchAcknowledged?r:null),n=e.realtimeFinalizeAttempted?e.realtimeFinalized:e.batchAcknowledged,i=null;return a?n||(i="run acknowledged but not closed out \u2014 finalize failed and was queued for retry"):i=e.failureReason?`upload failed (${e.failureReason}) \u2014 queued locally for retry`:"upload failed \u2014 the platform did not acknowledge this run",{attempted:true,acknowledged:a,runId:s,endpoint:t.endpoint,finalized:n,artifactsUploaded:e.artifactsUploaded,artifactsTotal:e.artifactsTotal,detail:i}}function No(t){if(!t)return null;let e=t.split(`
|
|
4399
|
+
`).map(n=>n.trim()).filter(Boolean);if(e.length===0)return null;let r=e.filter(n=>!/^Error:\s*expect\(/.test(n));if(r.length===0)return e[0]??null;let a=r[0],s=r[1];return s!==void 0&&/^Received:/.test(s)&&/^Expected:/.test(a)?`${a} \xB7 ${s}`:a}function lr(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 Fo(t,e,r){let a=`${t}::${e}::${r}`;return createHash("sha256").update(a).digest("hex").substring(0,16)}function Bo(t){return t.length<=3?"":t[t.length-2]}function Oo(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function vs(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 Uo(t){let e={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},r=e;for(let a of t){let s=typeof a.responseStatusCode=="number"?a.responseStatusCode:null;r[vs(s)]++;}return e}function gs(t){if(t){for(let e of t)if(e.status==="failed")return {type:e.type,expected:hs(e.expected),actual:hs(e.actual),...e.expression?{expression:e.expression}:{}}}}function hs(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 a of t)a.status===e&&r++;return r}function ys(t,e){for(let r of t)e[r.category]=(e[r.category]??0)+1,r.children.length>0&&ys(r.children,e);}function Ho(t){if(t.length===0)return null;let e=[...t].sort((a,s)=>a-s),r=e.reduce((a,s)=>a+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 bs=2e5,Ve=1e5;function ms(t,e,r,a,s,n,i){let o={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:a.length,navUrls:[],networkRequests:s,consoleLogs:n,actionSteps:i?.length??0,actionCategories:{}};if(e){let d=new Set;for(let c of e){let v=typeof c.method=="string"?c.method:"OTHER";o.methodCounts[v]=(o.methodCounts[v]??0)+1;let g=typeof c.url=="string"?c.url:null;g&&d.size<Ve&&d.add(Nt(g));let h=typeof c.responseStatusCode=="number"?c.responseStatusCode:typeof c.statusCode=="number"?c.statusCode:null,f=h!==null&&Number.isFinite(h)?h:null;o.statusRanges[vs(f)]++;let p=typeof c.responseTimeMs=="number"?c.responseTimeMs:typeof c.durationMs=="number"?c.durationMs:null;p!==null&&Number.isFinite(p)&&o.responseTimes.length<bs&&o.responseTimes.push(p);}o.apiUrls=Array.from(d);}for(let d of r)d.status==="passed"?o.passedAssertions++:o.failedAssertions++;let l=new Set;for(let d of a)d.url&&l.size<Ve&&l.add(d.url);return o.navUrls=Array.from(l),i&&ys(i,o.actionCategories),o}function zo(){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 qo(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 $o(){let t=platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function Vo(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:a}=e;if(a){let n=a.toLowerCase();return n==="chrome"||n==="chrome-stable"?"Chrome":n.startsWith("chrome-beta")?"Chrome Beta":n.startsWith("chrome-dev")?"Chrome Dev":n.startsWith("chrome-canary")?"Chrome Canary":n==="msedge"||n==="msedge-stable"?"Microsoft Edge":n.startsWith("msedge-beta")?"Edge Beta":n.startsWith("msedge-dev")?"Edge Dev":n.startsWith("msedge-canary")?"Edge Canary":a}if(r){let n=r.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":r}let s=e.defaultBrowserType;if(s){let n=s.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":s}}function jo(t,e,r){let a=r.parent?.project?.(),s="unknown";a!==void 0&&(a.use.isMobile===true?s="mobile":s="e2e");let n=["e2e","api","unit","mobile"];for(let l of n)if(t.some(d=>d===`@${l}`||d===l))return l;let i=e.replace(/\\/g,"/"),o=["e2e","api","unit"];for(let l of o)if(i.includes(`/${l}/`))return l;return s}var Go="__testrelic_api_config";function Wo(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var je=class{constructor(e){this.rootDir="";this.configDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.fixtureCoverage=new Oe;this.navigationsCaptured=false;this.memoryPressureWarned=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.updatingSnapshots=false;this.cloudReceipt=me;this.pendingArtifactEntries=[];this.detectedOs="";this.detectedSource="";this.cloudTestsBuffer=[];this.runTestTypes=new ge;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=Cr(e),this.apiConfig=Tr(e);}upsertAggContribution(e,r){let a=this.streamingTestAgg.get(e);(!a||r.retryIndex>a.retryIndex)&&this.streamingTestAgg.set(e,r);}async onBegin(e,r){try{this.rootDir=e.rootDir,this.configDir=e.configFile?dirname(e.configFile):"";let a=e.updateSnapshots;if(this.updatingSnapshots=a==="all"||a==="changed",this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??randomUUID(),this.config.reportMode==="auto"){let o=r.allTests().length;this.activeReportMode=o>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let s=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${s} tests)
|
|
4400
|
+
`),this.activeReportMode==="streaming"){let o=dirname(this.config.outputPath);this.streamingWriter=new le(o);let l=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let d={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(d);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let d=this.cloudClient.getAccessToken();d&&Gt(this.cloudClient.getEndpoint(),d,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",l),process.on("SIGINT",l);}if(this.config.includeArtifacts){let o=dirname(this.config.outputPath);this.runTimestamp=la(join(o,"artifacts"));try{Ca(join(o,"artifacts"));}catch{}}let n=$();this.detectedOs=$o(),this.detectedSource=qo(n);let i=await Q(async()=>(this.cloudClient=new Ne(this.config.cloud),await this.cloudClient.initialize(),ds(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),Aa,"Cloud initialization");if(this.cloudRunId=i??null,i===void 0&&this.cloudClient?.switchToLocalMode("init_error"),this.cloudReceipt=cs(this.cloudClient,this.config.cloud?.uploadStrategy,this.cloudRunId),this.activeReportMode!=="streaming"){let o=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let l=this.cloudClient.getAccessToken();l&&Gt(this.cloudClient.getEndpoint(),l,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:Go,description:Wo(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let a=r,s=e.outcome(),n;s==="flaky"?n="flaky":s==="skipped"?n="skipped":n=lr(a.status);let i=a.startTime.toISOString(),o=new Date(a.startTime.getTime()+a.duration).toISOString(),l=e.tags?[...e.tags]:e.annotations.filter(_=>_.type==="tag").map(_=>_.description??""),d=os(a.attachments,e.annotations,e.title);(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0);let c=d.payloadAttached||d.navigations.length>0;d.navigations.length>0&&(this.navigationsCaptured=!0),!this.config.captureNavigation&&d.navigations.length>0&&(d={...d,navigations:[]});let v=null;if(n==="failed"||n==="flaky"){let M=(n==="flaky"?e.results.find(H=>H.status!=="passed")?.errors??[]:a.errors)[0];if(M){let H=Ar(this.config.redactPatterns),se=M.location?.file??null,ne=d.apiAssertions.find(xs=>xs.status==="failed")?.location??null,ve=ne!==null&&(se===null||resolve(se)!==resolve(e.location.file)),I=ve?ne.file:se,B=ve?ne.line:M.location?.line??null,ie=null;this.config.includeCodeSnippets&&B!==null&&I&&(ie=Rr(I,B,this.config.codeContextLines),ie&&(ie=H(ie))),v={message:H(Re(M.message??"Unknown error")),line:B,code:ie,stack:this.config.includeStackTrace&&M.stack?H(Re(M.stack)):null};}}let g=e.titlePath().filter(Boolean),h=relative(this.rootDir||".",e.location.file).replace(/\\/g,"/"),f=Bo(g),p=g.join(" > "),u=h,b=Fo(u,f,p);n!=="skipped"&&this.fixtureCoverage.record(`${u}::${p}::${e.id??""}`,p,c,d.fixtureMarker);let m=jo(l,u,e),y=m!=="mobile"&&d.apiCallsCount>0?"api":m,x=s==="flaky",k=Oo(e.results),T=lr(e.expectedStatus),D=lr(a.status),C=null;if(this.config.includeArtifacts&&n!=="skipped"&&a.attachments){let _=dirname(this.config.outputPath),M=g[g.length-1]??e.title;C=ca(a.attachments,M,a.retry,_,this.runTimestamp||void 0,b);}let A=null;if(this.config.includeArtifacts&&n!=="skipped"&&a.attachments)try{let _=ha(a.attachments,{updatingSnapshots:this.updatingSnapshots,failureMessage:a.errors.map(M=>M.message??"").join(`
|
|
4401
|
+
`)});if(_.length>0){let M=dirname(this.config.outputPath),H=g[g.length-1]??e.title;A=ua(_,H,a.retry,M,this.runTimestamp||void 0,b,this.configDir||this.rootDir||process.cwd());}}catch{}let w=this.config.includeActionSteps&&a.steps?La(a.steps,a.startTime):null,R=Vo(e),E={titlePath:g,title:p,status:n,duration:a.duration,startedAt:i,completedAt:o,retryCount:e.results.length-1,retry:a.retry,tags:l,failure:v,specFile:h,navigations:d.navigations,testId:b,filePath:u,suiteName:f,testType:y,isFlaky:x,retryStatus:k,expectedStatus:T,actualStatus:D,artifacts:C,visual:A,apiAssertions:d.apiAssertions,actions:w,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount,apiStatusMix:d.apiStatusMix,browser:R,os:this.detectedOs||void 0,source:this.detectedSource||void 0},J=this.config.cloud?.uploadStrategy,dr=!1;try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(J==="realtime"||J==="both")){let _=this.cloudClient.getAccessToken();_&&(Wa(this.cloudClient.getEndpoint(),_,this.cloudRunId,this.buildCloudTestPayload(E)),dr=!0);}}catch{}this.runTestTypes.add(y);let cr=this.activeReportMode==="streaming"&&this.streamingWriter!==null,Ge=ss({cloudMode:this.cloudClient?.isCloudMode()??!1,uploadStrategy:J,sentRealtime:dr,streaming:cr}),Y=Ge==="none"?null:{testId:b,title:p,status:n,duration:a.duration,suiteName:f,filePath:u,testType:y,isFlaky:x,startedAt:i,completedAt:o,tags:l,failure:v,retry:a.retry,retryCount:e.results.length-1,retryStatus:k,browser:R,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...d.navigations&&d.navigations.length>0?{navigations:d.navigations}:{},...A&&A.length>0?{visual:A}:{}},P={consoleLogs:d.consoleLogsFile&&d.consoleLogsCount>0?d.consoleLogsFile:null,networkRequests:d.networkRequestsFile&&d.networkRequestsCount>0?d.networkRequestsFile:null,apiCalls:d.apiCallsFile&&d.apiCallsCount>0?d.apiCallsFile:null};if(Y&&!cr&&this.cloudTestsBuffer.push({test:Ge==="inline"?{...Y,...Be(w,d.apiAssertions),...Fe({...P.consoleLogs?{consoleLogs:[P.consoleLogs]}:{},...P.networkRequests?{networkRequests:[P.networkRequests]}:{},...P.apiCalls?{apiCalls:[P.apiCalls]}:{}})}:Y}),this.activeReportMode==="streaming"&&this.streamingWriter){let _=We(u,g,e.id??"",a.retry),M=a.retry===e.results.length-1,H={id:_,...T!=="passed"?{expectedStatus:T}:{},navigations:d.navigations,apiAssertions:d.apiAssertions,actions:w??[],artifacts:C,visual:A,failureDiagnostic:v,hasNetworkFile:d.networkRequestsFile!==null,networkRequestsCount:d.networkRequestsCount,hasConsoleFile:d.consoleLogsFile!==null,consoleLogsCount:d.consoleLogsCount,hasApiCallsFile:d.apiCallsFile!==null,apiCallsCount:d.apiCallsCount,startedAt:i},se=P.apiCalls?z(P.apiCalls):void 0,ne=this.streamingWriter.writeTestDetail(_,H,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});if(Y){let I=this.streamingWriter.getTestDetailPaths(_),B={...P.consoleLogs?{consoleLogs:[P.consoleLogs,I.consoleLogs]}:{},...P.networkRequests?{networkRequests:[P.networkRequests,I.networkRequests]}:{},...P.apiCalls?{apiCalls:[P.apiCalls,I.apiCalls]}:{}};Ge==="summary"?this.cloudTestsBuffer.push({test:Y}):ne?this.cloudTestsBuffer.push({test:Y,deferred:{metaFile:I.meta,heavy:B}}):this.cloudTestsBuffer.push({test:{...Y,...Be(w,d.apiAssertions),...Fe(B)}});}let ve={id:_,title:g[g.length-1]??e.title,titlePath:g,filePath:u,status:n,...T!=="passed"?{expectedStatus:T}:{},duration:a.duration,project:g[1]??"",retryIndex:a.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:C!==null,hasActionSteps:(w?.length??0)>0,visualCount:A?.length??0,visualFailedCount:A?.filter(I=>I.status==="failed").length??0,domChangeCount:A?.reduce((I,B)=>I+(B.domChangeCount??0),0)??0,...(()=>{let I=A?.find(B=>B.diff);return I?.diff?{visualDiffPath:I.diff}:{}})(),errorMessage:No(v?.message),networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:w?.length??0,testType:y,apiCallCount:d.apiCallsCount,...d.apiStatusMix?{apiStatusMix:d.apiStatusMix}:{},assertionsPassed:$e(d.apiAssertions,"passed"),assertionsFailed:$e(d.apiAssertions,"failed"),...(()=>{let I=gs(d.apiAssertions);return I?{firstFailedAssertion:I}:{}})(),isRetry:!M,retryGroupKey:Ke(u,g,e.id??"")};if(this.testIndex.push(ve),M)switch(this.summaryCounters.total++,n){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${u}::${g.join(" > ")}`,ms(a.retry,se,d.apiAssertions,d.navigations,d.networkRequestsCount,d.consoleLogsCount,w)),(C||A)&&this.cloudClient?.isCloudMode()&&sr(this.config.cloud)&&this.pendingArtifactEntries.push({testId:b,retry:a.retry,artifacts:C??{},visual:A,outputDir:dirname(this.config.outputPath)}),E.actions=null,E.apiAssertions=null,E.navigations=[],E.artifacts=null,E.failure=null,E.networkRequestsFile=null,E.consoleLogsFile=null,E.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(E),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(e){try{let r=new Date().toISOString(),a=new Date(this.startedAt).getTime(),n=new Date(r).getTime()-a,i=this.activeReportMode==="streaming"?this.testIndex.some(d=>d.status!=="skipped"):this.collectedTests.some(d=>d.status!=="skipped"),o=this.fixtureCoverage.message();o&&process.stderr.write(o),this.config.captureNavigation?this.fixtureDataReceived&&!this.navigationsCaptured&&i&&process.stderr.write(`[testrelic] Test Navigation: 0 navigation events captured this run. Navigation is recorded automatically on page.goto()/clicks; if you expected a navigation graph, ensure your tests drive page navigations (and use the '@testrelic/playwright-analytics/fixture' import).
|
|
4402
4402
|
`):process.stderr.write(`[testrelic] Test Navigation capture is disabled (captureNavigation: false). Remove the option or set it to true to capture the navigation graph.
|
|
4403
|
-
`),await
|
|
4404
|
-
`);let
|
|
4403
|
+
`),await Q(()=>oa(),Dt,"Artifact flush");let l=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let d=dirname(this.config.outputPath);l=ka(d,this.runTimestamp);let c=join(d,"artifact-manifest.json"),v=JSON.stringify(l),g=c+".tmp";writeFileSync(g,v,"utf-8"),renameSync(g,c);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await Q(()=>this.finalizeStreamingReport(r,n,e,l),Lt,"Report finalization");else {let d=this.buildTimeline(),c=new Map;for(let p of this.collectedTests){let u=c.get(p.testId);(!u||p.retry>u.retry)&&c.set(p.testId,p);}let v=Array.from(c.values()),g=Pa(v,d.length),h={schemaVersion:Ye,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:n,summary:g,ci:$(),metadata:this.config.metadata,timeline:d,shardRunIds:null},f=tt(g,v);if(this.writeReport(h),await Q(()=>Rt(h,this.config,l,f),Dt,"HTML report write"),Ft(g,this.config.outputPath,this.config.htmlReportPath,this.config.quiet,f),this.cloudClient){let p=this.collectArtifactEntries(),u=this.drainCloudTestsBuffer(),b=await Q(()=>nr(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,h,r,n,g,p,u,this.runTestTypes.signal()),Lt,"Cloud upload");this.cloudReceipt=ir(this.cloudReceipt,b,this.testRunId);}}}catch{}finally{await this.disposeCloudClient();}}drainCloudTestsBuffer(){let e=this.cloudTestsBuffer.map(ns);return this.cloudTestsBuffer.length=0,e}async disposeCloudClient(){let e=this.cloudClient;e&&(this.cloudClient=null,await Q(()=>e.dispose(),_a,"Cloud client shutdown"));}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=dirname(this.config.outputPath),r=[];for(let a of this.collectedTests)(a.artifacts||a.visual)&&r.push({testId:a.testId,retry:a.retry,artifacts:a.artifacts??{},visual:a.visual,outputDir:e});return r}async finalizeStreamingReport(e,r,a,s){if(!this.streamingWriter)return;this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};let n=new Map,i=new Map;for(let m of this.testIndex){let y=`${m.filePath}::${m.titlePath.join(" > ")}`,x=n.get(y);(x===void 0||m.retryIndex>x)&&n.set(y,m.retryIndex);}let o=0,l=[];for(let m of this.testIndex){let y=`${m.filePath}::${m.titlePath.join(" > ")}`,x=n.get(y);if(m.isRetry=m.retryIndex<x,m.isRetry)continue;switch(l.push(m),o++,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 k=i.get(m.filePath);switch(k||(k={filePath:m.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},i.set(m.filePath,k)),k.total++,m.status){case "passed":k.passed++;break;case "failed":k.failed++;break;case "flaky":k.flaky++;break;case "skipped":k.skipped++;break;case "timedout":k.timedOut++;break}}let d=Array.from(i.values()),c=zo();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 y in m.methodCounts)c.methodCounts[y]=(c.methodCounts[y]??0)+m.methodCounts[y];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 y in m.actionCategories)c.actionCategoryCounts[y]=(c.actionCategoryCounts[y]??0)+m.actionCategories[y];for(let y of m.apiUrls){if(c.apiUrlSet.size>=Ve)break;c.apiUrlSet.add(y);}for(let y of m.navUrls){if(c.navUrlSet.size>=Ve)break;c.navUrlSet.add(y);}for(let y of m.responseTimes){if(c.responseTimes.length>=bs)break;c.responseTimes.push(y);}}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 v={reporterTotal:this.summaryCounters.total,indexTotal:o,playwrightStatus:a.status,isValid:this.summaryCounters.total===o};v.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${v.reporterTotal}, index: ${v.indexTotal}
|
|
4404
|
+
`);let g={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:Ho(c.responseTimes),totalAssertions:this.summaryCounters.totalAssertions,passedAssertions:c.passedAssertions,failedAssertions:c.failedAssertions,totalNavigations:this.summaryCounters.totalNavigations,uniqueNavigationUrls:c.navUrlSet.size,totalTimelineSteps:o,totalActionSteps:this.summaryCounters.totalActionSteps,actionStepsByCategory:{...c.actionCategoryCounts},visualChecks:this.summaryCounters.visualChecks,visualFailures:this.summaryCounters.visualFailures,visualDomChanges:this.summaryCounters.visualDomChanges},h={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:d,enrichedSummary:g,validation:v,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);let p=tt(g,l);await Rt(this.buildStreamingReport(h,g,e,r),this.config,s,p),Ft(g,this.config.outputPath,this.config.htmlReportPath,this.config.quiet,p);let u=this.streamingWriter.getReportDir();process.stderr.write(`[testrelic] Streaming report written to ${u}
|
|
4405
4405
|
[testrelic] ${this.testIndex.length} test detail files on disk
|
|
4406
|
-
[testrelic] View report: npx testrelic serve ${
|
|
4406
|
+
[testrelic] View report: npx testrelic serve ${u}
|
|
4407
4407
|
`),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
|
|
4408
|
-
`);let
|
|
4408
|
+
`);let b=this.streamingWriter;try{if(this.cloudClient){let m=this.buildStreamingReport(h,g,e,r),y=this.collectArtifactEntries(),x=this.drainCloudTestsBuffer(),k=await nr(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,m,e,r,g,y,x,this.runTestTypes.signal());this.cloudReceipt=ir(this.cloudReceipt,k,this.testRunId);let T={...h,cloudUpload:this.cloudReceipt};try{b.writeSummary(T);}catch{}}}finally{b.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,a,s){return {schemaVersion:Ye,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:a,totalDuration:s,summary:r,ci:$(),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 a=e.heapUsed/e.heapTotal;a>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
|
|
4409
4409
|
`),this.switchToStreamingMode()):a>.8&&r>=500&&!this.memoryPressureWarned&&(this.memoryPressureWarned=!0,process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
|
|
4410
|
-
`));}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let
|
|
4411
|
-
`)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,testType:r.testType,apiCallCount:r.apiCallsCount,...r.apiStatusMix?{apiStatusMix:r.apiStatusMix}:s?{apiStatusMix:
|
|
4412
|
-
`);}}};export{
|
|
4410
|
+
`));}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=dirname(this.config.outputPath);this.streamingWriter=new le(e);for(let r of this.collectedTests){let a=We(r.filePath,r.titlePath,r.testId,r.retry),s=r.apiCallsFile&&r.apiCallsCount>0?z(r.apiCallsFile):void 0,n={id:a,...r.expectedStatus!=="passed"?{expectedStatus:r.expectedStatus}:{},navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(a,n,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let i={id:a,title:r.titlePath[r.titlePath.length-1]??r.title,titlePath:r.titlePath,filePath:r.filePath,status:r.status,...r.expectedStatus!=="passed"?{expectedStatus:r.expectedStatus}:{},duration:r.duration,project:r.titlePath[1]??"",retryIndex:r.retry,tags:r.tags,hasNetworkData:r.networkRequestsCount>0,hasConsoleData:r.consoleLogsCount>0,hasArtifacts:r.artifacts!==null,hasActionSteps:(r.actions?.length??0)>0,errorMessage:r.failure?.message?.split(`
|
|
4411
|
+
`)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,testType:r.testType,apiCallCount:r.apiCallsCount,...r.apiStatusMix?{apiStatusMix:r.apiStatusMix}:s?{apiStatusMix:Uo(s)}:{},assertionsPassed:$e(r.apiAssertions,"passed"),assertionsFailed:$e(r.apiAssertions,"failed"),...(()=>{let o=gs(r.apiAssertions);return o?{firstFailedAssertion:o}:{}})(),isRetry:!1,retryGroupKey:Ke(r.filePath,r.titlePath,r.testId)};switch(this.testIndex.push(i),this.summaryCounters.total++,r.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${r.filePath}::${r.titlePath.join(" > ")}`,ms(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 Ea(e,{navigationTypes:this.config.navigationTypes})}readJsonlFile(e){if(!e)return null;let r=z(e);return r.length>0?r:null}toTestResult(e,r){let a=null,s=null,n=null;return r?.loadFiles&&(a=this.readJsonlFile(e.networkRequestsFile),s=this.readJsonlFile(e.consoleLogsFile),n=this.readJsonlFile(e.apiCallsFile)),{title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,retry:e.retry,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,visual:e.visual,networkRequests:a,apiCalls:n,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=De(e.apiAssertions)),e.consoleLogsFile&&(r.consoleLogs=z(e.consoleLogsFile)),e.networkRequestsFile&&(r.networkRequests=z(e.networkRequestsFile)),e.apiCallsFile){let a=z(e.apiCallsFile);r.apiCalls=Pe(a),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=Le(a));}return r}writeReport(e){try{let r=JSON.stringify(e),a=this.config.outputPath,s=dirname(a);mkdirSync(s,{recursive:!0});let n=a+".tmp";writeFileSync(n,r,"utf-8"),renameSync(n,a);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
|
|
4412
|
+
`);}}};export{je as default};//# sourceMappingURL=reporter-entry.js.map
|
|
4413
4413
|
//# sourceMappingURL=reporter-entry.js.map
|