@testrelic/playwright-analytics 2.2.7 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
- import {randomUUID,createHash}from'crypto';import {writeFileSync,renameSync,mkdirSync,existsSync,readFileSync,appendFileSync,copyFileSync,readdirSync,unlinkSync,statSync,rmSync}from'fs';import {dirname,join,relative,extname,resolve,parse,basename}from'path';import {PAYLOAD_VERSION,ATTACHMENT_NAME,ATTACHMENT_CONTENT_TYPE,isValidConfig,createError,ErrorCode,isTestRelicDataPayload,isValidEndpointUrl,isValidCloudConfig,isValidQueueEntry}from'@testrelic/core';export{ATTACHMENT_CONTENT_TYPE,ATTACHMENT_NAME,PAYLOAD_VERSION,isTestRelicDataPayload}from'@testrelic/core';import {exec,execSync}from'child_process';import {createServer}from'http';import {gzipSync}from'zlib';import {test,defineConfig}from'@playwright/test';import {performance}from'perf_hooks';var er=".testrelic",rr=5,nr=new Set(["__proto__","constructor","prototype"]),At=Object.freeze({apiKey:null,endpoint:"https://api.testrelic.com/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:".testrelic/queue"}),sr={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function It(e){let t=resolve(e);for(let r=0;r<=rr;r++){let n=join(t,er);if(existsSync(n))return n;let s=dirname(t);if(s===t)break;t=s;}return null}function Nt(e){try{let t=readFileSync(e,"utf-8"),r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)||!Lt(r)?null:r}catch{return null}}function Lt(e){for(let t of Object.keys(e)){if(nr.has(t))return false;let r=e[t];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!Lt(r))return false}return true}function Et(e){let t=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(e);if(t)return process.env[t[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);return r?process.env[r[1]]??null:e}function rt(e){let t=Object.create(null);for(let r of Object.keys(e)){let n=e[r];typeof n=="string"&&n.startsWith("$")?t[r]=Et(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?t[r]=rt(n):t[r]=n;}return t}function _t(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let r=parseInt(t[1],10),n=t[2],s=sr[n];return !s||r<=0?null:r*s}function Bt(e,t){let r=Object.create(null);if(Object.assign(r,At),e){let o=e.cloud;o&&typeof o=="object"&&(typeof o.endpoint=="string"&&(r.endpoint=o.endpoint),typeof o.upload=="string"&&(r.uploadStrategy=o.upload),typeof o.timeout=="number"&&(r.timeout=o.timeout),typeof o.apiKey=="string"&&o.apiKey.length>0&&(r.apiKey=o.apiKey));let c=e.project;c&&typeof c=="object"&&typeof c.name=="string"&&(r.projectName=c.name);let d=e.queue;if(d&&typeof d=="object"){if(typeof d.maxAge=="string"){let p=_t(d.maxAge);p!==null&&(r.queueMaxAge=p);}typeof d.directory=="string"&&(r.queueDirectory=d.directory);}}if(t){if(typeof t.apiKey=="string"&&t.apiKey.length>0){let o=t.apiKey.startsWith("$")?Et(t.apiKey):t.apiKey;o&&(r.apiKey=o);}if(typeof t.endpoint=="string"&&(r.endpoint=t.endpoint),typeof t.upload=="string"&&(r.uploadStrategy=t.upload),typeof t.timeout=="number"&&(r.timeout=t.timeout),typeof t.projectName=="string"&&(r.projectName=t.projectName),typeof t.queueMaxAge=="string"){let o=_t(t.queueMaxAge);o!==null&&(r.queueMaxAge=o);}typeof t.queueDirectory=="string"&&(r.queueDirectory=t.queueDirectory);}let n=process.env.TESTRELIC_API_KEY;n&&n.length>0&&(r.apiKey=n);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&isValidEndpointUrl(s)&&(r.endpoint=s);let a=process.env.TESTRELIC_UPLOAD_STRATEGY;a&&["batch","realtime","both"].includes(a)&&(r.uploadStrategy=a);let l=process.env.TESTRELIC_CLOUD_TIMEOUT;if(l){let o=parseInt(l,10);!isNaN(o)&&o>=1e3&&o<=12e4&&(r.timeout=o);}let i=Object.freeze(r);return isValidCloudConfig(i)?i:At}var lr=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],dr=["authorization","cookie","set-cookie","x-api-key"],cr=["password","secret","token","apiKey","api_key"];function Mt(e){let t=Object.create(null);return t.trackApiCalls=e?.trackApiCalls??true,t.captureRequestHeaders=e?.captureRequestHeaders??true,t.captureResponseHeaders=e?.captureResponseHeaders??true,t.captureRequestBody=e?.captureRequestBody??true,t.captureResponseBody=e?.captureResponseBody??true,t.captureAssertions=e?.captureAssertions??true,t.redactHeaders=e?.redactHeaders??[...dr],t.redactBodyFields=e?.redactBodyFields??[...cr],t.apiIncludeUrls=e?.apiIncludeUrls??[],t.apiExcludeUrls=e?.apiExcludeUrls??[],Object.freeze(t)}function Pt(e){if(e!==void 0&&!isValidConfig(e))throw createError(ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let t=Object.create(null);t.outputPath=e?.outputPath??"./test-results/analytics-timeline.json",t.includeStackTrace=e?.includeStackTrace??false,t.includeCodeSnippets=e?.includeCodeSnippets??true,t.codeContextLines=e?.codeContextLines??3,t.includeNetworkStats=e?.includeNetworkStats??true,t.navigationTypes=e?.navigationTypes??null,t.redactPatterns=[...lr,...e?.redactPatterns??[]],t.testRunId=e?.testRunId??null,t.metadata=e?.metadata??null;let r=t.outputPath;t.openReport=e?.openReport??true,t.htmlReportPath=e?.htmlReportPath??r.replace(/\.json$/,".html"),t.includeArtifacts=e?.includeArtifacts??true,t.trackApiCalls=e?.trackApiCalls??true,t.quiet=e?.quiet??false,t.includeActionSteps=e?.includeActionSteps??true,t.captureConsoleLogs=e?.captureConsoleLogs??true;let n=It(process.cwd()),s=n?Nt(n):null,a=s?rt(s):null,l=Bt(a,e?.cloud);return t.cloud=l.apiKey?l:null,Object.freeze(t)}var nt="1.3.0";function qt(e,t,r){try{let s=readFileSync(e,"utf-8").split(`
2
- `);if(t<1||t>s.length)return null;let a=Math.max(1,t-r),l=Math.min(s.length,t+r),i=[];for(let o=a;o<=l;o++){let c=o===t?">":" ",d=String(o).padStart(String(l).length," ");i.push(`${c} ${d} | ${s[o-1]}`);}return i.join(`
3
- `)}catch{return null}}function Dt(e){return t=>{let r=t;for(let n of e)if(typeof n=="string"){let s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=n.flags.includes("g")?n.flags:n.flags+"g",a=new RegExp(n.source,s);r=r.replace(a,"[REDACTED]");}return r}}function ur(e){return e.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:e.GITHUB_RUN_ID??null,commitSha:e.GITHUB_SHA??null,branch:e.GITHUB_REF_NAME??null,runUrl:e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:null}}function fr(e){return e.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:e.CI_PIPELINE_ID??null,commitSha:e.CI_COMMIT_SHA??null,branch:e.CI_COMMIT_BRANCH??e.CI_COMMIT_REF_NAME??null,runUrl:e.CI_PIPELINE_URL??null}}function gr(e){if(!e.JENKINS_URL)return null;let t=e.GIT_BRANCH??null;return t?.startsWith("origin/")&&(t=t.slice(7)),{provider:"jenkins",buildId:e.BUILD_ID??null,commitSha:e.GIT_COMMIT??null,branch:t,runUrl:e.BUILD_URL??null}}function hr(e){return e.CIRCLECI!=="true"?null:{provider:"circleci",buildId:e.CIRCLE_BUILD_NUM??null,commitSha:e.CIRCLE_SHA1??null,branch:e.CIRCLE_BRANCH??null,runUrl:e.CIRCLE_BUILD_URL??null}}function mr(e){if(!e.BITBUCKET_PIPELINE_UUID)return null;let t=e.BITBUCKET_WORKSPACE&&e.BITBUCKET_REPO_SLUG&&e.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${e.BITBUCKET_WORKSPACE}/${e.BITBUCKET_REPO_SLUG}/pipelines/results/${e.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:e.BITBUCKET_BUILD_NUMBER??null,commitSha:e.BITBUCKET_COMMIT??null,branch:e.BITBUCKET_BRANCH??null,runUrl:t}}var vr=[ur,fr,gr,hr,mr];function _(e){let t=process.env;for(let r of vr){let n=r(t);if(n)return n}return null}var Ot=`
1
+ import {randomUUID,createHash}from'crypto';import {writeFileSync,renameSync,mkdirSync,existsSync,readFileSync,appendFileSync,copyFileSync,readdirSync,statSync,unlinkSync,rmSync}from'fs';import {dirname,join,relative,extname,resolve,parse,basename}from'path';import {PAYLOAD_VERSION,ATTACHMENT_NAME,ATTACHMENT_CONTENT_TYPE,isValidConfig,createError,ErrorCode,isTestRelicDataPayload,isValidEndpointUrl,isValidCloudConfig,isValidQueueEntry}from'@testrelic/core';export{ATTACHMENT_CONTENT_TYPE,ATTACHMENT_NAME,PAYLOAD_VERSION,isTestRelicDataPayload}from'@testrelic/core';import {spawn,exec,execSync}from'child_process';import {createServer}from'http';import {gzipSync}from'zlib';import {test,defineConfig}from'@playwright/test';import {performance}from'perf_hooks';var Ar=".testrelic-report";function st(t,e,r,n){let s=`${t}|${e.join("|")}|${r}|${n}`;return createHash("sha256").update(s).digest("hex").substring(0,12)}var ee=class{constructor(e){this.writeErrors=[];this.reportDir=join(e,Ar),this.testsDir=join(this.reportDir,"tests"),mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(e,r){try{let n=join(this.testsDir,`${e}.json`),s=n+".tmp";return writeFileSync(s,JSON.stringify(r),"utf-8"),renameSync(s,n),!0}catch(n){let s=n instanceof Error?n.message:String(n);return this.writeErrors.push({testId:e,error:s,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${e}: ${s}
2
+ `),false}}writeIndex(e){let r=join(this.reportDir,"index.json"),n=r+".tmp";writeFileSync(n,JSON.stringify(e),"utf-8"),renameSync(n,r);}writeSummary(e){let r=join(this.reportDir,"summary.json"),n=r+".tmp";writeFileSync(n,JSON.stringify(e,null,2),"utf-8"),renameSync(n,r);}writeManifest(e){let r=join(this.reportDir,"manifest.json"),n=r+".tmp";writeFileSync(n,JSON.stringify(e,null,2),"utf-8"),renameSync(n,r);}computeTotalSize(){return at(this.reportDir)}dispose(){}};function at(t){let e=0;try{let r=readdirSync(t,{withFileTypes:!0});for(let n of r){let s=join(t,n.name);n.isFile()?e+=statSync(s).size:n.isDirectory()&&(e+=at(s));}}catch{}return e}var Dr=".testrelic",Br=5,Or=new Set(["__proto__","constructor","prototype"]),it=Object.freeze({apiKey:null,endpoint:"https://api.testrelic.com/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:".testrelic/queue"}),qr={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function lt(t){let e=resolve(t);for(let r=0;r<=Br;r++){let n=join(e,Dr);if(existsSync(n))return n;let s=dirname(e);if(s===e)break;e=s;}return null}function dt(t){try{let e=readFileSync(t,"utf-8"),r=JSON.parse(e);return typeof r!="object"||r===null||Array.isArray(r)||!ct(r)?null:r}catch{return null}}function ct(t){for(let e of Object.keys(t)){if(Or.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!ct(r))return false}return true}function pt(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 ve(t){let e=Object.create(null);for(let r of Object.keys(t)){let n=t[r];typeof n=="string"&&n.startsWith("$")?e[r]=pt(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?e[r]=ve(n):e[r]=n;}return e}function ot(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),n=e[2],s=qr[n];return !s||r<=0?null:r*s}function ut(t,e){let r=Object.create(null);if(Object.assign(r,it),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.apiKey=="string"&&l.apiKey.length>0&&(r.apiKey=l.apiKey));let p=t.project;p&&typeof p=="object"&&typeof p.name=="string"&&(r.projectName=p.name);let d=t.queue;if(d&&typeof d=="object"){if(typeof d.maxAge=="string"){let u=ot(d.maxAge);u!==null&&(r.queueMaxAge=u);}typeof d.directory=="string"&&(r.queueDirectory=d.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let l=e.apiKey.startsWith("$")?pt(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.projectName=="string"&&(r.projectName=e.projectName),typeof e.queueMaxAge=="string"){let l=ot(e.queueMaxAge);l!==null&&(r.queueMaxAge=l);}typeof e.queueDirectory=="string"&&(r.queueDirectory=e.queueDirectory);}let n=process.env.TESTRELIC_API_KEY;n&&n.length>0&&(r.apiKey=n);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&isValidEndpointUrl(s)&&(r.endpoint=s);let a=process.env.TESTRELIC_UPLOAD_STRATEGY;a&&["batch","realtime","both"].includes(a)&&(r.uploadStrategy=a);let o=process.env.TESTRELIC_CLOUD_TIMEOUT;if(o){let l=parseInt(o,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let i=Object.freeze(r);return isValidCloudConfig(i)?i:it}var $r=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],zr=["authorization","cookie","set-cookie","x-api-key"],jr=["password","secret","token","apiKey","api_key"];function ft(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??[...zr],e.redactBodyFields=t?.redactBodyFields??[...jr],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function gt(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.navigationTypes=t?.navigationTypes??null,e.redactPatterns=[...$r,...t?.redactPatterns??[]],e.testRunId=t?.testRunId??null,e.metadata=t?.metadata??null;let r=e.outputPath;e.openReport=t?.openReport??true,e.htmlReportPath=t?.htmlReportPath??r.replace(/\.json$/,".html"),e.includeArtifacts=t?.includeArtifacts??true,e.trackApiCalls=t?.trackApiCalls??true,e.quiet=t?.quiet??false,e.includeActionSteps=t?.includeActionSteps??true,e.captureConsoleLogs=t?.captureConsoleLogs??true;let n=lt(process.cwd()),s=n?dt(n):null,a=s?ve(s):null,o=ut(a,t?.cloud);return e.cloud=o.apiKey?o:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var te="1.3.0";function ht(t,e,r){try{let s=readFileSync(t,"utf-8").split(`
3
+ `);if(e<1||e>s.length)return null;let a=Math.max(1,e-r),o=Math.min(s.length,e+r),i=[];for(let l=a;l<=o;l++){let p=l===e?">":" ",d=String(l).padStart(String(o).length," ");i.push(`${p} ${d} | ${s[l-1]}`);}return i.join(`
4
+ `)}catch{return null}}function mt(t){return e=>{let r=e;for(let n of t)if(typeof n=="string"){let s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=n.flags.includes("g")?n.flags:n.flags+"g",a=new RegExp(n.source,s);r=r.replace(a,"[REDACTED]");}return r}}function Gr(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 Jr(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 Wr(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 Kr(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 Yr(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 Zr=[Gr,Jr,Wr,Kr,Yr];function P(t){let e=process.env;for(let r of Zr){let n=r(e);if(n)return n}return null}var ye=`
4
5
  /* Theme Variables */
5
6
  :root,[data-theme="dark"]{
6
7
  --bg:#0f1117;--bg-1:#161b22;--bg-2:#1c2128;--bg-3:#21262d;--bg-code:#13111c;
@@ -289,6 +290,9 @@ body{
289
290
  /* \u2500\u2500 Failure Panel \u2500\u2500 */
290
291
  .failure-panel{margin-bottom:20px;border:1px solid rgba(239,68,68,0.2);border-radius:10px;overflow:hidden;background:var(--bg-2)}
291
292
  .failure-panel-header{display:flex;align-items:center;gap:8px;padding:10px 14px;background:rgba(239,68,68,0.08);font-size:12px;font-weight:600;color:#ef4444}
293
+ .copy-prompt-btn{margin-left:auto;display:inline-flex;align-items:center;gap:5px;padding:4px 10px;font-size:11px;font-weight:500;font-family:inherit;color:var(--fg-1);background:var(--bg-3);border:1px solid var(--bd);border-radius:6px;cursor:pointer;transition:all .15s;white-space:nowrap}
294
+ .copy-prompt-btn:hover{background:var(--bg-2);color:var(--fg);border-color:var(--bd-m)}
295
+ .copy-prompt-btn.copied{color:#34d399;border-color:rgba(52,211,153,0.3);background:rgba(52,211,153,0.08)}
292
296
  .failure-message{padding:12px 14px;background:var(--bg-code);color:var(--fg-err);font-size:12px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap;word-break:break-word;line-height:1.6;overflow-x:auto}
293
297
  .code-snippet{background:var(--bg-code);font-size:12px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;overflow-x:auto;border-top:1px solid var(--bd-s)}
294
298
  .code-line{display:flex;padding:0 14px;line-height:1.8}
@@ -381,21 +385,26 @@ body{
381
385
 
382
386
  /* \u2500\u2500 Network DevTools Panel \u2500\u2500 */
383
387
  .ndt{border:1px solid var(--bd);border-radius:10px;overflow:hidden;background:var(--bg-1)}
384
- .ndt-toolbar{display:flex;align-items:center;gap:6px;padding:6px 10px;background:var(--bg-2);border-bottom:1px solid var(--bd);flex-wrap:wrap}
388
+ .ndt{border:1px solid var(--bd);border-radius:8px;overflow:hidden;background:var(--bg-1)}
389
+ .ndt-toolbar{display:flex;align-items:center;gap:4px;padding:4px 8px;background:var(--bg-2);border-bottom:1px solid var(--bd);flex-wrap:wrap}
385
390
  .ndt-filter{display:flex;gap:2px;flex-wrap:wrap}
386
391
  .ndt-filter-btn{font-size:10px;padding:2px 8px;border-radius:4px;border:1px solid transparent;background:none;color:var(--fg-2);cursor:pointer;font-weight:500;transition:all .15s}
387
392
  .ndt-filter-btn:hover{background:var(--hvr);color:var(--fg-1)}
388
393
  .ndt-filter-btn.active{background:var(--bg-3);color:var(--fg);border-color:var(--bd-m);font-weight:600}
389
- .ndt-search{flex:1;min-width:100px;max-width:220px;font-size:10px;padding:3px 8px;border-radius:4px;border:1px solid var(--bd);background:var(--bg);color:var(--fg);outline:none;font-family:inherit}
394
+ .ndt-search{flex:1;min-width:100px;max-width:220px;font-size:10px;padding:3px 8px;border-radius:4px;border:1px solid var(--bd);background:var(--bg);color:var(--fg);outline:none;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
390
395
  .ndt-search:focus{border-color:rgba(3,183,156,0.4)}
391
396
  .ndt-count{font-size:10px;color:var(--fg-2);margin-left:auto;white-space:nowrap}
392
- .ndt-list{max-height:600px;overflow-y:auto}
397
+ .ndt-list{max-height:600px;overflow-y:auto;background:var(--bg)}
393
398
  .ndt-list::-webkit-scrollbar{width:5px}.ndt-list::-webkit-scrollbar-thumb{background:var(--scroll-thumb);border-radius:4px}
394
- .ndt-row{display:grid;grid-template-columns:42px 50px 1fr 52px 56px 56px;align-items:center;gap:4px;padding:5px 10px;border-bottom:1px solid var(--bd-xs);cursor:pointer;font-size:11px;transition:background .1s}
399
+ .ndt-row{display:grid;grid-template-columns:42px 50px 1fr 52px 56px 56px;align-items:center;gap:4px;padding:4px 10px;border-bottom:1px solid var(--bd-xs);cursor:pointer;font-size:11px;transition:background .1s}
395
400
  .ndt-row:hover{background:var(--hvr)}
396
401
  .ndt-row.ndt-row--open{background:var(--bg-2)}
397
402
  .ndt-row.ndt-row--fail{background:rgba(239,68,68,0.04)}
398
403
  .ndt-row.ndt-row--fail:hover{background:rgba(239,68,68,0.08)}
404
+ .ndt-row.seekable{cursor:pointer}
405
+ .ndt-row--active{background:rgba(3,183,156,0.1) !important;border-left:3px solid #03b79c}
406
+ .ndt-row--active .ndt-url{color:#2dd4a8}
407
+ .ndt-offset{color:#03b79c !important;font-weight:600}
399
408
  .ndt-status{font-weight:700;font-size:10px;padding:1px 5px;border-radius:3px;text-align:center;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
400
409
  .ndt-status--2xx{background:rgba(34,197,94,0.12);color:#22c55e}
401
410
  .ndt-status--3xx{background:rgba(59,130,246,0.12);color:#60a5fa}
@@ -462,23 +471,29 @@ body{
462
471
  @keyframes trSeekFlash{0%{background:rgba(3,183,156,0.15)}100%{background:transparent}}
463
472
 
464
473
  /* \u2500\u2500 Console/Logs Panel \u2500\u2500 */
465
- .console-panel{border:1px solid var(--bd);border-radius:8px;overflow:hidden}
466
- .console-header{font-size:11px;font-weight:700;color:var(--fg-1);text-transform:uppercase;letter-spacing:.06em;display:flex;align-items:center;gap:6px;padding:10px 12px 8px;border-bottom:1px solid var(--bd)}
474
+ .console-panel{border:1px solid var(--bd);border-radius:8px;overflow:hidden;background:var(--bg-1)}
475
+ .console-header{font-size:11px;font-weight:700;color:var(--fg-1);text-transform:uppercase;letter-spacing:.06em;display:flex;align-items:center;gap:6px;padding:8px 12px;border-bottom:1px solid var(--bd);background:var(--bg-2)}
467
476
  .console-header svg{opacity:.6}
468
477
  .console-count{font-weight:400;color:var(--fg-2);font-size:10px}
469
- .console-error-count{color:#f87171;font-weight:500;font-size:10px;text-transform:none;letter-spacing:0}
470
- .console-warn-count{color:#fbbf24;font-weight:500;font-size:10px;text-transform:none;letter-spacing:0}
471
- .console-toolbar{display:flex;gap:4px;padding:6px 12px;border-bottom:1px solid var(--bd);flex-wrap:wrap}
472
- .console-filter-btn{font-size:10px;padding:2px 8px;border-radius:4px;border:1px solid var(--bd);background:transparent;color:var(--fg-2);cursor:pointer;transition:all .15s;font-family:inherit}
473
- .console-filter-btn.active{background:var(--bg-3);color:var(--fg-1);border-color:var(--fg-2)}
474
- .console-filter-btn:hover{background:var(--hvr)}
475
- .console-list{max-height:400px;overflow-y:auto;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px}
476
- .console-entry{display:flex;align-items:baseline;gap:8px;padding:3px 12px;border-bottom:1px solid color-mix(in srgb,var(--bd) 50%,transparent)}
478
+ .console-error-count{color:#f87171;font-weight:500;font-size:10px;text-transform:none;letter-spacing:0;background:rgba(248,113,113,0.1);padding:1px 6px;border-radius:3px}
479
+ .console-warn-count{color:#fbbf24;font-weight:500;font-size:10px;text-transform:none;letter-spacing:0;background:rgba(251,191,36,0.1);padding:1px 6px;border-radius:3px}
480
+ .console-toolbar{display:flex;gap:3px;padding:4px 8px;border-bottom:1px solid var(--bd);flex-wrap:wrap;background:var(--bg-2)}
481
+ .console-filter-btn{font-size:10px;padding:2px 8px;border-radius:4px;border:1px solid transparent;background:transparent;color:var(--fg-2);cursor:pointer;transition:all .15s;font-family:inherit}
482
+ .console-filter-btn.active{background:var(--bg-3);color:var(--fg-1);border-color:var(--bd-m);font-weight:600}
483
+ .console-filter-btn:hover{background:var(--hvr);color:var(--fg-1)}
484
+ .console-list{max-height:400px;overflow-y:auto;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px;background:var(--bg)}
485
+ .console-list::-webkit-scrollbar{width:5px}.console-list::-webkit-scrollbar-thumb{background:var(--scroll-thumb);border-radius:4px}
486
+ .console-entry{display:flex;align-items:baseline;gap:6px;padding:2px 10px;border-bottom:1px solid var(--bd-xs);line-height:20px}
477
487
  .console-entry:hover{background:var(--hvr)}
478
488
  .console-level-badge{font-weight:600;font-size:9px;min-width:32px;text-transform:uppercase;letter-spacing:.03em}
479
489
  .console-time{color:var(--fg-2);font-size:10px;white-space:nowrap;min-width:65px}
480
490
  .console-text{flex:1;word-break:break-word;white-space:pre-wrap;color:var(--fg)}
481
491
  .console-loc{color:var(--fg-2);font-size:10px;white-space:nowrap;margin-left:auto;max-width:180px;overflow:hidden;text-overflow:ellipsis}
492
+ .console-entry.seekable{cursor:pointer}
493
+ .console-entry.seekable:hover{background:rgba(3,183,156,0.06)}
494
+ .console-active{background:rgba(3,183,156,0.12) !important;border-left:3px solid #03b79c}
495
+ .console-active .console-text{color:#2dd4a8}
496
+ .console-offset{color:#03b79c;font-size:9px;font-weight:600;min-width:42px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
482
497
  .console-level-error,.console-level-stderr{background:rgba(248,113,113,0.06)}
483
498
  .console-level-warn{background:rgba(251,191,36,0.06)}
484
499
 
@@ -511,42 +526,6 @@ body{
511
526
  .detail-duration{font-size:20px}
512
527
  }
513
528
 
514
- /* \u2500\u2500 Test Artifacts Section \u2500\u2500 */
515
- #artifact-section{margin-top:32px;margin-bottom:32px}
516
- .as-header{display:flex;align-items:center;gap:10px;margin-bottom:14px}
517
- .as-title{font-size:14px;font-weight:700;color:var(--fg)}
518
- .as-total{font-size:11px;color:var(--fg-2);margin-left:auto}
519
- .as-empty{text-align:center;padding:32px 20px;color:var(--fg-2);font-size:12px;font-style:italic;border:1px dashed var(--bd-m);border-radius:10px}
520
- .as-runs{border:1px solid var(--bd);border-radius:10px;overflow:hidden;background:var(--bg-1)}
521
- .as-run{border-bottom:1px solid var(--bd-s)}
522
- .as-run:last-child{border-bottom:none}
523
- .as-run-row{display:flex;align-items:center;gap:8px;padding:10px 14px;cursor:pointer;transition:background .1s}
524
- .as-run-row:hover{background:var(--hvr)}
525
- .as-run-arrow{font-size:9px;color:var(--fg-2);transition:transform .15s;display:inline-block;flex-shrink:0}
526
- .as-run.expanded .as-run-arrow{transform:rotate(90deg)}
527
- .as-run-label{font-size:12px;font-weight:500;color:var(--fg)}
528
- .as-current-tag{font-size:9px;font-weight:600;padding:1px 6px;border-radius:4px;background:rgba(3,183,156,0.12);color:#2dd4a8;margin-left:4px}
529
- .as-run-meta{font-size:11px;color:var(--fg-2);margin-left:auto;white-space:nowrap}
530
- .as-run-legacy .as-run-label{font-style:italic;color:var(--fg-2)}
531
- .as-run-detail{padding:0 14px 14px;background:var(--bg-2);border-top:1px solid var(--bd-s)}
532
- .as-no-tests{padding:12px;text-align:center;font-size:11px;color:var(--fg-2);font-style:italic}
533
- .as-test{padding:8px 0;border-bottom:1px solid var(--bd-xs)}
534
- .as-test:last-child{border-bottom:none}
535
- .as-test-name{font-size:11px;font-weight:600;color:var(--fg-1);margin-bottom:6px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
536
- .as-test-files{display:flex;flex-wrap:wrap;gap:10px}
537
- .as-file{display:flex;flex-direction:column;gap:4px;max-width:200px}
538
- .as-thumb{max-width:180px;max-height:120px;border-radius:6px;cursor:pointer;border:1px solid var(--bd);transition:border-color .15s;object-fit:contain}
539
- .as-thumb:hover{border-color:#03b79c}
540
- .as-video-wrap{border-radius:6px;overflow:hidden;border:1px solid var(--bd);background:#000;max-width:180px}
541
- .as-video-wrap video{width:100%;display:block;max-height:120px}
542
- .as-file-info{font-size:9px;color:var(--fg-2)}
543
- .as-file-icon{margin-right:4px}
544
- .as-loading{text-align:center;padding:24px;color:var(--fg-2);font-size:12px}
545
- .as-delete-btn{font-size:10px;padding:3px 10px;border-radius:4px;border:1px solid rgba(239,68,68,0.3);background:rgba(239,68,68,0.08);color:#ef4444;cursor:pointer;font-weight:500;transition:all .15s;flex-shrink:0}
546
- .as-delete-btn:hover{background:rgba(239,68,68,0.15);border-color:rgba(239,68,68,0.5)}
547
- .as-delete-all-btn{font-size:10px;padding:3px 12px;border-radius:4px;border:1px solid rgba(239,68,68,0.3);background:rgba(239,68,68,0.08);color:#ef4444;cursor:pointer;font-weight:600;transition:all .15s}
548
- .as-delete-all-btn:hover{background:rgba(239,68,68,0.15);border-color:rgba(239,68,68,0.5)}
549
-
550
529
  /* \u2500\u2500 Print \u2500\u2500 */
551
530
  @media print{
552
531
  body{background:#fff;color:#000}
@@ -571,15 +550,23 @@ body{
571
550
  ::-webkit-scrollbar-corner{background:transparent}
572
551
  /* Virtual grid sentinel */
573
552
  .vg-sentinel{height:1px}
574
- `;var Ft=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 247" fill="none">
553
+ /* \u2500\u2500 Streaming: detail loading / error states \u2500\u2500 */
554
+ .detail-loading{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:48px 20px;gap:14px}
555
+ .detail-loading .loading-spinner{width:28px;height:28px;border:3px solid var(--bd-l);border-top-color:var(--fg-1);border-radius:50%;animation:spin .8s linear infinite}
556
+ .detail-loading .loading-text{font-size:12px;color:var(--fg-2)}
557
+ .detail-error{padding:32px 20px;text-align:center;color:var(--fg-2);font-size:13px;line-height:1.7}
558
+ .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}
559
+ .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}
560
+ .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}
561
+ `;var be=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 247" fill="none">
575
562
  <path fill-rule="evenodd" clip-rule="evenodd" d="M4.75 1.08009C2.034 2.66209 -0.130999 7.63009 0.610001 10.5821C0.969001 12.0121 3.021 15.2131 5.17 17.6971C14.375 28.3321 18 39.7791 18 58.2101V71.0001H12.434C1.16501 71.0001 0 73.4641 0 97.3051C0 106.858 0.298003 128.922 0.662003 146.337L1.323 178H33.606C65.786 178 65.897 178.007 68.544 180.284C72.228 183.453 72.244 189.21 68.579 192.877L65.957 195.5L33.479 195.801L1 196.103V204.551V213H24.577H48.154L51.077 215.923C55.007 219.853 55.007 224.147 51.077 228.077L48.154 231H26.469H4.783L5.41901 233.534C5.76901 234.927 7.143 238.527 8.472 241.534L10.89 247H40.945H71L71.006 241.75C71.017 230.748 76.027 221.606 84.697 216.767C97.854 209.424 114.086 213.895 121.323 226.857C123.659 231.041 124.418 233.833 124.789 239.607L125.263 247H155.187H185.11L187.528 241.534C188.857 238.527 190.231 234.927 190.581 233.534L191.217 231H169.531H147.846L144.923 228.077C142.928 226.082 142 224.152 142 222C142 219.848 142.928 217.918 144.923 215.923L147.846 213H171.423H195V204.551V196.103L162.521 195.801L130.043 195.5L127.421 192.877C123.991 189.445 123.835 183.869 127.074 180.421L129.349 178H162.013H194.677L195.338 146.337C195.702 128.922 196 106.858 196 97.3051C196 73.4641 194.835 71.0001 183.566 71.0001H178V58.2101C178 39.6501 181.397 28.7731 190.538 18.0651C195.631 12.0971 196.572 9.00809 194.511 5.02109C192.672 1.46509 190.197 9.12233e-05 186.028 9.12233e-05C179.761 9.12233e-05 168.713 14.8831 163.388 30.5001C160.975 37.5771 160.608 40.3751 160.213 54.7501L159.765 71.0001H150.732H141.7L142.286 53.2501C142.904 34.5511 144.727 24.3761 148.938 16.1211C151.823 10.4671 151.628 5.90109 148.364 2.63609C145 -0.726907 140.105 -0.887909 136.596 2.25009C133.481 5.03609 128.686 17.0811 126.507 27.5921C125.569 32.1191 124.617 43.0901 124.28 53.2501L123.69 71.0001H115.345H107V38.4231V5.84609L104.077 2.92309C102.082 0.928088 100.152 9.12233e-05 98 9.12233e-05C95.848 9.12233e-05 93.918 0.928088 91.923 2.92309L89 5.84609V38.4231V71.0001H80.655H72.31L71.72 53.2501C71.383 43.0901 70.431 32.1191 69.493 27.5921C67.314 17.0811 62.519 5.03609 59.404 2.25009C55.998 -0.795909 51.059 -0.710905 47.646 2.45209C44.221 5.62609 44.191 9.92109 47.539 17.4911C51.71 26.9241 53.007 34.4791 53.676 53.2501L54.31 71.0001H45.272H36.235L35.787 54.7501C35.392 40.3751 35.025 37.5771 32.612 30.5001C27.194 14.6091 16.228 -0.02891 9.787 0.03009C7.979 0.04709 5.712 0.519093 4.75 1.08009ZM42.687 108.974C33.431 112.591 20.036 125.024 18.408 131.512C17.476 135.223 20.677 140.453 28.253 147.599C37.495 156.319 44.191 159.471 53.5 159.485C59.317 159.494 61.645 158.953 67.274 156.289C77.634 151.385 88.987 139.161 88.996 132.9C89.004 127.304 76.787 114.707 66.745 109.956C59.16 106.368 50.285 106.006 42.687 108.974ZM129.255 109.904C119.151 114.768 106.996 127.33 107.004 132.9C107.013 139.108 118.562 151.475 128.939 156.389C134.338 158.945 136.744 159.496 142.521 159.498C152.526 159.501 160.369 155.502 169.771 145.605C180.444 134.368 180.278 130.975 168.486 119.388C160.043 111.094 152.727 107.595 143 107.201C136.364 106.933 134.78 107.244 129.255 109.904ZM48.5 125.922C46.3 126.969 43.152 128.945 41.505 130.314L38.511 132.802L40.504 135.005C41.601 136.216 44.434 138.342 46.8 139.728C52.577 143.114 57.36 142.466 64.009 137.395L68.978 133.606L66.756 131.24C60.944 125.054 54.357 123.135 48.5 125.922ZM138.386 125.063C136.674 125.571 133.375 127.677 131.057 129.743L126.841 133.5L131.901 137.343C138.65 142.468 143.407 143.124 149.2 139.728C151.566 138.342 154.351 136.269 155.389 135.122C157.684 132.587 156.742 131.097 150.58 127.511C145.438 124.519 142.329 123.895 138.386 125.063ZM91.923 162.923C89.043 165.804 89 166.008 89 176.973C89 184.805 89.435 188.941 90.47 190.941C92.356 194.589 96.918 196.273 101.03 194.84C105.82 193.17 107 189.638 107 176.973C107 166.008 106.957 165.804 104.077 162.923C102.082 160.928 100.152 160 98 160C95.848 160 93.918 160.928 91.923 162.923ZM94.5 232.155C91.026 234.055 90 236.229 90 241.691V247H98H106V242.082C106 235.732 105.37 234.242 101.928 232.463C98.591 230.737 97.197 230.679 94.5 232.155Z" fill="url(#paint0_linear_55_11)"/>
576
563
  <defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
577
564
  <stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
578
- </linearGradient></defs></svg>`,Ht=`<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
565
+ </linearGradient></defs></svg>`,we=`<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
579
566
  <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)"/>
580
567
  <defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
581
568
  <stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
582
- </linearGradient></defs></svg>`;var Ut=`
569
+ </linearGradient></defs></svg>`;var xe=`
583
570
  /* \u2500\u2500 Utilities \u2500\u2500 */
584
571
  function esc(s){if(!s)return '';return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;')}
585
572
  function stripAnsi(s){return s?s.replace(/\\u001b\\[[0-9;]*m/g,'').replace(/\\x1b\\[[0-9;]*m/g,''):''}
@@ -627,6 +614,36 @@ body{
627
614
  return a.startedAt<b.startedAt?-1:1;
628
615
  });
629
616
 
617
+ /* \u2500\u2500 Streaming mode: build tests from compact index \u2500\u2500 */
618
+ if(data.reportMode==='streaming'&&data.index&&data.index.length>0){
619
+ tests=[];testMap={};
620
+ for(var xi=0;xi<data.index.length;xi++){
621
+ var ix=data.index[xi];
622
+ if(ix.isRetry)continue;
623
+ var st={
624
+ testId:ix.id,title:ix.title,status:ix.status,duration:ix.duration,
625
+ filePath:ix.filePath,tags:ix.tags||[],isFlaky:ix.status==='flaky',
626
+ testType:'e2e',retryCount:0,suiteName:'',
627
+ startedAt:'',completedAt:'',
628
+ networkRequests:[],steps:[],apiCalls:[],actions:[],consoleLogs:[],
629
+ artifacts:null,failure:null,retryStatus:null,expectedStatus:null,actualStatus:null,
630
+ hasNetworkData:ix.hasNetworkData,hasConsoleData:ix.hasConsoleData,
631
+ hasActionSteps:ix.hasActionSteps,hasArtifacts:ix.hasArtifacts,
632
+ errorMessage:ix.errorMessage,networkCount:ix.networkCount||0,
633
+ consoleCount:ix.consoleCount||0,actionCount:ix.actionCount||0
634
+ };
635
+ testMap[st.testId]=st;
636
+ tests.push(st);
637
+ }
638
+ tests.sort(function(a,b){
639
+ if(a.filePath!==b.filePath)return a.filePath<b.filePath?-1:1;
640
+ return 0;
641
+ });
642
+ }
643
+
644
+ /* \u2500\u2500 Streaming detail cache \u2500\u2500 */
645
+ var _detailCache={};
646
+
630
647
  /* \u2500\u2500 State \u2500\u2500 */
631
648
  var searchQuery='';
632
649
 
@@ -800,8 +817,8 @@ body{
800
817
  }
801
818
 
802
819
  /* \u2500\u2500 Render: Drawer Content \u2500\u2500 */
803
- function renderDrawer(testId){
804
- var t=testMap[testId];
820
+ function renderDrawer(testId,detail){
821
+ var t=detail||testMap[testId];
805
822
  if(!t){drawerBodyEl.innerHTML='';return;}
806
823
  var h='<div class="test-detail">';
807
824
 
@@ -820,7 +837,7 @@ body{
820
837
  h+='</div><div class="detail-duration">'+fmtDur(t.duration)+'</div></div></div>';
821
838
 
822
839
  /* \u2500\u2500 Failure panel (full width) \u2500\u2500 */
823
- if((t.status==='failed'||t.status==='flaky')&&t.failure)h+=renderFailure(t.failure);
840
+ if((t.status==='failed'||t.status==='flaky')&&t.failure)h+=renderFailure(t.failure,t.filePath,t.title,t.tags);
824
841
  else if(t.status==='failed'&&!t.failure)h+='<div style="margin-bottom:20px;padding:14px;background:var(--bg-2);border:1px solid var(--bd);border-radius:10px;font-size:12px;color:var(--fg-2);font-style:italic">No diagnostic information available</div>';
825
842
 
826
843
  /* \u2500\u2500 Stacked sections: 1) Artifacts 2) Timeline / Network 3) API Calls \u2500\u2500 */
@@ -830,12 +847,16 @@ body{
830
847
  var hasActions=t.actions&&t.actions.length>0;
831
848
  var hasConsoleLogs=t.consoleLogs&&t.consoleLogs.length>0;
832
849
  var hasVideo=!!(t.artifacts&&t.artifacts.video);
850
+ /* Compute base time for video offset calculation (console/network) */
851
+ var baseTime=0;
852
+ if(hasVideo&&t.startedAt){baseTime=Date.parse(t.startedAt);}
853
+ if(!baseTime&&hasVideo&&t.consoleLogs&&t.consoleLogs.length>0&&t.consoleLogs[0].timestamp){baseTime=Date.parse(t.consoleLogs[0].timestamp);}
833
854
  if(hasArt||hasSteps||hasApiCalls||hasActions||hasConsoleLogs){
834
855
  h+='<div class="drawer-sections">';
835
856
  if(hasArt)h+='<div class="drawer-section">'+renderArtifactColumn(t.artifacts)+'</div>';
836
857
  if(hasActions)h+='<div class="drawer-section">'+renderActionsColumn(t.actions,hasVideo)+'</div>';
837
- if(hasSteps)h+='<div class="drawer-section">'+renderTimelineColumn(t.steps,t.networkRequests,t.consoleLogs,t.testType)+'</div>';
838
- if(!hasSteps&&hasConsoleLogs)h+='<div class="drawer-section">'+renderConsoleColumn(t.consoleLogs,t.testType)+'</div>';
858
+ if(hasSteps)h+='<div class="drawer-section">'+renderTimelineColumn(t.steps,t.networkRequests,t.consoleLogs,t.testType,hasVideo,baseTime)+'</div>';
859
+ if(!hasSteps&&hasConsoleLogs)h+='<div class="drawer-section">'+renderConsoleColumn(t.consoleLogs,t.testType,hasVideo,baseTime)+'</div>';
839
860
  if(hasApiCalls)h+='<div class="drawer-section">'+renderApiCallsColumn(t.apiCalls)+'</div>';
840
861
  h+='</div>';
841
862
  }
@@ -849,6 +870,43 @@ body{
849
870
 
850
871
  /* \u2500\u2500 Drawer open / close \u2500\u2500 */
851
872
  function openDrawer(testId){
873
+ if(data.reportMode==='streaming'){
874
+ drawerEl.classList.add('open');
875
+ drawerBackdropEl.classList.add('open');
876
+ document.body.style.overflow='hidden';
877
+ if(_detailCache[testId]){renderDrawer(testId,_detailCache[testId]);return;}
878
+ drawerBodyEl.innerHTML='<div class="detail-loading"><div class="loading-spinner"></div><div class="loading-text">Loading test details...</div></div>';
879
+ if(window.__trStreamingFetchDetail){
880
+ window.__trStreamingFetchDetail(testId,function(err,detail){
881
+ if(err){
882
+ var t=testMap[testId];
883
+ var emsg=t&&t.errorMessage?'<div class="failure-message">'+esc(t.errorMessage)+'</div>':'';
884
+ drawerBodyEl.innerHTML='<div class="detail-error">'+emsg+'<p>Server unavailable &mdash; run <code>npx testrelic serve &lt;path&gt;</code> to view full details</p></div>';
885
+ return;
886
+ }
887
+ /* Merge index entry (title, status, duration, tags, etc.) with server detail (network, console, actions, etc.) */
888
+ var idx=testMap[testId]||{};
889
+ var merged={};
890
+ var k;for(k in idx){if(idx.hasOwnProperty(k))merged[k]=idx[k];}
891
+ merged.networkRequests=detail.networkRequests||[];
892
+ merged.consoleLogs=detail.consoleLogs||[];
893
+ merged.actions=detail.actions||[];
894
+ merged.apiCalls=detail.apiCalls||[];
895
+ merged.apiAssertions=detail.apiAssertions||[];
896
+ merged.artifacts=detail.artifacts||null;
897
+ merged.failure=detail.failureDiagnostic||detail.failure||null;
898
+ merged.steps=detail.navigations||[];
899
+ if(detail.startedAt)merged.startedAt=detail.startedAt;
900
+ _detailCache[testId]=merged;
901
+ renderDrawer(testId,merged);
902
+ });
903
+ }else{
904
+ var t=testMap[testId];
905
+ var emsg=t&&t.errorMessage?'<div class="failure-message">'+esc(t.errorMessage)+'</div>':'';
906
+ drawerBodyEl.innerHTML='<div class="detail-error">'+emsg+'<p>Server unavailable &mdash; run <code>npx testrelic serve &lt;path&gt;</code> to view full details</p></div>';
907
+ }
908
+ return;
909
+ }
852
910
  renderDrawer(testId);
853
911
  drawerEl.classList.add('open');
854
912
  drawerBackdropEl.classList.add('open');
@@ -869,7 +927,7 @@ body{
869
927
  clearTimeout(_searchTimer);
870
928
  _searchTimer=setTimeout(function(){searchQuery=q;applyFilters();},150);
871
929
  }
872
- `;var zt=`
930
+ `;var ke=`
873
931
  /* \u2500\u2500 Network Visualization Helpers \u2500\u2500 */
874
932
  var RES_COLORS={xhr:'#60a5fa',document:'#818cf8',script:'#fbbf24',stylesheet:'#a78bfa',image:'#34d399',font:'#f472b6',other:'#6b7280'};
875
933
  var RES_LABELS={xhr:'XHR',document:'Doc',script:'JS',stylesheet:'CSS',image:'Img',font:'Font',other:'Other'};
@@ -1006,7 +1064,15 @@ body{
1006
1064
  var NDT_ROW_H=32;
1007
1065
  var NDT_VBUF=30;
1008
1066
 
1009
- function renderNetworkDevTools(reqs){
1067
+ function ndtVideoOffset(req,baseTime){
1068
+ if(!baseTime||!req.startedAt)return -1;
1069
+ var t=Date.parse(req.startedAt);
1070
+ if(isNaN(t))return -1;
1071
+ var off=(t-baseTime)/1000;
1072
+ return off>=0?off:-1;
1073
+ }
1074
+
1075
+ function renderNetworkDevTools(reqs,hasVideo,baseTime){
1010
1076
  if(!reqs||reqs.length===0)return '<div class="artifact-empty">No network requests captured</div>';
1011
1077
  var uid='ndt-'+Math.random().toString(36).substr(2,6);
1012
1078
  var h='<div class="ndt" id="'+uid+'">';
@@ -1031,6 +1097,12 @@ body{
1031
1097
  h+='<div class="ndt-vspacer" style="height:'+(reqs.length*NDT_ROW_H)+'px;position:relative"></div>';
1032
1098
  h+='</div></div>';
1033
1099
 
1100
+ /* Pre-compute video offsets */
1101
+ var ndtVideoOffsets=[];
1102
+ if(hasVideo&&baseTime){
1103
+ for(var noi=0;noi<reqs.length;noi++){ndtVideoOffsets.push(ndtVideoOffset(reqs[noi],baseTime));}
1104
+ }
1105
+
1034
1106
  /* Store reqs data for virtual rendering */
1035
1107
  setTimeout(function(){
1036
1108
  var el=document.getElementById(uid);if(!el)return;
@@ -1039,6 +1111,7 @@ body{
1039
1111
  var allReqs=reqs;
1040
1112
  var filteredIdxs=null;
1041
1113
  var openIdx=-1;
1114
+ var highlightIdx=-1;
1042
1115
 
1043
1116
  function getVisible(){return filteredIdxs||allReqs.map(function(_,i){return i});}
1044
1117
 
@@ -1053,13 +1126,17 @@ body{
1053
1126
  var ri=vis[vi];var r=allReqs[ri];
1054
1127
  var isFail=r.statusCode>=400||r.statusCode===0;
1055
1128
  var isOpen=ri===openIdx;
1056
- out+='<div class="ndt-row'+(isFail?' ndt-row--fail':'')+(isOpen?' ndt-row--open':'')+'" data-ndt-idx="'+ri+'" data-ndt-type="'+esc(r.resourceType)+'" data-ndt-url="'+esc(r.url.toLowerCase())+'" style="position:absolute;top:'+(vi*NDT_ROW_H)+'px;left:0;right:0;height:'+NDT_ROW_H+'px">';
1129
+ var isActive=ri===highlightIdx;
1130
+ var off=ndtVideoOffsets[ri];
1131
+ var seekable=off>=0;
1132
+ out+='<div class="ndt-row'+(isFail?' ndt-row--fail':'')+(isOpen?' ndt-row--open':'')+(seekable?' seekable':'')+(isActive?' ndt-row--active':'')+'" data-ndt-idx="'+ri+'" data-ndt-type="'+esc(r.resourceType)+'" data-ndt-url="'+esc(r.url.toLowerCase())+'"'+(seekable?' data-offset="'+off.toFixed(2)+'"':'')+' style="position:absolute;top:'+(vi*NDT_ROW_H)+'px;left:0;right:0;height:'+NDT_ROW_H+'px">';
1057
1133
  out+='<span class="ndt-status '+ndtStatusClass(r.statusCode)+'">'+r.statusCode+'</span>';
1058
1134
  out+='<span class="ndt-method">'+esc(r.method)+'</span>';
1059
1135
  out+='<span class="ndt-url" title="'+esc(r.url)+'">'+esc(urlPath(r.url))+'</span>';
1060
1136
  out+='<span class="ndt-type">'+esc(RES_LABELS[r.resourceType]||r.resourceType)+'</span>';
1061
1137
  out+='<span class="ndt-size">'+fmtBytes(r.responseSize||0)+'</span>';
1062
- out+='<span class="ndt-time">'+fmtDur(r.responseTimeMs)+'</span>';
1138
+ if(seekable){out+='<span class="ndt-time ndt-offset">'+off.toFixed(1)+'s</span>';}
1139
+ else{out+='<span class="ndt-time">'+fmtDur(r.responseTimeMs)+'</span>';}
1063
1140
  out+='</div>';
1064
1141
  if(isOpen){out+=renderNdtDetail(r,ri);}
1065
1142
  }
@@ -1074,6 +1151,7 @@ body{
1074
1151
  /* Click handler for rows */
1075
1152
  list.addEventListener('click',function(e){
1076
1153
  var row=e.target.closest('.ndt-row');if(!row)return;
1154
+ /* If seekable and not clicking to expand, seek video */
1077
1155
  var idx=parseInt(row.getAttribute('data-ndt-idx'),10);
1078
1156
  openIdx=openIdx===idx?-1:idx;
1079
1157
  paint();
@@ -1097,12 +1175,33 @@ body{
1097
1175
  paint();
1098
1176
  };
1099
1177
 
1178
+ /* Video sync: scroll to matching request by time */
1179
+ if(ndtVideoOffsets.length){
1180
+ el.__videoSync=function(seconds){
1181
+ var vis=getVisible();
1182
+ var matchVi=-1;
1183
+ for(var i=vis.length-1;i>=0;i--){
1184
+ if(ndtVideoOffsets[vis[i]]>=0&&ndtVideoOffsets[vis[i]]<=seconds){matchVi=i;break;}
1185
+ }
1186
+ if(matchVi<0){highlightIdx=-1;paint();return;}
1187
+ var newHL=vis[matchVi];
1188
+ if(newHL===highlightIdx)return;
1189
+ highlightIdx=newHL;
1190
+ var rowTop=matchVi*NDT_ROW_H;
1191
+ var vh=list.clientHeight;
1192
+ if(rowTop<list.scrollTop||rowTop>list.scrollTop+vh-NDT_ROW_H){
1193
+ list.scrollTop=rowTop-vh/2;
1194
+ }
1195
+ paint();
1196
+ };
1197
+ }
1198
+
1100
1199
  paint();
1101
1200
  },0);
1102
1201
  return h;
1103
1202
  }
1104
1203
 
1105
- function renderTimelineColumn(steps,networkRequests,consoleLogs,testType){
1204
+ function renderTimelineColumn(steps,networkRequests,consoleLogs,testType,hasVideo,baseTime){
1106
1205
  if(!steps||steps.length===0)return '<div class="artifact-empty">No navigation data</div>';
1107
1206
  var hasReqs=networkRequests&&networkRequests.length>0;
1108
1207
  var hasCLogs=consoleLogs&&consoleLogs.length>0;
@@ -1112,20 +1211,71 @@ body{
1112
1211
  h+='<button class="seg-btn" data-seg="network"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>Network'+(hasReqs?' ('+networkRequests.length+')':'')+'</button>';
1113
1212
  h+='</div>';
1114
1213
  h+='<div class="seg-pane active" data-seg-pane="timeline">'+renderNavTimeline(steps)+'</div>';
1115
- if(hasCLogs)h+='<div class="seg-pane" data-seg-pane="console">'+renderConsoleColumn(consoleLogs,testType)+'</div>';
1116
- h+='<div class="seg-pane" data-seg-pane="network">'+renderNetworkDevTools(networkRequests)+'</div>';
1214
+ if(hasCLogs)h+='<div class="seg-pane" data-seg-pane="console">'+renderConsoleColumn(consoleLogs,testType,hasVideo,baseTime)+'</div>';
1215
+ h+='<div class="seg-pane" data-seg-pane="network">'+renderNetworkDevTools(networkRequests,hasVideo,baseTime)+'</div>';
1117
1216
  return h;
1118
1217
  }
1119
1218
 
1120
- function renderFailure(failure){
1219
+ function renderFailure(failure,filePath,testName,tags){
1121
1220
  if(!failure)return '';
1122
1221
  var sid='s-'+Math.random().toString(36).substr(2,8);
1123
- var h='<div class="failure-panel"><div class="failure-panel-header"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M15 9l-6 6M9 9l6 6"/></svg>Failure Details</div>';
1222
+ var cpid='cp-'+Math.random().toString(36).substr(2,8);
1223
+ var h='<div class="failure-panel"><div class="failure-panel-header"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M15 9l-6 6M9 9l6 6"/></svg>Failure Details<button class="copy-prompt-btn" id="'+cpid+'"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>Copy Prompt</button></div>';
1124
1224
  h+='<div class="failure-message">'+esc(stripAnsi(failure.message))+'</div>';
1125
1225
  if(failure.code)h+=renderCodeSnippet(failure.code);
1126
1226
  if(failure.line!==null&&failure.line!==undefined)h+='<div class="line-marker">Line '+failure.line+'</div>';
1127
1227
  if(failure.stack){h+='<button class="stack-toggle-btn" data-stack="'+sid+'">Show stack trace</button><div class="stack-trace" id="'+sid+'">'+esc(stripAnsi(failure.stack))+'</div>';}
1128
- h+='</div>';return h;
1228
+ h+='</div>';
1229
+ /* Wire up Copy Prompt button after render */
1230
+ setTimeout(function(){
1231
+ var btn=document.getElementById(cpid);
1232
+ if(!btn)return;
1233
+ btn.addEventListener('click',function(e){
1234
+ e.stopPropagation();
1235
+ var nl=String.fromCharCode(10);
1236
+ var ticks=String.fromCharCode(96,96,96);
1237
+ var msg=failure.message?stripAnsi(failure.message):'Unknown error';
1238
+ var tname=testName||'Unknown test';
1239
+ var tline=(failure.line!==null&&failure.line!==undefined)?String(failure.line):'unknown';
1240
+ var ttags=(tags&&tags.length>0)?tags.join(', '):'none';
1241
+ var fp=filePath||'unknown';
1242
+ /* Escape regex special chars in test name for --grep */
1243
+ function escGrep(s){return s.replace(/[.*+?^]/g,'\\\\$&').replace(/[()]/g,'\\\\$&');}
1244
+ var tnameEsc=escGrep(tname);
1245
+ var p='You are a Playwright test repair agent. A test in this codebase has failed. Your job is to fix the code and verify the fix passes.'+nl+nl;
1246
+ p+='## Failed Test'+nl+nl;
1247
+ p+='- **File:** '+fp+nl;
1248
+ p+='- **Test Name:** '+tname+nl;
1249
+ p+='- **Line:** '+tline+nl;
1250
+ p+='- **Tags:** '+ttags+nl+nl;
1251
+ p+='## Error'+nl+nl;
1252
+ p+=msg+nl+nl;
1253
+ if(failure.code){
1254
+ p+='## Failing Code'+nl+nl;
1255
+ p+=ticks+'typescript'+nl+stripAnsi(failure.code)+nl+ticks+nl+nl;
1256
+ }
1257
+ if(failure.stack){
1258
+ p+='## Stack Trace'+nl+nl;
1259
+ p+=ticks+nl+stripAnsi(failure.stack)+nl+ticks+nl+nl;
1260
+ }
1261
+ p+='## Your Task'+nl+nl;
1262
+ p+='1. Analyze the error and identify the root cause'+nl;
1263
+ p+='2. Edit '+ticks+fp+ticks+' to fix the failing assertion or logic '+String.fromCharCode(8212)+' do not delete the test'+nl;
1264
+ p+='3. Run the specific test to verify the fix: '+ticks+'npx playwright test '+fp+' --grep "'+tnameEsc+'" --reporter=line'+ticks+nl;
1265
+ p+='4. If the test passes, run the full file to confirm no regressions: '+ticks+'npx playwright test '+fp+' --reporter=line'+ticks+nl;
1266
+ p+='5. Stop only when the test exits with status '+ticks+'passed'+ticks+nl+nl;
1267
+ p+='## Constraints'+nl+nl;
1268
+ p+='- Only modify '+ticks+fp+ticks+nl;
1269
+ p+='- Do not alter shared fixtures, helpers, or '+ticks+'playwright.config.ts'+ticks+nl;
1270
+ p+='- Do not skip or remove the test'+nl;
1271
+ navigator.clipboard.writeText(p).then(function(){
1272
+ btn.innerHTML='<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 6L9 17l-5-5"/></svg>Copied!';
1273
+ btn.classList.add('copied');
1274
+ setTimeout(function(){btn.innerHTML='<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>Copy Prompt';btn.classList.remove('copied');},2000);
1275
+ });
1276
+ });
1277
+ },0);
1278
+ return h;
1129
1279
  }
1130
1280
 
1131
1281
  /* \u2500\u2500 Network DevTools Filter Logic \u2500\u2500 */
@@ -1238,7 +1388,7 @@ body{
1238
1388
  var countEl=ndt.querySelector('.ndt-count');
1239
1389
  if(countEl)countEl.textContent=visible+' / '+rows.length+' requests';
1240
1390
  }
1241
- `;var jt=`
1391
+ `;var Te=`
1242
1392
  var _filterState={status:{},type:{},specFile:{}};
1243
1393
  var _totalTests=0;
1244
1394
  var _originalSummary=null;
@@ -1409,7 +1559,7 @@ function _updateCard(cls,val){
1409
1559
  var el=document.querySelector('.'+cls+' .s-count');
1410
1560
  if(el)el.textContent=''+val;
1411
1561
  }
1412
- `;var $t=`
1562
+ `;var Ce=`
1413
1563
  /* \u2500\u2500 Event Delegation \u2500\u2500 */
1414
1564
  document.addEventListener('click',function(e){
1415
1565
  var target=e.target;
@@ -1553,37 +1703,6 @@ function _updateCard(cls,val){
1553
1703
  return;
1554
1704
  }
1555
1705
 
1556
- /* Artifact section: run row toggle */
1557
- var artToggle=target.closest('[data-artifact-toggle]');
1558
- if(artToggle){
1559
- var idx=artToggle.getAttribute('data-artifact-toggle');
1560
- var detail=document.getElementById('as-run-detail-'+idx);
1561
- var runEl=artToggle.closest('.as-run');
1562
- if(detail){
1563
- var isOpen=detail.style.display!=='none';
1564
- detail.style.display=isOpen?'none':'block';
1565
- if(runEl)runEl.classList.toggle('expanded',!isOpen);
1566
- }
1567
- return;
1568
- }
1569
-
1570
- /* Artifact section: delete single run */
1571
- var deleteBtn=target.closest('[data-artifact-action="delete"]');
1572
- if(deleteBtn){
1573
- e.stopPropagation();
1574
- var folder=deleteBtn.getAttribute('data-run-folder');
1575
- var isCurrent=deleteBtn.getAttribute('data-is-current')==='true';
1576
- if(folder&&typeof deleteArtifactRun==='function')deleteArtifactRun(folder,isCurrent);
1577
- return;
1578
- }
1579
-
1580
- /* Artifact section: delete all */
1581
- var deleteAllBtn=target.closest('[data-artifact-action="delete-all"]');
1582
- if(deleteAllBtn){
1583
- if(typeof deleteAllArtifacts==='function')deleteAllArtifacts();
1584
- return;
1585
- }
1586
-
1587
1706
  /* Stack trace toggle */
1588
1707
  if(target.classList.contains('stack-toggle-btn')){var se=document.getElementById(target.getAttribute('data-stack'));if(se){var sv=se.classList.toggle('show');target.textContent=sv?'Hide stack trace':'Show stack trace';}return;}
1589
1708
 
@@ -1641,42 +1760,58 @@ function _updateCard(cls,val){
1641
1760
  var b=document.querySelector('.lightbox-close');if(b)b.remove();
1642
1761
  }
1643
1762
 
1644
- /* \u2500\u2500 Video \u2194 Action Steps Sync \u2500\u2500 */
1763
+ /* \u2500\u2500 Video \u2194 All Panels Sync \u2500\u2500 */
1645
1764
  var _videoSyncCleanup=null;
1646
1765
  function syncActionsWithVideo(){
1647
1766
  /* Clean up previous listener */
1648
1767
  if(_videoSyncCleanup){_videoSyncCleanup();_videoSyncCleanup=null;}
1649
1768
  var video=document.querySelector('.drawer-body video');
1650
1769
  if(!video)return;
1770
+
1771
+ /* Action steps sync */
1651
1772
  var steps=document.querySelectorAll('.action-step.seekable');
1652
- if(!steps.length)return;
1653
- /* Build sorted offset list from DOM */
1654
1773
  var offsets=[];
1655
1774
  for(var i=0;i<steps.length;i++){
1656
1775
  var o=parseFloat(steps[i].getAttribute('data-offset'));
1657
1776
  if(!isNaN(o))offsets.push({el:steps[i],offset:o});
1658
1777
  }
1659
- if(!offsets.length)return;
1660
1778
  offsets.sort(function(a,b){return a.offset-b.offset;});
1779
+
1780
+ /* Collect console and network panels with video sync */
1781
+ var consolePanels=document.querySelectorAll('.console-panel');
1782
+ var ndtPanels=document.querySelectorAll('.ndt');
1783
+
1661
1784
  var lastActive=null;
1662
1785
  function onTimeUpdate(){
1663
1786
  var ct=video.currentTime;
1664
- /* Find the last step whose offset <= current time */
1665
- var match=null;
1666
- for(var i=offsets.length-1;i>=0;i--){
1667
- if(offsets[i].offset<=ct){match=offsets[i].el;break;}
1787
+
1788
+ /* Sync action steps */
1789
+ if(offsets.length){
1790
+ var match=null;
1791
+ for(var i=offsets.length-1;i>=0;i--){
1792
+ if(offsets[i].offset<=ct){match=offsets[i].el;break;}
1793
+ }
1794
+ if(match!==lastActive){
1795
+ if(lastActive)lastActive.classList.remove('action-active');
1796
+ if(match){
1797
+ match.classList.add('action-active');
1798
+ match.scrollIntoView({block:'nearest',behavior:'smooth'});
1799
+ }
1800
+ lastActive=match;
1801
+ }
1668
1802
  }
1669
- if(match===lastActive)return;
1670
- if(lastActive)lastActive.classList.remove('action-active');
1671
- if(match){
1672
- match.classList.add('action-active');
1673
- /* Scroll the active step into view within the drawer */
1674
- match.scrollIntoView({block:'nearest',behavior:'smooth'});
1803
+
1804
+ /* Sync console panels */
1805
+ for(var ci=0;ci<consolePanels.length;ci++){
1806
+ if(consolePanels[ci].__videoSync)consolePanels[ci].__videoSync(ct);
1807
+ }
1808
+
1809
+ /* Sync network panels */
1810
+ for(var ni=0;ni<ndtPanels.length;ni++){
1811
+ if(ndtPanels[ni].__videoSync)ndtPanels[ni].__videoSync(ct);
1675
1812
  }
1676
- lastActive=match;
1677
1813
  }
1678
1814
  video.addEventListener('timeupdate',onTimeUpdate);
1679
- /* Also sync on seek */
1680
1815
  video.addEventListener('seeked',onTimeUpdate);
1681
1816
  _videoSyncCleanup=function(){
1682
1817
  video.removeEventListener('timeupdate',onTimeUpdate);
@@ -1694,7 +1829,7 @@ function _updateCard(cls,val){
1694
1829
  var d=document.getElementById('filter-drawer');if(d)d.classList.remove('open');
1695
1830
  var b=document.getElementById('filter-drawer-backdrop');if(b)b.classList.remove('open');
1696
1831
  }
1697
- `;var Gt=`
1832
+ `;var Se=`
1698
1833
  /* \u2500\u2500 Category badge helpers \u2500\u2500 */
1699
1834
  function actionBadgeClass(cat){
1700
1835
  if(cat==='assertion')return 'action-badge-assertion';
@@ -1740,15 +1875,26 @@ function _updateCard(cls,val){
1740
1875
  h+='</div>';
1741
1876
  return h;
1742
1877
  }
1743
- `;var Vt=`
1878
+ `;var Re=`
1744
1879
  /* \u2500\u2500 Console Log Level Colors & Labels \u2500\u2500 */
1745
1880
  var LOG_COLORS={log:'#9ca3af',warn:'#fbbf24',error:'#f87171',info:'#60a5fa',debug:'#a78bfa',stdout:'#9ca3af',stderr:'#f87171'};
1746
1881
  var LOG_LABELS={log:'LOG',warn:'WARN',error:'ERR',info:'INFO',debug:'DBG',stdout:'OUT',stderr:'ERR'};
1747
1882
 
1748
- function renderConsoleLogEntry(entry){
1749
- var h='<div class="console-entry console-level-'+esc(entry.level)+'" data-console-level="'+esc(entry.level)+'">';
1883
+ function consoleVideoOffset(entry,baseTime){
1884
+ if(!baseTime||!entry.timestamp)return -1;
1885
+ var t=Date.parse(entry.timestamp);
1886
+ if(isNaN(t))return -1;
1887
+ var off=(t-baseTime)/1000;
1888
+ return off>=0?off:-1;
1889
+ }
1890
+
1891
+ function renderConsoleLogEntry(entry,hasVideo,baseTime){
1892
+ var off=hasVideo?consoleVideoOffset(entry,baseTime):-1;
1893
+ var seekable=off>=0;
1894
+ var h='<div class="console-entry console-level-'+esc(entry.level)+(seekable?' seekable':'')+'" data-console-level="'+esc(entry.level)+'"'+(seekable?' data-offset="'+off.toFixed(2)+'"':'')+'>';
1750
1895
  h+='<span class="console-level-badge" style="color:'+LOG_COLORS[entry.level]+'">'+LOG_LABELS[entry.level]+'</span>';
1751
- h+='<span class="console-time">'+fmtDate(entry.timestamp).split(', ').pop()+'</span>';
1896
+ if(seekable){h+='<span class="console-offset">'+off.toFixed(1)+'s</span>';}
1897
+ else{h+='<span class="console-time">'+fmtDate(entry.timestamp).split(', ').pop()+'</span>';}
1752
1898
  h+='<span class="console-text">'+esc(stripAnsi(entry.text))+'</span>';
1753
1899
  if(entry.location){var short=entry.location.split('/').pop()||entry.location;h+='<span class="console-loc" title="'+esc(entry.location)+'">'+esc(short)+'</span>';}
1754
1900
  h+='</div>';
@@ -1758,7 +1904,7 @@ function _updateCard(cls,val){
1758
1904
  var CON_ROW_H=24;
1759
1905
  var CON_VBUF=40;
1760
1906
 
1761
- function renderConsoleColumn(logs,testType){
1907
+ function renderConsoleColumn(logs,testType,hasVideo,baseTime){
1762
1908
  if(!logs||logs.length===0)return '';
1763
1909
  var isApi=testType==='api';
1764
1910
  var label=isApi?'Terminal Logs':'Console';
@@ -1784,6 +1930,12 @@ function _updateCard(cls,val){
1784
1930
  }
1785
1931
  h+='</div>';
1786
1932
 
1933
+ /* Pre-compute video offsets for all entries */
1934
+ var videoOffsets=[];
1935
+ if(hasVideo&&baseTime){
1936
+ for(var oi=0;oi<logs.length;oi++){videoOffsets.push(consoleVideoOffset(logs[oi],baseTime));}
1937
+ }
1938
+
1787
1939
  /* Use virtualization for large log lists */
1788
1940
  if(logs.length>200){
1789
1941
  h+='<div class="console-list console-vlist" style="overflow-y:auto;max-height:400px;position:relative">';
@@ -1797,6 +1949,7 @@ function _updateCard(cls,val){
1797
1949
  var spacer=list.querySelector('.console-vspacer');
1798
1950
  var allLogs=logs;
1799
1951
  var filteredIdxs=null;
1952
+ var highlightIdx=-1;
1800
1953
 
1801
1954
  function getVis(){return filteredIdxs||allLogs.map(function(_,i){return i});}
1802
1955
 
@@ -1808,10 +1961,14 @@ function _updateCard(cls,val){
1808
1961
  var s1=Math.min(vis.length,Math.ceil((st+vh)/CON_ROW_H)+CON_VBUF);
1809
1962
  var out='';
1810
1963
  for(var vi=s0;vi<s1;vi++){
1811
- var entry=allLogs[vis[vi]];
1812
- out+='<div class="console-entry console-level-'+esc(entry.level)+'" data-console-level="'+esc(entry.level)+'" style="position:absolute;top:'+(vi*CON_ROW_H)+'px;left:0;right:0;height:'+CON_ROW_H+'px">';
1964
+ var ri=vis[vi];var entry=allLogs[ri];
1965
+ var off=videoOffsets[ri];
1966
+ var seekable=off>=0;
1967
+ var isActive=ri===highlightIdx;
1968
+ out+='<div class="console-entry console-level-'+esc(entry.level)+(seekable?' seekable':'')+(isActive?' console-active':'')+'" data-console-level="'+esc(entry.level)+'"'+(seekable?' data-offset="'+off.toFixed(2)+'"':'')+' data-vidx="'+ri+'" style="position:absolute;top:'+(vi*CON_ROW_H)+'px;left:0;right:0;height:'+CON_ROW_H+'px">';
1813
1969
  out+='<span class="console-level-badge" style="color:'+LOG_COLORS[entry.level]+'">'+LOG_LABELS[entry.level]+'</span>';
1814
- out+='<span class="console-time">'+fmtDate(entry.timestamp).split(', ').pop()+'</span>';
1970
+ if(seekable){out+='<span class="console-offset">'+off.toFixed(1)+'s</span>';}
1971
+ else{out+='<span class="console-time">'+fmtDate(entry.timestamp).split(', ').pop()+'</span>';}
1815
1972
  out+='<span class="console-text">'+esc(stripAnsi(entry.text))+'</span>';
1816
1973
  if(entry.location){var short=entry.location.split('/').pop()||entry.location;out+='<span class="console-loc" title="'+esc(entry.location)+'">'+esc(short)+'</span>';}
1817
1974
  out+='</div>';
@@ -1822,6 +1979,16 @@ function _updateCard(cls,val){
1822
1979
  var rafP=false;
1823
1980
  list.addEventListener('scroll',function(){if(!rafP){rafP=true;requestAnimationFrame(function(){rafP=false;paint();})}},{passive:true});
1824
1981
 
1982
+ /* Click-to-seek for virtual entries */
1983
+ list.addEventListener('click',function(e){
1984
+ var entry=e.target.closest('.console-entry.seekable');
1985
+ if(!entry)return;
1986
+ var off=parseFloat(entry.getAttribute('data-offset'));
1987
+ if(isNaN(off))return;
1988
+ var video=document.querySelector('.drawer-body video');
1989
+ if(video){video.currentTime=off;video.play();}
1990
+ });
1991
+
1825
1992
  /* Store filter handler */
1826
1993
  panel.__conFilter=function(level){
1827
1994
  if(!level||level==='all'){filteredIdxs=null;}
@@ -1829,21 +1996,74 @@ function _updateCard(cls,val){
1829
1996
  list.scrollTop=0;paint();
1830
1997
  };
1831
1998
 
1999
+ /* Video sync: scroll to matching entry by time */
2000
+ panel.__videoSync=function(seconds){
2001
+ if(!videoOffsets.length)return;
2002
+ var vis=getVis();
2003
+ var matchVi=-1;
2004
+ for(var i=vis.length-1;i>=0;i--){
2005
+ if(videoOffsets[vis[i]]>=0&&videoOffsets[vis[i]]<=seconds){matchVi=i;break;}
2006
+ }
2007
+ if(matchVi<0){highlightIdx=-1;paint();return;}
2008
+ var newHL=vis[matchVi];
2009
+ if(newHL===highlightIdx)return;
2010
+ highlightIdx=newHL;
2011
+ /* Scroll to row */
2012
+ var rowTop=matchVi*CON_ROW_H;
2013
+ var vh=list.clientHeight;
2014
+ if(rowTop<list.scrollTop||rowTop>list.scrollTop+vh-CON_ROW_H){
2015
+ list.scrollTop=rowTop-vh/2;
2016
+ }
2017
+ paint();
2018
+ };
2019
+
1832
2020
  paint();
1833
2021
  },0);
1834
2022
  }else{
1835
2023
  h+='<div class="console-list">';
1836
- for(var i=0;i<logs.length;i++){h+=renderConsoleLogEntry(logs[i]);}
2024
+ for(var i=0;i<logs.length;i++){h+=renderConsoleLogEntry(logs[i],hasVideo,baseTime);}
1837
2025
  h+='</div>';
1838
2026
  h+='</div>';
2027
+
2028
+ /* Wire up click-to-seek for non-virtual entries */
2029
+ if(hasVideo&&baseTime){
2030
+ setTimeout(function(){
2031
+ var panel=document.getElementById(uid);if(!panel)return;
2032
+ panel.addEventListener('click',function(e){
2033
+ var entry=e.target.closest('.console-entry.seekable');
2034
+ if(!entry)return;
2035
+ var off=parseFloat(entry.getAttribute('data-offset'));
2036
+ if(isNaN(off))return;
2037
+ var video=document.querySelector('.drawer-body video');
2038
+ if(video){video.currentTime=off;video.play();}
2039
+ });
2040
+ /* Video sync for non-virtual */
2041
+ var entries=panel.querySelectorAll('.console-entry.seekable');
2042
+ var offsets=[];
2043
+ for(var i=0;i<entries.length;i++){
2044
+ var off=parseFloat(entries[i].getAttribute('data-offset'));
2045
+ if(!isNaN(off))offsets.push({el:entries[i],offset:off});
2046
+ }
2047
+ if(offsets.length){
2048
+ var lastHL=null;
2049
+ panel.__videoSync=function(seconds){
2050
+ var match=null;
2051
+ for(var i=offsets.length-1;i>=0;i--){
2052
+ if(offsets[i].offset<=seconds){match=offsets[i].el;break;}
2053
+ }
2054
+ if(match===lastHL)return;
2055
+ if(lastHL)lastHL.classList.remove('console-active');
2056
+ if(match){match.classList.add('console-active');match.scrollIntoView({block:'nearest',behavior:'smooth'});}
2057
+ lastHL=match;
2058
+ };
2059
+ }
2060
+ },0);
2061
+ }
1839
2062
  }
1840
2063
  return h;
1841
2064
  }
1842
- `;var Jt=`
1843
- /* \u2500\u2500 Test Artifacts Section \u2500\u2500 */
1844
- var _artifactManifest=null;
1845
- var _artifactServerPort=null;
1846
-
2065
+ `;var Ae=`
2066
+ /* \u2500\u2500 Artifact Utilities \u2500\u2500 */
1847
2067
  function formatBytes(bytes){
1848
2068
  if(bytes===0)return '0 B';
1849
2069
  var k=1024;var sizes=['B','KB','MB','GB'];
@@ -1851,186 +2071,153 @@ function _updateCard(cls,val){
1851
2071
  if(i>=sizes.length)i=sizes.length-1;
1852
2072
  return parseFloat((bytes/Math.pow(k,i)).toFixed(1))+' '+sizes[i];
1853
2073
  }
1854
-
1855
- function formatTimestamp(ts){
1856
- try{
1857
- var d=new Date(ts);
1858
- if(isNaN(d.getTime()))return ts;
1859
- return d.toLocaleDateString(undefined,{year:'numeric',month:'short',day:'numeric'})+' '+d.toLocaleTimeString(undefined,{hour:'2-digit',minute:'2-digit',second:'2-digit'});
1860
- }catch(e){return ts;}
1861
- }
1862
-
1863
- function renderArtifactSection(){
1864
- var section=document.getElementById('artifact-section');
1865
- if(!section)return;
1866
-
1867
- /* Read server port from meta tag */
1868
- var portMeta=document.querySelector('meta[name="artifact-server-port"]');
1869
- var candidatePort=null;
1870
- if(portMeta&&portMeta.content&&portMeta.content!=='null'){
1871
- candidatePort=parseInt(portMeta.content,10);
1872
- if(isNaN(candidatePort))candidatePort=null;
1873
- }
1874
-
1875
- /* Read manifest from embedded script tag (self-contained HTML) */
1876
- var manifestEl=document.getElementById('artifact-manifest-data');
1877
- var manifest=null;
1878
- if(manifestEl){
1879
- try{manifest=JSON.parse(manifestEl.textContent);}catch(e){}
1880
- }
1881
-
1882
- if(manifest){
1883
- _artifactManifest=manifest;
1884
- /* Verify server is actually reachable before enabling delete actions */
1885
- if(candidatePort){
1886
- fetch('http://127.0.0.1:'+candidatePort+'/api/health',{method:'GET'}).then(function(r){
1887
- if(r.ok){_artifactServerPort=candidatePort;}
1888
- renderArtifactContent(section,manifest);
1889
- }).catch(function(){
1890
- _artifactServerPort=null;
1891
- renderArtifactContent(section,manifest);
1892
- });
1893
- }else{
1894
- renderArtifactContent(section,manifest);
1895
- }
1896
- return;
1897
- }
1898
-
1899
- /* Fallback: try fetch (works when served via HTTP) */
1900
- fetch('artifact-manifest.json').then(function(r){
1901
- if(!r.ok)throw new Error('HTTP '+r.status);
1902
- return r.json();
1903
- }).then(function(m){
1904
- _artifactManifest=m;
1905
- renderArtifactContent(section,m);
1906
- }).catch(function(){
1907
- /* No manifest embedded and fetch failed \u2014 hide section entirely */
1908
- section.style.display='none';
1909
- });
1910
- }
1911
-
1912
- function renderArtifactContent(section,manifest){
1913
- var runs=manifest.runs||[];
1914
- var hasServer=!!_artifactServerPort;
1915
- var html='<div class="as-header"><span class="as-title">Test Artifacts</span><span class="as-total">'+formatBytes(manifest.totalSizeBytes||0)+' total</span>';
1916
- if(hasServer&&runs.length>0){
1917
- html+='<button class="as-delete-all-btn" data-artifact-action="delete-all">Delete All</button>';
1918
- }
1919
- html+='</div>';
1920
-
1921
- if(runs.length===0){
1922
- html+='<div class="as-empty">No artifact runs found.</div>';
1923
- }else{
1924
- html+='<div class="as-runs">';
1925
- for(var i=0;i<runs.length;i++){
1926
- var run=runs[i];
1927
- var isLegacy=run.folderName==='__legacy__';
1928
- var label=isLegacy?'Legacy (pre-timestamp)':formatTimestamp(run.timestamp);
1929
- var currentTag=run.isCurrentRun?' <span class="as-current-tag">Current</span>':'';
1930
- var legacyClass=isLegacy?' as-run-legacy':'';
1931
- html+='<div class="as-run'+legacyClass+'" data-run-folder="'+run.folderName+'">';
1932
- html+='<div class="as-run-row" data-artifact-toggle="'+i+'">';
1933
- html+='<span class="as-run-arrow">&#9654;</span>';
1934
- html+='<span class="as-run-label">'+label+currentTag+'</span>';
1935
- html+='<span class="as-run-meta">'+run.testCount+' test'+(run.testCount!==1?'s':'')+' &middot; '+formatBytes(run.totalSizeBytes)+'</span>';
1936
- if(hasServer&&!isLegacy){
1937
- html+='<button class="as-delete-btn" data-artifact-action="delete" data-run-folder="'+run.folderName+'"'+(run.isCurrentRun?' data-is-current="true"':'')+'>Delete</button>';
1938
- }
1939
- html+='</div>';
1940
- html+='<div class="as-run-detail" id="as-run-detail-'+i+'" style="display:none;">';
1941
- var tests=run.tests||[];
1942
- if(tests.length===0){
1943
- html+='<div class="as-no-tests">No test artifacts in this run.</div>';
1944
- }else{
1945
- for(var t=0;t<tests.length;t++){
1946
- var test=tests[t];
1947
- html+='<div class="as-test">';
1948
- html+='<div class="as-test-name">'+test.testName+'</div>';
1949
- html+='<div class="as-test-files">';
1950
- for(var f=0;f<test.files.length;f++){
1951
- var file=test.files[f];
1952
- if(file.type==='screenshot'){
1953
- html+='<div class="as-file"><img class="as-thumb artifact-col-img" src="'+file.relativePath+'" alt="'+file.name+'" loading="lazy"><span class="as-file-info">'+file.name+' ('+formatBytes(file.sizeBytes)+')</span></div>';
1954
- }else if(file.type==='video'){
1955
- html+='<div class="as-file"><div class="as-video-wrap"><video src="'+file.relativePath+'" controls preload="metadata"></video></div><span class="as-file-info">'+file.name+' ('+formatBytes(file.sizeBytes)+')</span></div>';
1956
- }else{
1957
- html+='<div class="as-file"><span class="as-file-icon">&#128196;</span><a href="'+file.relativePath+'" target="_blank">'+file.name+'</a> ('+formatBytes(file.sizeBytes)+')</div>';
1958
- }
1959
- }
1960
- html+='</div></div>';
1961
- }
1962
- }
1963
- html+='</div></div>';
1964
- }
1965
- html+='</div>';
2074
+ `;var Qr=`
2075
+ (function(){
2076
+ var data=JSON.parse(document.getElementById('report-data').textContent);
2077
+ ${xe}
2078
+ ${Se}
2079
+ ${Re}
2080
+ ${ke}
2081
+ ${Te}
2082
+ ${Ae}
2083
+ ${Ce}
2084
+ applyTheme();
2085
+ renderRunMeta();
2086
+ renderSummary();
2087
+ initFilters();
2088
+ renderFilterBar();
2089
+ renderTestGrid();
2090
+ var _lo=document.getElementById('loading-overlay');if(_lo)_lo.remove();
2091
+ })();`;function vt(t,e,r){let n=t.replace(/<\//g,"<\\/"),s=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
2092
+ <!DOCTYPE html>
2093
+ <html lang="en" data-theme="">
2094
+ <head>
2095
+ <meta charset="UTF-8">
2096
+ <meta name="viewport" content="width=device-width,initial-scale=1">
2097
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: blob: 'self'; media-src blob: 'self'; connect-src 'self' http://127.0.0.1:*;">
2098
+ <title>TestRelic AI Analytics Report</title>
2099
+ ${""}
2100
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(be).toString("base64")}">
2101
+ <style>${ye}</style>
2102
+ <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>
2103
+ </head>
2104
+ <body>
2105
+ <div class="wrap">
2106
+ <div class="top-bar">
2107
+ <div class="brand">
2108
+ ${we}
2109
+ <div class="brand-text">
2110
+ <span class="brand-title">TestRelic AI</span>
2111
+ <span class="brand-sub">Analytics Report</span>
2112
+ </div>
2113
+ </div>
2114
+ <div class="run-meta" id="run-meta"></div>
2115
+ <div class="theme-toggle" id="theme-toggle">
2116
+ <button class="theme-btn" data-theme-val="system" title="System"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg></button>
2117
+ <button class="theme-btn" data-theme-val="light" title="Light"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg></button>
2118
+ <button class="theme-btn" data-theme-val="dark" title="Dark"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg></button>
2119
+ </div>
2120
+ <a class="cta-btn" href="https://testrelic.ai" target="_blank" rel="noopener noreferrer"><svg class="cta-icon" viewBox="0 0 16 16" fill="none"><path d="M8 1l1.545 4.955L14.5 7.5l-4.955 1.545L8 14l-1.545-4.955L1.5 7.5l4.955-1.545L8 1z" fill="currentColor"/></svg>Advanced Insights with AI<span class="cta-sep">\u2013</span><strong>Get Started</strong><svg class="cta-arrow" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M2.5 6h7M6.5 3l3 3-3 3"/></svg></a>
2121
+ </div>
2122
+ <div id="summary-strip" class="summary-strip"></div>
2123
+ <div id="filter-bar" class="filter-bar"></div>
2124
+ <div id="test-grid"></div>
2125
+ </div>
2126
+ <div class="loading-overlay" id="loading-overlay"><div class="loading-spinner"></div><div class="loading-text">Loading report...</div></div>
2127
+ <div class="drawer-backdrop" id="drawer-backdrop"></div>
2128
+ <aside class="drawer" id="drawer">
2129
+ <div class="drawer-bar">
2130
+ <span class="drawer-bar-title">Test Details</span>
2131
+ <button class="drawer-close" id="drawer-close">&times;</button>
2132
+ </div>
2133
+ <div class="drawer-body" id="drawer-body"></div>
2134
+ </aside>
2135
+ <div class="filter-drawer-backdrop" id="filter-drawer-backdrop"></div>
2136
+ <aside class="filter-drawer" id="filter-drawer">
2137
+ <div class="filter-drawer-bar">
2138
+ <span class="filter-drawer-title">Filters</span>
2139
+ <button class="filter-drawer-close" id="filter-drawer-close">&times;</button>
2140
+ </div>
2141
+ <div class="filter-drawer-body" id="filter-drawer-body"></div>
2142
+ </aside>
2143
+ <script id="report-data" type="application/json">${n}</script>
2144
+ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:""}
2145
+ <script>${Qr}</script>
2146
+ </body>
2147
+ </html>`}function yt(t,e,r,n){let s=t.replace(/<\//g,"<\\/"),a=e;try{let d=JSON.parse(e);if(Array.isArray(d)){let u=d.map(f=>{let{titlePath:c,project:h,...g}=f;return g});a=JSON.stringify(u);}}catch{}let o=a.replace(/<\//g,"<\\/"),i=n?n.replace(/<\//g,"<\\/"):null,l=`{
2148
+ "schemaVersion":"2.0",
2149
+ "reportMode":"streaming",
2150
+ "serverPort":${"null"},
2151
+ "summary":${s},
2152
+ "index":${o},
2153
+ "timeline":[],
2154
+ "testRunId":"",
2155
+ "startedAt":"",
2156
+ "completedAt":"",
2157
+ "totalDuration":0,
2158
+ "ci":null,
2159
+ "metadata":null,
2160
+ "shardRunIds":null
2161
+ }`,p=`
2162
+ (function(){
2163
+ var data=JSON.parse(document.getElementById('report-data').textContent);
2164
+ var _serverPort=data.serverPort||null;
2165
+ var _serverAvailable=false;
2166
+ var _detailCache={};
2167
+ var _testIndex=data.index||[];
2168
+
2169
+ /* Resolve the API base URL: if served from http, use same origin; otherwise use explicit port */
2170
+ function getApiBase(){
2171
+ if(window.location.protocol==='http:'||window.location.protocol==='https:'){
2172
+ return window.location.origin;
1966
2173
  }
1967
- section.innerHTML=html;
2174
+ if(_serverPort){return 'http://127.0.0.1:'+_serverPort;}
2175
+ return null;
1968
2176
  }
1969
-
1970
- function refreshArtifactSection(){
1971
- var section=document.getElementById('artifact-section');
1972
- if(!section)return;
1973
- if(_artifactServerPort){
1974
- fetch('http://127.0.0.1:'+_artifactServerPort+'/api/artifacts').then(function(r){
1975
- if(!r.ok)throw new Error('HTTP '+r.status);
1976
- return r.json();
1977
- }).then(function(data){
1978
- _artifactManifest={schemaVersion:'1.0',generatedAt:new Date().toISOString(),artifactBaseDir:'artifacts',totalSizeBytes:data.totalSizeBytes||0,runs:data.runs||[],serverPort:_artifactServerPort};
1979
- renderArtifactContent(section,_artifactManifest);
1980
- }).catch(function(){
1981
- section.innerHTML='<div class="as-header"><span class="as-title">Test Artifacts</span></div><div class="as-empty">Failed to refresh artifact data.</div>';
1982
- });
1983
- }else{
1984
- renderArtifactSection();
1985
- }
2177
+ var _apiBase=getApiBase();
2178
+
2179
+ /* Check server availability */
2180
+ function checkServer(cb){
2181
+ if(!_apiBase){cb(false);return;}
2182
+ fetch(_apiBase+'/api/health',{method:'GET'}).then(function(r){
2183
+ _serverAvailable=r.ok;cb(r.ok);
2184
+ }).catch(function(){_serverAvailable=false;cb(false);});
1986
2185
  }
1987
2186
 
1988
- function deleteArtifactRun(folderName,isCurrent){
1989
- var msg='Delete artifact run "'+folderName+'"?';
1990
- if(isCurrent)msg+='\\n\\nWarning: This will remove the current run\\'s artifacts.';
1991
- if(!confirm(msg))return;
1992
- if(!_artifactServerPort)return;
1993
- fetch('http://127.0.0.1:'+_artifactServerPort+'/api/artifacts/'+encodeURIComponent(folderName),{method:'DELETE'}).then(function(r){
2187
+ /* Fetch test detail from server */
2188
+ function fetchTestDetail(testId,cb){
2189
+ if(_detailCache[testId]){cb(null,_detailCache[testId]);return;}
2190
+ if(!_serverAvailable||!_apiBase){cb('Server unavailable');return;}
2191
+ fetch(_apiBase+'/api/tests/'+testId).then(function(r){
1994
2192
  if(!r.ok)throw new Error('HTTP '+r.status);
1995
2193
  return r.json();
1996
- }).then(function(){
1997
- refreshArtifactSection();
1998
- }).catch(function(err){
1999
- alert('Failed to delete: '+err.message);
2000
- });
2194
+ }).then(function(d){
2195
+ _detailCache[testId]=d;cb(null,d);
2196
+ }).catch(function(e){cb(e.message||'Failed to fetch');});
2001
2197
  }
2002
2198
 
2003
- function deleteAllArtifacts(){
2004
- if(!confirm('Delete ALL artifact run folders? This cannot be undone.'))return;
2005
- if(!_artifactServerPort)return;
2006
- fetch('http://127.0.0.1:'+_artifactServerPort+'/api/artifacts',{method:'DELETE'}).then(function(r){
2007
- if(!r.ok)throw new Error('HTTP '+r.status);
2008
- return r.json();
2009
- }).then(function(){
2010
- refreshArtifactSection();
2011
- }).catch(function(err){
2012
- alert('Failed to delete all: '+err.message);
2013
- });
2014
- }
2015
- `;var yr=`
2016
- (function(){
2017
- var data=JSON.parse(document.getElementById('report-data').textContent);
2018
- ${Ut}
2019
- ${Gt}
2020
- ${Vt}
2021
- ${zt}
2022
- ${jt}
2023
- ${Jt}
2024
- ${$t}
2199
+ /* Make fetchTestDetail and index available globally for other modules */
2200
+ window.__trStreamingFetchDetail=fetchTestDetail;
2201
+ window.__trTestIndex=_testIndex;
2202
+ window.__trServerPort=_serverPort;
2203
+ window.__trIsStreaming=true;
2204
+
2205
+ ${xe}
2206
+ ${Se}
2207
+ ${Re}
2208
+ ${ke}
2209
+ ${Te}
2210
+ ${Ae}
2211
+ ${Ce}
2025
2212
  applyTheme();
2026
2213
  renderRunMeta();
2027
2214
  renderSummary();
2028
2215
  initFilters();
2029
2216
  renderFilterBar();
2030
2217
  renderTestGrid();
2031
- renderArtifactSection();
2218
+ checkServer(function(ok){});
2032
2219
  var _lo=document.getElementById('loading-overlay');if(_lo)_lo.remove();
2033
- })();`;function Kt(e,t,r){let n=e.replace(/<\//g,"<\\/"),s=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
2220
+ })();`;return `<!-- TestRelic AI Analytics Report \u2014 streaming mode -->
2034
2221
  <!DOCTYPE html>
2035
2222
  <html lang="en" data-theme="">
2036
2223
  <head>
@@ -2038,16 +2225,17 @@ function _updateCard(cls,val){
2038
2225
  <meta name="viewport" content="width=device-width,initial-scale=1">
2039
2226
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: blob: 'self'; media-src blob: 'self'; connect-src 'self' http://127.0.0.1:*;">
2040
2227
  <title>TestRelic AI Analytics Report</title>
2041
- ${t?`<meta name="artifact-server-port" content="${t}">`:""}
2042
- <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Ft).toString("base64")}">
2043
- <style>${Ot}</style>
2228
+ ${""}
2229
+ ${""}
2230
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(be).toString("base64")}">
2231
+ <style>${ye}</style>
2044
2232
  <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>
2045
2233
  </head>
2046
2234
  <body>
2047
2235
  <div class="wrap">
2048
2236
  <div class="top-bar">
2049
2237
  <div class="brand">
2050
- ${Ht}
2238
+ ${we}
2051
2239
  <div class="brand-text">
2052
2240
  <span class="brand-title">TestRelic AI</span>
2053
2241
  <span class="brand-sub">Analytics Report</span>
@@ -2064,7 +2252,6 @@ ${t?`<meta name="artifact-server-port" content="${t}">`:""}
2064
2252
  <div id="summary-strip" class="summary-strip"></div>
2065
2253
  <div id="filter-bar" class="filter-bar"></div>
2066
2254
  <div id="test-grid"></div>
2067
- <div id="artifact-section"></div>
2068
2255
  </div>
2069
2256
  <div class="loading-overlay" id="loading-overlay"><div class="loading-spinner"></div><div class="loading-text">Loading report...</div></div>
2070
2257
  <div class="drawer-backdrop" id="drawer-backdrop"></div>
@@ -2083,50 +2270,58 @@ ${t?`<meta name="artifact-server-port" content="${t}">`:""}
2083
2270
  </div>
2084
2271
  <div class="filter-drawer-body" id="filter-drawer-body"></div>
2085
2272
  </aside>
2086
- <script id="report-data" type="application/json">${n}</script>
2087
- ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:""}
2088
- <script>${yr}</script>
2273
+ <script id="report-data" type="application/json">${l}</script>
2274
+ ${i?`<script id="artifact-manifest-data" type="application/json">${i}</script>`:""}
2275
+ <script>${p}</script>
2089
2276
  </body>
2090
- </html>`}function Wt(e){try{let t=process.platform,r;t==="darwin"?r=`open "${e}"`:t==="win32"?r=`start "" "${e}"`:r=`xdg-open "${e}"`,exec(r,n=>{n&&process.stderr.write(`[testrelic] Failed to open browser: ${n.message}
2091
- `);});}catch{}}var st=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,wr=1800*1e3;function kr(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 R(e,t,r){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(r));}function j(e){let t=0;try{let r=readdirSync(e,{withFileTypes:!0});for(let n of r){let s=join(e,n.name);n.isFile()?t+=statSync(s).size:n.isDirectory()&&(t+=j(s));}}catch{}return t}function Qt(e){return new Promise((t,r)=>{let n;function s(){clearTimeout(n),n=setTimeout(()=>{a.close();},wr);}let a=createServer((l,i)=>{if(s(),kr(i),l.method==="OPTIONS"){i.writeHead(204),i.end();return}let c=new URL(l.url??"/",`http://${l.headers.host}`).pathname;if(l.method==="GET"&&c==="/api/health"){R(i,200,{status:"ok"});return}if(l.method==="GET"&&c==="/api/artifacts"){try{let p=[],f=0,u=readdirSync(e,{withFileTypes:!0});for(let h of u){if(!h.isDirectory()||!st.test(h.name))continue;let g=join(e,h.name),v=j(g),y=readdirSync(g,{withFileTypes:!0}).filter(b=>b.isDirectory());p.push({folderName:h.name,totalSizeBytes:v,testCount:y.length}),f+=v;}p.sort((h,g)=>g.folderName.localeCompare(h.folderName)),R(i,200,{runs:p,totalSizeBytes:f});}catch(p){R(i,500,{error:p instanceof Error?p.message:String(p)});}return}if(l.method==="DELETE"&&c==="/api/artifacts"){try{let p=0,f=0,u=readdirSync(e,{withFileTypes:!0});for(let h of u){if(!h.isDirectory()||!st.test(h.name))continue;let g=join(e,h.name),v=j(g);rmSync(g,{recursive:!0,force:!0}),f+=v,p++;}R(i,200,{deletedCount:p,freedBytes:f});}catch(p){R(i,500,{error:p instanceof Error?p.message:String(p)});}return}let d=c.match(/^\/api\/artifacts\/(.+)$/);if(l.method==="DELETE"&&d){let p=decodeURIComponent(d[1]);if(!st.test(p)){R(i,400,{error:"Invalid folder name"});return}let f=join(e,p);try{if(!statSync(f).isDirectory()){R(i,404,{error:"Not found"});return}}catch{R(i,404,{error:"Not found"});return}try{let u=j(f);rmSync(f,{recursive:!0,force:!0}),R(i,200,{deleted:p,freedBytes:u});}catch(u){R(i,500,{error:u instanceof Error?u.message:String(u)});}return}R(i,404,{error:"Not found"});});a.listen(0,"127.0.0.1",()=>{let l=a.address();if(!l||typeof l=="string"){r(new Error("Failed to get server address"));return}s(),t({port:l.port,dispose:()=>new Promise(i=>{clearTimeout(n),a.close(()=>i());})});}),a.on("error",r);})}function Ir(e,t,r){let n=JSON.stringify(e),s=r?JSON.stringify(r):null;return Kt(n,t,s)}async function te(e,t,r){try{let n=null;if(t.openReport&&e.ci===null&&t.includeArtifacts){let o=dirname(t.outputPath),c=join(o,"artifacts");if(existsSync(c))try{let d=await Qt(c);n=d.port,process.on("exit",()=>{d.dispose();});}catch{}}let s=Ir(e,n,r),a=t.htmlReportPath,l=dirname(a);mkdirSync(l,{recursive:!0});let i=a+".tmp";if(writeFileSync(i,s,"utf-8"),renameSync(i,a),t.openReport&&e.ci===null){let o=resolve(a);Wt(o);}}catch(n){process.stderr.write(`[testrelic] Failed to write HTML report: ${n instanceof Error?n.message:String(n)}
2092
- `);}}function ne(e){let t=new Date,r=a=>String(a).padStart(2,"0"),n=`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())}T${r(t.getHours())}-${r(t.getMinutes())}-${r(t.getSeconds())}`;if(!existsSync(join(e,n)))return n;let s=1;for(;existsSync(join(e,`${n}-${s}`));)s++;return `${n}-${s}`}function Lr(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"}function se(e,t,r,n,s){let a=e.find(f=>f.name==="screenshot"&&f.path),l=e.find(f=>f.name==="video"&&f.path);if(!a&&!l)return null;let i=Lr(t);r>0&&(i+=`--retry-${r}`);let o=s?["artifacts",s,i]:["artifacts",i],c=join(n,...o),d=o,p={};try{mkdirSync(c,{recursive:!0});}catch{return null}if(a?.path)try{if(existsSync(a.path)){let u=`screenshot${extname(a.path)||".png"}`;copyFileSync(a.path,join(c,u)),p.screenshot=`${d.join("/")}/${u}`;}}catch{}if(l?.path)try{if(existsSync(l.path)){let u=`video${extname(l.path)||".webm"}`;copyFileSync(l.path,join(c,u)),p.video=`${d.join("/")}/${u}`;}}catch{}return !p.screenshot&&!p.video?null:p}var Mr=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Pr="1.0";function qr(e){let t=extname(e).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(t)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(t)?"video":"other"}function ae(e,t,r){let n=[];try{let s=readdirSync(e,{withFileTypes:!0});for(let a of s){if(!a.isFile())continue;let l=join(e,a.name),i=statSync(l);n.push({name:a.name,type:qr(a.name),relativePath:`artifacts/${t}/${r}/${a.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:n}}function Dr(e,t){let r=join(e,t),n=[],s=0;try{let l=readdirSync(r,{withFileTypes:!0});for(let i of l){if(!i.isDirectory())continue;let o=ae(join(r,i.name),t,i.name);n.push(o);for(let c of o.files)s+=c.sizeBytes;}}catch{}let a=t.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return n.sort((l,i)=>l.testName.localeCompare(i.testName)),{folderName:t,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function ie(e,t){let r=join(e,"artifacts"),n=[],s=[],a=0;try{let i=readdirSync(r,{withFileTypes:!0});for(let o of i)if(o.isDirectory())if(Mr.test(o.name)){let c=Dr(r,o.name);n.push({...c,isCurrentRun:o.name===t});}else {let c=ae(join(r,o.name),o.name,o.name);s.push(c);for(let d of c.files)a+=d.sizeBytes;}}catch{}n.sort((i,o)=>o.timestamp.localeCompare(i.timestamp)),s.length>0&&(s.sort((i,o)=>i.testName.localeCompare(o.testName)),n.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:a,testCount:s.length,tests:s,isCurrentRun:false}));let l=n.reduce((i,o)=>i+o.totalSizeBytes,0);return {schemaVersion:Pr,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:l,runs:n,serverPort:null}}function zr(e){let t=e,{root:r}=parse(t);for(;t!==r;){if(existsSync(join(t,".git")))return t;t=join(t,"..");}return null}function le(e){try{let t=zr(e);if(!t)return;let r=join(t,".gitignore"),n=relative(t,e).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
2093
- `).map(o=>o.trim()).some(o=>o===s||o===n))return;let a=`
2277
+ </html>`}function _e(t){try{let e=process.platform,r;e==="darwin"?r=`open "${t}"`:e==="win32"?r=`start "" "${t}"`:r=`xdg-open "${t}"`,exec(r,n=>{n&&process.stderr.write(`[testrelic] Failed to open browser: ${n.message}
2278
+ `);});}catch{}}var tn=/^[a-f0-9]{12}$/,Le=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,rn=500;function w(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function xt(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 ne(t){try{return existsSync(t)?JSON.parse(readFileSync(t,"utf-8")):null}catch{return null}}function se(t){let e=0;try{let r=readdirSync(t,{withFileTypes:!0});for(let n of r){let s=join(t,n.name);n.isFile()?e+=statSync(s).size:n.isDirectory()&&(e+=se(s));}}catch{}return e}function kt(t,e,r,n){let s=ne(join(r,"index.json"));w(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function Tt(t,e,r){let n=ne(join(r,"summary.json"));if(!n){w(e,404,{error:"Summary not found"});return}w(e,200,n);}function Ct(t,e,r){let n=ne(join(r,"index.json"));if(!n){w(e,404,{error:"Test index not found"});return}let a=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,o=Math.max(1,parseInt(a.get("page")??"1",10)||1),i=Math.min(rn,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),l=a.get("status")?.split(",").filter(Boolean)??null,p=a.get("file")??null,d=a.get("search")?.toLowerCase()??null,u=a.get("tag")?.split(",").filter(Boolean)??null,f=a.get("sort")??"file",c=a.get("order")==="desc"?-1:1,h=n;l&&l.length>0&&(h=h.filter(v=>l.includes(v.status))),p&&(h=h.filter(v=>v.filePath===p||v.filePath.startsWith(p+"/"))),d&&(h=h.filter(v=>v.title.toLowerCase().includes(d)||v.filePath.toLowerCase().includes(d))),u&&u.length>0&&(h=h.filter(v=>u.some(T=>v.tags.includes(T)))),h=[...h].sort((v,T)=>{let S=0;switch(f){case "duration":S=v.duration-T.duration;break;case "status":S=v.status.localeCompare(T.status);break;case "title":S=v.title.localeCompare(T.title);break;default:S=v.filePath.localeCompare(T.filePath);break}return S*c});let g=h.length,x=Math.max(1,Math.ceil(g/i)),k=(o-1)*i,b=h.slice(k,k+i);w(e,200,{tests:b,pagination:{page:o,pageSize:i,totalItems:g,totalPages:x},filters:{status:l,file:p,search:d,tag:u}});}function St(t,e,r,n){if(!tn.test(n)){w(e,400,{error:"Invalid test ID format"});return}let s=join(r,"tests",`${n}.json`);if(!existsSync(s)){w(e,404,{error:`Test not found: ${n}`});return}try{let a=readFileSync(s,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(a);}catch(a){w(e,500,{error:a instanceof Error?a.message:String(a)});}}function Rt(t,e,r){let n=ne(join(r,"index.json"));if(!n){w(e,404,{error:"Test index not found"});return}let s=new Map;for(let o of n){if(o.isRetry)continue;let i=s.get(o.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.set(o.filePath,i)),i.total++,o.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let a=Array.from(s.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));w(e,200,{files:a});}function At(t,e,r){if(!existsSync(r)){w(e,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Le.test(o.name))continue;let i=join(r,o.name),l=se(i),p=readdirSync(i,{withFileTypes:!0}).filter(d=>d.isDirectory());n.push({folderName:o.name,totalSizeBytes:l,testCount:p.length}),s+=l;}n.sort((o,i)=>i.folderName.localeCompare(o.folderName)),w(e,200,{runs:n,totalSizeBytes:s});}catch(n){w(e,500,{error:n instanceof Error?n.message:String(n)});}}function _t(t,e,r){try{let n=0,s=0;if(existsSync(r)){let a=readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Le.test(o.name))continue;let i=join(r,o.name),l=se(i);rmSync(i,{recursive:!0,force:!0}),s+=l,n++;}}w(e,200,{deletedCount:n,freedBytes:s});}catch(n){w(e,500,{error:n instanceof Error?n.message:String(n)});}}function It(t,e,r,n){if(!Le.test(n)){w(e,400,{error:"Invalid folder name"});return}let s=join(r,n);try{if(!statSync(s).isDirectory()){w(e,404,{error:"Not found"});return}}catch{w(e,404,{error:"Not found"});return}try{let a=se(s);rmSync(s,{recursive:!0,force:!0}),w(e,200,{deleted:n,freedBytes:a});}catch(a){w(e,500,{error:a instanceof Error?a.message:String(a)});}}function Lt(t,e,r){w(e,200,{status:"shutting_down"}),r.close();}function Ne(t,e,r){if(!existsSync(r)){w(e,404,{error:"File not found"});return}try{let n=readFileSync(r),s=extname(r).toLowerCase(),a=nn[s]??"application/octet-stream";e.writeHead(200,{"Content-Type":a}),e.end(n);}catch(n){w(e,500,{error:n instanceof Error?n.message:String(n)});}}var nn={".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 ln=9323,dn=10,cn=1800*1e3;function V(t,e){return new Promise((r,n)=>{let s=e?.port??ln,a=Date.now(),o,i=0,l=existsSync(join(t,"artifacts"))?join(t,"artifacts"):existsSync(join(t,"..","artifacts"))?join(t,"..","artifacts"):join(t,"artifacts");function p(){clearTimeout(o),o=setTimeout(()=>{u.close();},cn);}let d=e?.htmlPath??null;if(!d){let c=dirname(t);try{let h=readdirSync(c).find(g=>g.endsWith(".html"));h&&(d=join(c,h));}catch{}}let u=createServer((c,h)=>{if(p(),xt(h),c.method==="OPTIONS"){h.writeHead(204),h.end();return}let g;try{g=new URL(c.url??"/",`http://${c.headers.host??"localhost"}`).pathname;}catch{w(h,400,{error:"Invalid URL"});return}if(c.method==="GET"&&(g==="/"||g==="/index.html")){if(d&&existsSync(d)){Ne(c,h,d);return}w(h,404,{error:"HTML report not found"});return}if(c.method==="GET"&&g==="/api/health"){kt(c,h,t,a);return}if(c.method==="GET"&&g==="/api/summary"){Tt(c,h,t);return}if(c.method==="GET"&&g==="/api/tests"){Ct(c,h,t);return}if(c.method==="GET"&&g==="/api/files"){Rt(c,h,t);return}let x=g.match(/^\/api\/tests\/([a-f0-9]+)$/);if(c.method==="GET"&&x){St(c,h,t,x[1]);return}if(c.method==="GET"&&g==="/api/artifacts"){At(c,h,l);return}if(c.method==="DELETE"&&g==="/api/artifacts"){_t(c,h,l);return}let k=g.match(/^\/api\/artifacts\/(.+)$/);if(c.method==="DELETE"&&k){It(c,h,l,decodeURIComponent(k[1]));return}if(c.method==="GET"&&g.startsWith("/artifacts/")){let b=decodeURIComponent(g.slice(11));if(b.includes("..")||b.includes("\0")){w(h,400,{error:"Invalid path"});return}Ne(c,h,join(l,b));return}if(c.method==="POST"&&g==="/api/shutdown"){Lt(c,h,u);return}w(h,404,{error:"Not found"});});function f(c){let h=g=>{g.code==="EADDRINUSE"&&i<dn?(i++,f(c+1)):n(g);};u.once("error",h),u.listen(c,"127.0.0.1",()=>{u.removeListener("error",h);let g=u.address();if(!g||typeof g=="string"){n(new Error("Failed to get server address"));return}p(),r({port:g.port,dispose:()=>new Promise(x=>{clearTimeout(o),u.close(()=>x());})});});}f(s);})}async function Nt(t){let e=await V(t);return {port:e.port,dispose:e.dispose}}function mn(t,e,r){let n=JSON.stringify(t),s=r?JSON.stringify(r):null;return vt(n,e,s)}async function Pe(t,e,r){try{let n=null,s=null,a=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,i=e.htmlReportPath,l=dirname(i);if(mkdirSync(l,{recursive:!0}),a){let d=JSON.stringify(t.summary),u=dirname(e.outputPath),f=join(u,".testrelic-report"),c="[]";try{let g=join(f,"index.json");existsSync(g)&&(c=readFileSync(g,"utf-8"));}catch{}let h=r?JSON.stringify(r):null;o=yt(d,c,null,h);}else o=mn(t,null,r);let p=i+".tmp";if(writeFileSync(p,o,"utf-8"),renameSync(p,i),a){if(t.ci===null){let d=dirname(e.outputPath),u=join(d,".testrelic-report"),f=resolve(i);try{if(await yn(),n=await bn(u),!n){s=await V(u,{htmlPath:f}),n=s.port;let c=setInterval(()=>{},6e4),h=()=>{clearInterval(c),s?.dispose();};process.on("SIGINT",h),process.on("SIGTERM",h),setTimeout(h,1800*1e3).unref();}n&&process.stderr.write(`
2279
+ Report server: http://127.0.0.1:${n}
2280
+ `);}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let d=dirname(e.outputPath),u=join(d,"artifacts");if(existsSync(u))try{let f=await Nt(u);n=f.port,process.on("exit",()=>{f.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(a&&n)_e(`http://127.0.0.1:${n}`);else {let d=resolve(i);_e(d);}}catch(n){process.stderr.write(`[testrelic] Failed to write HTML report: ${n instanceof Error?n.message:String(n)}
2281
+ `);}}var ie=9323,Mt=10;async function vn(){for(let t=ie;t<ie+Mt;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),n.ok)return t}catch{}return null}async function yn(){for(let t=ie;t<ie+Mt;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 bn(t){let r=[join(__dirname,"cli.cjs"),join(__dirname,"cli.js"),join(__dirname,"..","dist","cli.cjs"),join(__dirname,"..","dist","cli.js")].find(n=>existsSync(n));if(!r){let n=await V(t);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",o=false,i=setTimeout(()=>{o||(o=true,s.stderr?.removeAllListeners(),vn().then(n));},5e3);s.stderr?.on("data",l=>{a+=l.toString();let p=a.match(/127\.0\.0\.1:(\d+)/);p&&!o&&(o=true,clearTimeout(i),s.stderr?.removeAllListeners(),s.unref(),n(Number(p[1])));}),s.on("error",()=>{o||(o=true,clearTimeout(i),n(null));}),s.on("exit",()=>{o||(o=true,clearTimeout(i),n(null));}),s.unref();})}function Bt(t){let e=new Date,r=a=>String(a).padStart(2,"0"),n=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!existsSync(join(t,n)))return n;let s=1;for(;existsSync(join(t,`${n}-${s}`));)s++;return `${n}-${s}`}function xn(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"}function Ot(t,e,r,n,s){let a=t.find(f=>f.name==="screenshot"&&f.path),o=t.find(f=>f.name==="video"&&f.path);if(!a&&!o)return null;let i=xn(e);r>0&&(i+=`--retry-${r}`);let l=s?["artifacts",s,i]:["artifacts",i],p=join(n,...l),d=l,u={};try{mkdirSync(p,{recursive:!0});}catch{return null}if(a?.path)try{if(existsSync(a.path)){let c=`screenshot${extname(a.path)||".png"}`;copyFileSync(a.path,join(p,c)),u.screenshot=`${d.join("/")}/${c}`;}}catch{}if(o?.path)try{if(existsSync(o.path)){let c=`video${extname(o.path)||".webm"}`;copyFileSync(o.path,join(p,c)),u.video=`${d.join("/")}/${c}`;}}catch{}return !u.screenshot&&!u.video?null:u}var Cn=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Sn="1.0";function Rn(t){let e=extname(t).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(e)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(e)?"video":"other"}function qt(t,e,r){let n=[];try{let s=readdirSync(t,{withFileTypes:!0});for(let a of s){if(!a.isFile())continue;let o=join(t,a.name),i=statSync(o);n.push({name:a.name,type:Rn(a.name),relativePath:`artifacts/${e}/${r}/${a.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:n}}function An(t,e){let r=join(t,e),n=[],s=0;try{let o=readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=qt(join(r,i.name),e,i.name);n.push(l);for(let p of l.files)s+=p.sizeBytes;}}catch{}let a=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return n.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function Ft(t,e){let r=join(t,"artifacts"),n=[],s=[],a=0;try{let i=readdirSync(r,{withFileTypes:!0});for(let l of i)if(l.isDirectory())if(Cn.test(l.name)){let p=An(r,l.name);n.push({...p,isCurrentRun:l.name===e});}else {let p=qt(join(r,l.name),l.name,l.name);s.push(p);for(let d of p.files)a+=d.sizeBytes;}}catch{}n.sort((i,l)=>l.timestamp.localeCompare(i.timestamp)),s.length>0&&(s.sort((i,l)=>i.testName.localeCompare(l.testName)),n.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:a,testCount:s.length,tests:s,isCurrentRun:false}));let o=n.reduce((i,l)=>i+l.totalSizeBytes,0);return {schemaVersion:Sn,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:n,serverPort:null}}function En(t){let e=t,{root:r}=parse(e);for(;e!==r;){if(existsSync(join(e,".git")))return e;e=join(e,"..");}return null}function Ut(t){try{let e=En(t);if(!e)return;let r=join(e,".gitignore"),n=relative(e,t).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
2282
+ `).map(l=>l.trim()).some(l=>l===s||l===n))return;let a=`
2094
2283
  # TestRelic test artifacts
2095
2284
  ${s}
2096
- `;appendFileSync(r,a,"utf-8");}catch{}}function pe(e,t){let r=[];for(let n of e){let s=jr(n),a=$r(n),l=Gr(n,s,a,t),i=Vr(n,s,a);if(l.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:n.startedAt,durationOnUrl:n.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:n.specFile,test:s,tests:[a],_testTitle:n.title});continue}r.push(...l,...i);}return r.sort(Jr),Kr(r,e),r.map((n,s)=>n.type==="navigation"?{...{index:s,type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:n.durationOnUrl??0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:n.specFile,test:n.test},tests:n.tests}:{...{index:s,type:"api_call",callId:n.callId,method:n.method,url:n.url,timestamp:n.timestamp,responseTime:n.responseTime??null,request:n.request,response:n.response??null,...n.error?{error:n.error}:{},assertions:n.assertions??[],specFile:n.specFile,test:n.test},tests:n.tests})}function jr(e){return {title:e.title,fullTitle:e.titlePath,status:e.status,duration:e.duration,retries:e.retryCount,retry:e.retry,tags:e.tags,failure:e.failure}}function $r(e){return {title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:e.networkRequests,apiCalls:e.apiCalls,apiAssertions:e.apiAssertions,actions:e.actions,consoleLogs:e.consoleLogs}}function Gr(e,t,r,n){let s=[];for(let a of e.navigations)n.navigationTypes!==null&&!n.navigationTypes.includes(a.navigationType)||s.push({type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title});return s}function Vr(e,t,r){if(!e.apiCalls||e.apiCalls.length===0)return [];let n=e.apiAssertions??[];return e.apiCalls.map(s=>{let a=n.filter(i=>i.callId===s.id).map(i=>({type:i.type,expected:i.expected,actual:i.actual,status:i.status,location:i.location,...i.expression!==void 0?{expression:i.expression}:{}})),l=null;return s.responseStatusCode!==null&&s.responseStatusText!==null&&(l={statusCode:s.responseStatusCode,statusText:s.responseStatusText,headers:s.responseHeaders,body:ce(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:ce(s.requestBody)},response:l,...s.error?{error:s.error}:{},assertions:a,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title}})}function Jr(e,t){let r=new Date(e.timestamp).getTime(),n=new Date(t.timestamp).getTime();if(r!==n)return r-n;let s={navigation:0,api_call:1},a=s[e.type],l=s[t.type];return a!==l?a-l:e.type==="api_call"&&t.type==="api_call"&&e.callId&&t.callId?de(e.callId)-de(t.callId):0}function de(e){let t=e.match(/(\d+)$/);return t?parseInt(t[1],10):0}function Kr(e,t){for(let r=0;r<e.length;r++){let n=e[r];if(n.type!=="navigation")continue;let s=new Date(n.timestamp).getTime(),a=null;for(let l=r+1;l<e.length;l++)if(e[l]._testTitle===n._testTitle){a=new Date(e[l].timestamp).getTime();break}if(a!==null)n.durationOnUrl=Math.max(0,a-s);else {let l=t.find(i=>i.title===n._testTitle);if(l){let i=new Date(l.completedAt).getTime();n.durationOnUrl=Math.max(0,i-s);}}}}function ce(e){if(e==null)return null;try{return JSON.parse(e)}catch{return e}}function ot(e,t){let r=e.length,n=Math.min(Math.ceil(t/100*r)-1,r-1);return e[Math.max(0,n)]}function Wr(e){try{let t=new URL(e);return t.origin+t.pathname}catch{return e}}function Yr(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 ue(e,t){let r=0,n=0,s=0,a=0,l=0;for(let m of e)switch(m.status){case "passed":r++;break;case "failed":n++;break;case "flaky":s++;break;case "skipped":a++;break;case "timedout":l++;break}let i=[];for(let m of e)m.apiCalls&&i.push(...m.apiCalls);let o=i.length,c=new Set,d={},p={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},f=[];for(let m of i)c.add(Wr(m.url)),d[m.method]=(d[m.method]??0)+1,p[Yr(m.responseStatusCode)]+=1,f.push(m.responseTimeMs);let u=null;if(f.length>0){let m=[...f].sort((B,M)=>B-M),k=m.reduce((B,M)=>B+M,0);u={avg:Math.round(k/m.length),min:m[0],max:m[m.length-1],p50:ot(m,50),p95:ot(m,95),p99:ot(m,99)};}let h=0,g=0,v=0;for(let m of e)if(m.apiAssertions)for(let k of m.apiAssertions)h++,k.status==="passed"?g++:v++;let y=0,b=new Set;for(let m of e){y+=m.navigations.length;for(let k of m.navigations)b.add(k.url);}let x=0,w={};function A(m){for(let k of m)x++,w[k.category]=(w[k.category]??0)+1,k.children.length>0&&A(k.children);}for(let m of e)m.actions&&A(m.actions);return {total:e.length,passed:r,failed:n,flaky:s,skipped:a,timedout:l,totalApiCalls:o,uniqueApiUrls:c.size,apiCallsByMethod:d,apiCallsByStatusRange:p,apiResponseTime:u,totalAssertions:h,passedAssertions:g,failedAssertions:v,totalNavigations:y,uniqueNavigationUrls:b.size,totalTimelineSteps:t,totalActionSteps:x,actionStepsByCategory:w}}function Zr(e){let t=56-e.length;return t>0?e+" ".repeat(t):e}function C(e){return `\u2502 ${Zr(e)} \u2502
2097
- `}function fe(e,t,r,n){if(n||e.total===0)return;let s=`\u250C${"\u2500".repeat(58)}\u2510
2285
+ `;appendFileSync(r,a,"utf-8");}catch{}}function jt(t,e){let r=[];for(let n of t){let s=Mn(n),a=Pn(n),o=Dn(n,s,a,e),i=Bn(n,s,a);if(o.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:n.startedAt,durationOnUrl:n.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:n.specFile,test:s,tests:[a],_testTitle:n.title});continue}r.push(...o,...i);}return r.sort(On),qn(r,t),r.map((n,s)=>n.type==="navigation"?{...{index:s,type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:n.durationOnUrl??0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:n.specFile,test:n.test},tests:n.tests}:{...{index:s,type:"api_call",callId:n.callId,method:n.method,url:n.url,timestamp:n.timestamp,responseTime:n.responseTime??null,request:n.request,response:n.response??null,...n.error?{error:n.error}:{},assertions:n.assertions??[],specFile:n.specFile,test:n.test},tests:n.tests})}function Mn(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 Pn(t){return {title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,networkRequests:t.networkRequests,apiCalls:t.apiCalls,apiAssertions:t.apiAssertions,actions:t.actions,consoleLogs:t.consoleLogs}}function Dn(t,e,r,n){let s=[];for(let a of t.navigations)n.navigationTypes!==null&&!n.navigationTypes.includes(a.navigationType)||s.push({type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title});return s}function Bn(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let n=t.apiAssertions??[];return t.apiCalls.map(s=>{let a=n.filter(i=>i.callId===s.id).map(i=>({type:i.type,expected:i.expected,actual:i.actual,status:i.status,location:i.location,...i.expression!==void 0?{expression:i.expression}:{}})),o=null;return s.responseStatusCode!==null&&s.responseStatusText!==null&&(o={statusCode:s.responseStatusCode,statusText:s.responseStatusText,headers:s.responseHeaders,body:zt(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:zt(s.requestBody)},response:o,...s.error?{error:s.error}:{},assertions:a,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function On(t,e){let r=new Date(t.timestamp).getTime(),n=new Date(e.timestamp).getTime();if(r!==n)return r-n;let s={navigation:0,api_call:1},a=s[t.type],o=s[e.type];return a!==o?a-o:t.type==="api_call"&&e.type==="api_call"&&t.callId&&e.callId?$t(t.callId)-$t(e.callId):0}function $t(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function qn(t,e){for(let r=0;r<t.length;r++){let n=t[r];if(n.type!=="navigation")continue;let s=new Date(n.timestamp).getTime(),a=null;for(let o=r+1;o<t.length;o++)if(t[o]._testTitle===n._testTitle){a=new Date(t[o].timestamp).getTime();break}if(a!==null)n.durationOnUrl=Math.max(0,a-s);else {let o=e.find(i=>i.title===n._testTitle);if(o){let i=new Date(o.completedAt).getTime();n.durationOnUrl=Math.max(0,i-s);}}}}function zt(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function Oe(t,e){let r=t.length,n=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,n)]}function Fn(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function Hn(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 qe(t,e){let r=0,n=0,s=0,a=0,o=0;for(let m of t)switch(m.status){case "passed":r++;break;case "failed":n++;break;case "flaky":s++;break;case "skipped":a++;break;case "timedout":o++;break}let i=[];for(let m of t)m.apiCalls&&i.push(...m.apiCalls);let l=i.length,p=new Set,d={},u={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},f=[];for(let m of i)p.add(Fn(m.url)),d[m.method]=(d[m.method]??0)+1,u[Hn(m.responseStatusCode)]+=1,f.push(m.responseTimeMs);let c=null;if(f.length>0){let m=[...f].sort((_,H)=>_-H),y=m.reduce((_,H)=>_+H,0);c={avg:Math.round(y/m.length),min:m[0],max:m[m.length-1],p50:Oe(m,50),p95:Oe(m,95),p99:Oe(m,99)};}let h=0,g=0,x=0;for(let m of t)if(m.apiAssertions)for(let y of m.apiAssertions)h++,y.status==="passed"?g++:x++;let k=0,b=new Set;for(let m of t){k+=m.navigations.length;for(let y of m.navigations)b.add(y.url);}let v=0,T={};function S(m){for(let y of m)v++,T[y.category]=(T[y.category]??0)+1,y.children.length>0&&S(y.children);}for(let m of t)m.actions&&S(m.actions);return {total:t.length,passed:r,failed:n,flaky:s,skipped:a,timedout:o,totalApiCalls:l,uniqueApiUrls:p.size,apiCallsByMethod:d,apiCallsByStatusRange:u,apiResponseTime:c,totalAssertions:h,passedAssertions:g,failedAssertions:x,totalNavigations:k,uniqueNavigationUrls:b.size,totalTimelineSteps:e,totalActionSteps:v,actionStepsByCategory:T}}function Un(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function A(t){return `\u2502 ${Un(t)} \u2502
2286
+ `}function Fe(t,e,r,n){if(n||t.total===0)return;let s=`\u250C${"\u2500".repeat(58)}\u2510
2098
2287
  `,a=`\u2514${"\u2500".repeat(58)}\u2518
2099
- `,l=C(""),i=s;i+=C("TestRelic AI - Playwright Test Report"),i+=l;let o=[];if(e.passed>0&&o.push(`${e.passed} \u2713`),e.failed>0&&o.push(`${e.failed} \u2717`),e.flaky>0&&o.push(`${e.flaky} \u26A0`),e.skipped>0&&o.push(`${e.skipped} skipped`),e.timedout>0&&o.push(`${e.timedout} timedout`),i+=C(`Tests: ${e.total} total (${o.join(" ")})`),e.totalNavigations>0&&(i+=C(`Navigations: ${e.totalNavigations} visits across ${e.uniqueNavigationUrls} unique URLs`)),e.totalApiCalls>0){i+=C(`API Calls: ${e.totalApiCalls} calls across ${e.uniqueApiUrls} unique endpoints`);let c=Object.entries(e.apiCallsByMethod).filter(([,p])=>p>0).map(([p,f])=>`${p}: ${f}`);c.length>0&&(i+=C(` ${c.join(" ")}`));let d=Object.entries(e.apiCallsByStatusRange).filter(([,p])=>p>0).map(([p,f])=>`${p}: ${f}`);d.length>0&&(i+=C(` ${d.join(" ")}`)),e.apiResponseTime&&(i+=C(` Avg response: ${e.apiResponseTime.avg}ms P95: ${e.apiResponseTime.p95}ms`));}if(e.totalAssertions>0&&(i+=C(`Assertions: ${e.totalAssertions} total (${e.passedAssertions} \u2713 ${e.failedAssertions} \u2717)`)),e.totalActionSteps>0){let c=[],d=e.actionStepsByCategory;d.ui_action&&c.push(`${d.ui_action} UI`),d.assertion&&c.push(`${d.assertion} assertions`),d.custom_step&&c.push(`${d.custom_step} custom`);let p=c.length>0?` (${c.join(" ")})`:"";i+=C(`Actions: ${e.totalActionSteps} steps${p}`);}i+=C(`Report: ${r}`),i+=C(`Data: ${t}`),i+=a,i+=`For more information visit us at https://docs.testrelic.ai
2100
- `,process.stderr.write(i);}var Qr=new Set(["pw:api","expect","test.step"]);function Xr(e){return e==="expect"?"assertion":e==="test.step"?"custom_step":"ui_action"}function lt(e,t,r){if(Qr.has(e.category)){let n=[];for(let a of e.steps)lt(a,t,n);let s=e.startTime.getTime()-t.getTime();r.push({title:e.title,category:Xr(e.category),timestamp:e.startTime.toISOString(),duration:e.duration,videoOffset:s>=0?s/1e3:null,status:e.error?"failed":"passed",error:e.error?.message??null,children:n});}else for(let n of e.steps)lt(n,t,r);}function ge(e,t){let r=[];for(let n of e)lt(n,t,r);return r}var rn=new Set(["localhost","127.0.0.1","0.0.0.0"]);function me(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&rn.has(t.hostname)))throw createError(ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${t.protocol}//${t.hostname}`)}var nn=3e3;async function dt(e){let t=new AbortController,r=setTimeout(()=>t.abort(),nn);try{return (await fetch(`${e}/health`,{method:"GET",signal:t.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function ve(e){return new Promise(t=>setTimeout(t,e))}async function he(e){try{let r=(await e.json()).error;if(r&&typeof r.message=="string"){let n=r.details;if(Array.isArray(n)&&n.length>0){let s=n.map(a=>`${a.field}: ${a.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${e.status}`}async function ct(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:n.signal});if(a.ok){let i=await a.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(a.status===429){let i=a.headers.get("Retry-After"),o=i?parseInt(i,10)*1e3:5e3;if(!isNaN(o)&&o>0){await ve(o);let c=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:n.signal});if(c.ok){let d=await c.json();return {accessToken:d.accessToken,refreshToken:d.refreshToken,expiresIn:d.expiresIn,orgId:d.orgId,orgName:d.orgName,userId:d.userId,userName:d.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return a.status===400?{code:"validation_error",message:await he(a),statusCode:400}:a.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:a.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await he(a),statusCode:a.status}}catch(a){return a instanceof DOMException&&a.name==="AbortError"?{code:"timeout",message:"Token exchange timed out.",statusCode:null}:{code:"network_error",message:"Failed to reach cloud for token exchange.",statusCode:null}}finally{clearTimeout(s);}}function pt(e){return "code"in e&&typeof e.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(e.code)}async function ye(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:n.signal});if(a.status===429){let i=a.headers.get("Retry-After"),o=i?parseInt(i,10)*1e3:5e3;!isNaN(o)&&o>0&&(await ve(o),a=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:n.signal}));}if(!a.ok)return null;let l=await a.json();return {accessToken:l.accessToken,refreshToken:l.refreshToken,expiresIn:l.expiresIn}}catch{return null}finally{clearTimeout(s);}}async function be(e,t,r,n,s,a){let l=new AbortController,i=setTimeout(()=>l.abort(),s);try{let o={gitId:r,displayName:n};a&&(o.branch=a);let c=await fetch(`${e}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(o),signal:l.signal});if(!c.ok)return null;let d=await c.json();return {repoId:d.repoId,displayName:d.displayName}}catch{return null}finally{clearTimeout(i);}}var dn=5e3;function I(e,t){try{return execSync(e,{cwd:t,timeout:dn,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function xe(e){let t=I("git rev-parse --abbrev-ref HEAD",e),r=I("git rev-parse --short HEAD",e),n=I("git log -1 --pretty=%s",e),s=cn(e),a=s?F(s):null;return {branch:t,commitSha:r,commitMessage:n,remoteUrl:a}}function cn(e){let t=I("git remote get-url origin",e);if(t)return t;let r=I("git remote",e);if(!r)return null;let n=r.split(`
2101
- `)[0]?.trim();return n?I(`git remote get-url ${n}`,e):null}function F(e){let t=e.trim();return t=t.replace(/^[a-z+]+:\/\//,""),t=t.replace(/^[^@]+@/,""),t=t.replace(/:(?!\d)/,"/"),t=t.replace(/\.git$/,""),t=t.replace(/\/+$/,""),t=t.replace(/^[^@/]+@/,""),t.toLowerCase()}function we(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function ut(e){try{let t=readFileSync(join(e,"package.json"),"utf-8"),r=JSON.parse(t);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function H(e){let t=ut(e);return t||`local/${basename(e)}`}var mn="1.0.0",ke=10;function gt(e,t,r,n,s,a,l,i){try{mkdirSync(e,{recursive:!0});let o=Date.now(),c=`${o}-${t}-${r}.json`,d=join(e,c),p={version:mn,queuedAt:new Date(o).toISOString(),reason:n,retryCount:0,targetEndpoint:s,method:a,payload:l,headers:i},f=d+".tmp";writeFileSync(f,JSON.stringify(p,null,2),"utf-8"),renameSync(f,d);}catch(o){o.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
2288
+ `,o=A(""),i=s;i+=A("TestRelic AI - Playwright Test Report"),i+=o;let l=[];if(t.passed>0&&l.push(`${t.passed} \u2713`),t.failed>0&&l.push(`${t.failed} \u2717`),t.flaky>0&&l.push(`${t.flaky} \u26A0`),t.skipped>0&&l.push(`${t.skipped} skipped`),t.timedout>0&&l.push(`${t.timedout} timedout`),i+=A(`Tests: ${t.total} total (${l.join(" ")})`),t.totalNavigations>0&&(i+=A(`Navigations: ${t.totalNavigations} visits across ${t.uniqueNavigationUrls} unique URLs`)),t.totalApiCalls>0){i+=A(`API Calls: ${t.totalApiCalls} calls across ${t.uniqueApiUrls} unique endpoints`);let p=Object.entries(t.apiCallsByMethod).filter(([,u])=>u>0).map(([u,f])=>`${u}: ${f}`);p.length>0&&(i+=A(` ${p.join(" ")}`));let d=Object.entries(t.apiCallsByStatusRange).filter(([,u])=>u>0).map(([u,f])=>`${u}: ${f}`);d.length>0&&(i+=A(` ${d.join(" ")}`)),t.apiResponseTime&&(i+=A(` Avg response: ${t.apiResponseTime.avg}ms P95: ${t.apiResponseTime.p95}ms`));}if(t.totalAssertions>0&&(i+=A(`Assertions: ${t.totalAssertions} total (${t.passedAssertions} \u2713 ${t.failedAssertions} \u2717)`)),t.totalActionSteps>0){let p=[],d=t.actionStepsByCategory;d.ui_action&&p.push(`${d.ui_action} UI`),d.assertion&&p.push(`${d.assertion} assertions`),d.custom_step&&p.push(`${d.custom_step} custom`);let u=p.length>0?` (${p.join(" ")})`:"";i+=A(`Actions: ${t.totalActionSteps} steps${u}`);}i+=A(`Report: ${r}`),i+=A(`Data: ${e}`),i+=a,i+=`For more information visit us at https://docs.testrelic.ai
2289
+ `,process.stderr.write(i);}var $n=new Set(["pw:api","expect","test.step"]);function zn(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function He(t,e,r){if($n.has(t.category)){let n=[];for(let a of t.steps)He(a,e,n);let s=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:zn(t.category),timestamp:t.startTime.toISOString(),duration:t.duration,videoOffset:s>=0?s/1e3:null,status:t.error?"failed":"passed",error:t.error?.message??null,children:n});}else for(let n of t.steps)He(n,e,r);}function Vt(t,e){let r=[];for(let n of t)He(n,e,r);return r}var Gn=new Set(["localhost","127.0.0.1","0.0.0.0"]);function Jt(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Gn.has(e.hostname)))throw createError(ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var Jn=3e3;async function Ue(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Jn);try{return (await fetch(`${t}/health`,{method:"GET",signal:e.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function Wt(t){return new Promise(e=>setTimeout(e,t))}async function Gt(t){try{let r=(await t.json()).error;if(r&&typeof r.message=="string"){let n=r.details;if(Array.isArray(n)&&n.length>0){let s=n.map(a=>`${a.field}: ${a.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${t.status}`}async function $e(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.signal});if(a.ok){let i=await a.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(a.status===429){let i=a.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;if(!isNaN(l)&&l>0){await Wt(l);let p=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.signal});if(p.ok){let d=await p.json();return {accessToken:d.accessToken,refreshToken:d.refreshToken,expiresIn:d.expiresIn,orgId:d.orgId,orgName:d.orgName,userId:d.userId,userName:d.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return a.status===400?{code:"validation_error",message:await Gt(a),statusCode:400}:a.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:a.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await Gt(a),statusCode:a.status}}catch(a){return a instanceof DOMException&&a.name==="AbortError"?{code:"timeout",message:"Token exchange timed out.",statusCode:null}:{code:"network_error",message:"Failed to reach cloud for token exchange.",statusCode:null}}finally{clearTimeout(s);}}function ze(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 Kt(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.signal});if(a.status===429){let i=a.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;!isNaN(l)&&l>0&&(await Wt(l),a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.signal}));}if(!a.ok)return null;let o=await a.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn}}catch{return null}finally{clearTimeout(s);}}async function Yt(t,e,r,n,s,a){let o=new AbortController,i=setTimeout(()=>o.abort(),s);try{let l={gitId:r,displayName:n};a&&(l.branch=a);let p=await fetch(`${t}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(l),signal:o.signal});if(!p.ok)return null;let d=await p.json();return {repoId:d.repoId,displayName:d.displayName}}catch{return null}finally{clearTimeout(i);}}var Qn=5e3;function B(t,e){try{return execSync(t,{cwd:e,timeout:Qn,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Zt(t){let e=B("git rev-parse --abbrev-ref HEAD",t),r=B("git rev-parse --short HEAD",t),n=B("git log -1 --pretty=%s",t),s=Xn(t),a=s?W(s):null;return {branch:e,commitSha:r,commitMessage:n,remoteUrl:a}}function Xn(t){let e=B("git remote get-url origin",t);if(e)return e;let r=B("git remote",t);if(!r)return null;let n=r.split(`
2290
+ `)[0]?.trim();return n?B(`git remote get-url ${n}`,t):null}function W(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 Qt(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??t}function je(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 K(t){let e=je(t);return e||`local/${basename(t)}`}var as="1.0.0",Xt=10;function Ge(t,e,r,n,s,a,o,i){try{mkdirSync(t,{recursive:!0});let l=Date.now(),p=`${l}-${e}-${r}.json`,d=join(t,p),u={version:as,queuedAt:new Date(l).toISOString(),reason:n,retryCount:0,targetEndpoint:s,method:a,payload:o,headers:i},f=d+".tmp";writeFileSync(f,JSON.stringify(u,null,2),"utf-8"),renameSync(f,d);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
2102
2291
  `):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
2103
- `);}}async function Re(e,t,r){let n;try{n=readdirSync(e).filter(a=>a.endsWith(".json")&&!a.endsWith(".tmp")).sort();}catch{return}if(n.length===0)return;let s=[];for(let a=0;a<n.length;a+=ke)s.push(n.slice(a,a+ke));for(let a of s)for(let l of a){let i=join(e,l);try{if(!statSync(i).isFile())continue;let c=readFileSync(i,"utf-8"),d=JSON.parse(c);if(!isValidQueueEntry(d)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${l}
2104
- `),unlinkSync(i);continue}let p=d;if((await fetch(p.targetEndpoint,{method:p.method,headers:{...p.headers,Authorization:`Bearer ${r}`},body:JSON.stringify(p.payload)})).ok)unlinkSync(i);else return}catch{return}}}function Se(e,t){try{let r=readdirSync(e).filter(s=>s.endsWith(".json")&&!s.endsWith(".tmp")),n=Date.now();for(let s of r){let a=join(e,s);try{let l=readFileSync(a,"utf-8"),o=JSON.parse(l).queuedAt;if(typeof o=="string"){let c=new Date(o).getTime();n-c>t&&unlinkSync(a);}}catch{try{unlinkSync(a);}catch{}}}}catch{}}var Tn=3e5,Cn=864e5,Rn=6e4,Ae=3e4,mt="https://app.testrelic.com/settings/api-keys",V=class{constructor(t){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=t,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
2105
- `);return}try{if(me(this.config.endpoint),this.gitMetadata=xe(),!await dt(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.
2106
- `);return}let r=await ct(this.config.endpoint,this.config.apiKey,this.config.timeout);if(pt(r)){this.handleAuthError(r.code,r.statusCode);return}let n=r;this.authState={mode:"cloud",accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:Date.now()+n.expiresIn*1e3,orgId:n.orgId,orgName:n.orgName,userId:n.userId,userName:n.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${n.orgName} / ${n.userName})
2107
- `),await this.resolveRepoId(),this.config.queueDirectory&&(Se(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch{this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode.
2108
- `);}}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://api.testrelic.com/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let t=this.authState.expiresAt??0;if(Date.now()+Tn<t)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await ye(this.config.endpoint,this.authState.refreshToken,this.config.timeout);return r?(this.authState.accessToken=r.accessToken,this.authState.refreshToken=r.refreshToken,this.authState.expiresAt=Date.now()+r.expiresIn*1e3,!0):(this.switchToLocalMode("token_refresh_failed"),!1)}catch{return this.switchToLocalMode("token_refresh_error"),false}}switchToLocalMode(t){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=t,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${t}).
2109
- `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(t=>setTimeout(t,Ae))]);}catch{}this.flushPromise=null;}this.authState={mode:"local",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null},this.repoId=null,this.gitMetadata=null;}setLocalMode(t){this.authState.mode="local",this.failureReason=t;}handleAuthError(t,r){switch(t){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
2110
- \u2192 Manage keys: ${mt}
2292
+ `);}}async function rr(t,e,r){let n;try{n=readdirSync(t).filter(a=>a.endsWith(".json")&&!a.endsWith(".tmp")).sort();}catch{return}if(n.length===0)return;let s=[];for(let a=0;a<n.length;a+=Xt)s.push(n.slice(a,a+Xt));for(let a of s)for(let o of a){let i=join(t,o);try{if(!statSync(i).isFile())continue;let p=readFileSync(i,"utf-8"),d=JSON.parse(p);if(!isValidQueueEntry(d)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
2293
+ `),unlinkSync(i);continue}let u=d;if((await fetch(u.targetEndpoint,{method:u.method,headers:{...u.headers,Authorization:`Bearer ${r}`},body:JSON.stringify(u.payload)})).ok)unlinkSync(i);else return}catch{return}}}function nr(t,e){try{let r=readdirSync(t).filter(s=>s.endsWith(".json")&&!s.endsWith(".tmp")),n=Date.now();for(let s of r){let a=join(t,s);try{let o=readFileSync(a,"utf-8"),l=JSON.parse(o).queuedAt;if(typeof l=="string"){let p=new Date(l).getTime();n-p>e&&unlinkSync(a);}}catch{try{unlinkSync(a);}catch{}}}}catch{}}var us=3e5,fs=864e5,gs=6e4,sr=3e4,We="https://app.testrelic.com/settings/api-keys",de=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.
2294
+ `);return}try{if(Jt(this.config.endpoint),this.gitMetadata=Zt(),!await Ue(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.
2295
+ `);return}let r=await $e(this.config.endpoint,this.config.apiKey,this.config.timeout);if(ze(r)){this.handleAuthError(r.code,r.statusCode);return}let n=r;this.authState={mode:"cloud",accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:Date.now()+n.expiresIn*1e3,orgId:n.orgId,orgName:n.orgName,userId:n.userId,userName:n.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${n.orgName} / ${n.userName})
2296
+ `),await this.resolveRepoId(),this.config.queueDirectory&&(nr(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch{this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode.
2297
+ `);}}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://api.testrelic.com/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let e=this.authState.expiresAt??0;if(Date.now()+us<e)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Kt(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}).
2298
+ `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(e=>setTimeout(e,sr))]);}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.
2299
+ \u2192 Manage keys: ${We}
2111
2300
  `);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
2112
- \u2192 Generate a new key: ${mt}
2301
+ \u2192 Generate a new key: ${We}
2113
2302
  `);break;case "validation_error":this.setLocalMode("validation_error"),process.stderr.write(`\u26A0 TestRelic: API key format invalid. Running in local mode.
2114
- \u2192 Manage keys: ${mt}
2303
+ \u2192 Manage keys: ${We}
2115
2304
  `);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
2116
2305
  `);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
2117
2306
  `);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
2118
- `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let t=this.gitMetadata?.remoteUrl?F(this.gitMetadata.remoteUrl):null,r=t?we(t):this.config.projectName??H(process.cwd()),n=t??this.config.projectName??H(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await be(this.config.endpoint,this.authState.accessToken,n,r,this.config.timeout,this.gitMetadata?.branch);a&&(this.repoId=a.repoId,this.writeRepoCache(n,a.repoId,a.displayName));}catch{}!t&&!this.config.projectName&&!ut(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2119
- `);}readRepoCache(t){if(!this.config)return null;let r=join(this.config.queueDirectory,"..","cache","repo.json");try{if(!existsSync(r))return null;let n=readFileSync(r,"utf-8"),s=JSON.parse(n);if(s.gitId!==t||Date.now()-s.resolvedAt>Cn)return null;let a=this.hashApiKey();return a&&s.apiKeyHash!==a?null:s}catch{return null}}writeRepoCache(t,r,n){if(!this.config)return;let s=join(this.config.queueDirectory,"..","cache"),a=join(s,"repo.json");try{mkdirSync(s,{recursive:!0});let l={repoId:r,gitId:t,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=a+".tmp";writeFileSync(i,JSON.stringify(l,null,2),"utf-8"),renameSync(i,a);}catch{}}hashApiKey(){return this.config?.apiKey?createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let t=this.authState.accessToken,r=this.config.queueDirectory,n=this.config.endpoint;this.flushPromise=Promise.race([Re(r,n,t),new Promise(s=>setTimeout(s,Ae))]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let t=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await dt(t))return;if(this.config?.apiKey){let n=await ct(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!pt(n)){let s=n;this.authState={mode:"cloud",accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:Date.now()+s.expiresIn*1e3,orgId:s.orgId,orgName:s.orgName,userId:s.userId,userName:s.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
2120
- `),this.startBackgroundFlush();}}}catch{}},Rn);}};var An=1048576,J=[1e3,3e3,9e3],K=3;function vt(e,t,r,n){return {runId:e.testRunId,repoGitId:t,startedAt:e.startedAt,summary:e.summary,timeline:e.timeline,...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...e.completedAt?{finishedAt:e.completedAt}:{},...e.totalDuration?{duration:e.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{}}}async function W(e){return new Promise(t=>setTimeout(t,e))}function _n(e){let t={};for(let[r,n]of Object.entries(e))n!=null&&(t[r]=n);return t}async function In(e,t,r){for(let n=0;n<K;n++)try{let s=await fetch(e,t);if(s.ok)return s;if(s.status===401&&r&&n===0){let a=await r();if(a){let l={...t,headers:{...t.headers,Authorization:`Bearer ${a}`}},i=await fetch(e,l);if(i.ok)return i}return null}if(s.status===429&&n<K-1){let a=s.headers.get("Retry-After"),l=a?parseInt(a,10)*1e3:J[n];!isNaN(l)&&l>0?await W(l):await W(J[n]);continue}if(s.status>=500&&n<K-1){await W(J[n]);continue}return s}catch{if(n<K-1){await W(J[n]);continue}return null}return null}function Nn(e){let t=JSON.stringify(e),r={"Content-Type":"application/json"};if(Buffer.byteLength(t,"utf-8")>An){let n=gzipSync(Buffer.from(t,"utf-8"));return r["Content-Encoding"]="gzip",{body:n,headers:r}}return {body:t,headers:r}}async function _e(e,t,r,n){let s=`${e}/runs`,{body:a,headers:l}=Nn(r);l.Authorization=`Bearer ${t}`;let i=await In(s,{method:"POST",headers:l,body:a},n);return i?.ok?{success:true,statusCode:i.status,error:null}:i?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:i?`Upload failed with status ${i.status}`:"Upload failed after retries",statusCode:i?.status??null,payload:r,targetEndpoint:s,method:"POST"}}async function Ie(e,t,r){let n=`${e}/runs/init`;try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(_n(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function Ne(e,t,r,n){let s=`${e}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)}).catch(()=>{});}async function Le(e,t,r,n){let s=`${e}/runs/${r}/finalize`;try{return (await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)})).ok}catch{return false}}function Ee(e,t,r,n){let s=[],a=null,l=null,i=null,o=null,c=e.filter(f=>f.name===ATTACHMENT_NAME&&f.body),d=false;if(c.length>0)for(let f of c)try{let u=JSON.parse(f.body.toString());if(isTestRelicDataPayload(u)){s=s.concat(u.navigations),u.networkRequests.length>0&&(a=(a??[]).concat(u.networkRequests)),u.apiCalls.length>0&&(l=(l??[]).concat(u.apiCalls)),u.apiAssertions.length>0&&(i=(i??[]).concat(u.apiAssertions));let h=u.consoleLogs;Array.isArray(h)&&h.length>0&&(o=(o??[]).concat(h)),d=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}", falling back to annotations
2121
- `);}if(!d){s=t.filter(g=>g.type==="lambdatest-navigation"&&g.description).map(g=>{try{return JSON.parse(g.description)}catch{return null}}).filter(g=>g!==null);let f=t.find(g=>g.type==="__testrelic_network_requests"&&g.description);if(f)try{a=JSON.parse(f.description);}catch{}let u=t.find(g=>g.type==="__testrelic_api_calls"&&g.description);if(u)try{l=JSON.parse(u.description);}catch{}let h=t.find(g=>g.type==="__testrelic_api_assertions"&&g.description);if(h)try{i=JSON.parse(h.description);}catch{}}return s.length===0&&!a&&!l&&!i&&!o&&!n&&process.stderr.write(`[testrelic] Warning: No data found for test "${r}". Make sure your tests import { test, expect } from '@testrelic/playwright-analytics/fixture' instead of '@playwright/test'. Without the TestRelic fixture, network logs, video sync, and timeline data cannot be captured.
2122
- `),{navigations:s,networkRequests:a,apiCalls:l,apiAssertions:i,consoleLogs:o}}function yt(e){let r=e.getGitMetadata()?.remoteUrl;return r?F(r):e.getConfig()?.projectName??H(process.cwd())}async function Be(e,t,r,n){if(!e.isCloudMode()||t!=="realtime"&&t!=="both"||!await e.ensureValidToken())return null;let a=e.getGitMetadata(),l=_();return (await Ie(e.getEndpoint(),e.getAccessToken(),{runId:r,repoGitId:yt(e),branch:a?.branch??null,commit:a?.commitSha??null,startedAt:n,totalTests:null,ciProvider:l?.provider??null,ciRunUrl:l?.runUrl??null}))?.runId??null}async function Me(e,t,r,n,s,a,l,i,o){try{if(e.isCloudMode()&&s&&(r==="realtime"||r==="both")&&await e.ensureValidToken()&&await Le(e.getEndpoint(),e.getAccessToken(),s,{finishedAt:l,duration:i,summary:o}),e.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await e.ensureValidToken()){let d=e.getGitMetadata(),p=_(),f=yt(e),u=vt(a,f,d,p),h=await _e(e.getEndpoint(),e.getAccessToken(),u,async()=>await e.ensureValidToken()?e.getAccessToken():null);if(!h.success){let g=h,v=t?.queueDirectory??".testrelic/queue";gt(v,n,"batch",g.reason,g.targetEndpoint,g.method,g.payload,{"Content-Type":"application/json"});}}else {let d=t?.queueDirectory??".testrelic/queue",p=e.getGitMetadata(),f=_(),u=yt(e),h=vt(a,u,p,f);gt(d,n,"batch",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs`,"POST",h,{"Content-Type":"application/json"});}await e.dispose();}catch{try{await e.dispose();}catch{}}}function xt(e){switch(e){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function Dn(e,t,r){let n=`${e}::${t}::${r}`;return createHash("sha256").update(n).digest("hex").substring(0,16)}function On(e){return e.length<=4?"":e[e.length-2]}function Fn(e){let t=e.findIndex(r=>r.status==="passed");return t>0?`passed on retry ${t}`:null}function Hn(e,t){let r=["e2e","api","unit"];for(let s of r)if(e.some(a=>a===`@${s}`||a===s))return s;let n=t.replace(/\\/g,"/");for(let s of r)if(n.includes(`/${s}/`))return s;return "unknown"}var Un="__testrelic_api_config";function zn(e){return JSON.stringify(e,(t,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var Z=class{constructor(t){this.rootDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.config=Pt(t),this.apiConfig=Mt(t);}async onBegin(t,r){try{if(this.rootDir=t.rootDir,this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??randomUUID(),this.config.includeArtifacts){let n=dirname(this.config.outputPath);this.runTimestamp=ne(join(n,"artifacts"));try{le(join(n,"artifacts"));}catch{}}try{this.cloudClient=new V(this.config.cloud),await this.cloudClient.initialize(),this.cloudRunId=await Be(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt);}catch{this.cloudClient?.switchToLocalMode("init_error");}}catch{}}onTestBegin(t,r){try{t.annotations.push({type:Un,description:zn(this.apiConfig)});}catch{}}onTestEnd(t,r){try{let n=r,s=t.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=xt(n.status);let l=n.startTime.toISOString(),i=new Date(n.startTime.getTime()+n.duration).toISOString(),o=t.tags?[...t.tags]:t.annotations.filter(S=>S.type==="tag").map(S=>S.description??""),{navigations:c,networkRequests:d,apiCalls:p,apiAssertions:f,consoleLogs:u}=Ee(n.attachments,t.annotations,t.title,a==="skipped");(c.length>0||d||p)&&(this.fixtureDataReceived=!0);let h=null;if(a==="failed"||a==="flaky"){let T=(a==="flaky"?t.results.find(P=>P.status!=="passed")?.errors??[]:n.errors)[0];if(T){let P=Dt(this.config.redactPatterns),et=T.location?.line??null,q=null;this.config.includeCodeSnippets&&et!==null&&T.location?.file&&(q=qt(T.location.file,et,this.config.codeContextLines),q&&(q=P(q))),h={message:P(T.message??"Unknown error"),line:et,code:q,stack:this.config.includeStackTrace&&T.stack?P(T.stack):null};}}let g=t.titlePath().filter(Boolean),v=relative(this.rootDir||".",t.location.file),y=On(g),b=g.join(" > "),x=v,w=Dn(x,y,b),A=Hn(o,x),m=s==="flaky",k=Fn(t.results),B=xt(t.expectedStatus),M=xt(n.status),Rt=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let S=dirname(this.config.outputPath),T=g[g.length-1]??t.title;Rt=se(n.attachments,T,n.retry,S,this.runTimestamp||void 0);}let Je=this.config.includeActionSteps&&n.steps?ge(n.steps,n.startTime):null,St={titlePath:g,title:b,status:a,duration:n.duration,startedAt:l,completedAt:i,retryCount:t.results.length-1,retry:n.retry,tags:o,failure:h,specFile:v,navigations:c,testId:w,filePath:x,suiteName:y,testType:A,isFlaky:m,retryStatus:k,expectedStatus:B,actualStatus:M,artifacts:Rt,networkRequests:d,apiCalls:p,apiAssertions:f,actions:Je,consoleLogs:u};this.collectedTests.push(St);try{let S=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(S==="realtime"||S==="both")){let T=this.cloudClient.getAccessToken();T&&Ne(this.cloudClient.getEndpoint(),T,this.cloudRunId,this.toTestResult(St));}}catch{}}catch{}}async onEnd(t){try{let r=new Date().toISOString(),n=new Date(this.startedAt).getTime(),a=new Date(r).getTime()-n,l=this.buildTimeline(),i=ue(this.collectedTests,l.length),o={schemaVersion:nt,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:i,ci:_(),metadata:this.config.metadata,timeline:l,shardRunIds:null};!this.fixtureDataReceived&&this.collectedTests.some(d=>d.status!=="skipped")&&process.stderr.write(`
2307
+ `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?W(this.gitMetadata.remoteUrl):null,r=e?Qt(e):this.config.projectName??K(process.cwd()),n=e??this.config.projectName??K(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await Yt(this.config.endpoint,this.authState.accessToken,n,r,this.config.timeout,this.gitMetadata?.branch);a&&(this.repoId=a.repoId,this.writeRepoCache(n,a.repoId,a.displayName));}catch{}!e&&!this.config.projectName&&!je(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2308
+ `);}readRepoCache(e){if(!this.config)return null;let r=join(this.config.queueDirectory,"..","cache","repo.json");try{if(!existsSync(r))return null;let n=readFileSync(r,"utf-8"),s=JSON.parse(n);if(s.gitId!==e||Date.now()-s.resolvedAt>fs)return null;let a=this.hashApiKey();return a&&s.apiKeyHash!==a?null:s}catch{return null}}writeRepoCache(e,r,n){if(!this.config)return;let s=join(this.config.queueDirectory,"..","cache"),a=join(s,"repo.json");try{mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:e,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=a+".tmp";writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),renameSync(i,a);}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,n=this.config.endpoint;this.flushPromise=Promise.race([rr(r,n,e),new Promise(s=>setTimeout(s,sr))]).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 Ue(e))return;if(this.config?.apiKey){let n=await $e(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!ze(n)){let s=n;this.authState={mode:"cloud",accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:Date.now()+s.expiresIn*1e3,orgId:s.orgId,orgName:s.orgName,userId:s.userId,userName:s.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
2309
+ `),this.startBackgroundFlush();}}}catch{}},gs);}};var ms=1048576,ce=[1e3,3e3,9e3],pe=3;function Ke(t,e,r,n){return {runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{}}}async function ue(t){return new Promise(e=>setTimeout(e,t))}function vs(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}async function ys(t,e,r){for(let n=0;n<pe;n++)try{let s=await fetch(t,e);if(s.ok)return s;if(s.status===401&&r&&n===0){let a=await r();if(a){let o={...e,headers:{...e.headers,Authorization:`Bearer ${a}`}},i=await fetch(t,o);if(i.ok)return i}return null}if(s.status===429&&n<pe-1){let a=s.headers.get("Retry-After"),o=a?parseInt(a,10)*1e3:ce[n];!isNaN(o)&&o>0?await ue(o):await ue(ce[n]);continue}if(s.status>=500&&n<pe-1){await ue(ce[n]);continue}return s}catch{if(n<pe-1){await ue(ce[n]);continue}return null}return null}function bs(t){let e=JSON.stringify(t),r={"Content-Type":"application/json"};if(Buffer.byteLength(e,"utf-8")>ms){let n=gzipSync(Buffer.from(e,"utf-8"));return r["Content-Encoding"]="gzip",{body:n,headers:r}}return {body:e,headers:r}}async function ar(t,e,r,n){let s=`${t}/runs`,{body:a,headers:o}=bs(r);o.Authorization=`Bearer ${e}`;let i=await ys(s,{method:"POST",headers:o,body:a},n);return i?.ok?{success:true,statusCode:i.status,error:null}:i?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:i?`Upload failed with status ${i.status}`:"Upload failed after retries",statusCode:i?.status??null,payload:r,targetEndpoint:s,method:"POST"}}async function ir(t,e,r){let n=`${t}/runs/init`;try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(vs(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function or(t,e,r,n){let s=`${t}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}).catch(()=>{});}async function lr(t,e,r,n){let s=`${t}/runs/${r}/finalize`;try{return (await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)})).ok}catch{return false}}function dr(t,e,r,n){let s=[],a=null,o=null,i=null,l=null,p=t.filter(f=>f.name===ATTACHMENT_NAME&&f.body),d=false;if(p.length>0)for(let f of p)try{let c=JSON.parse(f.body.toString());if(isTestRelicDataPayload(c)){s=s.concat(c.navigations),c.networkRequests.length>0&&(a=(a??[]).concat(c.networkRequests)),c.apiCalls.length>0&&(o=(o??[]).concat(c.apiCalls)),c.apiAssertions.length>0&&(i=(i??[]).concat(c.apiAssertions));let h=c.consoleLogs;Array.isArray(h)&&h.length>0&&(l=(l??[]).concat(h)),d=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}", falling back to annotations
2310
+ `);}if(!d){s=e.filter(g=>g.type==="lambdatest-navigation"&&g.description).map(g=>{try{return JSON.parse(g.description)}catch{return null}}).filter(g=>g!==null);let f=e.find(g=>g.type==="__testrelic_network_requests"&&g.description);if(f)try{a=JSON.parse(f.description);}catch{}let c=e.find(g=>g.type==="__testrelic_api_calls"&&g.description);if(c)try{o=JSON.parse(c.description);}catch{}let h=e.find(g=>g.type==="__testrelic_api_assertions"&&g.description);if(h)try{i=JSON.parse(h.description);}catch{}}return s.length===0&&!a&&!o&&!i&&!l&&!n&&process.stderr.write(`[testrelic] Warning: No data found for test "${r}". Make sure your tests import { test, expect } from '@testrelic/playwright-analytics/fixture' instead of '@playwright/test'. Without the TestRelic fixture, network logs, video sync, and timeline data cannot be captured.
2311
+ `),{navigations:s,networkRequests:a,apiCalls:o,apiAssertions:i,consoleLogs:l}}function Ye(t){let r=t.getGitMetadata()?.remoteUrl;return r?W(r):t.getConfig()?.projectName??K(process.cwd())}async function cr(t,e,r,n){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let a=t.getGitMetadata(),o=P();return (await ir(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:Ye(t),branch:a?.branch??null,commit:a?.commitSha??null,startedAt:n,totalTests:null,ciProvider:o?.provider??null,ciRunUrl:o?.runUrl??null}))?.runId??null}async function Ze(t,e,r,n,s,a,o,i,l){try{if(t.isCloudMode()&&s&&(r==="realtime"||r==="both")&&await t.ensureValidToken()&&await lr(t.getEndpoint(),t.getAccessToken(),s,{finishedAt:o,duration:i,summary:l}),t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await t.ensureValidToken()){let d=t.getGitMetadata(),u=P(),f=Ye(t),c=Ke(a,f,d,u),h=await ar(t.getEndpoint(),t.getAccessToken(),c,async()=>await t.ensureValidToken()?t.getAccessToken():null);if(!h.success){let g=h,x=e?.queueDirectory??".testrelic/queue";Ge(x,n,"batch",g.reason,g.targetEndpoint,g.method,g.payload,{"Content-Type":"application/json"});}}else {let d=e?.queueDirectory??".testrelic/queue",u=t.getGitMetadata(),f=P(),c=Ye(t),h=Ke(a,c,u,f);Ge(d,n,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",h,{"Content-Type":"application/json"});}await t.dispose();}catch{try{await t.dispose();}catch{}}}function Xe(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 Rs(t,e,r){let n=`${t}::${e}::${r}`;return createHash("sha256").update(n).digest("hex").substring(0,16)}function As(t){return t.length<=4?"":t[t.length-2]}function _s(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function Is(t,e){let r=["e2e","api","unit"];for(let s of r)if(t.some(a=>a===`@${s}`||a===s))return s;let n=e.replace(/\\/g,"/");for(let s of r)if(n.includes(`/${s}/`))return s;return "unknown"}var Ls="__testrelic_api_config";function Ns(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var fe=class{constructor(e){this.rootDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";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};this.config=gt(e),this.apiConfig=ft(e);}async onBegin(e,r){try{if(this.rootDir=e.rootDir,this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??randomUUID(),this.config.reportMode==="auto"){let s=r.allTests().length;this.activeReportMode=s>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let n=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${n} tests)
2312
+ `),this.activeReportMode==="streaming"){let s=dirname(this.config.outputPath);this.streamingWriter=new ee(s);let a=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let o={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()};this.streamingWriter.writeSummary(o);}catch{}this.streamingWriter.dispose();}};process.on("SIGTERM",a),process.on("SIGINT",a);}if(this.config.includeArtifacts){let s=dirname(this.config.outputPath);this.runTimestamp=Bt(join(s,"artifacts"));try{Ut(join(s,"artifacts"));}catch{}}try{this.cloudClient=new de(this.config.cloud),await this.cloudClient.initialize(),this.cloudRunId=await cr(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt);}catch{this.cloudClient?.switchToLocalMode("init_error");}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:Ls,description:Ns(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let n=r,s=e.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=Xe(n.status);let o=n.startTime.toISOString(),i=new Date(n.startTime.getTime()+n.duration).toISOString(),l=e.tags?[...e.tags]:e.annotations.filter(R=>R.type==="tag").map(R=>R.description??""),{navigations:p,networkRequests:d,apiCalls:u,apiAssertions:f,consoleLogs:c}=dr(n.attachments,e.annotations,e.title,a==="skipped");(p.length>0||d||u)&&(this.fixtureDataReceived=!0);let h=null;if(a==="failed"||a==="flaky"){let C=(a==="flaky"?e.results.find(E=>E.status!=="passed")?.errors??[]:n.errors)[0];if(C){let E=mt(this.config.redactPatterns),$=C.location?.line??null,z=null;this.config.includeCodeSnippets&&$!==null&&C.location?.file&&(z=ht(C.location.file,$,this.config.codeContextLines),z&&(z=E(z))),h={message:E(C.message??"Unknown error"),line:$,code:z,stack:this.config.includeStackTrace&&C.stack?E(C.stack):null};}}let g=e.titlePath().filter(Boolean),x=relative(this.rootDir||".",e.location.file),k=As(g),b=g.join(" > "),v=x,T=Rs(v,k,b),S=Is(l,v),m=s==="flaky",y=_s(e.results),_=Xe(e.expectedStatus),H=Xe(n.status),Z=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let R=dirname(this.config.outputPath),C=g[g.length-1]??e.title;Z=Ot(n.attachments,C,n.retry,R,this.runTimestamp||void 0);}let U=this.config.includeActionSteps&&n.steps?Vt(n.steps,n.startTime):null,N={titlePath:g,title:b,status:a,duration:n.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:n.retry,tags:l,failure:h,specFile:x,navigations:p,testId:T,filePath:v,suiteName:k,testType:S,isFlaky:m,retryStatus:y,expectedStatus:_,actualStatus:H,artifacts:Z,networkRequests:d,apiCalls:u,apiAssertions:f,actions:U,consoleLogs:c};if(this.activeReportMode==="streaming"&&this.streamingWriter){let R=st(v,g,e.id??"",n.retry),C=n.retry===e.results.length-1,E={id:R,navigations:p??[],networkRequests:d??[],apiCalls:u??[],apiAssertions:f??[],consoleLogs:c??[],actions:U??[],artifacts:Z,failureDiagnostic:h};this.streamingWriter.writeTestDetail(R,E);let $={id:R,title:g[g.length-1]??e.title,titlePath:g,filePath:v,status:a,duration:n.duration,project:g[1]??"",retryIndex:n.retry,tags:l,hasNetworkData:(d?.length??0)>0,hasConsoleData:(c?.length??0)>0,hasArtifacts:Z!==null,hasActionSteps:(U?.length??0)>0,errorMessage:h?.message?.split(`
2313
+ `)[0]??null,networkCount:d?.length??0,consoleCount:c?.length??0,actionCount:U?.length??0,isRetry:!C};if(this.testIndex.push($),C)switch(this.summaryCounters.total++,a){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.summaryCounters.totalApiCalls+=u?.length??0,this.summaryCounters.totalAssertions+=f?.length??0,this.summaryCounters.totalNavigations+=p?.length??0,this.summaryCounters.totalNetworkRequests+=d?.length??0,this.summaryCounters.totalConsoleLogs+=c?.length??0,this.summaryCounters.totalActionSteps+=U?.length??0,N.networkRequests=null,N.consoleLogs=null,N.actions=null,N.apiCalls=null,N.apiAssertions=null;}this.collectedTests.push(N);try{let R=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(R==="realtime"||R==="both")){let C=this.cloudClient.getAccessToken();C&&or(this.cloudClient.getEndpoint(),C,this.cloudRunId,this.toTestResult(N));}}catch{}}catch{}}async onEnd(e){try{let r=new Date().toISOString(),n=new Date(this.startedAt).getTime(),a=new Date(r).getTime()-n;!this.fixtureDataReceived&&this.collectedTests.some(i=>i.status!=="skipped")&&process.stderr.write(`
2123
2314
  \u26A0 TestRelic: No fixture data received from any test.
2124
2315
  To enable network logs, video sync, and timeline tracking, import the TestRelic fixture:
2125
2316
  import { test, expect } from '@testrelic/playwright-analytics/fixture';
2126
2317
  instead of:
2127
2318
  import { test, expect } from '@playwright/test';
2128
2319
 
2129
- `);let c=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let d=dirname(this.config.outputPath);c=ie(d,this.runTimestamp);let p=join(d,"artifact-manifest.json"),f=JSON.stringify(c,null,2),u=p+".tmp";writeFileSync(u,f,"utf-8"),renameSync(u,p);}catch{}this.writeReport(o),await te(o,this.config,c),fe(i,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient&&await Me(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,o,r,a,i);}catch{}}printsToStdio(){return false}buildTimeline(){let t=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:r.apiCalls,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:r.networkRequests,actions:r.actions,consoleLogs:r.consoleLogs}));return pe(t,{navigationTypes:this.config.navigationTypes})}toTestResult(t){return {title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,networkRequests:t.networkRequests,apiCalls:t.apiCalls,apiAssertions:t.apiAssertions,actions:t.actions??null,consoleLogs:t.consoleLogs??null}}writeReport(t){try{let r=JSON.stringify(t,null,2),n=this.config.outputPath,s=dirname(n);mkdirSync(s,{recursive:!0});let a=n+".tmp";writeFileSync(a,r,"utf-8"),renameSync(a,n);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2130
- `);}}};var Jn=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Kn(e){let t=e.toLowerCase();return Jn.some(r=>t.includes(r))}var Q=class e{constructor(t,r){this.page=t;this.records=[];this.listeners=[];this.currentNetworkCounter=null;this.pendingRequests=new Map;this.capturedRequests=[];this.pendingBodyReads=[];this.requestIdCounter=0;this.consoleLogs=[];this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=t.goto.bind(t),this.origGoBack=t.goBack.bind(t),this.origGoForward=t.goForward.bind(t),this.origReload=t.reload.bind(t),this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async getCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[t,r]of this.pendingRequests)this.capturedRequests.push({url:r.url,method:r.method,resourceType:r.resourceType,statusCode:0,responseTimeMs:Date.now()-r.startTimeMs,startedAt:r.startedAt,requestHeaders:r.headers,requestBody:r.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:r.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.pendingRequests.delete(t);return [...this.capturedRequests].sort((t,r)=>t.startedAt.localeCompare(r.startedAt))}static mapConsoleType(t){switch(t){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getData(){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});let t=this.records.map(n=>({url:n.url,navigationType:n.navigationType,timestamp:n.timestamp,domContentLoadedAt:n.domContentLoadedAt,networkIdleAt:n.networkIdleAt,networkStats:n.networkStats})),r=this.includeNetworkStats?await this.getCapturedRequests():[];return {navigations:t,networkRequests:r,consoleLogs:[...this.consoleLogs]}}async flushLegacyAnnotations(t){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});for(let r of this.records){let n={url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}if(this.includeNetworkStats){let r=await this.getCapturedRequests();r.length>0&&t.annotations.push({type:"__testrelic_network_requests",description:JSON.stringify(r)});}}dispose(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:t,handler:r}of this.listeners)this.page.off(t,r);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.capturedRequests=[],this.pendingBodyReads=[];}getRecords(){return this.records}interceptMethods(){let t=this,r=this.page;r.goto=async function(n,s){return t.recordNavigation(n,"goto"),t.origGoto(n,s)},r.goBack=async function(n){let s=await t.origGoBack(n);return t.recordNavigation(r.url(),"back"),s},r.goForward=async function(n){let s=await t.origGoForward(n);return t.recordNavigation(r.url(),"forward"),s},r.reload=async function(n){return t.recordNavigation(r.url(),"refresh"),t.origReload(n)};}attachListeners(){let t=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",t),this.listeners.push({event:"domcontentloaded",handler:t});let r=s=>{try{let a=s;if(typeof a.parentFrame=="function"&&a.parentFrame()!==null)return;let l=a.url(),i=this.records[this.records.length-1];if(i&&Date.now()-new Date(i.timestamp).getTime()<50&&i.url===l)return;this.recordNavigation(l,"navigation");}catch{}};this.page.on("framenavigated",r),this.listeners.push({event:"framenavigated",handler:r});let n=s=>{try{let a=s,l=a.type(),i=a.text();if(l==="debug"&&i.startsWith("__testrelic_nav:")){try{let o=JSON.parse(i.slice(16));o.type&&o.url&&this.recordNavigation(o.url,o.type);}catch{}return}{let o=null;try{let d=a.location();d&&d.url&&(o=`${d.url}:${d.lineNumber}:${d.columnNumber}`);}catch{}let c=e.mapConsoleType(l);this.consoleLogs.push({level:c,text:i,timestamp:new Date().toISOString(),location:o});}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=i=>{this.currentNetworkCounter&&this.currentNetworkCounter.totalRequests++;try{let o=i,c=String(this.requestIdCounter++),d=o.postData()??null,p={url:o.url(),method:o.method(),resourceType:this.mapResourceType(o.resourceType()),headers:o.headers(),postData:d,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now()};this.pendingRequests.set(c,p),i.__testrelic_id=c;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=i=>{try{let o=i;if(this.currentNetworkCounter){let y=o.status();y>=400&&(this.currentNetworkCounter.failedRequests++,this.currentNetworkCounter.failedRequestUrls.push(y+" "+o.url()));let b=o.headers()["content-length"];b&&(this.currentNetworkCounter.totalBytes+=parseInt(b,10)||0);let x=o.request().resourceType(),w=this.mapResourceType(x);this.currentNetworkCounter.byType[w]++;}let c=o.request().__testrelic_id;if(!c)return;let d=this.pendingRequests.get(c);if(!d)return;this.pendingRequests.delete(c);let p=Date.now()-d.startTimeMs,f=o.headers(),u=f["content-type"]??null,h=parseInt(f["content-length"]??"0",10)||0,g=u?!Kn(u):!1,v=(async()=>{let y=null;if(!g)try{y=(await o.body()).toString("utf-8");}catch{}let b={url:d.url,method:d.method,resourceType:d.resourceType,statusCode:o.status(),responseTimeMs:p,startedAt:d.startedAt,requestHeaders:d.headers,requestBody:d.postData,responseBody:y,responseHeaders:f,contentType:u,responseSize:h,requestBodyTruncated:d.postDataTruncated,responseBodyTruncated:!1,isBinary:g,error:null};this.capturedRequests.push(b);})();this.pendingBodyReads.push(v);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});let l=i=>{if(this.currentNetworkCounter){this.currentNetworkCounter.failedRequests++;try{let o=i;this.currentNetworkCounter.failedRequestUrls.push("ERR "+o.url());}catch{}}try{let o=i,c=o.__testrelic_id;if(!c)return;let d=this.pendingRequests.get(c);if(!d)return;this.pendingRequests.delete(c);let p={url:d.url,method:d.method,resourceType:d.resourceType,statusCode:0,responseTimeMs:Date.now()-d.startTimeMs,startedAt:d.startedAt,requestHeaders:d.headers,requestBody:d.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:d.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:o.failure()?.errorText??"Unknown error"};this.capturedRequests.push(p);}catch{}};this.page.on("requestfailed",l),this.listeners.push({event:"requestfailed",handler:l});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let t=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){t(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(t,r){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}}),this.records.push({url:t,navigationType:r,timestamp:new Date().toISOString()}),this.includeNetworkStats&&(this.currentNetworkCounter=this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}mapResourceType(t){switch(t){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var De=Symbol.for("__testrelic_call_id"),Wn="__testrelic_api_assertions",L=new WeakMap,N=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(t){this.assertions.push(t);}getAssertions(){return this.assertions}setCurrentCallId(t){this.currentCallId=t;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(t){this.assertions.length!==0&&t.annotations.push({type:Wn,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}};var Oe="[REDACTED]";function kt(e,t){if(e===null||t.length===0)return e;let r=new Set(t.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(e))Object.hasOwn(e,s)&&(n[s]=r.has(s.toLowerCase())?Oe:e[s]);return n}function X(e,t){if(e===null||t.length===0)return e;let r;try{r=JSON.parse(e);}catch{return e}if(typeof r!="object"||r===null)return e;let n=new Set(t),s=wt(r,n);return JSON.stringify(s)}function wt(e,t){if(Array.isArray(e))return e.map(r=>wt(r,t));if(typeof e=="object"&&e!==null){let r={};for(let n of Object.keys(e)){if(!Object.hasOwn(e,n))continue;let s=e[n];t.has(n)?r[n]=Oe:r[n]=wt(s,t);}return r}return e}function He(e,t,r){if(r.length>0){for(let n of r)if(Fe(e,n))return false}if(t.length>0){for(let n of t)if(Fe(e,n))return true;return false}return true}function Fe(e,t){try{return t instanceof RegExp?t.test(e):Yn(t).test(e)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(t)}`),false}}function Yn(e){let t="",r=0;for(;r<e.length;){let n=e[r];n==="*"&&e[r+1]==="*"?(t+=".*",r+=2,e[r]==="/"&&r++):n==="*"?(t+="[^/]*",r++):n==="?"?(t+="[^/]",r++):".+^${}()|[]\\".includes(n)?(t+="\\"+n,r++):(t+=n,r++);}return new RegExp(t)}var Zn=["get","post","put","patch","delete","head","fetch"],Qn=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"],Xn="__testrelic_api_calls";function ts(e){let t=e.toLowerCase();return Qn.some(r=>t.includes(r))}function es(e){if(!e)return null;if(e.data!==void 0&&e.data!==null){let t=e.data;return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("base64"):JSON.stringify(t)}if(e.form!==void 0&&e.form!==null)return JSON.stringify(e.form);if(e.multipart!==void 0&&e.multipart!==null){let t=e.multipart,r={};for(let[n,s]of Object.entries(t))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?r[n]=String(s):s&&typeof s=="object"&&"name"in s?r[n]=`[file: ${s.name}]`:r[n]="[binary]";return JSON.stringify(r)}return null}var tt=class tt{constructor(t,r,n){this.originals=new Map;this.capturedCalls=[];this.callCounter=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=t,this.assertionTracker=r??null,this.apiConfig=n??tt.DEFAULT_API_CONFIG;}get lastCallId(){return this._lastCallId}getCallIdForValue(t){return t!=null&&typeof t=="object"?L.get(t)??null:this.primitiveCallIds.get(t)??null}intercept(){for(let r of Zn){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let t=this.context.dispose.bind(this.context);this.originals.set("dispose",t),this.context.dispose=async r=>(this.disposed=true,t(r));}getData(){return [...this.capturedCalls]}flushLegacyAnnotations(t){this.capturedCalls.length!==0&&t.annotations.push({type:Xn,description:JSON.stringify(this.capturedCalls)});}dispose(){for(let[t,r]of this.originals)this.context[t]=r;this.originals.clear(),this.capturedCalls=[],this.callCounter=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCalls(){return this.capturedCalls}tagResponseMethods(t,r){let n=this,s=t.headers.bind(t);t.headers=function(){let u=s();return L.set(u,r),u};let a=t.headersArray.bind(t);t.headersArray=function(){let u=a();return L.set(u,r),u};let l=t.json.bind(t);t.json=async function(){let u=await l();return u!=null&&typeof u=="object"&&L.set(u,r),u};let i=t.status.bind(t);t.status=function(){let u=i();return n.primitiveCallIds.set(u,r),u};let o=t.statusText.bind(t);t.statusText=function(){let u=o();return n.primitiveCallIds.set(u,r),u};let c=t.ok.bind(t);t.ok=function(){let u=c();return n.primitiveCallIds.set(u,r),u};let d=t.text.bind(t);t.text=async function(){let u=await d();return n.primitiveCallIds.set(u,r),u};let p=t.body.bind(t);t.body=async function(){let u=await p();return L.set(u,r),u};}createWrapper(t,r){let n=this;return async function(a,l){if(!He(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,l);let i=`api-call-${n.callCounter++}`,o=new Date().toISOString(),c=t==="fetch"?(l?.method??"GET").toUpperCase():t.toUpperCase(),d=es(l),p=performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let f;try{f=await r(a,l);}catch(u){let h=performance.now();try{let g=n.apiConfig.captureRequestBody?X(d,n.apiConfig.redactBodyFields):null,v={id:i,timestamp:o,method:c,url:a,requestHeaders:null,requestBody:g,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((h-p)*100)/100,isBinary:!1,error:u instanceof Error?u.message:String(u)};n.capturedCalls.push(v);}catch{}throw u}try{let u=performance.now(),h=f.headers(),g=h["content-type"]??null,v=g?!ts(g):!1,y=null;n.apiConfig.captureRequestHeaders&&l?.headers&&(y=l.headers);let b=null;n.apiConfig.captureResponseHeaders&&(b=h);let x=n.apiConfig.captureRequestBody?d:null,w=null;if(n.apiConfig.captureResponseBody)try{v?w=(await f.body()).toString("base64"):w=await f.text();}catch{}y=kt(y,n.apiConfig.redactHeaders),b=kt(b,n.apiConfig.redactHeaders),x=X(x,n.apiConfig.redactBodyFields),w=X(w,n.apiConfig.redactBodyFields);let A={id:i,timestamp:o,method:c,url:f.url(),requestHeaders:y,requestBody:x,responseStatusCode:f.status(),responseStatusText:f.statusText(),responseHeaders:b,responseBody:w,responseTimeMs:Math.round((u-p)*100)/100,isBinary:v,error:null};n.capturedCalls.push(A);}catch{}try{f[De]=i,n.tagResponseMethods(f,i);}catch{}return f}}};tt.DEFAULT_API_CONFIG=Object.freeze({trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]});var E=tt;var ns="__testrelic_api_config",ss="__testrelic_config_trackApiCalls";function Ct(e){let t=e.annotations.find(n=>n.type===ns&&n.description!==void 0);if(t)try{return JSON.parse(t.description,as)}catch{}let r=e.annotations.find(n=>n.type===ss&&n.description!==void 0);return r?{trackApiCalls:r.description!=="false",captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}:{trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}}function as(e,t){if(typeof t=="object"&&t!==null&&t.__regexp===true&&typeof t.source=="string"){let{source:r,flags:n}=t;return new RegExp(r,n)}return t}var $e={page:async({page:e},t,r)=>{let n=new Q(e);try{await n.init();}catch{}await t(e);try{let{navigations:s,networkRequests:a,consoleLogs:l}=await n.getData(),i={testRelicData:!0,version:PAYLOAD_VERSION,navigations:s,networkRequests:a,apiCalls:[],apiAssertions:[],consoleLogs:l};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(i)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{await n.flushLegacyAnnotations(r);}catch{}n.dispose();},request:async({request:e},t,r)=>{let n=Ct(r);if(!n.trackApiCalls){await t(e);return}let s=new N,a=new E(e,s,n);a.intercept(),await t(e);try{let l=a.getData(),i=n.captureAssertions?s.getData():[],o={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:l,apiAssertions:i,consoleLogs:[]};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(o)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{a.flushLegacyAnnotations(r);}catch{}try{s.flushLegacyAnnotations(r);}catch{}a.dispose(),s.dispose();}};test.extend($e);var ds={request:async({request:e},t,r)=>{let n=Ct(r);if(!n.trackApiCalls){await t(e);return}let s=new N,a=new E(e,s,n);a.intercept();let l=[],i=process.stdout.write,o=process.stderr.write;process.stdout.write=function(c,...d){try{let p=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!p.startsWith("[testrelic]")&&!p.startsWith("\u2139 TestRelic")&&!p.startsWith("\u2713 TestRelic")&&!p.startsWith("\u26A0 TestRelic")&&l.push({level:"stdout",text:p.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null});}catch{}return i.apply(process.stdout,[c,...d])},process.stderr.write=function(c,...d){try{let p=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!p.startsWith("[testrelic]")&&!p.startsWith("\u26A0 TestRelic")&&l.push({level:"stderr",text:p.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null});}catch{}return o.apply(process.stderr,[c,...d])};try{await t(e);}finally{process.stdout.write=i,process.stderr.write=o;}try{let c=a.getData(),d=n.captureAssertions?s.getData():[],p={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:c,apiAssertions:d,consoleLogs:l};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(p)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{a.flushLegacyAnnotations(r);}catch{}try{s.flushLegacyAnnotations(r);}catch{}a.dispose(),s.dispose();}};var Ge="@testrelic/playwright-analytics";function ps(e){return Array.isArray(e)?e.some(t=>Array.isArray(t)&&typeof t[0]=="string"&&t[0]===Ge):false}function us(e,t){let n={video:"on",screenshot:"on",trace:"on",...e.use??{}},s;Array.isArray(e.reporter)?s=e.reporter:typeof e.reporter=="string"?s=[[e.reporter]]:s=[["list"]];let a=ps(s)?s:[...s,[Ge,t??{}]];return defineConfig({...e,use:n,reporter:a})}var Ve=false;function Fi(e,t,r="manual_record"){if(!e||!e.annotations){Ve||(Ve=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
2131
- `));return}let n={url:t,navigationType:r,timestamp:new Date().toISOString()};e.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}export{nt as SCHEMA_VERSION,Z as default,us as defineConfig,Fi as recordNavigation,ds as testRelicApiFixture,$e as testRelicFixture};//# sourceMappingURL=index.js.map
2320
+ `);let o=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let i=dirname(this.config.outputPath);o=Ft(i,this.runTimestamp);let l=join(i,"artifact-manifest.json"),p=JSON.stringify(o,null,2),d=l+".tmp";writeFileSync(d,p,"utf-8"),renameSync(d,l);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await this.finalizeStreamingReport(r,a,e,o);else {let i=this.buildTimeline(),l=new Map;for(let f of this.collectedTests){let c=l.get(f.testId);(!c||f.retry>c.retry)&&l.set(f.testId,f);}let p=Array.from(l.values()),d=qe(p,i.length),u={schemaVersion:te,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:d,ci:P(),metadata:this.config.metadata,timeline:i,shardRunIds:null};this.writeReport(u),await Pe(u,this.config,o),Fe(d,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient&&await Ze(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,u,r,a,d);}}catch{}}async finalizeStreamingReport(e,r,n,s){if(!this.streamingWriter)return;let a=new Map;for(let m of this.testIndex){let y=`${m.filePath}::${m.titlePath.join(" > ")}`,_=a.get(y);(_===void 0||m.retryIndex>_)&&a.set(y,m.retryIndex);}let{totalApiCalls:o,totalAssertions:i,totalNavigations:l,totalNetworkRequests:p,totalConsoleLogs:d,totalActionSteps:u}=this.summaryCounters;this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:o,totalAssertions:i,totalNavigations:l,totalNetworkRequests:p,totalConsoleLogs:d,totalActionSteps:u};for(let m of this.testIndex){let y=`${m.filePath}::${m.titlePath.join(" > ")}`,_=a.get(y);if(m.isRetry=m.retryIndex<_,!m.isRetry)switch(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.streamingWriter.writeIndex(this.testIndex);let f=this.testIndex.filter(m=>!m.isRetry).length,c={reporterTotal:this.summaryCounters.total,indexTotal:f,playwrightStatus:n.status,isValid:this.summaryCounters.total===f};c.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${c.reporterTotal}, index: ${c.indexTotal}
2321
+ `);let h=new Map;for(let m of this.testIndex){if(m.isRetry)continue;let y=h.get(m.filePath);switch(y||(y={filePath:m.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},h.set(m.filePath,y)),y.total++,m.status){case "passed":y.passed++;break;case "failed":y.failed++;break;case "flaky":y.flaky++;break;case "skipped":y.skipped++;break;case "timedout":y.timedOut++;break}}let g=Array.from(h.values()),x=new Map;for(let m of this.collectedTests){let y=x.get(m.testId);(!y||m.retry>y.retry)&&x.set(m.testId,m);}let k=Array.from(x.values()),b=qe(k,this.testIndex.length),v={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:g,enrichedSummary:b,validation:c,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(v);let T={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(T),await Pe(this.buildStreamingReport(v,b,e,r),this.config,s),Fe(b,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let S=this.streamingWriter.getReportDir();if(process.stderr.write(`[testrelic] Streaming report written to ${S}
2322
+ [testrelic] ${this.testIndex.length} test detail files on disk
2323
+ `),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
2324
+ `),this.streamingWriter.dispose(),this.cloudClient){let m=this.buildStreamingReport(v,b,e,r);await Ze(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,m,e,r,b);}}buildStreamingReport(e,r,n,s){return {schemaVersion:te,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:n,totalDuration:s,summary:r,ci:P(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}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:r.apiCalls,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:r.networkRequests,actions:r.actions,consoleLogs:r.consoleLogs}));return jt(e,{navigationTypes:this.config.navigationTypes})}toTestResult(e){return {title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:e.networkRequests,apiCalls:e.apiCalls,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:e.consoleLogs??null}}writeReport(e){try{let r=JSON.stringify(e,null,2),n=this.config.outputPath,s=dirname(n);mkdirSync(s,{recursive:!0});let a=n+".tmp";writeFileSync(a,r,"utf-8"),renameSync(a,n);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2325
+ `);}}};var Bs=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Os(t){let e=t.toLowerCase();return Bs.some(r=>e.includes(r))}var ge=class t{constructor(e,r){this.page=e;this.records=[];this.listeners=[];this.currentNetworkCounter=null;this.pendingRequests=new Map;this.capturedRequests=[];this.pendingBodyReads=[];this.requestIdCounter=0;this.consoleLogs=[];this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=e.goto.bind(e),this.origGoBack=e.goBack.bind(e),this.origGoForward=e.goForward.bind(e),this.origReload=e.reload.bind(e),this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async getCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[e,r]of this.pendingRequests)this.capturedRequests.push({url:r.url,method:r.method,resourceType:r.resourceType,statusCode:0,responseTimeMs:Date.now()-r.startTimeMs,startedAt:r.startedAt,requestHeaders:r.headers,requestBody:r.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:r.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.pendingRequests.delete(e);return [...this.capturedRequests].sort((e,r)=>e.startedAt.localeCompare(r.startedAt))}static mapConsoleType(e){switch(e){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getData(){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});let e=this.records.map(n=>({url:n.url,navigationType:n.navigationType,timestamp:n.timestamp,domContentLoadedAt:n.domContentLoadedAt,networkIdleAt:n.networkIdleAt,networkStats:n.networkStats})),r=this.includeNetworkStats?await this.getCapturedRequests():[];return {navigations:e,networkRequests:r,consoleLogs:[...this.consoleLogs]}}async flushLegacyAnnotations(e){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});for(let r of this.records){let n={url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats};e.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}if(this.includeNetworkStats){let r=await this.getCapturedRequests();r.length>0&&e.annotations.push({type:"__testrelic_network_requests",description:JSON.stringify(r)});}}dispose(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:e,handler:r}of this.listeners)this.page.off(e,r);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.capturedRequests=[],this.pendingBodyReads=[];}getRecords(){return this.records}interceptMethods(){let e=this,r=this.page;r.goto=async function(n,s){return e.recordNavigation(n,"goto"),e.origGoto(n,s)},r.goBack=async function(n){let s=await e.origGoBack(n);return e.recordNavigation(r.url(),"back"),s},r.goForward=async function(n){let s=await e.origGoForward(n);return e.recordNavigation(r.url(),"forward"),s},r.reload=async function(n){return e.recordNavigation(r.url(),"refresh"),e.origReload(n)};}attachListeners(){let e=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",e),this.listeners.push({event:"domcontentloaded",handler:e});let r=s=>{try{let a=s;if(typeof a.parentFrame=="function"&&a.parentFrame()!==null)return;let o=a.url(),i=this.records[this.records.length-1];if(i&&Date.now()-new Date(i.timestamp).getTime()<50&&i.url===o)return;this.recordNavigation(o,"navigation");}catch{}};this.page.on("framenavigated",r),this.listeners.push({event:"framenavigated",handler:r});let n=s=>{try{let a=s,o=a.type(),i=a.text();if(o==="debug"&&i.startsWith("__testrelic_nav:")){try{let l=JSON.parse(i.slice(16));l.type&&l.url&&this.recordNavigation(l.url,l.type);}catch{}return}{let l=null;try{let d=a.location();d&&d.url&&(l=`${d.url}:${d.lineNumber}:${d.columnNumber}`);}catch{}let p=t.mapConsoleType(o);this.consoleLogs.push({level:p,text:i,timestamp:new Date().toISOString(),location:l});}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=i=>{this.currentNetworkCounter&&this.currentNetworkCounter.totalRequests++;try{let l=i,p=String(this.requestIdCounter++),d=l.postData()??null,u={url:l.url(),method:l.method(),resourceType:this.mapResourceType(l.resourceType()),headers:l.headers(),postData:d,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now()};this.pendingRequests.set(p,u),i.__testrelic_id=p;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=i=>{try{let l=i;if(this.currentNetworkCounter){let k=l.status();k>=400&&(this.currentNetworkCounter.failedRequests++,this.currentNetworkCounter.failedRequestUrls.push(k+" "+l.url()));let b=l.headers()["content-length"];b&&(this.currentNetworkCounter.totalBytes+=parseInt(b,10)||0);let v=l.request().resourceType(),T=this.mapResourceType(v);this.currentNetworkCounter.byType[T]++;}let p=l.request().__testrelic_id;if(!p)return;let d=this.pendingRequests.get(p);if(!d)return;this.pendingRequests.delete(p);let u=Date.now()-d.startTimeMs,f=l.headers(),c=f["content-type"]??null,h=parseInt(f["content-length"]??"0",10)||0,g=c?!Os(c):!1,x=(async()=>{let k=null;if(!g)try{k=(await l.body()).toString("utf-8");}catch{}let b={url:d.url,method:d.method,resourceType:d.resourceType,statusCode:l.status(),responseTimeMs:u,startedAt:d.startedAt,requestHeaders:d.headers,requestBody:d.postData,responseBody:k,responseHeaders:f,contentType:c,responseSize:h,requestBodyTruncated:d.postDataTruncated,responseBodyTruncated:!1,isBinary:g,error:null};this.capturedRequests.push(b);})();this.pendingBodyReads.push(x);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});let o=i=>{if(this.currentNetworkCounter){this.currentNetworkCounter.failedRequests++;try{let l=i;this.currentNetworkCounter.failedRequestUrls.push("ERR "+l.url());}catch{}}try{let l=i,p=l.__testrelic_id;if(!p)return;let d=this.pendingRequests.get(p);if(!d)return;this.pendingRequests.delete(p);let u={url:d.url,method:d.method,resourceType:d.resourceType,statusCode:0,responseTimeMs:Date.now()-d.startTimeMs,startedAt:d.startedAt,requestHeaders:d.headers,requestBody:d.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:d.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:l.failure()?.errorText??"Unknown error"};this.capturedRequests.push(u);}catch{}};this.page.on("requestfailed",o),this.listeners.push({event:"requestfailed",handler:o});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let e=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(e,r){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}}),this.records.push({url:e,navigationType:r,timestamp:new Date().toISOString()}),this.includeNetworkStats&&(this.currentNetworkCounter=this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}mapResourceType(e){switch(e){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var fr=Symbol.for("__testrelic_call_id"),qs="__testrelic_api_assertions",q=new WeakMap,O=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(e){this.assertions.push(e);}getAssertions(){return this.assertions}setCurrentCallId(e){this.currentCallId=e;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(e){this.assertions.length!==0&&e.annotations.push({type:qs,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}};var gr="[REDACTED]";function tt(t,e){if(t===null||e.length===0)return t;let r=new Set(e.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(t))Object.hasOwn(t,s)&&(n[s]=r.has(s.toLowerCase())?gr:t[s]);return n}function he(t,e){if(t===null||e.length===0)return t;let r;try{r=JSON.parse(t);}catch{return t}if(typeof r!="object"||r===null)return t;let n=new Set(e),s=et(r,n);return JSON.stringify(s)}function et(t,e){if(Array.isArray(t))return t.map(r=>et(r,e));if(typeof t=="object"&&t!==null){let r={};for(let n of Object.keys(t)){if(!Object.hasOwn(t,n))continue;let s=t[n];e.has(n)?r[n]=gr:r[n]=et(s,e);}return r}return t}function mr(t,e,r){if(r.length>0){for(let n of r)if(hr(t,n))return false}if(e.length>0){for(let n of e)if(hr(t,n))return true;return false}return true}function hr(t,e){try{return e instanceof RegExp?e.test(t):Fs(e).test(t)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(e)}`),false}}function Fs(t){let e="",r=0;for(;r<t.length;){let n=t[r];n==="*"&&t[r+1]==="*"?(e+=".*",r+=2,t[r]==="/"&&r++):n==="*"?(e+="[^/]*",r++):n==="?"?(e+="[^/]",r++):".+^${}()|[]\\".includes(n)?(e+="\\"+n,r++):(e+=n,r++);}return new RegExp(e)}var Hs=["get","post","put","patch","delete","head","fetch"],Us=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"],$s="__testrelic_api_calls";function zs(t){let e=t.toLowerCase();return Us.some(r=>e.includes(r))}function js(t){if(!t)return null;if(t.data!==void 0&&t.data!==null){let e=t.data;return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):JSON.stringify(e)}if(t.form!==void 0&&t.form!==null)return JSON.stringify(t.form);if(t.multipart!==void 0&&t.multipart!==null){let e=t.multipart,r={};for(let[n,s]of Object.entries(e))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?r[n]=String(s):s&&typeof s=="object"&&"name"in s?r[n]=`[file: ${s.name}]`:r[n]="[binary]";return JSON.stringify(r)}return null}var me=class me{constructor(e,r,n){this.originals=new Map;this.capturedCalls=[];this.callCounter=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=e,this.assertionTracker=r??null,this.apiConfig=n??me.DEFAULT_API_CONFIG;}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?q.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let r of Hs){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let e=this.context.dispose.bind(this.context);this.originals.set("dispose",e),this.context.dispose=async r=>(this.disposed=true,e(r));}getData(){return [...this.capturedCalls]}flushLegacyAnnotations(e){this.capturedCalls.length!==0&&e.annotations.push({type:$s,description:JSON.stringify(this.capturedCalls)});}dispose(){for(let[e,r]of this.originals)this.context[e]=r;this.originals.clear(),this.capturedCalls=[],this.callCounter=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCalls(){return this.capturedCalls}tagResponseMethods(e,r){let n=this,s=e.headers.bind(e);e.headers=function(){let c=s();return q.set(c,r),c};let a=e.headersArray.bind(e);e.headersArray=function(){let c=a();return q.set(c,r),c};let o=e.json.bind(e);e.json=async function(){let c=await o();return c!=null&&typeof c=="object"&&q.set(c,r),c};let i=e.status.bind(e);e.status=function(){let c=i();return n.primitiveCallIds.set(c,r),c};let l=e.statusText.bind(e);e.statusText=function(){let c=l();return n.primitiveCallIds.set(c,r),c};let p=e.ok.bind(e);e.ok=function(){let c=p();return n.primitiveCallIds.set(c,r),c};let d=e.text.bind(e);e.text=async function(){let c=await d();return n.primitiveCallIds.set(c,r),c};let u=e.body.bind(e);e.body=async function(){let c=await u();return q.set(c,r),c};}createWrapper(e,r){let n=this;return async function(a,o){if(!mr(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,o);let i=`api-call-${n.callCounter++}`,l=new Date().toISOString(),p=e==="fetch"?(o?.method??"GET").toUpperCase():e.toUpperCase(),d=js(o),u=performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let f;try{f=await r(a,o);}catch(c){let h=performance.now();try{let g=n.apiConfig.captureRequestBody?he(d,n.apiConfig.redactBodyFields):null,x={id:i,timestamp:l,method:p,url:a,requestHeaders:null,requestBody:g,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((h-u)*100)/100,isBinary:!1,error:c instanceof Error?c.message:String(c)};n.capturedCalls.push(x);}catch{}throw c}try{let c=performance.now(),h=f.headers(),g=h["content-type"]??null,x=g?!zs(g):!1,k=null;n.apiConfig.captureRequestHeaders&&o?.headers&&(k=o.headers);let b=null;n.apiConfig.captureResponseHeaders&&(b=h);let v=n.apiConfig.captureRequestBody?d:null,T=null;if(n.apiConfig.captureResponseBody)try{x?T=(await f.body()).toString("base64"):T=await f.text();}catch{}k=tt(k,n.apiConfig.redactHeaders),b=tt(b,n.apiConfig.redactHeaders),v=he(v,n.apiConfig.redactBodyFields),T=he(T,n.apiConfig.redactBodyFields);let S={id:i,timestamp:l,method:p,url:f.url(),requestHeaders:k,requestBody:v,responseStatusCode:f.status(),responseStatusText:f.statusText(),responseHeaders:b,responseBody:T,responseTimeMs:Math.round((c-u)*100)/100,isBinary:x,error:null};n.capturedCalls.push(S);}catch{}try{f[fr]=i,n.tagResponseMethods(f,i);}catch{}return f}}};me.DEFAULT_API_CONFIG=Object.freeze({trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]});var F=me;var Gs="__testrelic_api_config",Js="__testrelic_config_trackApiCalls";function nt(t){let e=t.annotations.find(n=>n.type===Gs&&n.description!==void 0);if(e)try{return JSON.parse(e.description,Ws)}catch{}let r=t.annotations.find(n=>n.type===Js&&n.description!==void 0);return r?{trackApiCalls:r.description!=="false",captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}:{trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}}function Ws(t,e){if(typeof e=="object"&&e!==null&&e.__regexp===true&&typeof e.source=="string"){let{source:r,flags:n}=e;return new RegExp(r,n)}return e}var wr={page:async({page:t},e,r)=>{let n=new ge(t);try{await n.init();}catch{}await e(t);try{let{navigations:s,networkRequests:a,consoleLogs:o}=await n.getData(),i={testRelicData:!0,version:PAYLOAD_VERSION,navigations:s,networkRequests:a,apiCalls:[],apiAssertions:[],consoleLogs:o};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(i)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{await n.flushLegacyAnnotations(r);}catch{}n.dispose();},request:async({request:t},e,r)=>{let n=nt(r);if(!n.trackApiCalls){await e(t);return}let s=new O,a=new F(t,s,n);a.intercept(),await e(t);try{let o=a.getData(),i=n.captureAssertions?s.getData():[],l={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:o,apiAssertions:i,consoleLogs:[]};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(l)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{a.flushLegacyAnnotations(r);}catch{}try{s.flushLegacyAnnotations(r);}catch{}a.dispose(),s.dispose();}};test.extend(wr);var Qs={request:async({request:t},e,r)=>{let n=nt(r);if(!n.trackApiCalls){await e(t);return}let s=new O,a=new F(t,s,n);a.intercept();let o=[],i=process.stdout.write,l=process.stderr.write;process.stdout.write=function(p,...d){try{let u=typeof p=="string"?p:Buffer.isBuffer(p)?p.toString("utf-8"):String(p);!u.startsWith("[testrelic]")&&!u.startsWith("\u2139 TestRelic")&&!u.startsWith("\u2713 TestRelic")&&!u.startsWith("\u26A0 TestRelic")&&o.push({level:"stdout",text:u.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null});}catch{}return i.apply(process.stdout,[p,...d])},process.stderr.write=function(p,...d){try{let u=typeof p=="string"?p:Buffer.isBuffer(p)?p.toString("utf-8"):String(p);!u.startsWith("[testrelic]")&&!u.startsWith("\u26A0 TestRelic")&&o.push({level:"stderr",text:u.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null});}catch{}return l.apply(process.stderr,[p,...d])};try{await e(t);}finally{process.stdout.write=i,process.stderr.write=l;}try{let p=a.getData(),d=n.captureAssertions?s.getData():[],u={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:p,apiAssertions:d,consoleLogs:o};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(u)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{a.flushLegacyAnnotations(r);}catch{}try{s.flushLegacyAnnotations(r);}catch{}a.dispose(),s.dispose();}};var xr="@testrelic/playwright-analytics";function ea(t){return Array.isArray(t)?t.some(e=>Array.isArray(e)&&typeof e[0]=="string"&&e[0]===xr):false}function ta(t,e){let n={video:"on",screenshot:"on",trace:"on",...t.use??{}},s;Array.isArray(t.reporter)?s=t.reporter:typeof t.reporter=="string"?s=[[t.reporter]]:s=[["list"]];let a=ea(s)?s:[...s,[xr,e??{}]];return defineConfig({...t,use:n,reporter:a})}var kr=false;function $o(t,e,r="manual_record"){if(!t||!t.annotations){kr||(kr=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
2326
+ `));return}let n={url:e,navigationType:r,timestamp:new Date().toISOString()};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}export{te as SCHEMA_VERSION,fe as default,ta as defineConfig,$o as recordNavigation,Qs as testRelicApiFixture,wr as testRelicFixture};//# sourceMappingURL=index.js.map
2132
2327
  //# sourceMappingURL=index.js.map