@testrelic/playwright-analytics 2.9.0-next.65 → 2.9.0-next.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2545,14 +2545,14 @@ ${o?`<script id="artifact-manifest-data" type="application/json">${o}</script>`:
2545
2545
  </body>
2546
2546
  </html>`}function je(t){try{let e=process.platform,r;e==="darwin"?r=`open "${t}"`:e==="win32"?r=`start "" "${t}"`:r=`xdg-open "${t}"`,child_process.exec(r,n=>{n&&process.stderr.write(`[testrelic] Failed to open browser: ${n.message}
2547
2547
  `);});}catch{}}var Jt=path.join(os$1.tmpdir(),"testrelic-data"),E=class{constructor(e){this.count=0;this.closed=false;fs$1.mkdirSync(Jt,{recursive:true}),this.filePath=path.join(Jt,`${e}-${crypto.randomUUID().substring(0,8)}.jsonl`),this.fd=fs$1.openSync(this.filePath,"w");}append(e){if(this.closed)return;let r=JSON.stringify(e)+`
2548
- `;fs$1.writeSync(this.fd,r),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{fs$1.closeSync(this.fd);}catch{}}}cleanup(){try{fs$1.unlinkSync(this.filePath);}catch{}}};async function Yt(t,e,r,n){let s=(e-1)*r,a=[],o=0,i=readline.createInterface({input:fs$1.createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let u of i)if(u.length!==0){if(o>=s&&a.length<r)try{a.push(JSON.parse(u));}catch{}if(o++,a.length>=r&&n!==void 0)break}let l=n??o,d=Math.max(1,Math.ceil(l/r));return {items:a,total:l,page:e,pageSize:r,totalPages:d}}var Qt=/^[a-f0-9]{12}$/,$e=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,er=500;function x(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function tr(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 de(t){try{return fs$1.existsSync(t)?JSON.parse(fs$1.readFileSync(t,"utf-8")):null}catch{return null}}function ce(t){let e=0;try{let r=fs$1.readdirSync(t,{withFileTypes:!0});for(let n of r){let s=path.join(t,n.name);n.isFile()?e+=fs$1.statSync(s).size:n.isDirectory()&&(e+=ce(s));}}catch{}return e}function rr(t,e,r,n){let s=de(path.join(r,"index.json"));x(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function nr(t,e,r){let n=de(path.join(r,"summary.json"));if(!n){x(e,404,{error:"Summary not found"});return}x(e,200,n);}function sr(t,e,r){let n=de(path.join(r,"index.json"));if(!n){x(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(er,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),l=a.get("status")?.split(",").filter(Boolean)??null,d=a.get("file")??null,u=a.get("search")?.toLowerCase()??null,p=a.get("tag")?.split(",").filter(Boolean)??null,f=a.get("sort")??"file",c=a.get("order")==="desc"?-1:1,g=n;l&&l.length>0&&(g=g.filter(v=>l.includes(v.status))),d&&(g=g.filter(v=>v.filePath===d||v.filePath.startsWith(d+"/"))),u&&(g=g.filter(v=>v.title.toLowerCase().includes(u)||v.filePath.toLowerCase().includes(u))),p&&p.length>0&&(g=g.filter(v=>p.some(b=>v.tags.includes(b)))),g=[...g].sort((v,b)=>{let C=0;switch(f){case "duration":C=v.duration-b.duration;break;case "status":C=v.status.localeCompare(b.status);break;case "title":C=v.title.localeCompare(b.title);break;default:C=v.filePath.localeCompare(b.filePath);break}return C*c});let h=g.length,m=Math.max(1,Math.ceil(h/i)),y=(o-1)*i,T=g.slice(y,y+i);x(e,200,{tests:T,pagination:{page:o,pageSize:i,totalItems:h,totalPages:m},filters:{status:l,file:d,search:u,tag:p}});}function ar(t,e,r,n){if(!Qt.test(n)){x(e,400,{error:"Invalid test ID format"});return}let s=path.join(r,"tests",n,"meta.json"),a=path.join(r,"tests",`${n}.json`),o=fs$1.existsSync(s)?s:fs$1.existsSync(a)?a:null;if(!o){x(e,404,{error:`Test not found: ${n}`});return}try{let i=fs$1.readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}async function ir(t,e,r,n,s){if(!Qt.test(n)){x(e,400,{error:"Invalid test ID format"});return}let o=path.join(r,"tests",n,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!fs$1.existsSync(o)){x(e,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),u=Math.min(er,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),p,f=path.join(r,"tests",n,"meta.json");if(fs$1.existsSync(f))try{let g=JSON.parse(fs$1.readFileSync(f,"utf-8"));switch(s){case "network":p=g.networkRequestsCount;break;case "console":p=g.consoleLogsCount;break;case "api-calls":p=g.apiCallsCount;break}}catch{}let c=await Yt(o,d,u,p);x(e,200,c);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}function or(t,e,r){let n=de(path.join(r,"index.json"));if(!n){x(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));x(e,200,{files:a});}function lr(t,e,r){if(!fs$1.existsSync(r)){x(e,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!$e.test(o.name))continue;let i=path.join(r,o.name),l=ce(i),d=fs$1.readdirSync(i,{withFileTypes:!0}).filter(u=>u.isDirectory());n.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),s+=l;}n.sort((o,i)=>i.folderName.localeCompare(o.folderName)),x(e,200,{runs:n,totalSizeBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function dr(t,e,r){try{let n=0,s=0;if(fs$1.existsSync(r)){let a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!$e.test(o.name))continue;let i=path.join(r,o.name),l=ce(i);fs$1.rmSync(i,{recursive:!0,force:!0}),s+=l,n++;}}x(e,200,{deletedCount:n,freedBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function cr(t,e,r,n){if(!$e.test(n)){x(e,400,{error:"Invalid folder name"});return}let s=path.join(r,n);try{if(!fs$1.statSync(s).isDirectory()){x(e,404,{error:"Not found"});return}}catch{x(e,404,{error:"Not found"});return}try{let a=ce(s);fs$1.rmSync(s,{recursive:!0,force:!0}),x(e,200,{deleted:n,freedBytes:a});}catch(a){x(e,500,{error:a instanceof Error?a.message:String(a)});}}function ur(t,e,r){x(e,200,{status:"shutting_down"}),r.close();}function We(t,e,r){if(!fs$1.existsSync(r)){x(e,404,{error:"File not found"});return}try{let n=fs$1.readFileSync(r),s=path.extname(r).toLowerCase(),a=rs[s]??"application/octet-stream";e.writeHead(200,{"Content-Type":a}),e.end(n);}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}var rs={".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 is=9323,os=10,ls=1800*1e3;function X(t,e){return new Promise((r,n)=>{let s=e?.port??is,a=Date.now(),o,i=0,l=fs$1.existsSync(path.join(t,"artifacts"))?path.join(t,"artifacts"):fs$1.existsSync(path.join(t,"..","artifacts"))?path.join(t,"..","artifacts"):path.join(t,"artifacts");function d(){clearTimeout(o),o=setTimeout(()=>{p.close();},ls);}let u=e?.htmlPath??null;if(!u){let c=path.dirname(t);try{let g=fs$1.readdirSync(c).find(h=>h.endsWith(".html"));g&&(u=path.join(c,g));}catch{}}let p=http.createServer((c,g)=>{if(d(),tr(g),c.method==="OPTIONS"){g.writeHead(204),g.end();return}let h;try{h=new URL(c.url??"/",`http://${c.headers.host??"localhost"}`).pathname;}catch{x(g,400,{error:"Invalid URL"});return}if(c.method==="GET"&&(h==="/"||h==="/index.html")){if(u&&fs$1.existsSync(u)){We(c,g,u);return}x(g,404,{error:"HTML report not found"});return}if(c.method==="GET"&&h==="/api/health"){rr(c,g,t,a);return}if(c.method==="GET"&&h==="/api/summary"){nr(c,g,t);return}if(c.method==="GET"&&h==="/api/tests"){sr(c,g,t);return}if(c.method==="GET"&&h==="/api/files"){or(c,g,t);return}let m=h.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(c.method==="GET"&&m){ir(c,g,t,m[1],m[2]);return}let y=h.match(/^\/api\/tests\/([a-f0-9]+)$/);if(c.method==="GET"&&y){ar(c,g,t,y[1]);return}if(c.method==="GET"&&h==="/api/artifacts"){lr(c,g,l);return}if(c.method==="DELETE"&&h==="/api/artifacts"){dr(c,g,l);return}let T=h.match(/^\/api\/artifacts\/(.+)$/);if(c.method==="DELETE"&&T){cr(c,g,l,decodeURIComponent(T[1]));return}if(c.method==="GET"&&h.startsWith("/artifacts/")){let v=decodeURIComponent(h.slice(11));if(v.includes("..")||v.includes("\0")){x(g,400,{error:"Invalid path"});return}We(c,g,path.join(l,v));return}if(c.method==="POST"&&h==="/api/shutdown"){ur(c,g,p);return}x(g,404,{error:"Not found"});});function f(c){let g=h=>{h.code==="EADDRINUSE"&&i<os?(i++,f(c+1)):n(h);};p.once("error",g),p.listen(c,"127.0.0.1",()=>{p.removeListener("error",g);let h=p.address();if(!h||typeof h=="string"){n(new Error("Failed to get server address"));return}d(),r({port:h.port,dispose:()=>new Promise(m=>{clearTimeout(o),p.close(()=>m());})});});}f(s);})}async function pr(t){let e=await X(t);return {port:e.port,dispose:e.dispose}}function us(t,e,r){let n=JSON.stringify(t),s=r?JSON.stringify(r):null;return Gt(n,e,s)}async function Ge(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=path.dirname(i);fs$1.mkdirSync(l,{recursive:!0});let d="",u="[]",p=null;if(a){d=JSON.stringify(t.summary);let c=path.dirname(e.outputPath),g=path.join(c,".testrelic-report");try{let h=path.join(g,"index-compact.json"),m=path.join(g,"index.json");fs$1.existsSync(h)?u=fs$1.readFileSync(h,"utf-8"):fs$1.existsSync(m)&&(u=fs$1.readFileSync(m,"utf-8"));}catch{}p=r?JSON.stringify(r):null,o=ze(d,u,null,p);}else o=us(t,null,r);let f=i+".tmp";if(fs$1.writeFileSync(f,o,"utf-8"),fs$1.renameSync(f,i),a){if(t.ci===null){let c=path.dirname(e.outputPath),g=path.join(c,".testrelic-report"),h=path.resolve(i);try{if(await fs(),n=await gs(g),!n){s=await X(g,{htmlPath:h}),n=s.port;let m=setInterval(()=>{},6e4),y=()=>{clearInterval(m),s?.dispose();};process.on("SIGINT",y),process.on("SIGTERM",y),setTimeout(y,1800*1e3).unref();}if(n){process.stderr.write(`
2548
+ `;fs$1.writeSync(this.fd,r),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{fs$1.closeSync(this.fd);}catch{}}}cleanup(){try{fs$1.unlinkSync(this.filePath);}catch{}}};async function Yt(t,e,r,n){let s=(e-1)*r,a=[],o=0,i=readline.createInterface({input:fs$1.createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let u of i)if(u.length!==0){if(o>=s&&a.length<r)try{a.push(JSON.parse(u));}catch{}if(o++,a.length>=r&&n!==void 0)break}let l=n??o,d=Math.max(1,Math.ceil(l/r));return {items:a,total:l,page:e,pageSize:r,totalPages:d}}var Qt=/^[a-f0-9]{12}$/,$e=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,er=500;function x(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function tr(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 de(t){try{return fs$1.existsSync(t)?JSON.parse(fs$1.readFileSync(t,"utf-8")):null}catch{return null}}function ce(t){let e=0;try{let r=fs$1.readdirSync(t,{withFileTypes:!0});for(let n of r){let s=path.join(t,n.name);n.isFile()?e+=fs$1.statSync(s).size:n.isDirectory()&&(e+=ce(s));}}catch{}return e}function rr(t,e,r,n){let s=de(path.join(r,"index.json"));x(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function nr(t,e,r){let n=de(path.join(r,"summary.json"));if(!n){x(e,404,{error:"Summary not found"});return}x(e,200,n);}function sr(t,e,r){let n=de(path.join(r,"index.json"));if(!n){x(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(er,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),l=a.get("status")?.split(",").filter(Boolean)??null,d=a.get("file")??null,u=a.get("search")?.toLowerCase()??null,p=a.get("tag")?.split(",").filter(Boolean)??null,f=a.get("sort")??"file",c=a.get("order")==="desc"?-1:1,g=n;l&&l.length>0&&(g=g.filter(y=>l.includes(y.status))),d&&(g=g.filter(y=>y.filePath===d||y.filePath.startsWith(d+"/"))),u&&(g=g.filter(y=>y.title.toLowerCase().includes(u)||y.filePath.toLowerCase().includes(u))),p&&p.length>0&&(g=g.filter(y=>p.some(v=>y.tags.includes(v)))),g=[...g].sort((y,v)=>{let C=0;switch(f){case "duration":C=y.duration-v.duration;break;case "status":C=y.status.localeCompare(v.status);break;case "title":C=y.title.localeCompare(v.title);break;default:C=y.filePath.localeCompare(v.filePath);break}return C*c});let h=g.length,m=Math.max(1,Math.ceil(h/i)),b=(o-1)*i,T=g.slice(b,b+i);x(e,200,{tests:T,pagination:{page:o,pageSize:i,totalItems:h,totalPages:m},filters:{status:l,file:d,search:u,tag:p}});}function ar(t,e,r,n){if(!Qt.test(n)){x(e,400,{error:"Invalid test ID format"});return}let s=path.join(r,"tests",n,"meta.json"),a=path.join(r,"tests",`${n}.json`),o=fs$1.existsSync(s)?s:fs$1.existsSync(a)?a:null;if(!o){x(e,404,{error:`Test not found: ${n}`});return}try{let i=fs$1.readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}async function ir(t,e,r,n,s){if(!Qt.test(n)){x(e,400,{error:"Invalid test ID format"});return}let o=path.join(r,"tests",n,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!fs$1.existsSync(o)){x(e,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),u=Math.min(er,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),p,f=path.join(r,"tests",n,"meta.json");if(fs$1.existsSync(f))try{let g=JSON.parse(fs$1.readFileSync(f,"utf-8"));switch(s){case "network":p=g.networkRequestsCount;break;case "console":p=g.consoleLogsCount;break;case "api-calls":p=g.apiCallsCount;break}}catch{}let c=await Yt(o,d,u,p);x(e,200,c);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}function or(t,e,r){let n=de(path.join(r,"index.json"));if(!n){x(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));x(e,200,{files:a});}function lr(t,e,r){if(!fs$1.existsSync(r)){x(e,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!$e.test(o.name))continue;let i=path.join(r,o.name),l=ce(i),d=fs$1.readdirSync(i,{withFileTypes:!0}).filter(u=>u.isDirectory());n.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),s+=l;}n.sort((o,i)=>i.folderName.localeCompare(o.folderName)),x(e,200,{runs:n,totalSizeBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function dr(t,e,r){try{let n=0,s=0;if(fs$1.existsSync(r)){let a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!$e.test(o.name))continue;let i=path.join(r,o.name),l=ce(i);fs$1.rmSync(i,{recursive:!0,force:!0}),s+=l,n++;}}x(e,200,{deletedCount:n,freedBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function cr(t,e,r,n){if(!$e.test(n)){x(e,400,{error:"Invalid folder name"});return}let s=path.join(r,n);try{if(!fs$1.statSync(s).isDirectory()){x(e,404,{error:"Not found"});return}}catch{x(e,404,{error:"Not found"});return}try{let a=ce(s);fs$1.rmSync(s,{recursive:!0,force:!0}),x(e,200,{deleted:n,freedBytes:a});}catch(a){x(e,500,{error:a instanceof Error?a.message:String(a)});}}function ur(t,e,r){x(e,200,{status:"shutting_down"}),r.close();}function We(t,e,r){if(!fs$1.existsSync(r)){x(e,404,{error:"File not found"});return}try{let n=fs$1.readFileSync(r),s=path.extname(r).toLowerCase(),a=rs[s]??"application/octet-stream";e.writeHead(200,{"Content-Type":a}),e.end(n);}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}var rs={".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 is=9323,os=10,ls=1800*1e3;function X(t,e){return new Promise((r,n)=>{let s=e?.port??is,a=Date.now(),o,i=0,l=fs$1.existsSync(path.join(t,"artifacts"))?path.join(t,"artifacts"):fs$1.existsSync(path.join(t,"..","artifacts"))?path.join(t,"..","artifacts"):path.join(t,"artifacts");function d(){clearTimeout(o),o=setTimeout(()=>{p.close();},ls);}let u=e?.htmlPath??null;if(!u){let c=path.dirname(t);try{let g=fs$1.readdirSync(c).find(h=>h.endsWith(".html"));g&&(u=path.join(c,g));}catch{}}let p=http.createServer((c,g)=>{if(d(),tr(g),c.method==="OPTIONS"){g.writeHead(204),g.end();return}let h;try{h=new URL(c.url??"/",`http://${c.headers.host??"localhost"}`).pathname;}catch{x(g,400,{error:"Invalid URL"});return}if(c.method==="GET"&&(h==="/"||h==="/index.html")){if(u&&fs$1.existsSync(u)){We(c,g,u);return}x(g,404,{error:"HTML report not found"});return}if(c.method==="GET"&&h==="/api/health"){rr(c,g,t,a);return}if(c.method==="GET"&&h==="/api/summary"){nr(c,g,t);return}if(c.method==="GET"&&h==="/api/tests"){sr(c,g,t);return}if(c.method==="GET"&&h==="/api/files"){or(c,g,t);return}let m=h.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(c.method==="GET"&&m){ir(c,g,t,m[1],m[2]);return}let b=h.match(/^\/api\/tests\/([a-f0-9]+)$/);if(c.method==="GET"&&b){ar(c,g,t,b[1]);return}if(c.method==="GET"&&h==="/api/artifacts"){lr(c,g,l);return}if(c.method==="DELETE"&&h==="/api/artifacts"){dr(c,g,l);return}let T=h.match(/^\/api\/artifacts\/(.+)$/);if(c.method==="DELETE"&&T){cr(c,g,l,decodeURIComponent(T[1]));return}if(c.method==="GET"&&h.startsWith("/artifacts/")){let y=decodeURIComponent(h.slice(11));if(y.includes("..")||y.includes("\0")){x(g,400,{error:"Invalid path"});return}We(c,g,path.join(l,y));return}if(c.method==="POST"&&h==="/api/shutdown"){ur(c,g,p);return}x(g,404,{error:"Not found"});});function f(c){let g=h=>{h.code==="EADDRINUSE"&&i<os?(i++,f(c+1)):n(h);};p.once("error",g),p.listen(c,"127.0.0.1",()=>{p.removeListener("error",g);let h=p.address();if(!h||typeof h=="string"){n(new Error("Failed to get server address"));return}d(),r({port:h.port,dispose:()=>new Promise(m=>{clearTimeout(o),p.close(()=>m());})});});}f(s);})}async function pr(t){let e=await X(t);return {port:e.port,dispose:e.dispose}}function us(t,e,r){let n=JSON.stringify(t),s=r?JSON.stringify(r):null;return Gt(n,e,s)}async function Ge(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=path.dirname(i);fs$1.mkdirSync(l,{recursive:!0});let d="",u="[]",p=null;if(a){d=JSON.stringify(t.summary);let c=path.dirname(e.outputPath),g=path.join(c,".testrelic-report");try{let h=path.join(g,"index-compact.json"),m=path.join(g,"index.json");fs$1.existsSync(h)?u=fs$1.readFileSync(h,"utf-8"):fs$1.existsSync(m)&&(u=fs$1.readFileSync(m,"utf-8"));}catch{}p=r?JSON.stringify(r):null,o=ze(d,u,null,p);}else o=us(t,null,r);let f=i+".tmp";if(fs$1.writeFileSync(f,o,"utf-8"),fs$1.renameSync(f,i),a){if(t.ci===null){let c=path.dirname(e.outputPath),g=path.join(c,".testrelic-report"),h=path.resolve(i);try{if(await fs(),n=await gs(g),!n){s=await X(g,{htmlPath:h}),n=s.port;let m=setInterval(()=>{},6e4),b=()=>{clearInterval(m),s?.dispose();};process.on("SIGINT",b),process.on("SIGTERM",b),setTimeout(b,1800*1e3).unref();}if(n){process.stderr.write(`
2549
2549
  Report server: http://127.0.0.1:${n}
2550
- `);try{let m=ze(d,u,n,p),y=i+".tmp";fs$1.writeFileSync(y,m,"utf-8"),fs$1.renameSync(y,i);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let c=path.dirname(e.outputPath),g=path.join(c,"artifacts");if(fs$1.existsSync(g))try{let h=await pr(g);n=h.port,process.on("exit",()=>{h.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(a&&n)je(`http://127.0.0.1:${n}`);else {let c=path.resolve(i);je(c);}}catch(n){process.stderr.write(`[testrelic] Failed to write HTML report: ${n instanceof Error?n.message:String(n)}
2550
+ `);try{let m=ze(d,u,n,p),b=i+".tmp";fs$1.writeFileSync(b,m,"utf-8"),fs$1.renameSync(b,i);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let c=path.dirname(e.outputPath),g=path.join(c,"artifacts");if(fs$1.existsSync(g))try{let h=await pr(g);n=h.port,process.on("exit",()=>{h.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(a&&n)je(`http://127.0.0.1:${n}`);else {let c=path.resolve(i);je(c);}}catch(n){process.stderr.write(`[testrelic] Failed to write HTML report: ${n instanceof Error?n.message:String(n)}
2551
2551
  `);}}var fe=9323,yr=10;async function ps(){for(let t=fe;t<fe+yr;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 fs(){for(let t=fe;t<fe+yr;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 gs(t){let r=[path.join(__dirname,"cli.cjs"),path.join(__dirname,"cli.js"),path.join(__dirname,"..","dist","cli.cjs"),path.join(__dirname,"..","dist","cli.js")].find(n=>fs$1.existsSync(n));if(!r){let n=await X(t);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=child_process.spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",o=false,i=setTimeout(()=>{o||(o=true,s.stderr?.removeAllListeners(),ps().then(n));},5e3);s.stderr?.on("data",l=>{a+=l.toString();let d=a.match(/127\.0\.0\.1:(\d+)/);d&&!o&&(o=true,clearTimeout(i),s.stderr?.removeAllListeners(),s.unref(),n(Number(d[1])));}),s.on("error",()=>{o||(o=true,clearTimeout(i),n(null));}),s.on("exit",()=>{o||(o=true,clearTimeout(i),n(null));}),s.unref();})}var ys=20,Je=0,Ke=[];async function br(t,e){Je>=ys&&await new Promise(r=>Ke.push(r)),Je++;try{return await promises.copyFile(t,e),!0}catch{return false}finally{Je--,Ke.length>0&&Ke.shift()();}}var ee=[];async function wr(){ee.length!==0&&(await Promise.allSettled(ee),ee.length=0);}function xr(t){let e=new Date,r=a=>String(a).padStart(2,"0"),n=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!fs$1.existsSync(path.join(t,n)))return n;let s=1;for(;fs$1.existsSync(path.join(t,`${n}-${s}`));)s++;return `${n}-${s}`}function vs(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 kr(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=vs(e);r>0&&(i+=`--retry-${r}`);let l=s?["artifacts",s,i]:["artifacts",i],d=path.join(n,...l),u=l,p={};try{fs$1.mkdirSync(d,{recursive:!0});}catch{return null}if(a?.path&&fs$1.existsSync(a.path)){let c=`screenshot${path.extname(a.path)||".png"}`,g=path.join(d,c);ee.push(br(a.path,g).then(()=>{})),p.screenshot=`${u.join("/")}/${c}`;}if(o?.path&&fs$1.existsSync(o.path)){let c=`video${path.extname(o.path)||".webm"}`,g=path.join(d,c);ee.push(br(o.path,g).then(()=>{})),p.video=`${u.join("/")}/${c}`;}return !p.screenshot&&!p.video?null:p}var xs=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,ks="1.0";function Ts(t){let e=path.extname(t).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(e)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(e)?"video":"other"}function Tr(t,e,r){let n=[];try{let s=fs$1.readdirSync(t,{withFileTypes:!0});for(let a of s){if(!a.isFile())continue;let o=path.join(t,a.name),i=fs$1.statSync(o);n.push({name:a.name,type:Ts(a.name),relativePath:`artifacts/${e}/${r}/${a.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:n}}function Cs(t,e){let r=path.join(t,e),n=[],s=0;try{let o=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=Tr(path.join(r,i.name),e,i.name);n.push(l);for(let d of l.files)s+=d.sizeBytes;}}catch{}let a=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return n.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function Cr(t,e){let r=path.join(t,"artifacts"),n=[],s=[],a=0;try{let i=fs$1.readdirSync(r,{withFileTypes:!0});for(let l of i)if(l.isDirectory())if(xs.test(l.name)){let d=Cs(r,l.name);n.push({...d,isCurrentRun:l.name===e});}else {let d=Tr(path.join(r,l.name),l.name,l.name);s.push(d);for(let u of d.files)a+=u.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:ks,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:n,serverPort:null}}function Is(t){let e=t,{root:r}=path.parse(e);for(;e!==r;){if(fs$1.existsSync(path.join(e,".git")))return e;e=path.join(e,"..");}return null}function Rr(t){try{let e=Is(t);if(!e)return;let r=path.join(e,".gitignore"),n=path.relative(e,t).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(fs$1.existsSync(r)&&fs$1.readFileSync(r,"utf-8").split(`
2552
2552
  `).map(l=>l.trim()).some(l=>l===s||l===n))return;let a=`
2553
2553
  # TestRelic test artifacts
2554
2554
  ${s}
2555
- `;fs$1.appendFileSync(r,a,"utf-8");}catch{}}function Ir(t,e){let r=[];for(let n of t){let s=Ls(n),a=Ps(n),o=Es(n,s,a,e),i=Ms(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(Ns),Fs(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 Ls(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 Ps(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 Es(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 Ms(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:_r(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:_r(s.requestBody)},response:o,...s.error?{error:s.error}:{},assertions:a,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function Ns(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?Ar(t.callId)-Ar(e.callId):0}function Ar(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function Fs(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 _r(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function Xe(t,e){let r=t.length,n=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,n)]}function Ds(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function Bs(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 Lr(t,e){let r=0,n=0,s=0,a=0,o=0;for(let w of t)switch(w.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 w of t)w.apiCalls&&i.push(...w.apiCalls);let l=i.length,d=new Set,u={},p={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},f=[];for(let w of i)d.add(Ds(w.url)),u[w.method]=(u[w.method]??0)+1,p[Bs(w.responseStatusCode)]+=1,f.push(w.responseTimeMs);let c=null;if(f.length>0){let w=[...f].sort((A,z)=>A-z),k=w.reduce((A,z)=>A+z,0);c={avg:Math.round(k/w.length),min:w[0],max:w[w.length-1],p50:Xe(w,50),p95:Xe(w,95),p99:Xe(w,99)};}let g=0,h=0,m=0;for(let w of t)if(w.apiAssertions)for(let k of w.apiAssertions)g++,k.status==="passed"?h++:m++;let y=0,T=new Set;for(let w of t){y+=w.navigations.length;for(let k of w.navigations)T.add(k.url);}let v=0,b={};function C(w){for(let k of w)v++,b[k.category]=(b[k.category]??0)+1,k.children.length>0&&C(k.children);}for(let w of t)w.actions&&C(w.actions);return {total:t.length,passed:r,failed:n,flaky:s,skipped:a,timedout:o,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:u,apiCallsByStatusRange:p,apiResponseTime:c,totalAssertions:g,passedAssertions:h,failedAssertions:m,totalNavigations:y,uniqueNavigationUrls:T.size,totalTimelineSteps:e,totalActionSteps:v,actionStepsByCategory:b}}function Os(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function I(t){return `\u2502 ${Os(t)} \u2502
2555
+ `;fs$1.appendFileSync(r,a,"utf-8");}catch{}}function Ir(t,e){let r=[];for(let n of t){let s=Ls(n),a=Ps(n),o=Es(n,s,a,e),i=Ms(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(Ns),Fs(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 Ls(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 Ps(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 Es(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 Ms(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:_r(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:_r(s.requestBody)},response:o,...s.error?{error:s.error}:{},assertions:a,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function Ns(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?Ar(t.callId)-Ar(e.callId):0}function Ar(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function Fs(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 _r(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function Xe(t,e){let r=t.length,n=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,n)]}function Ds(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function Bs(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 Lr(t,e){let r=0,n=0,s=0,a=0,o=0;for(let w of t)switch(w.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 w of t)w.apiCalls&&i.push(...w.apiCalls);let l=i.length,d=new Set,u={},p={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},f=[];for(let w of i)d.add(Ds(w.url)),u[w.method]=(u[w.method]??0)+1,p[Bs(w.responseStatusCode)]+=1,f.push(w.responseTimeMs);let c=null;if(f.length>0){let w=[...f].sort((A,z)=>A-z),k=w.reduce((A,z)=>A+z,0);c={avg:Math.round(k/w.length),min:w[0],max:w[w.length-1],p50:Xe(w,50),p95:Xe(w,95),p99:Xe(w,99)};}let g=0,h=0,m=0;for(let w of t)if(w.apiAssertions)for(let k of w.apiAssertions)g++,k.status==="passed"?h++:m++;let b=0,T=new Set;for(let w of t){b+=w.navigations.length;for(let k of w.navigations)T.add(k.url);}let y=0,v={};function C(w){for(let k of w)y++,v[k.category]=(v[k.category]??0)+1,k.children.length>0&&C(k.children);}for(let w of t)w.actions&&C(w.actions);return {total:t.length,passed:r,failed:n,flaky:s,skipped:a,timedout:o,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:u,apiCallsByStatusRange:p,apiResponseTime:c,totalAssertions:g,passedAssertions:h,failedAssertions:m,totalNavigations:b,uniqueNavigationUrls:T.size,totalTimelineSteps:e,totalActionSteps:y,actionStepsByCategory:v}}function Os(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function I(t){return `\u2502 ${Os(t)} \u2502
2556
2556
  `}function Qe(t,e,r,n){if(n||t.total===0)return;let s=`\u250C${"\u2500".repeat(58)}\u2510
2557
2557
  `,a=`\u2514${"\u2500".repeat(58)}\u2518
2558
2558
  `,o=I(""),i=s;i+=I("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+=I(`Tests: ${t.total} total (${l.join(" ")})`),t.totalNavigations>0&&(i+=I(`Navigations: ${t.totalNavigations} visits across ${t.uniqueNavigationUrls} unique URLs`)),t.totalApiCalls>0){i+=I(`API Calls: ${t.totalApiCalls} calls across ${t.uniqueApiUrls} unique endpoints`);let d=Object.entries(t.apiCallsByMethod).filter(([,p])=>p>0).map(([p,f])=>`${p}: ${f}`);d.length>0&&(i+=I(` ${d.join(" ")}`));let u=Object.entries(t.apiCallsByStatusRange).filter(([,p])=>p>0).map(([p,f])=>`${p}: ${f}`);u.length>0&&(i+=I(` ${u.join(" ")}`)),t.apiResponseTime&&(i+=I(` Avg response: ${t.apiResponseTime.avg}ms P95: ${t.apiResponseTime.p95}ms`));}if(t.totalAssertions>0&&(i+=I(`Assertions: ${t.totalAssertions} total (${t.passedAssertions} \u2713 ${t.failedAssertions} \u2717)`)),t.totalActionSteps>0){let d=[],u=t.actionStepsByCategory;u.ui_action&&d.push(`${u.ui_action} UI`),u.assertion&&d.push(`${u.assertion} assertions`),u.custom_step&&d.push(`${u.custom_step} custom`);let p=d.length>0?` (${d.join(" ")})`:"";i+=I(`Actions: ${t.totalActionSteps} steps${p}`);}i+=I(`Report: ${r}`),i+=I(`Data: ${e}`),i+=a,i+=`For more information visit us at https://docs.testrelic.ai
@@ -2576,12 +2576,12 @@ ${s}
2576
2576
  `);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
2577
2577
  `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?re(this.gitMetadata.remoteUrl):null,r=e?Or(e):this.config.projectName??ne(process.cwd()),n=e??this.config.projectName??ne(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await Dr(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&&!st(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2578
2578
  `);}readRepoCache(e){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs$1.existsSync(r))return null;let n=fs$1.readFileSync(r,"utf-8"),s=JSON.parse(n);if(s.gitId!==e||Date.now()-s.resolvedAt>pa)return null;let a=this.hashApiKey();return a&&s.apiKeyHash!==a?null:s}catch{return null}}writeRepoCache(e,r,n){if(!this.config)return;let s=path.join(this.config.queueDirectory,"..","cache"),a=path.join(s,"repo.json");try{fs$1.mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:e,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=a+".tmp";fs$1.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),fs$1.renameSync(i,a);}catch{}}hashApiKey(){return this.config?.apiKey?crypto.createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let e=this.authState.accessToken,r=this.config.queueDirectory,n=this.config.endpoint;this.flushPromise=Promise.race([zr(r,n,e),new Promise(s=>setTimeout(s,$r))]).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 tt(e))return;if(this.config?.apiKey){let n=await rt(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!nt(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.
2579
- `),this.startBackgroundFlush();}}}catch{}},fa);}};var ga=new Set(["smoke","regression","nightly","ci"]);function ye(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&ga.has(t))return t}var ma=1048576,ve=[1e3,3e3,9e3],be=3,ya=40*1048576,va=new Set(["e2e","mobile","unit"]);function dt(t){if(t&&t.length>0&&t.every(s=>s.testType==="api")){let s=new Map;for(let i of t){let l=i.apiProtocol??"rest";s.set(l,(s.get(l)??0)+1);}let a="rest",o=0;for(let[i,l]of s)l>o&&(o=l,a=i);return {testType:"api",apiProtocol:a,metadata:{testType:"api",primaryProtocol:a}}}let e=new Map;for(let s of t??[])va.has(s.testType)&&e.set(s.testType,(e.get(s.testType)??0)+1);let r=null,n=0;for(let[s,a]of e)a>n&&(n=a,r=s);return {testType:r??"e2e"}}function ct(t,e,r,n,s,a){let o=a?.cloudPlatform?a.cloudPlatform:n?.provider&&n.provider!=="unknown"?n.provider:"local",i=ye(),l=dt(s),d=l.testType==="api"?l:null,u=d&&s?s.map(f=>f.apiProtocol?f:{...f,apiProtocol:d.apiProtocol}):s,p={runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,environment:o,...i?{runType:i}:{},...d?{testType:d.testType,apiProtocol:d.apiProtocol,metadata:d.metadata}:{testType:l.testType},...u&&u.length>0?{tests:u}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{},...a?.cloudPlatform?{cloudPlatform:a.cloudPlatform}:{},...a?.cloudBuildId?{cloudBuildId:a.cloudBuildId}:{},...a?.cloudSessionId?{cloudSessionId:a.cloudSessionId}:{}};if(p.tests&&p.tests.length>0){let f=JSON.stringify(p);if(Buffer.byteLength(f,"utf-8")>ya){let c=p.tests.map(({consoleLogs:g,networkRequests:h,apiCalls:m,...y})=>y);return {...p,tests:c}}}return p}function lt(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function ut(t){return Array.isArray(t)?t.map(e=>{let r=e.statusCode??e.responseStatusCode??null;return {...e.protocol!=null?{protocol:e.protocol}:{},method:e.method??null,url:e.url??null,statusCode:r,statusText:e.statusText??e.responseStatusText??null,ok:typeof r=="number"?r<400:e.ok??null,durationMs:e.durationMs??e.responseTimeMs??null,bytesIn:typeof e.bytesIn=="number"?e.bytesIn:lt(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:lt(e.requestBody),requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null}}):[]}function pt(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,n=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:lt(e.responseBody),duration:e.responseTimeMs??e.durationMs??0,responseTimeMs:e.responseTimeMs??e.durationMs??0,requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,timestamp:n,startedAt:n}}):[]}function ft(t){if(!Array.isArray(t))return [];let e=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return t.map(r=>{let n=r.status==="failed"?"failed":"passed",s=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,a=r.kind??r.type??"assertion",o=n==="failed"?`expected ${e(r.expected)}, received ${e(r.actual)}`:r.expected!==void 0?`expected ${e(r.expected)}`:null;return {kind:a,description:s??r.description??`${a} assertion`,status:n,detail:o}})}async function we(t){return new Promise(e=>setTimeout(e,t))}function ba(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}async function Wr(t,e,r){for(let n=0;n<be;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<be-1){let a=s.headers.get("Retry-After"),o=a?parseInt(a,10)*1e3:ve[n];!isNaN(o)&&o>0?await we(o):await we(ve[n]);continue}if(s.status>=500&&n<be-1){await we(ve[n]);continue}return s}catch{if(n<be-1){await we(ve[n]);continue}return null}return null}function wa(t){let e=JSON.stringify(t),r={"Content-Type":"application/json"};if(Buffer.byteLength(e,"utf-8")>ma){let n=zlib.gzipSync(Buffer.from(e,"utf-8"));return r["Content-Encoding"]="gzip",{body:n,headers:r}}return {body:e,headers:r}}async function Vr(t,e,r,n){let s=`${t}/runs`,{body:a,headers:o}=wa(r);o.Authorization=`Bearer ${e}`;let i=await Wr(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 Gr(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(ba(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function Jr(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 Kr(t,e,r,n){let s=`${t}/runs/${r}/finalize`;return (await Wr(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}))?.ok??false}function gt(t,e,r,n){let s=`${t}/runs/${r}/finalize`,a=new Date,o={finishedAt:a.toISOString(),duration:a.getTime()-new Date(n).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}function Yr(t,e,r,n){let s=[],a=[],o=null,i=0,l=null,d=0,u=null,p=0,f=t.filter(h=>h.name===core.ATTACHMENT_NAME&&h.body),c=false;if(f.length>0)for(let h of f)try{let m=JSON.parse(h.body.toString());if(core.isTestRelicFilePayload(m)){s=s.concat(m.navigations),a=a.concat(m.apiAssertions),m.networkRequestsFile&&(o=m.networkRequestsFile,i+=m.networkRequestsCount),m.consoleLogsFile&&(l=m.consoleLogsFile,d+=m.consoleLogsCount),m.apiCallsFile&&(u=m.apiCallsFile,p+=m.apiCallsCount),c=!0;continue}if(core.isTestRelicDataPayload(m)){s=s.concat(m.navigations),Array.isArray(m.apiAssertions)&&(a=a.concat(m.apiAssertions)),i+=m.networkRequests?.length??0,p+=m.apiCalls?.length??0;let y=m.consoleLogs;Array.isArray(y)&&(d+=y.length),c=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2579
+ `),this.startBackgroundFlush();}}}catch{}},fa);}};var ga=new Set(["smoke","regression","nightly","ci"]);function ye(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&ga.has(t))return t}var ma=1048576,ve=[1e3,3e3,9e3],be=3,ya=40*1048576,va=new Set(["e2e","mobile","unit"]);function dt(t){if(t&&t.length>0&&t.every(s=>s.testType==="api")){let s=new Map;for(let i of t){let l=i.apiProtocol??"rest";s.set(l,(s.get(l)??0)+1);}let a="rest",o=0;for(let[i,l]of s)l>o&&(o=l,a=i);return {testType:"api",apiProtocol:a,metadata:{testType:"api",primaryProtocol:a}}}let e=new Map;for(let s of t??[])va.has(s.testType)&&e.set(s.testType,(e.get(s.testType)??0)+1);let r=null,n=0;for(let[s,a]of e)a>n&&(n=a,r=s);return {testType:r??"e2e"}}function ct(t,e,r,n,s,a){let o=a?.cloudPlatform?a.cloudPlatform:n?.provider&&n.provider!=="unknown"?n.provider:"local",i=ye(),l=dt(s),d=l.testType==="api"?l:null,u=d&&s?s.map(f=>f.apiProtocol?f:{...f,apiProtocol:d.apiProtocol}):s,p={runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,environment:o,...i?{runType:i}:{},...d?{testType:d.testType,apiProtocol:d.apiProtocol,metadata:d.metadata}:{testType:l.testType},...u&&u.length>0?{tests:u}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{},...a?.cloudPlatform?{cloudPlatform:a.cloudPlatform}:{},...a?.cloudBuildId?{cloudBuildId:a.cloudBuildId}:{},...a?.cloudSessionId?{cloudSessionId:a.cloudSessionId}:{}};if(p.tests&&p.tests.length>0){let f=JSON.stringify(p);if(Buffer.byteLength(f,"utf-8")>ya){let c=p.tests.map(({consoleLogs:g,networkRequests:h,apiCalls:m,...b})=>b);return {...p,tests:c}}}return p}function lt(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function ut(t){return Array.isArray(t)?t.map(e=>{let r=e.statusCode??e.responseStatusCode??null;return {...e.protocol!=null?{protocol:e.protocol}:{},method:e.method??null,url:e.url??null,statusCode:r,statusText:e.statusText??e.responseStatusText??null,ok:typeof r=="number"?r<400:e.ok??null,durationMs:e.durationMs??e.responseTimeMs??null,bytesIn:typeof e.bytesIn=="number"?e.bytesIn:lt(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:lt(e.requestBody),requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null}}):[]}function pt(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,n=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:lt(e.responseBody),duration:e.responseTimeMs??e.durationMs??0,responseTimeMs:e.responseTimeMs??e.durationMs??0,requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,timestamp:n,startedAt:n}}):[]}function ft(t){if(!Array.isArray(t))return [];let e=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return t.map(r=>{let n=r.status==="failed"?"failed":"passed",s=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,a=r.kind??r.type??"assertion",o=n==="failed"?`expected ${e(r.expected)}, received ${e(r.actual)}`:r.expected!==void 0?`expected ${e(r.expected)}`:null;return {kind:a,description:s??r.description??`${a} assertion`,status:n,detail:o}})}async function we(t){return new Promise(e=>setTimeout(e,t))}function ba(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}async function Wr(t,e,r){for(let n=0;n<be;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<be-1){let a=s.headers.get("Retry-After"),o=a?parseInt(a,10)*1e3:ve[n];!isNaN(o)&&o>0?await we(o):await we(ve[n]);continue}if(s.status>=500&&n<be-1){await we(ve[n]);continue}return s}catch{if(n<be-1){await we(ve[n]);continue}return null}return null}function wa(t){let e=JSON.stringify(t),r={"Content-Type":"application/json"};if(Buffer.byteLength(e,"utf-8")>ma){let n=zlib.gzipSync(Buffer.from(e,"utf-8"));return r["Content-Encoding"]="gzip",{body:n,headers:r}}return {body:e,headers:r}}async function Vr(t,e,r,n){let s=`${t}/runs`,{body:a,headers:o}=wa(r);o.Authorization=`Bearer ${e}`;let i=await Wr(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 Gr(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(ba(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function Jr(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 Kr(t,e,r,n){let s=`${t}/runs/${r}/finalize`;return (await Wr(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}))?.ok??false}function gt(t,e,r,n){let s=`${t}/runs/${r}/finalize`,a=new Date,o={finishedAt:a.toISOString(),duration:a.getTime()-new Date(n).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}function Yr(t,e,r,n){let s=[],a=[],o=null,i=0,l=null,d=0,u=null,p=0,f=t.filter(h=>h.name===core.ATTACHMENT_NAME&&h.body),c=false;if(f.length>0)for(let h of f)try{let m=JSON.parse(h.body.toString());if(core.isTestRelicFilePayload(m)){s=s.concat(m.navigations),a=a.concat(m.apiAssertions),m.networkRequestsFile&&(o=m.networkRequestsFile,i+=m.networkRequestsCount),m.consoleLogsFile&&(l=m.consoleLogsFile,d+=m.consoleLogsCount),m.apiCallsFile&&(u=m.apiCallsFile,p+=m.apiCallsCount),c=!0;continue}if(core.isTestRelicDataPayload(m)){s=s.concat(m.navigations),Array.isArray(m.apiAssertions)&&(a=a.concat(m.apiAssertions)),i+=m.networkRequests?.length??0,p+=m.apiCalls?.length??0;let b=m.consoleLogs;Array.isArray(b)&&(d+=b.length),c=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2580
2580
  `);}return c||(s=e.filter(h=>h.type==="lambdatest-navigation"&&h.description).map(h=>{try{return JSON.parse(h.description)}catch{return null}}).filter(h=>h!==null)),s.length===0&&i===0&&p===0&&!n&&!c&&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.
2581
2581
  `),{navigations:s,apiAssertions:a,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:u,apiCallsCount:p}}function xe(t=process.env){let e=Ca(t.TESTRELIC_CLOUD_PLATFORM);if(e)return {cloudPlatform:e,cloudBuildId:t.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:t.TESTRELIC_CLOUD_SESSION_ID||void 0};if(t.BROWSERSTACK_USERNAME||t.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:t.BROWSERSTACK_BUILD_NAME||t.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:t.BROWSERSTACK_SESSION_ID||void 0};if(t.LT_USERNAME||t.LAMBDATEST_USERNAME||t.LT_ACCESS_KEY||t.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:t.LT_BUILD||t.LAMBDATEST_BUILD||void 0,cloudSessionId:t.LT_SESSION_ID||t.LAMBDATEST_SESSION_ID||void 0};let r=t.PLAYWRIGHT_WS_ENDPOINT;if(r){if(/cdp\.lambdatest\.com/i.test(r))return {cloudPlatform:"lambdatest"};if(/cdp\.browserstack\.com/i.test(r))return {cloudPlatform:"browserstack"}}return {}}function Ca(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var Ia=5,ke=[1e3,3e3,9e3],$=3,La={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip"},ht=0,mt=[];async function Pa(){ht>=Ia&&await new Promise(t=>mt.push(t)),ht++;}function Ea(){ht--,mt.length>0&&mt.shift()();}async function Te(t){return new Promise(e=>setTimeout(e,t))}function Ma(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return La[e]??"application/octet-stream"}function Na(t){try{return fs$1.statSync(t).size}catch{return 0}}async function Fa(t,e,r,n,s){let a=`${t}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:s,type:r.type,sizeBytes:n});for(let i=0;i<$;i++)try{let l=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:o});if(l.ok)return await l.json();if(l.status>=500&&i<$-1){await Te(ke[i]);continue}return null}catch{if(i<$-1){await Te(ke[i]);continue}return null}return null}async function Da(t,e,r,n){for(let s=0;s<$;s++)try{let a=fs$1.createReadStream(e),o=stream.Readable.toWeb(a),i=await fetch(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(n)},body:o,duplex:"half"});if(i.ok)return !0;if(i.status>=500&&s<$-1){await Te(ke[s]);continue}return !1}catch{if(s<$-1){await Te(ke[s]);continue}return false}return false}async function Ba(t,e,r){let n=`${t}/artifacts/confirm`;try{return (await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function Oa(t,e,r,n){let s=Na(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>n*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let a=Ma(r.filePath);await Pa();try{let o=await Fa(t,e,r,s,a);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await Da(o.uploadUrl,r.filePath,a,s))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let l=await Ba(t,e,o.artifactId);return {success:l,storageKey:o.storageKey,artifactId:o.artifactId,error:l?null:"confirm_failed"}}finally{Ea();}}async function Zr(t,e,r,n){let s=new Map,a=r.map(async o=>{let i=await Oa(t,e,o,n);s.set(o.filePath,i);});return await Promise.allSettled(a),s}function yt(t){let r=t.getGitMetadata()?.remoteUrl;return r?re(r):t.getConfig()?.projectName??ne(process.cwd())}async function Qr(t,e,r,n,s){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let o=t.getGitMetadata(),i=N(),l=xe(),d=ye();return (await Gr(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:yt(t),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:n,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:s??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{},testType:"e2e"}))?.runId??null}var qa=true,Ha=50;async function Ua(t,e,r,n){let s=new Map;if(!(e?.uploadArtifacts??qa)||!await t.ensureValidToken())return s;let i=[],l=new Map;for(let c of n){if(c.artifacts.screenshot){let g=path.join(c.outputDir,c.artifacts.screenshot);i.push({filePath:g,runId:r,testId:c.testId,type:"screenshot"}),l.set(g,{testId:c.testId,field:"screenshot"});}if(c.artifacts.video){let g=path.join(c.outputDir,c.artifacts.video);i.push({filePath:g,runId:r,testId:c.testId,type:"video"}),l.set(g,{testId:c.testId,field:"video"});}}if(i.length===0)return s;let d=e?.artifactMaxSizeMb??Ha,u=await Zr(t.getEndpoint(),t.getAccessToken(),i,d),p=new Map;for(let[c,g]of u){if(!g.success||!g.storageKey)continue;let h=l.get(c);if(!h)continue;let m=p.get(h.testId)??{};h.field==="screenshot"&&(m.screenshotKey=g.storageKey),h.field==="video"&&(m.videoKey=g.storageKey),p.set(h.testId,m);}for(let c of n){let g=p.get(c.testId);s.set(c.testId,{...c.artifacts,...g?.screenshotKey?{screenshotKey:g.screenshotKey}:{},...g?.videoKey?{videoKey:g.videoKey}:{}});}let f=Array.from(u.values()).filter(c=>c.success).length;return f>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${f} artifact(s) to cloud storage.
2582
- `),s}async function vt(t,e,r,n,s,a,o,i,l,d,u){try{if(t.isCloudMode()&&s&&(r==="realtime"||r==="both")){let f=await t.ensureValidToken(),c=t.getGitMetadata(),g=dt(u),h={finishedAt:o,duration:i,summary:l,...c?.commitMessage?{commitMessage:c.commitMessage}:{},testType:g.testType,...g.testType==="api"?{apiProtocol:g.apiProtocol,metadata:g.metadata}:{}};if(f){if(!await Kr(t.getEndpoint(),t.getAccessToken(),s,h)){let y=e?.queueDirectory??".testrelic/queue";se(y,n,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",h,{"Content-Type":"application/json"});}}else {let m=e?.queueDirectory??".testrelic/queue";se(m,n,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",h,{"Content-Type":"application/json"});}}let p=new Map;if(t.isCloudMode()&&d&&d.length>0&&(p=await Ua(t,e,n,d)),t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await t.ensureValidToken()){let c=t.getGitMetadata(),g=N(),h=yt(t),m=za(a,p),y=ct(m,h,c,g,u,xe()),T=await Vr(t.getEndpoint(),t.getAccessToken(),y,async()=>await t.ensureValidToken()?t.getAccessToken():null);if(!T.success){let v=T,b=e?.queueDirectory??".testrelic/queue";se(b,n,"batch",v.reason,v.targetEndpoint,v.method,v.payload,{"Content-Type":"application/json"});}}else {let c=e?.queueDirectory??".testrelic/queue",g=t.getGitMetadata(),h=N(),m=yt(t),y=ct(a,m,g,h,void 0,xe());se(c,n,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",y,{"Content-Type":"application/json"});}await t.dispose();}catch{try{await t.dispose();}catch{}}}function za(t,e){if(e.size===0)return t;let r=t.timeline.map(n=>{let s=n.testId;if(!s)return n;let a=e.get(s);return a?{...n,...a.screenshotKey?{screenshotKey:a.screenshotKey}:{},...a.videoKey?{videoKey:a.videoKey}:{}}:n});return {...t,timeline:r}}function H(t){try{return fs$1.readFileSync(t,"utf-8").split(`
2582
+ `),s}async function vt(t,e,r,n,s,a,o,i,l,d,u){try{if(t.isCloudMode()&&s&&(r==="realtime"||r==="both")){let f=await t.ensureValidToken(),c=t.getGitMetadata(),g=dt(u),h={finishedAt:o,duration:i,summary:l,...c?.commitMessage?{commitMessage:c.commitMessage}:{},testType:g.testType,...g.testType==="api"?{apiProtocol:g.apiProtocol,metadata:g.metadata}:{}};if(f){if(!await Kr(t.getEndpoint(),t.getAccessToken(),s,h)){let b=e?.queueDirectory??".testrelic/queue";se(b,n,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",h,{"Content-Type":"application/json"});}}else {let m=e?.queueDirectory??".testrelic/queue";se(m,n,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",h,{"Content-Type":"application/json"});}}let p=new Map;if(t.isCloudMode()&&d&&d.length>0&&(p=await Ua(t,e,n,d)),t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await t.ensureValidToken()){let c=t.getGitMetadata(),g=N(),h=yt(t),m=za(a,p),b=ct(m,h,c,g,u,xe()),T=await Vr(t.getEndpoint(),t.getAccessToken(),b,async()=>await t.ensureValidToken()?t.getAccessToken():null);if(!T.success){let y=T,v=e?.queueDirectory??".testrelic/queue";se(v,n,"batch",y.reason,y.targetEndpoint,y.method,y.payload,{"Content-Type":"application/json"});}}else {let c=e?.queueDirectory??".testrelic/queue",g=t.getGitMetadata(),h=N(),m=yt(t),b=ct(a,m,g,h,void 0,xe());se(c,n,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",b,{"Content-Type":"application/json"});}await t.dispose();}catch{try{await t.dispose();}catch{}}}function za(t,e){if(e.size===0)return t;let r=t.timeline.map(n=>{let s=n.testId;if(!s)return n;let a=e.get(s);return a?{...n,...a.screenshotKey?{screenshotKey:a.screenshotKey}:{},...a.videoKey?{videoKey:a.videoKey}:{}}:n});return {...t,timeline:r}}function H(t){try{return fs$1.readFileSync(t,"utf-8").split(`
2583
2583
  `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function wt(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 Ka(t,e,r){let n=`${t}::${e}::${r}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,16)}function Ya(t){return t.length<=3?"":t[t.length-2]}function Za(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function Xa(t){return process.env.BROWSERSTACK_USERNAME?"BrowserStack":t?{"github-actions":"GitHub Actions","gitlab-ci":"GitLab CI",jenkins:"Jenkins",circleci:"CircleCI","bitbucket-pipelines":"Bitbucket Pipelines"}[t.provider]??"CI":"Local"}function Qa(){let t=os$1.platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function ei(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:n}=e;if(n){let a=n.toLowerCase();return a==="chrome"||a==="chrome-stable"?"Chrome":a.startsWith("chrome-beta")?"Chrome Beta":a.startsWith("chrome-dev")?"Chrome Dev":a.startsWith("chrome-canary")?"Chrome Canary":a==="msedge"||a==="msedge-stable"?"Microsoft Edge":a.startsWith("msedge-beta")?"Edge Beta":a.startsWith("msedge-dev")?"Edge Dev":a.startsWith("msedge-canary")?"Edge Canary":n}if(r){let a=r.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":r}let s=e.defaultBrowserType;if(s){let a=s.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":s}}function ti(t,e,r){let n=r.parent?.project?.(),s="unknown";n!==void 0&&(n.use.isMobile===true?s="mobile":s="e2e");let a=["e2e","api","unit","mobile"];for(let l of a)if(t.some(d=>d===`@${l}`||d===l))return l;let o=e.replace(/\\/g,"/"),i=["e2e","api","unit"];for(let l of i)if(o.includes(`/${l}/`))return l;return s}var ri="__testrelic_api_config";function ni(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var Ce=class{constructor(e){this.rootDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.pendingArtifactEntries=[];this.detectedOs="";this.detectedSource="";this.cloudTestsBuffer=[];this.activeReportMode="embedded";this.streamingWriter=null;this.testIndex=[];this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0};this.config=$t(e),this.apiConfig=jt(e);}async onBegin(e,r){try{if(this.rootDir=e.rootDir,this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??crypto.randomUUID(),this.config.reportMode==="auto"){let a=r.allTests().length;this.activeReportMode=a>=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)
2584
- `),this.activeReportMode==="streaming"){let a=path.dirname(this.config.outputPath);this.streamingWriter=new Z(a);let o=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let i={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(i);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let i=this.cloudClient.getAccessToken();i&&gt(this.cloudClient.getEndpoint(),i,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}if(this.config.includeArtifacts){let a=path.dirname(this.config.outputPath);this.runTimestamp=xr(path.join(a,"artifacts"));try{Rr(path.join(a,"artifacts"));}catch{}}let s=N();this.detectedOs=Qa(),this.detectedSource=Xa(s);try{this.cloudClient=new me(this.config.cloud),await this.cloudClient.initialize(),this.cloudRunId=await Qr(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource);}catch{this.cloudClient?.switchToLocalMode("init_error");}if(this.activeReportMode!=="streaming"){let a=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let o=this.cloudClient.getAccessToken();o&&gt(this.cloudClient.getEndpoint(),o,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",a),process.on("SIGINT",a);}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:ri,description:ni(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let n=r,s=e.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=wt(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??""),d=Yr(n.attachments,e.annotations,e.title,a==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0);let u=null;if(a==="failed"||a==="flaky"){let S=(a==="flaky"?e.results.find(O=>O.status!=="passed")?.errors??[]:n.errors)[0];if(S){let O=Vt(this.config.redactPatterns),J=S.location?.line??null,K=null;this.config.includeCodeSnippets&&J!==null&&S.location?.file&&(K=Wt(S.location.file,J,this.config.codeContextLines),K&&(K=O(K))),u={message:O(S.message??"Unknown error"),line:J,code:K,stack:this.config.includeStackTrace&&S.stack?O(S.stack):null};}}let p=e.titlePath().filter(Boolean),f=path.relative(this.rootDir||".",e.location.file),c=Ya(p),g=p.join(" > "),h=f,m=Ka(h,c,g),y=ti(l,h,e),T=y!=="mobile"&&d.apiCallsCount>0?"api":y,v=s==="flaky",b=Za(e.results),C=wt(e.expectedStatus),w=wt(n.status),k=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let R=path.dirname(this.config.outputPath),S=p[p.length-1]??e.title;k=kr(n.attachments,S,n.retry,R,this.runTimestamp||void 0);}let A=this.config.includeActionSteps&&n.steps?Pr(n.steps,n.startTime):null,z=ei(e),P={titlePath:p,title:g,status:a,duration:n.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:n.retry,tags:l,failure:u,specFile:f,navigations:d.navigations,testId:m,filePath:h,suiteName:c,testType:T,isFlaky:v,retryStatus:b,expectedStatus:C,actualStatus:w,artifacts:k,apiAssertions:d.apiAssertions,actions:A,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount,browser:z,os:this.detectedOs||void 0,source:this.detectedSource||void 0},At=d.consoleLogsFile&&d.consoleLogsCount>0?H(d.consoleLogsFile):void 0,Ie=d.networkRequestsFile&&d.networkRequestsCount>0?H(d.networkRequestsFile):void 0,ae=d.apiCallsFile&&d.apiCallsCount>0?H(d.apiCallsFile):void 0,_t=ae?ut(ae):void 0,It=!Ie&&ae?pt(ae):void 0,Lt=d.apiAssertions&&d.apiAssertions.length>0?ft(d.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:m,title:g,status:a,duration:n.duration,suiteName:c,filePath:h,testType:T,isFlaky:v,startedAt:o,completedAt:i,tags:l,failure:u,retry:n.retry,retryCount:e.results.length-1,retryStatus:b,browser:z,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...A&&A.length>0?{actions:A}:{},...At?{consoleLogs:At}:{},...Ie?{networkRequests:Ie}:It?{networkRequests:It}:{},..._t?{apiCalls:_t}:{},...Lt?{protocolAssertions:Lt}:{}});try{let R=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(R==="realtime"||R==="both")){let S=this.cloudClient.getAccessToken();S&&Jr(this.cloudClient.getEndpoint(),S,this.cloudRunId,this.buildCloudTestPayload(P));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let R=Le(h,p,e.id??"",n.retry),S=n.retry===e.results.length-1,O={id:R,navigations:d.navigations,apiAssertions:d.apiAssertions,actions:A??[],artifacts:k,failureDiagnostic:u,hasNetworkFile:d.networkRequestsFile!==null,networkRequestsCount:d.networkRequestsCount,hasConsoleFile:d.consoleLogsFile!==null,consoleLogsCount:d.consoleLogsCount,hasApiCallsFile:d.apiCallsFile!==null,apiCallsCount:d.apiCallsCount,startedAt:o};this.streamingWriter.writeTestDetail(R,O,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let J={id:R,title:p[p.length-1]??e.title,titlePath:p,filePath:h,status:a,duration:n.duration,project:p[1]??"",retryIndex:n.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:k!==null,hasActionSteps:(A?.length??0)>0,errorMessage:u?.message?.split(`
2584
+ `),this.activeReportMode==="streaming"){let a=path.dirname(this.config.outputPath);this.streamingWriter=new Z(a);let o=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let i={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(i);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let i=this.cloudClient.getAccessToken();i&&gt(this.cloudClient.getEndpoint(),i,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}if(this.config.includeArtifacts){let a=path.dirname(this.config.outputPath);this.runTimestamp=xr(path.join(a,"artifacts"));try{Rr(path.join(a,"artifacts"));}catch{}}let s=N();this.detectedOs=Qa(),this.detectedSource=Xa(s);try{this.cloudClient=new me(this.config.cloud),await this.cloudClient.initialize(),this.cloudRunId=await Qr(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource);}catch{this.cloudClient?.switchToLocalMode("init_error");}if(this.activeReportMode!=="streaming"){let a=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let o=this.cloudClient.getAccessToken();o&&gt(this.cloudClient.getEndpoint(),o,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",a),process.on("SIGINT",a);}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:ri,description:ni(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let n=r,s=e.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=wt(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??""),d=Yr(n.attachments,e.annotations,e.title,a==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0);let u=null;if(a==="failed"||a==="flaky"){let S=(a==="flaky"?e.results.find(O=>O.status!=="passed")?.errors??[]:n.errors)[0];if(S){let O=Vt(this.config.redactPatterns),J=S.location?.line??null,K=null;this.config.includeCodeSnippets&&J!==null&&S.location?.file&&(K=Wt(S.location.file,J,this.config.codeContextLines),K&&(K=O(K))),u={message:O(S.message??"Unknown error"),line:J,code:K,stack:this.config.includeStackTrace&&S.stack?O(S.stack):null};}}let p=e.titlePath().filter(Boolean),f=path.relative(this.rootDir||".",e.location.file),c=Ya(p),g=p.join(" > "),h=f,m=Ka(h,c,g),b=ti(l,h,e),T=b!=="mobile"&&d.apiCallsCount>0?"api":b,y=s==="flaky",v=Za(e.results),C=wt(e.expectedStatus),w=wt(n.status),k=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let R=path.dirname(this.config.outputPath),S=p[p.length-1]??e.title;k=kr(n.attachments,S,n.retry,R,this.runTimestamp||void 0);}let A=this.config.includeActionSteps&&n.steps?Pr(n.steps,n.startTime):null,z=ei(e),P={titlePath:p,title:g,status:a,duration:n.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:n.retry,tags:l,failure:u,specFile:f,navigations:d.navigations,testId:m,filePath:h,suiteName:c,testType:T,isFlaky:y,retryStatus:v,expectedStatus:C,actualStatus:w,artifacts:k,apiAssertions:d.apiAssertions,actions:A,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount,browser:z,os:this.detectedOs||void 0,source:this.detectedSource||void 0},At=d.consoleLogsFile&&d.consoleLogsCount>0?H(d.consoleLogsFile):void 0,Ie=d.networkRequestsFile&&d.networkRequestsCount>0?H(d.networkRequestsFile):void 0,ae=d.apiCallsFile&&d.apiCallsCount>0?H(d.apiCallsFile):void 0,_t=ae?ut(ae):void 0,It=!Ie&&ae?pt(ae):void 0,Lt=d.apiAssertions&&d.apiAssertions.length>0?ft(d.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:m,title:g,status:a,duration:n.duration,suiteName:c,filePath:h,testType:T,isFlaky:y,startedAt:o,completedAt:i,tags:l,failure:u,retry:n.retry,retryCount:e.results.length-1,retryStatus:v,browser:z,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...A&&A.length>0?{actions:A}:{},...At?{consoleLogs:At}:{},...Ie?{networkRequests:Ie}:It?{networkRequests:It}:{},..._t?{apiCalls:_t}:{},...Lt?{protocolAssertions:Lt}:{}});try{let R=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(R==="realtime"||R==="both")){let S=this.cloudClient.getAccessToken();S&&Jr(this.cloudClient.getEndpoint(),S,this.cloudRunId,this.buildCloudTestPayload(P));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let R=Le(h,p,e.id??"",n.retry),S=n.retry===e.results.length-1,O={id:R,navigations:d.navigations,apiAssertions:d.apiAssertions,actions:A??[],artifacts:k,failureDiagnostic:u,hasNetworkFile:d.networkRequestsFile!==null,networkRequestsCount:d.networkRequestsCount,hasConsoleFile:d.consoleLogsFile!==null,consoleLogsCount:d.consoleLogsCount,hasApiCallsFile:d.apiCallsFile!==null,apiCallsCount:d.apiCallsCount,startedAt:o};this.streamingWriter.writeTestDetail(R,O,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let J={id:R,title:p[p.length-1]??e.title,titlePath:p,filePath:h,status:a,duration:n.duration,project:p[1]??"",retryIndex:n.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:k!==null,hasActionSteps:(A?.length??0)>0,errorMessage:u?.message?.split(`
2585
2585
  `)[0]??null,networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:A?.length??0,isRetry:!S};if(this.testIndex.push(J),S)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+=d.apiCallsCount,this.summaryCounters.totalAssertions+=d.apiAssertions.length,this.summaryCounters.totalNavigations+=d.navigations.length,this.summaryCounters.totalNetworkRequests+=d.networkRequestsCount,this.summaryCounters.totalConsoleLogs+=d.consoleLogsCount,this.summaryCounters.totalActionSteps+=A?.length??0,k&&this.pendingArtifactEntries.push({testId:m,artifacts:k,outputDir:path.dirname(this.config.outputPath)}),P.actions=null,P.apiAssertions=null,P.navigations=[],P.artifacts=null,P.failure=null,P.networkRequestsFile=null,P.consoleLogsFile=null,P.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(P),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(e){try{let r=new Date().toISOString(),n=new Date(this.startedAt).getTime(),a=new Date(r).getTime()-n,o=this.activeReportMode==="streaming"?this.testIndex.some(l=>l.status!=="skipped"):this.collectedTests.some(l=>l.status!=="skipped");!this.fixtureDataReceived&&o&&process.stderr.write(`
2586
2586
  \u26A0 TestRelic: No fixture data received from any test.
2587
2587
  To enable network logs, video sync, and timeline tracking, import the TestRelic fixture:
@@ -2589,17 +2589,17 @@ ${s}
2589
2589
  instead of:
2590
2590
  import { test, expect } from '@playwright/test';
2591
2591
 
2592
- `),await wr();let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let l=path.dirname(this.config.outputPath);i=Cr(l,this.runTimestamp);let d=path.join(l,"artifact-manifest.json"),u=JSON.stringify(i),p=d+".tmp";fs$1.writeFileSync(p,u,"utf-8"),fs$1.renameSync(p,d);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await this.finalizeStreamingReport(r,a,e,i);else {let l=this.buildTimeline(),d=new Map;for(let c of this.collectedTests){let g=d.get(c.testId);(!g||c.retry>g.retry)&&d.set(c.testId,c);}let u=Array.from(d.values()),p=Lr(u,l.length),f={schemaVersion:ie,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:p,ci:N(),metadata:this.config.metadata,timeline:l,shardRunIds:null};if(this.writeReport(f),await Ge(f,this.config,i),Qe(p,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let c=this.collectArtifactEntries(),g=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await vt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,f,r,a,p,c,g);}}}catch{}}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=path.dirname(this.config.outputPath),r=[];for(let n of this.collectedTests)n.artifacts&&r.push({testId:n.testId,artifacts:n.artifacts,outputDir:e});return r}async finalizeStreamingReport(e,r,n,s){if(!this.streamingWriter)return;let{totalApiCalls:a,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:u}=this.summaryCounters;this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:a,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:u};let p=new Map,f=new Map;for(let b of this.testIndex){let C=`${b.filePath}::${b.titlePath.join(" > ")}`,w=p.get(C);(w===void 0||b.retryIndex>w)&&p.set(C,b.retryIndex);}let c=0;for(let b of this.testIndex){let C=`${b.filePath}::${b.titlePath.join(" > ")}`,w=p.get(C);if(b.isRetry=b.retryIndex<w,b.isRetry)continue;switch(c++,this.summaryCounters.total++,b.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}let k=f.get(b.filePath);switch(k||(k={filePath:b.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},f.set(b.filePath,k)),k.total++,b.status){case "passed":k.passed++;break;case "failed":k.failed++;break;case "flaky":k.flaky++;break;case "skipped":k.skipped++;break;case "timedout":k.timedOut++;break}}let g=Array.from(f.values());this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let h={reporterTotal:this.summaryCounters.total,indexTotal:c,playwrightStatus:n.status,isValid:this.summaryCounters.total===c};h.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${h.reporterTotal}, index: ${h.indexTotal}
2593
- `);let m={total:this.summaryCounters.total,passed:this.summaryCounters.passed,failed:this.summaryCounters.failed,flaky:this.summaryCounters.flaky,skipped:this.summaryCounters.skipped,timedout:this.summaryCounters.timedOut,totalApiCalls:this.summaryCounters.totalApiCalls,uniqueApiUrls:0,apiCallsByMethod:{},apiCallsByStatusRange:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},apiResponseTime:null,totalAssertions:this.summaryCounters.totalAssertions,passedAssertions:0,failedAssertions:0,totalNavigations:this.summaryCounters.totalNavigations,uniqueNavigationUrls:0,totalTimelineSteps:this.testIndex.length,totalActionSteps:this.summaryCounters.totalActionSteps,actionStepsByCategory:{}},y={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:g,enrichedSummary:m,validation:h,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(y);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 Ge(this.buildStreamingReport(y,m,e,r),this.config,s),Qe(m,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let v=this.streamingWriter.getReportDir();if(process.stderr.write(`[testrelic] Streaming report written to ${v}
2592
+ `),await wr();let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let l=path.dirname(this.config.outputPath);i=Cr(l,this.runTimestamp);let d=path.join(l,"artifact-manifest.json"),u=JSON.stringify(i),p=d+".tmp";fs$1.writeFileSync(p,u,"utf-8"),fs$1.renameSync(p,d);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await this.finalizeStreamingReport(r,a,e,i);else {let l=this.buildTimeline(),d=new Map;for(let c of this.collectedTests){let g=d.get(c.testId);(!g||c.retry>g.retry)&&d.set(c.testId,c);}let u=Array.from(d.values()),p=Lr(u,l.length),f={schemaVersion:ie,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:p,ci:N(),metadata:this.config.metadata,timeline:l,shardRunIds:null};if(this.writeReport(f),await Ge(f,this.config,i),Qe(p,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let c=this.collectArtifactEntries(),g=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await vt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,f,r,a,p,c,g);}}}catch{}}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=path.dirname(this.config.outputPath),r=[];for(let n of this.collectedTests)n.artifacts&&r.push({testId:n.testId,artifacts:n.artifacts,outputDir:e});return r}async finalizeStreamingReport(e,r,n,s){if(!this.streamingWriter)return;let{totalApiCalls:a,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:u}=this.summaryCounters;this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:a,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:u};let p=new Map,f=new Map;for(let v of this.testIndex){let C=`${v.filePath}::${v.titlePath.join(" > ")}`,w=p.get(C);(w===void 0||v.retryIndex>w)&&p.set(C,v.retryIndex);}let c=0;for(let v of this.testIndex){let C=`${v.filePath}::${v.titlePath.join(" > ")}`,w=p.get(C);if(v.isRetry=v.retryIndex<w,v.isRetry)continue;switch(c++,this.summaryCounters.total++,v.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}let k=f.get(v.filePath);switch(k||(k={filePath:v.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},f.set(v.filePath,k)),k.total++,v.status){case "passed":k.passed++;break;case "failed":k.failed++;break;case "flaky":k.flaky++;break;case "skipped":k.skipped++;break;case "timedout":k.timedOut++;break}}let g=Array.from(f.values());this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let h={reporterTotal:this.summaryCounters.total,indexTotal:c,playwrightStatus:n.status,isValid:this.summaryCounters.total===c};h.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${h.reporterTotal}, index: ${h.indexTotal}
2593
+ `);let m={total:this.summaryCounters.total,passed:this.summaryCounters.passed,failed:this.summaryCounters.failed,flaky:this.summaryCounters.flaky,skipped:this.summaryCounters.skipped,timedout:this.summaryCounters.timedOut,totalApiCalls:this.summaryCounters.totalApiCalls,uniqueApiUrls:0,apiCallsByMethod:{},apiCallsByStatusRange:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},apiResponseTime:null,totalAssertions:this.summaryCounters.totalAssertions,passedAssertions:0,failedAssertions:0,totalNavigations:this.summaryCounters.totalNavigations,uniqueNavigationUrls:0,totalTimelineSteps:this.testIndex.length,totalActionSteps:this.summaryCounters.totalActionSteps,actionStepsByCategory:{}},b={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:g,enrichedSummary:m,validation:h,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(b);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 Ge(this.buildStreamingReport(b,m,e,r),this.config,s),Qe(m,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let y=this.streamingWriter.getReportDir();if(process.stderr.write(`[testrelic] Streaming report written to ${y}
2594
2594
  [testrelic] ${this.testIndex.length} test detail files on disk
2595
- [testrelic] View report: npx testrelic serve ${v}
2595
+ [testrelic] View report: npx testrelic serve ${y}
2596
2596
  `),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
2597
- `),this.streamingWriter.dispose(),this.cloudClient){let b=this.buildStreamingReport(y,m,e,r),C=this.collectArtifactEntries(),w=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await vt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,b,e,r,m,C,w);}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(e,r,n,s){return {schemaVersion:ie,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:n,totalDuration:s,summary:r,ci:N(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let e=process.memoryUsage(),r=e.heapUsed/1024/1024;if(r<200)return;let n=e.heapUsed/e.heapTotal;n>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
2597
+ `),this.streamingWriter.dispose(),this.cloudClient){let v=this.buildStreamingReport(b,m,e,r),C=this.collectArtifactEntries(),w=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await vt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,v,e,r,m,C,w);}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(e,r,n,s){return {schemaVersion:ie,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:n,totalDuration:s,summary:r,ci:N(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let e=process.memoryUsage(),r=e.heapUsed/1024/1024;if(r<200)return;let n=e.heapUsed/e.heapTotal;n>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
2598
2598
  `),this.switchToStreamingMode()):n>.8&&process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
2599
2599
  `);}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=path.dirname(this.config.outputPath);this.streamingWriter=new Z(e);for(let r of this.collectedTests){let n=Le(r.filePath,r.titlePath,r.testId,r.retry),s={id:n,navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(n,s,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let a={id:n,title:r.titlePath[r.titlePath.length-1]??r.title,titlePath:r.titlePath,filePath:r.filePath,status:r.status,duration:r.duration,project:r.titlePath[1]??"",retryIndex:r.retry,tags:r.tags,hasNetworkData:r.networkRequestsCount>0,hasConsoleData:r.consoleLogsCount>0,hasArtifacts:r.artifacts!==null,hasActionSteps:(r.actions?.length??0)>0,errorMessage:r.failure?.message?.split(`
2600
2600
  `)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,isRetry:!1};switch(this.testIndex.push(a),this.summaryCounters.total++,r.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.summaryCounters.totalApiCalls+=r.apiCallsCount,this.summaryCounters.totalAssertions+=r.apiAssertions?.length??0,this.summaryCounters.totalNavigations+=r.navigations?.length??0,this.summaryCounters.totalNetworkRequests+=r.networkRequestsCount,this.summaryCounters.totalConsoleLogs+=r.consoleLogsCount,this.summaryCounters.totalActionSteps+=r.actions?.length??0;}this.collectedTests.length=0;}catch{}}buildTimeline(){let e=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return Ir(e,{navigationTypes:this.config.navigationTypes})}readJsonlFile(e){if(!e)return null;let r=H(e);return r.length>0?r:null}toTestResult(e,r){let n=null,s=null,a=null;return r?.loadFiles&&(n=this.readJsonlFile(e.networkRequestsFile),s=this.readJsonlFile(e.consoleLogsFile),a=this.readJsonlFile(e.apiCallsFile)),{title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:n,apiCalls:a,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:s}}buildCloudTestPayload(e){let r={title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retry:e.retry,retryCount:e.retryCount,retryStatus:e.retryStatus,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,actions:e.actions??[],navigations:e.navigations??[],steps:e.actions??[],browser:e.browser,os:e.os,source:e.source};if(e.apiAssertions&&e.apiAssertions.length>0&&(r.protocolAssertions=ft(e.apiAssertions)),e.consoleLogsFile&&(r.consoleLogs=H(e.consoleLogsFile)),e.networkRequestsFile&&(r.networkRequests=H(e.networkRequestsFile)),e.apiCallsFile){let n=H(e.apiCallsFile);r.apiCalls=ut(n),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=pt(n));}return r}writeReport(e){try{let r=JSON.stringify(e),n=this.config.outputPath,s=path.dirname(n);fs$1.mkdirSync(s,{recursive:!0});let a=n+".tmp";fs$1.writeFileSync(a,r,"utf-8"),fs$1.renameSync(a,n);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2601
- `);}}};var li=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function di(t){let e=t.toLowerCase();return li.some(r=>e.includes(r))}var Se=class t{constructor(e,r){this.page=e;this.records=[];this.listeners=[];this.currentNetworkCounter=null;this.pendingRequests=new Map;this.networkWriter=null;this.consoleWriter=null;this.pendingBodyReads=[];this.requestIdCounter=0;this.networkRequestCount=0;this.consoleLogCount=0;this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=e.goto.bind(e),this.origGoBack=e.goBack.bind(e),this.origGoForward=e.goForward.bind(e),this.origReload=e.reload.bind(e);try{this.includeNetworkStats&&(this.networkWriter=new E("network")),this.consoleWriter=new E("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,e]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:e.url,method:e.method,resourceType:e.resourceType,statusCode:0,responseTimeMs:Date.now()-e.startTimeMs,startedAt:e.startedAt,requestHeaders:e.headers,requestBody:e.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:e.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(e){switch(e){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.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(r=>({url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:e,networkRequestsFile:this.networkWriter?.getCount()?this.networkWriter.getPath():null,networkRequestsCount:this.networkWriter?.getCount()??0,consoleLogsFile:this.consoleWriter?.getCount()?this.consoleWriter.getPath():null,consoleLogsCount:this.consoleWriter?.getCount()??0}}async flushLegacyAnnotations(e){}dispose(){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.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}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 u=a.location();u&&u.url&&(l=`${u.url}:${u.lineNumber}:${u.columnNumber}`);}catch{}let d=t.mapConsoleType(o);this.consoleWriter&&(this.consoleWriter.append({level:d,text:i,timestamp:new Date().toISOString(),location:l}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=i=>{this.currentNetworkCounter&&this.currentNetworkCounter.totalRequests++;try{let l=i,d=String(this.requestIdCounter++),u=l.postData()??null,p={url:l.url(),method:l.method(),resourceType:this.mapResourceType(l.resourceType()),headers:l.headers(),postData:u,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now()};this.pendingRequests.set(d,p),i.__testrelic_id=d;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=i=>{try{let l=i;if(this.currentNetworkCounter){let y=l.status();y>=400&&(this.currentNetworkCounter.failedRequests++,this.currentNetworkCounter.failedRequestUrls.push(y+" "+l.url()));let T=l.headers()["content-length"];T&&(this.currentNetworkCounter.totalBytes+=parseInt(T,10)||0);let v=l.request().resourceType(),b=this.mapResourceType(v);this.currentNetworkCounter.byType[b]++;}let d=l.request().__testrelic_id;if(!d)return;let u=this.pendingRequests.get(d);if(!u)return;this.pendingRequests.delete(d);let p=Date.now()-u.startTimeMs,f=l.headers(),c=f["content-type"]??null,g=parseInt(f["content-length"]??"0",10)||0,h=c?!di(c):!1,m=(async()=>{let y=null;if(!h)try{y=(await l.body()).toString("utf-8");}catch{}let T={url:u.url,method:u.method,resourceType:u.resourceType,statusCode:l.status(),responseTimeMs:p,startedAt:u.startedAt,requestHeaders:u.headers,requestBody:u.postData,responseBody:y,responseHeaders:f,contentType:c,responseSize:g,requestBodyTruncated:u.postDataTruncated,responseBodyTruncated:!1,isBinary:h,error:null};this.networkWriter&&(this.networkWriter.append(T),this.networkRequestCount++);})();this.pendingBodyReads.push(m);}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,d=l.__testrelic_id;if(!d)return;let u=this.pendingRequests.get(d);if(!u)return;this.pendingRequests.delete(d);let p={url:u.url,method:u.method,resourceType:u.resourceType,statusCode:0,responseTimeMs:Date.now()-u.startTimeMs,startedAt:u.startedAt,requestHeaders:u.headers,requestBody:u.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:u.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:l.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(p),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",o),this.listeners.push({event:"requestfailed",handler:o});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let e=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(e,r){this.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 kt=Symbol.for("__testrelic_call_id"),pi="__testrelic_api_assertions",U=new WeakMap,W=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:pi,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}},rn=new Map;function fi(t){let e=rn.get(t);if(e)return e;try{let r=t.startsWith("file://")?url.fileURLToPath(t):t,s=fs$1.readFileSync(r,"utf-8").split(`
2601
+ `);}}};var li=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function di(t){let e=t.toLowerCase();return li.some(r=>e.includes(r))}var Se=class t{constructor(e,r){this.page=e;this.records=[];this.listeners=[];this.navCounters=[];this.pendingRequests=new Map;this.networkWriter=null;this.consoleWriter=null;this.pendingBodyReads=[];this.requestIdCounter=0;this.networkRequestCount=0;this.consoleLogCount=0;this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=e.goto.bind(e),this.origGoBack=e.goBack.bind(e),this.origGoForward=e.goForward.bind(e),this.origReload=e.reload.bind(e);try{this.includeNetworkStats&&(this.networkWriter=new E("network")),this.consoleWriter=new E("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,e]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:e.url,method:e.method,resourceType:e.resourceType,statusCode:0,responseTimeMs:Date.now()-e.startTimeMs,startedAt:e.startedAt,requestHeaders:e.headers,requestBody:e.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:e.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(e){switch(e){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.assembleNetworkStats();let e=this.records.map(r=>({url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:e,networkRequestsFile:this.networkWriter?.getCount()?this.networkWriter.getPath():null,networkRequestsCount:this.networkWriter?.getCount()??0,consoleLogsFile:this.consoleWriter?.getCount()?this.consoleWriter.getPath():null,consoleLogsCount:this.consoleWriter?.getCount()??0}}async flushLegacyAnnotations(e){}dispose(){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.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.assembleNetworkStats(),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 u=a.location();u&&u.url&&(l=`${u.url}:${u.lineNumber}:${u.columnNumber}`);}catch{}let d=t.mapConsoleType(o);this.consoleWriter&&(this.consoleWriter.append({level:d,text:i,timestamp:new Date().toISOString(),location:l}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=i=>{let l=this.records.length-1,d=this.counterForNav(l);d&&d.totalRequests++;try{let u=i,p=String(this.requestIdCounter++),f=u.postData()??null,c={url:u.url(),method:u.method(),resourceType:this.mapResourceType(u.resourceType()),headers:u.headers(),postData:f,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now(),navIndex:l};this.pendingRequests.set(p,c),i.__testrelic_id=p;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=i=>{try{let l=i,d=l.request().__testrelic_id,u=d?this.pendingRequests.get(d):void 0,p=this.counterForNav(u?u.navIndex:this.records.length-1);if(p){let T=l.status();T>=400&&(p.failedRequests++,p.failedRequestUrls.push(T+" "+l.url()));let y=l.headers()["content-length"];y&&(p.totalBytes+=parseInt(y,10)||0);let v=l.request().resourceType(),C=this.mapResourceType(v);p.byType[C]++;}if(!d||!u)return;this.pendingRequests.delete(d);let f=Date.now()-u.startTimeMs,c=l.headers(),g=c["content-type"]??null,h=parseInt(c["content-length"]??"0",10)||0,m=g?!di(g):!1,b=(async()=>{let T=null;if(!m)try{T=(await l.body()).toString("utf-8");}catch{}let y={url:u.url,method:u.method,resourceType:u.resourceType,statusCode:l.status(),responseTimeMs:f,startedAt:u.startedAt,requestHeaders:u.headers,requestBody:u.postData,responseBody:T,responseHeaders:c,contentType:g,responseSize:h,requestBodyTruncated:u.postDataTruncated,responseBodyTruncated:!1,isBinary:m,error:null};this.networkWriter&&(this.networkWriter.append(y),this.networkRequestCount++);})();this.pendingBodyReads.push(b);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});let o=i=>{let l=i.__testrelic_id,d=l?this.pendingRequests.get(l):void 0,u=this.counterForNav(d?d.navIndex:this.records.length-1);if(u){u.failedRequests++;try{let p=i;u.failedRequestUrls.push("ERR "+p.url());}catch{}}try{let p=i;if(!l||!d)return;this.pendingRequests.delete(l);let f={url:d.url,method:d.method,resourceType:d.resourceType,statusCode:0,responseTimeMs:Date.now()-d.startTimeMs,startedAt:d.startedAt,requestHeaders:d.headers,requestBody:d.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:d.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:p.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(f),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",o),this.listeners.push({event:"requestfailed",handler:o});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let e=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(e,r){this.records.push({url:e,navigationType:r,timestamp:new Date().toISOString()}),this.includeNetworkStats&&this.navCounters.push(this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}counterForNav(e){return e>=0?this.navCounters[e]:void 0}assembleNetworkStats(){if(this.includeNetworkStats)for(let e=0;e<this.records.length;e++){let r=this.navCounters[e];r&&(this.records[e].networkStats={totalRequests:r.totalRequests,failedRequests:r.failedRequests,failedRequestUrls:[...r.failedRequestUrls],totalBytes:r.totalBytes,byType:{...r.byType}});}}mapResourceType(e){switch(e){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var kt=Symbol.for("__testrelic_call_id"),pi="__testrelic_api_assertions",U=new WeakMap,W=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:pi,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}},rn=new Map;function fi(t){let e=rn.get(t);if(e)return e;try{let r=t.startsWith("file://")?url.fileURLToPath(t):t,s=fs$1.readFileSync(r,"utf-8").split(`
2602
2602
  `);return rn.set(t,s),s}catch{return null}}function gi(){let e=new Error().stack;if(!e)return null;let r=e.split(`
2603
- `);for(let n of r){if(n.includes("/assertion-tracker.")||n.includes("/api-request-tracker.")||n.includes("node:internal")||n.includes(" at new Error")||n.includes(" at captureAssertionLocation")||n.includes(" at expectWrapper")||n.includes(" at wrappedMatcher"))continue;let s=n.match(/at\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?$/);if(s)return {file:s[1],line:parseInt(s[2],10),column:parseInt(s[3],10)}}return null}function hi(t,e){if(!t)return "custom";let r=t.toLowerCase();return r.includes(".status()")&&!r.includes(".statustext()")?r.includes(".ok()")?"statusOk":"status":r.includes(".ok()")?"statusOk":r.includes(".headers()")||r.includes(".headersarray()")?"header":r.includes("tomatchobject")||r.includes("toequal")?"bodyMatch":r.includes("tocontain")||r.includes("tostringcontaining")?"bodyContains":r.includes(".json()")||r.includes(".text()")?"bodyField":"custom"}function mi(t,e,r){let n=function(a,...o){let i=t(),l=e();if(!i||!l)return r(a,...o);let d=null;if(a!=null&&typeof a=="object"){let c=a[kt];typeof c=="string"&&(d=c);}if(!d&&a!==null&&a!==void 0&&typeof a=="object"&&(d=U.get(a)??null),d||(d=l.getCallIdForValue(a)),d||(d=i.getCurrentCallId()),!d)return r(a,...o);let u=gi(),p;if(u){let c=fi(u.file);c&&u.line>0&&u.line<=c.length&&(p=c[u.line-1].trim());}let f=r(a,...o);return d?on(f,{tracker:i,callId:d,received:a,location:u??{file:"unknown",line:0},expression:p}):f};for(let s of Object.keys(r))n[s]=r[s];return n}var sn=null,an=null;function V(t,e){sn=t,an=e;}function Re(t){return mi(()=>sn,()=>an,t)}function on(t,e){return new Proxy(t,{get(r,n,s){let a=Reflect.get(r,n,s);return typeof a!="function"||typeof n=="symbol"?a:n==="not"?on(a,e):function(...i){let l=i[0],d="passed",u=e.received,p=null;try{let f=a.apply(this??r,i);return f&&typeof f=="object"&&typeof f.then=="function"?f.then(()=>{xt(e,n,l,u,"passed");},c=>{throw xt(e,n,l,u,"failed"),c}):f}catch(f){if(d="failed",p=f,f instanceof Error&&f.message){let c=f.message.match(/Received:\s*(.+)/);c&&(u=c[1]);}throw f}finally{(p!==null||d==="passed")&&xt(e,n,l,u,d);}}}})}function xt(t,e,r,n,s){let a=hi(t.expression,t.received),o={callId:t.callId,type:a,expected:nn(r),actual:nn(n),status:s,location:t.location,expression:t.expression};t.tracker.recordAssertion(o);}function nn(t){if(t==null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;try{return JSON.stringify(t),t}catch{return String(t)}}var ln="[REDACTED]";function Ct(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())?ln:t[s]);return n}function Ae(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=Tt(r,n);return JSON.stringify(s)}function Tt(t,e){if(Array.isArray(t))return t.map(r=>Tt(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]=ln:r[n]=Tt(s,e);}return r}return t}function cn(t,e,r){if(r.length>0){for(let n of r)if(dn(t,n))return false}if(e.length>0){for(let n of e)if(dn(t,n))return true;return false}return true}function dn(t,e){try{return e instanceof RegExp?e.test(t):yi(e).test(t)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(e)}`),false}}function yi(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 vi=["get","post","put","patch","delete","head","fetch"],bi=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function wi(t){let e=t.toLowerCase();return bi.some(r=>e.includes(r))}function xi(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 _e=class _e{constructor(e,r,n){this.originals=new Map;this.apiCallWriter=null;this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=e,this.assertionTracker=r??null,this.apiConfig=n??_e.DEFAULT_API_CONFIG;try{this.apiCallWriter=new E("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?U.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let r of vi){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));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(e){}dispose(){for(let[e,r]of this.originals)this.context[e]=r;this.originals.clear(),this.apiCallWriter?.close(),this.callCounter=0,this.apiCallCount=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCallCount(){return this.apiCallCount}tagResponseMethods(e,r){let n=this,s=e.headers.bind(e);e.headers=function(){let c=s();return U.set(c,r),c};let a=e.headersArray.bind(e);e.headersArray=function(){let c=a();return U.set(c,r),c};let o=e.json.bind(e);e.json=async function(){let c=await o();return c!=null&&typeof c=="object"&&U.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 d=e.ok.bind(e);e.ok=function(){let c=d();return n.primitiveCallIds.set(c,r),c};let u=e.text.bind(e);e.text=async function(){let c=await u();return n.primitiveCallIds.set(c,r),c};let p=e.body.bind(e);e.body=async function(){let c=await p();return U.set(c,r),c};}createWrapper(e,r){let n=this;return async function(a,o){if(!cn(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,o);let i=`api-call-${n.callCounter++}`,l=new Date().toISOString(),d=e==="fetch"?(o?.method??"GET").toUpperCase():e.toUpperCase(),u=xi(o),p=perf_hooks.performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let f;try{f=await r(a,o);}catch(c){let g=perf_hooks.performance.now();try{let h=n.apiConfig.captureRequestBody?Ae(u,n.apiConfig.redactBodyFields):null,m={id:i,timestamp:l,method:d,url:a,requestHeaders:null,requestBody:h,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((g-p)*100)/100,isBinary:!1,error:c instanceof Error?c.message:String(c)};n.apiCallWriter&&(n.apiCallWriter.append(m),n.apiCallCount++);}catch{}throw c}try{let c=perf_hooks.performance.now(),g=f.headers(),h=g["content-type"]??null,m=h?!wi(h):!1,y=null;n.apiConfig.captureRequestHeaders&&o?.headers&&(y=o.headers);let T=null;n.apiConfig.captureResponseHeaders&&(T=g);let v=n.apiConfig.captureRequestBody?u:null,b=null;if(n.apiConfig.captureResponseBody)try{m?b=(await f.body()).toString("base64"):b=await f.text();}catch{}y=Ct(y,n.apiConfig.redactHeaders),T=Ct(T,n.apiConfig.redactHeaders),v=Ae(v,n.apiConfig.redactBodyFields),b=Ae(b,n.apiConfig.redactBodyFields);let C={id:i,timestamp:l,method:d,url:f.url(),requestHeaders:y,requestBody:v,responseStatusCode:f.status(),responseStatusText:f.statusText(),responseHeaders:T,responseBody:b,responseTimeMs:Math.round((c-p)*100)/100,isBinary:m,error:null};n.apiCallWriter&&(n.apiCallWriter.append(C),n.apiCallCount++);}catch{}try{f[kt]=i,n.tagResponseMethods(f,i);}catch{}return f}}};_e.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 G=_e;Re(test.expect);var Ci="__testrelic_api_config",Si="__testrelic_config_trackApiCalls";function Rt(t){let e=t.annotations.find(n=>n.type===Ci&&n.description!==void 0);if(e)try{return JSON.parse(e.description,Ri)}catch{}let r=t.annotations.find(n=>n.type===Si&&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 Ri(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 gn={page:async({page:t},e,r)=>{let n=new Se(t);try{await n.init();}catch{}await e(t);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l}=await n.getFileData(),d={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l,apiCallsFile:null,apiCallsCount:0};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:t},e,r)=>{let n=Rt(r);if(!n.trackApiCalls){await e(t);return}let s=new W,a=new G(t,s,n);a.intercept(),V(s,a);try{await e(t);}finally{V(null,null);}try{let{apiCallsFile:o,apiCallsCount:i}=a.getFileData(),l=n.captureAssertions?s.getData():[],d={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:l,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:o,apiCallsCount:i};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};test.test.extend(gn);Re(test.expect);var Pi={request:async({request:t},e,r)=>{let n=Rt(r);if(!n.trackApiCalls){await e(t);return}let s=new W,a=new G(t,s,n);a.intercept(),V(s,a);let o=null;try{o=new E("api-console");}catch{}let i=0,l=process.stdout.write,d=process.stderr.write;process.stdout.write=function(u,...p){try{let f=typeof u=="string"?u:Buffer.isBuffer(u)?u.toString("utf-8"):String(u);!f.startsWith("[testrelic]")&&!f.startsWith("\u2139 TestRelic")&&!f.startsWith("\u2713 TestRelic")&&!f.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stdout",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return l.apply(process.stdout,[u,...p])},process.stderr.write=function(u,...p){try{let f=typeof u=="string"?u:Buffer.isBuffer(u)?u.toString("utf-8"):String(u);!f.startsWith("[testrelic]")&&!f.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stderr",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return d.apply(process.stderr,[u,...p])};try{await e(t);}finally{process.stdout.write=l,process.stderr.write=d,V(null,null);}try{o?.close();let{apiCallsFile:u,apiCallsCount:p}=a.getFileData(),f=n.captureAssertions?s.getData():[],c={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:f,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:i>0?o?.getPath()??null:null,consoleLogsCount:i,apiCallsFile:u,apiCallsCount:p};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};var hn="@testrelic/playwright-analytics";function Mi(t){return Array.isArray(t)?t.some(e=>Array.isArray(e)&&typeof e[0]=="string"&&e[0]===hn):false}function Ni(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=Mi(s)?s:[...s,[hn,e??{}]];return test.defineConfig({...t,use:n,reporter:a})}var mn=false;function Jd(t,e,r="manual_record"){if(!t||!t.annotations){mn||(mn=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
2603
+ `);for(let n of r){if(n.includes("/assertion-tracker.")||n.includes("/api-request-tracker.")||n.includes("node:internal")||n.includes(" at new Error")||n.includes(" at captureAssertionLocation")||n.includes(" at expectWrapper")||n.includes(" at wrappedMatcher"))continue;let s=n.match(/at\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?$/);if(s)return {file:s[1],line:parseInt(s[2],10),column:parseInt(s[3],10)}}return null}function hi(t,e){if(!t)return "custom";let r=t.toLowerCase();return r.includes(".status()")&&!r.includes(".statustext()")?r.includes(".ok()")?"statusOk":"status":r.includes(".ok()")?"statusOk":r.includes(".headers()")||r.includes(".headersarray()")?"header":r.includes("tomatchobject")||r.includes("toequal")?"bodyMatch":r.includes("tocontain")||r.includes("tostringcontaining")?"bodyContains":r.includes(".json()")||r.includes(".text()")?"bodyField":"custom"}function mi(t,e,r){let n=function(a,...o){let i=t(),l=e();if(!i||!l)return r(a,...o);let d=null;if(a!=null&&typeof a=="object"){let c=a[kt];typeof c=="string"&&(d=c);}if(!d&&a!==null&&a!==void 0&&typeof a=="object"&&(d=U.get(a)??null),d||(d=l.getCallIdForValue(a)),d||(d=i.getCurrentCallId()),!d)return r(a,...o);let u=gi(),p;if(u){let c=fi(u.file);c&&u.line>0&&u.line<=c.length&&(p=c[u.line-1].trim());}let f=r(a,...o);return d?on(f,{tracker:i,callId:d,received:a,location:u??{file:"unknown",line:0},expression:p}):f};for(let s of Object.keys(r))n[s]=r[s];return n}var sn=null,an=null;function V(t,e){sn=t,an=e;}function Re(t){return mi(()=>sn,()=>an,t)}function on(t,e){return new Proxy(t,{get(r,n,s){let a=Reflect.get(r,n,s);return typeof a!="function"||typeof n=="symbol"?a:n==="not"?on(a,e):function(...i){let l=i[0],d="passed",u=e.received,p=null;try{let f=a.apply(this??r,i);return f&&typeof f=="object"&&typeof f.then=="function"?f.then(()=>{xt(e,n,l,u,"passed");},c=>{throw xt(e,n,l,u,"failed"),c}):f}catch(f){if(d="failed",p=f,f instanceof Error&&f.message){let c=f.message.match(/Received:\s*(.+)/);c&&(u=c[1]);}throw f}finally{(p!==null||d==="passed")&&xt(e,n,l,u,d);}}}})}function xt(t,e,r,n,s){let a=hi(t.expression,t.received),o={callId:t.callId,type:a,expected:nn(r),actual:nn(n),status:s,location:t.location,expression:t.expression};t.tracker.recordAssertion(o);}function nn(t){if(t==null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;try{return JSON.stringify(t),t}catch{return String(t)}}var ln="[REDACTED]";function Ct(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())?ln:t[s]);return n}function Ae(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=Tt(r,n);return JSON.stringify(s)}function Tt(t,e){if(Array.isArray(t))return t.map(r=>Tt(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]=ln:r[n]=Tt(s,e);}return r}return t}function cn(t,e,r){if(r.length>0){for(let n of r)if(dn(t,n))return false}if(e.length>0){for(let n of e)if(dn(t,n))return true;return false}return true}function dn(t,e){try{return e instanceof RegExp?e.test(t):yi(e).test(t)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(e)}`),false}}function yi(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 vi=["get","post","put","patch","delete","head","fetch"],bi=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function wi(t){let e=t.toLowerCase();return bi.some(r=>e.includes(r))}function xi(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 _e=class _e{constructor(e,r,n){this.originals=new Map;this.apiCallWriter=null;this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=e,this.assertionTracker=r??null,this.apiConfig=n??_e.DEFAULT_API_CONFIG;try{this.apiCallWriter=new E("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?U.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let r of vi){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));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(e){}dispose(){for(let[e,r]of this.originals)this.context[e]=r;this.originals.clear(),this.apiCallWriter?.close(),this.callCounter=0,this.apiCallCount=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCallCount(){return this.apiCallCount}tagResponseMethods(e,r){let n=this,s=e.headers.bind(e);e.headers=function(){let c=s();return U.set(c,r),c};let a=e.headersArray.bind(e);e.headersArray=function(){let c=a();return U.set(c,r),c};let o=e.json.bind(e);e.json=async function(){let c=await o();return c!=null&&typeof c=="object"&&U.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 d=e.ok.bind(e);e.ok=function(){let c=d();return n.primitiveCallIds.set(c,r),c};let u=e.text.bind(e);e.text=async function(){let c=await u();return n.primitiveCallIds.set(c,r),c};let p=e.body.bind(e);e.body=async function(){let c=await p();return U.set(c,r),c};}createWrapper(e,r){let n=this;return async function(a,o){if(!cn(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,o);let i=`api-call-${n.callCounter++}`,l=new Date().toISOString(),d=e==="fetch"?(o?.method??"GET").toUpperCase():e.toUpperCase(),u=xi(o),p=perf_hooks.performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let f;try{f=await r(a,o);}catch(c){let g=perf_hooks.performance.now();try{let h=n.apiConfig.captureRequestBody?Ae(u,n.apiConfig.redactBodyFields):null,m={id:i,timestamp:l,method:d,url:a,requestHeaders:null,requestBody:h,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((g-p)*100)/100,isBinary:!1,error:c instanceof Error?c.message:String(c)};n.apiCallWriter&&(n.apiCallWriter.append(m),n.apiCallCount++);}catch{}throw c}try{let c=perf_hooks.performance.now(),g=f.headers(),h=g["content-type"]??null,m=h?!wi(h):!1,b=null;n.apiConfig.captureRequestHeaders&&o?.headers&&(b=o.headers);let T=null;n.apiConfig.captureResponseHeaders&&(T=g);let y=n.apiConfig.captureRequestBody?u:null,v=null;if(n.apiConfig.captureResponseBody)try{m?v=(await f.body()).toString("base64"):v=await f.text();}catch{}b=Ct(b,n.apiConfig.redactHeaders),T=Ct(T,n.apiConfig.redactHeaders),y=Ae(y,n.apiConfig.redactBodyFields),v=Ae(v,n.apiConfig.redactBodyFields);let C={id:i,timestamp:l,method:d,url:f.url(),requestHeaders:b,requestBody:y,responseStatusCode:f.status(),responseStatusText:f.statusText(),responseHeaders:T,responseBody:v,responseTimeMs:Math.round((c-p)*100)/100,isBinary:m,error:null};n.apiCallWriter&&(n.apiCallWriter.append(C),n.apiCallCount++);}catch{}try{f[kt]=i,n.tagResponseMethods(f,i);}catch{}return f}}};_e.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 G=_e;Re(test.expect);var Ci="__testrelic_api_config",Si="__testrelic_config_trackApiCalls";function Rt(t){let e=t.annotations.find(n=>n.type===Ci&&n.description!==void 0);if(e)try{return JSON.parse(e.description,Ri)}catch{}let r=t.annotations.find(n=>n.type===Si&&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 Ri(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 gn={page:async({page:t},e,r)=>{let n=new Se(t);try{await n.init();}catch{}await e(t);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l}=await n.getFileData(),d={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l,apiCallsFile:null,apiCallsCount:0};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:t},e,r)=>{let n=Rt(r);if(!n.trackApiCalls){await e(t);return}let s=new W,a=new G(t,s,n);a.intercept(),V(s,a);try{await e(t);}finally{V(null,null);}try{let{apiCallsFile:o,apiCallsCount:i}=a.getFileData(),l=n.captureAssertions?s.getData():[],d={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:l,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:o,apiCallsCount:i};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};test.test.extend(gn);Re(test.expect);var Pi={request:async({request:t},e,r)=>{let n=Rt(r);if(!n.trackApiCalls){await e(t);return}let s=new W,a=new G(t,s,n);a.intercept(),V(s,a);let o=null;try{o=new E("api-console");}catch{}let i=0,l=process.stdout.write,d=process.stderr.write;process.stdout.write=function(u,...p){try{let f=typeof u=="string"?u:Buffer.isBuffer(u)?u.toString("utf-8"):String(u);!f.startsWith("[testrelic]")&&!f.startsWith("\u2139 TestRelic")&&!f.startsWith("\u2713 TestRelic")&&!f.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stdout",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return l.apply(process.stdout,[u,...p])},process.stderr.write=function(u,...p){try{let f=typeof u=="string"?u:Buffer.isBuffer(u)?u.toString("utf-8"):String(u);!f.startsWith("[testrelic]")&&!f.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stderr",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return d.apply(process.stderr,[u,...p])};try{await e(t);}finally{process.stdout.write=l,process.stderr.write=d,V(null,null);}try{o?.close();let{apiCallsFile:u,apiCallsCount:p}=a.getFileData(),f=n.captureAssertions?s.getData():[],c={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:f,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:i>0?o?.getPath()??null:null,consoleLogsCount:i,apiCallsFile:u,apiCallsCount:p};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};var hn="@testrelic/playwright-analytics";function Mi(t){return Array.isArray(t)?t.some(e=>Array.isArray(e)&&typeof e[0]=="string"&&e[0]===hn):false}function Ni(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=Mi(s)?s:[...s,[hn,e??{}]];return test.defineConfig({...t,use:n,reporter:a})}var mn=false;function Jd(t,e,r="manual_record"){if(!t||!t.annotations){mn||(mn=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
2604
2604
  `));return}let n={url:e,navigationType:r,timestamp:new Date().toISOString()};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}Object.defineProperty(exports,"ATTACHMENT_CONTENT_TYPE",{enumerable:true,get:function(){return core.ATTACHMENT_CONTENT_TYPE}});Object.defineProperty(exports,"ATTACHMENT_NAME",{enumerable:true,get:function(){return core.ATTACHMENT_NAME}});Object.defineProperty(exports,"PAYLOAD_VERSION",{enumerable:true,get:function(){return core.PAYLOAD_VERSION}});Object.defineProperty(exports,"isTestRelicDataPayload",{enumerable:true,get:function(){return core.isTestRelicDataPayload}});exports.SCHEMA_VERSION=ie;exports.default=Ce;exports.defineConfig=Ni;exports.recordNavigation=Jd;exports.testRelicApiFixture=Pi;exports.testRelicFixture=gn;//# sourceMappingURL=index.cjs.map
2605
2605
  //# sourceMappingURL=index.cjs.map