@testrelic/playwright-analytics 2.11.0 → 2.11.1-next.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- 'use strict';var test=require('@playwright/test'),perf_hooks=require('perf_hooks'),fs=require('fs'),path=require('path'),os=require('os'),crypto=require('crypto');require('readline');var url=require('url'),core=require('@testrelic/core');var M=path.join(os.tmpdir(),"testrelic-data"),h=class{constructor(t){this.count=0;this.closed=false;fs.mkdirSync(M,{recursive:true}),this.filePath=path.join(M,`${t}-${crypto.randomUUID().substring(0,8)}.jsonl`),this.fd=fs.openSync(this.filePath,"w");}append(t){if(this.closed)return;let e=JSON.stringify(t)+`
2
- `;fs.writeSync(this.fd,e),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{fs.closeSync(this.fd);}catch{}}}cleanup(){try{fs.unlinkSync(this.filePath);}catch{}}};var B=Symbol.for("__testrelic_call_id"),ut="__testrelic_api_assertions",C=new WeakMap,A=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(t){this.assertions.push(t);}getAssertions(){return this.assertions}setCurrentCallId(t){this.currentCallId=t;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(t){this.assertions.length!==0&&t.annotations.push({type:ut,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}},H=new Map;function dt(r){let t=H.get(r);if(t)return t;try{let e=r.startsWith("file://")?url.fileURLToPath(r):r,s=fs.readFileSync(e,"utf-8").split(`
3
- `);return H.set(r,s),s}catch{return null}}function pt(){let t=new Error().stack;if(!t)return null;let e=t.split(`
4
- `);for(let n of e){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 gt(r,t){if(!r)return "custom";let e=r.toLowerCase();return e.includes(".status()")&&!e.includes(".statustext()")?e.includes(".ok()")?"statusOk":"status":e.includes(".ok()")?"statusOk":e.includes(".headers()")||e.includes(".headersarray()")?"header":e.includes("tomatchobject")||e.includes("toequal")?"bodyMatch":e.includes("tocontain")||e.includes("tostringcontaining")?"bodyContains":e.includes(".json()")||e.includes(".text()")?"bodyField":"custom"}function ft(r,t,e){let n=function(i,...p){let u=r(),d=t();if(!u||!d)return e(i,...p);let c=null;if(i!=null&&typeof i=="object"){let a=i[B];typeof a=="string"&&(c=a);}if(!c&&i!==null&&i!==void 0&&typeof i=="object"&&(c=C.get(i)??null),c||(c=d.getCallIdForValue(i)),c||(c=u.getCurrentCallId()),!c)return e(i,...p);let o=pt(),g;if(o){let a=dt(o.file);a&&o.line>0&&o.line<=a.length&&(g=a[o.line-1].trim());}let l=e(i,...p);return c?$(l,{tracker:u,callId:c,received:i,location:o??{file:"unknown",line:0},expression:g}):l};for(let s of Object.keys(e))n[s]=e[s];return n}var U=null,G=null;function v(r,t){U=r,G=t;}function q(r){return ft(()=>U,()=>G,r)}function $(r,t){return new Proxy(r,{get(e,n,s){let i=Reflect.get(e,n,s);return typeof i!="function"||typeof n=="symbol"?i:n==="not"?$(i,t):function(...u){let d=u[0],c="passed",o=t.received,g=null;try{let l=i.apply(this??e,u);return l&&typeof l=="object"&&typeof l.then=="function"?l.then(()=>{L(t,n,d,o,"passed");},a=>{throw L(t,n,d,o,"failed"),a}):l}catch(l){if(c="failed",g=l,l instanceof Error&&l.message){let a=l.message.match(/Received:\s*(.+)/);a&&(o=a[1]);}throw l}finally{(g!==null||c==="passed")&&L(t,n,d,o,c);}}}})}function L(r,t,e,n,s){let i=gt(r.expression,r.received),p={callId:r.callId,type:i,expected:J(e),actual:J(n),status:s,location:r.location,expression:r.expression};r.tracker.recordAssertion(p);}function J(r){if(r==null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;try{return JSON.stringify(r),r}catch{return String(r)}}var Y="[REDACTED]";function O(r,t){if(r===null||t.length===0)return r;let e=new Set(t.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(r))Object.hasOwn(r,s)&&(n[s]=e.has(s.toLowerCase())?Y:r[s]);return n}function S(r,t){if(r===null||t.length===0)return r;let e;try{e=JSON.parse(r);}catch{return r}if(typeof e!="object"||e===null)return r;let n=new Set(t),s=F(e,n);return JSON.stringify(s)}function F(r,t){if(Array.isArray(r))return r.map(e=>F(e,t));if(typeof r=="object"&&r!==null){let e={};for(let n of Object.keys(r)){if(!Object.hasOwn(r,n))continue;let s=r[n];t.has(n)?e[n]=Y:e[n]=F(s,t);}return e}return r}function V(r,t,e){if(e.length>0){for(let n of e)if(z(r,n))return false}if(t.length>0){for(let n of t)if(z(r,n))return true;return false}return true}function z(r,t){try{return t instanceof RegExp?t.test(r):ht(t).test(r)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(t)}`),false}}function ht(r){let t="",e=0;for(;e<r.length;){let n=r[e];n==="*"&&r[e+1]==="*"?(t+=".*",e+=2,r[e]==="/"&&e++):n==="*"?(t+="[^/]*",e++):n==="?"?(t+="[^/]",e++):".+^${}()|[]\\".includes(n)?(t+="\\"+n,e++):(t+=n,e++);}return new RegExp(t)}var yt=["get","post","put","patch","delete","head","fetch"],wt=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function kt(r){let t=r.toLowerCase();return wt.some(e=>t.includes(e))}function mt(r){if(!r)return null;if(r.data!==void 0&&r.data!==null){let t=r.data;return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("base64"):JSON.stringify(t)}if(r.form!==void 0&&r.form!==null)return JSON.stringify(r.form);if(r.multipart!==void 0&&r.multipart!==null){let t=r.multipart,e={};for(let[n,s]of Object.entries(t))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?e[n]=String(s):s&&typeof s=="object"&&"name"in s?e[n]=`[file: ${s.name}]`:e[n]="[binary]";return JSON.stringify(e)}return null}function K(r){return r?"\u2022\u2022\u2022\u2022":""}function Ct(r){if(!r)return [];let t;for(let[n,s]of Object.entries(r))if(n.toLowerCase()==="cookie"){t=s;break}if(!t)return [];let e=[];for(let n of t.split(";")){let s=n.trim();if(!s)continue;let i=s.indexOf("="),p=i===-1?s:s.slice(0,i).trim(),u=i===-1?"":s.slice(i+1).trim();p&&e.push({name:p,value:K(u)});}return e}function Rt(r){let t=[];for(let e of r)for(let n of e.split(/,(?=\s*[A-Za-z0-9_.\-]+=)/)){let s=n.trim();if(!s)continue;let i=s.split(";"),p=i[0].indexOf("=");if(p===-1)continue;let u=i[0].slice(0,p).trim(),d=i[0].slice(p+1).trim(),c=i.slice(1).map(o=>o.trim()).filter(Boolean).join(" \xB7 ")||void 0;u&&t.push({name:u,value:K(d),attributes:c});}return t}var N=class N{constructor(t,e,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=t,this.assertionTracker=e??null,this.apiConfig=n??N.DEFAULT_API_CONFIG;try{this.apiCallWriter=new h("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(t){return t!=null&&typeof t=="object"?C.get(t)??null:this.primitiveCallIds.get(t)??null}intercept(){for(let e of yt){let n=this.context[e].bind(this.context);this.originals.set(e,n),this.context[e]=this.createWrapper(e,n);}let t=this.context.dispose.bind(this.context);this.originals.set("dispose",t),this.context.dispose=async e=>(this.disposed=true,t(e));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(t){}dispose(){for(let[t,e]of this.originals)this.context[t]=e;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(t,e){let n=this,s=t.headers.bind(t);t.headers=function(){let a=s();return C.set(a,e),a};let i=t.headersArray.bind(t);t.headersArray=function(){let a=i();return C.set(a,e),a};let p=t.json.bind(t);t.json=async function(){let a=await p();return a!=null&&typeof a=="object"&&C.set(a,e),a};let u=t.status.bind(t);t.status=function(){let a=u();return n.primitiveCallIds.set(a,e),a};let d=t.statusText.bind(t);t.statusText=function(){let a=d();return n.primitiveCallIds.set(a,e),a};let c=t.ok.bind(t);t.ok=function(){let a=c();return n.primitiveCallIds.set(a,e),a};let o=t.text.bind(t);t.text=async function(){let a=await o();return n.primitiveCallIds.set(a,e),a};let g=t.body.bind(t);t.body=async function(){let a=await g();return C.set(a,e),a};}createWrapper(t,e){let n=this;return async function(i,p){if(!V(i,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return e(i,p);let u=`api-call-${n.callCounter++}`,d=new Date().toISOString(),c=t==="fetch"?(p?.method??"GET").toUpperCase():t.toUpperCase(),o=mt(p),g=perf_hooks.performance.now();n._lastCallId=u,n.assertionTracker&&n.assertionTracker.setCurrentCallId(u);let l;try{l=await e(i,p);}catch(a){let y=perf_hooks.performance.now();try{let R=n.apiConfig.captureRequestBody?S(o,n.apiConfig.redactBodyFields):null,m={id:u,timestamp:d,method:c,url:i,requestHeaders:null,requestBody:R,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((y-g)*100)/100,isBinary:!1,error:a instanceof Error?a.message:String(a)};n.apiCallWriter&&(n.apiCallWriter.append(m),n.apiCallCount++);}catch{}throw a}try{let a=perf_hooks.performance.now(),y=l.headers(),R=y["content-type"]??null,m=R?!kt(R):!1,T=null;n.apiConfig.captureRequestHeaders&&p?.headers&&(T=p.headers);let f=null;n.apiConfig.captureResponseHeaders&&(f=y);let w=n.apiConfig.captureRequestBody?o:null,k=null;if(n.apiConfig.captureResponseBody)try{m?k=(await l.body()).toString("base64"):k=await l.text();}catch{}let x=[],I=[];try{if(n.apiConfig.captureRequestHeaders&&(x=Ct(p?.headers)),n.apiConfig.captureResponseHeaders){let W=l.headersArray().filter(_=>_.name.toLowerCase()==="set-cookie").map(_=>_.value);I=Rt(W);}}catch{}T=O(T,n.apiConfig.redactHeaders),f=O(f,n.apiConfig.redactHeaders),w=S(w,n.apiConfig.redactBodyFields),k=S(k,n.apiConfig.redactBodyFields);let tt={id:u,timestamp:d,method:c,url:l.url(),requestHeaders:T,requestBody:w,responseStatusCode:l.status(),responseStatusText:l.statusText(),responseHeaders:f,responseBody:k,requestCookies:x.length?x:null,responseCookies:I.length?I:null,responseTimeMs:Math.round((a-g)*100)/100,isBinary:m,error:null};n.apiCallWriter&&(n.apiCallWriter.append(tt),n.apiCallCount++);}catch{}try{l[B]=u,n.tagResponseMethods(l,u);}catch{}return l}}};N.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 b=N;var Tt=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function At(r){let t=r.toLowerCase();return Tt.some(e=>t.includes(e))}var P=class r{constructor(t,e){this.page=t;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=e?.includeNetworkStats??true,this.origGoto=t.goto.bind(t),this.origGoBack=t.goBack.bind(t),this.origGoForward=t.goForward.bind(t),this.origReload=t.reload.bind(t);try{this.includeNetworkStats&&(this.networkWriter=new h("network")),this.consoleWriter=new h("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,t]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:t.url,method:t.method,resourceType:t.resourceType,statusCode:0,responseTimeMs:Date.now()-t.startTimeMs,startedAt:t.startedAt,requestHeaders:t.headers,requestBody:t.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:t.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(t){switch(t){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.assembleNetworkStats();let t=this.records.map(e=>({url:e.url,navigationType:e.navigationType,timestamp:e.timestamp,domContentLoadedAt:e.domContentLoadedAt,networkIdleAt:e.networkIdleAt,networkStats:e.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:t,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(t){}dispose(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:t,handler:e}of this.listeners)this.page.off(t,e);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.assembleNetworkStats(),this.records}interceptMethods(){let t=this,e=this.page;e.goto=async function(n,s){return t.recordNavigation(n,"goto"),t.origGoto(n,s)},e.goBack=async function(n){let s=await t.origGoBack(n);return t.recordNavigation(e.url(),"back"),s},e.goForward=async function(n){let s=await t.origGoForward(n);return t.recordNavigation(e.url(),"forward"),s},e.reload=async function(n){return t.recordNavigation(e.url(),"refresh"),t.origReload(n)};}attachListeners(){let t=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",t),this.listeners.push({event:"domcontentloaded",handler:t});let e=s=>{try{let i=s;if(typeof i.parentFrame=="function"&&i.parentFrame()!==null)return;let p=i.url(),u=this.records[this.records.length-1];if(u&&Date.now()-new Date(u.timestamp).getTime()<50&&u.url===p)return;this.recordNavigation(p,"navigation");}catch{}};this.page.on("framenavigated",e),this.listeners.push({event:"framenavigated",handler:e});let n=s=>{try{let i=s,p=i.type(),u=i.text();if(p==="debug"&&u.startsWith("__testrelic_nav:")){try{let d=JSON.parse(u.slice(16));d.type&&d.url&&this.recordNavigation(d.url,d.type);}catch{}return}{let d=null;try{let o=i.location();o&&o.url&&(d=`${o.url}:${o.lineNumber}:${o.columnNumber}`);}catch{}let c=r.mapConsoleType(p);this.consoleWriter&&(this.consoleWriter.append({level:c,text:u,timestamp:new Date().toISOString(),location:d}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=u=>{let d=this.records.length-1,c=this.counterForNav(d);c&&c.totalRequests++;try{let o=u,g=String(this.requestIdCounter++),l=o.postData()??null,a={url:o.url(),method:o.method(),resourceType:this.mapResourceType(o.resourceType()),headers:o.headers(),postData:l,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now(),navIndex:d};this.pendingRequests.set(g,a),u.__testrelic_id=g;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let i=u=>{try{let d=u,c=d.request().__testrelic_id,o=c?this.pendingRequests.get(c):void 0,g=this.counterForNav(o?o.navIndex:this.records.length-1);if(g){let f=d.status();f>=400&&(g.failedRequests++,g.failedRequestUrls.push(f+" "+d.url()));let w=d.headers()["content-length"];w&&(g.totalBytes+=parseInt(w,10)||0);let k=d.request().resourceType(),x=this.mapResourceType(k);g.byType[x]++;}if(!c||!o)return;this.pendingRequests.delete(c);let l=Date.now()-o.startTimeMs,a=d.headers(),y=a["content-type"]??null,R=parseInt(a["content-length"]??"0",10)||0,m=y?!At(y):!1,T=(async()=>{let f=null;if(!m)try{f=(await d.body()).toString("utf-8");}catch{}let w={url:o.url,method:o.method,resourceType:o.resourceType,statusCode:d.status(),responseTimeMs:l,startedAt:o.startedAt,requestHeaders:o.headers,requestBody:o.postData,responseBody:f,responseHeaders:a,contentType:y,responseSize:R,requestBodyTruncated:o.postDataTruncated,responseBodyTruncated:!1,isBinary:m,error:null};this.networkWriter&&(this.networkWriter.append(w),this.networkRequestCount++);})();this.pendingBodyReads.push(T);}catch{}};this.page.on("response",i),this.listeners.push({event:"response",handler:i});let p=u=>{let d=u.__testrelic_id,c=d?this.pendingRequests.get(d):void 0,o=this.counterForNav(c?c.navIndex:this.records.length-1);if(o){o.failedRequests++;try{let g=u;o.failedRequestUrls.push("ERR "+g.url());}catch{}}try{let g=u;if(!d||!c)return;this.pendingRequests.delete(d);let l={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:0,responseTimeMs:Date.now()-c.startTimeMs,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:c.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:g.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(l),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",p),this.listeners.push({event:"requestfailed",handler:p});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let t=history.pushState.bind(history),e=history.replaceState.bind(history);history.pushState=function(...n){t(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(t,e){this.records.push({url:t,navigationType:e,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(t){return t>=0?this.navCounters[t]:void 0}assembleNetworkStats(){if(this.includeNetworkStats)for(let t=0;t<this.records.length;t++){let e=this.navCounters[t];e&&(this.records[t].networkStats={totalRequests:e.totalRequests,failedRequests:e.failedRequests,failedRequestUrls:[...e.failedRequestUrls],totalBytes:e.totalBytes,byType:{...e.byType}});}}mapResourceType(t){switch(t){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};q(test.expect);var xt="__testrelic_api_config",qt="__testrelic_config_trackApiCalls";function D(r){let t=r.annotations.find(n=>n.type===xt&&n.description!==void 0);if(t)try{return JSON.parse(t.description,St)}catch{}let e=r.annotations.find(n=>n.type===qt&&n.description!==void 0);return e?{trackApiCalls:e.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 St(r,t){if(typeof t=="object"&&t!==null&&t.__regexp===true&&typeof t.source=="string"){let{source:e,flags:n}=t;return new RegExp(e,n)}return t}var Nt={page:async({page:r},t,e)=>{let n=new P(r);try{await n.init();}catch{}await t(r);try{let{navigations:s,networkRequestsFile:i,networkRequestsCount:p,consoleLogsFile:u,consoleLogsCount:d}=await n.getFileData(),c={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:i,networkRequestsCount:p,consoleLogsFile:u,consoleLogsCount:d,apiCallsFile:null,apiCallsCount:0};await e.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:r},t,e)=>{let n=D(e);if(!n.trackApiCalls){await t(r);return}let s=new A,i=new b(r,s,n);i.intercept(),v(s,i);try{await t(r);}finally{v(null,null);}try{let{apiCallsFile:p,apiCallsCount:u}=i.getFileData(),d=n.captureAssertions?s.getData():[],c={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:d,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:p,apiCallsCount:u};await e.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}i.dispose(),s.dispose();}};test.test.extend(Nt);var he=q(test.expect),ye={request:async({request:r},t,e)=>{let n=D(e);if(!n.trackApiCalls){await t(r);return}let s=new A,i=new b(r,s,n);i.intercept(),v(s,i);let p=null;try{p=new h("api-console");}catch{}let u=0,d=process.stdout.write,c=process.stderr.write;process.stdout.write=function(o,...g){try{let l=typeof o=="string"?o:Buffer.isBuffer(o)?o.toString("utf-8"):String(o);!l.startsWith("[testrelic]")&&!l.startsWith("\u2139 TestRelic")&&!l.startsWith("\u2713 TestRelic")&&!l.startsWith("\u26A0 TestRelic")&&p&&(p.append({level:"stdout",text:l.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),u++);}catch{}return d.apply(process.stdout,[o,...g])},process.stderr.write=function(o,...g){try{let l=typeof o=="string"?o:Buffer.isBuffer(o)?o.toString("utf-8"):String(o);!l.startsWith("[testrelic]")&&!l.startsWith("\u26A0 TestRelic")&&p&&(p.append({level:"stderr",text:l.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),u++);}catch{}return c.apply(process.stderr,[o,...g])};try{await t(r);}finally{process.stdout.write=d,process.stderr.write=c,v(null,null);}try{p?.close();let{apiCallsFile:o,apiCallsCount:g}=i.getFileData(),l=n.captureAssertions?s.getData():[],a={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:l,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:u>0?p?.getPath()??null:null,consoleLogsCount:u,apiCallsFile:o,apiCallsCount:g};await e.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(a)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}i.dispose(),s.dispose();}};exports.expect=he;exports.testRelicApiFixture=ye;//# sourceMappingURL=api-fixture.cjs.map
1
+ 'use strict';var test=require('@playwright/test'),perf_hooks=require('perf_hooks'),fs=require('fs'),path=require('path'),os=require('os'),crypto=require('crypto');require('readline');var url=require('url'),core=require('@testrelic/core');var j=path.join(os.tmpdir(),"testrelic-data"),h=class{constructor(t){this.count=0;this.closed=false;fs.mkdirSync(j,{recursive:true}),this.filePath=path.join(j,`${t}-${crypto.randomUUID().substring(0,8)}.jsonl`),this.fd=fs.openSync(this.filePath,"w");}append(t){if(this.closed)return;let e=JSON.stringify(t)+`
2
+ `;fs.writeSync(this.fd,e),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{fs.closeSync(this.fd);}catch{}}}cleanup(){try{fs.unlinkSync(this.filePath);}catch{}}};var B=Symbol.for("__testrelic_call_id"),dt="__testrelic_api_assertions",C=new WeakMap,A=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(t){this.assertions.push(t);}getAssertions(){return this.assertions}setCurrentCallId(t){this.currentCallId=t;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(t){this.assertions.length!==0&&t.annotations.push({type:dt,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}},J=new Map;function pt(r){let t=J.get(r);if(t)return t;try{let e=r.startsWith("file://")?url.fileURLToPath(r):r,s=fs.readFileSync(e,"utf-8").split(`
3
+ `);return J.set(r,s),s}catch{return null}}function gt(){let t=new Error().stack;if(!t)return null;let e=t.split(`
4
+ `);for(let n of e){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 ft(r,t){if(!r)return "custom";let e=r.toLowerCase();return e.includes(".status()")&&!e.includes(".statustext()")?e.includes(".ok()")?"statusOk":"status":e.includes(".ok()")?"statusOk":e.includes(".headers()")||e.includes(".headersarray()")?"header":e.includes("tomatchobject")||e.includes("toequal")?"bodyMatch":e.includes("tocontain")||e.includes("tostringcontaining")?"bodyContains":e.includes(".json()")||e.includes(".text()")?"bodyField":"custom"}function ht(r,t,e){let n=function(o,...p){let u=r(),d=t();if(!u||!d)return e(o,...p);let l=null;if(o!=null&&typeof o=="object"){let a=o[B];typeof a=="string"&&(l=a);}if(!l&&o!==null&&o!==void 0&&typeof o=="object"&&(l=C.get(o)??null),l||(l=d.getCallIdForValue(o)),l||(l=u.getCurrentCallId()),!l)return e(o,...p);let i=gt(),g;if(i){let a=pt(i.file);a&&i.line>0&&i.line<=a.length&&(g=a[i.line-1].trim());}let c=e(o,...p);return l?$(c,{tracker:u,callId:l,received:o,location:i??{file:"unknown",line:0},expression:g}):c};for(let s of Object.keys(e))n[s]=e[s];return n}var G=null,Y=null;function v(r,t){G=r,Y=t;}function S(r){return ht(()=>G,()=>Y,r)}function $(r,t){return new Proxy(r,{get(e,n,s){let o=Reflect.get(e,n,s);return typeof o!="function"||typeof n=="symbol"?o:n==="not"?$(o,t):function(...u){let d=u[0],l="passed",i=t.received,g=null;try{let c=o.apply(this??e,u);return c&&typeof c=="object"&&typeof c.then=="function"?c.then(()=>{L(t,n,d,i,"passed");},a=>{throw L(t,n,d,i,"failed"),a}):c}catch(c){if(l="failed",g=c,c instanceof Error&&c.message){let a=c.message.match(/Received:\s*(.+)/);a&&(i=a[1]);}throw c}finally{(g!==null||l==="passed")&&L(t,n,d,i,l);}}}})}function L(r,t,e,n,s){let o=ft(r.expression,r.received),p={callId:r.callId,type:o,expected:U(e),actual:U(n),status:s,location:r.location,expression:r.expression};r.tracker.recordAssertion(p);}function U(r){if(r==null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;try{return JSON.stringify(r),r}catch{return String(r)}}var z="[REDACTED]";function O(r,t){if(r===null||t.length===0)return r;let e=new Set(t.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(r))Object.hasOwn(r,s)&&(n[s]=e.has(s.toLowerCase())?z:r[s]);return n}function q(r,t){if(r===null||t.length===0)return r;let e;try{e=JSON.parse(r);}catch{return r}if(typeof e!="object"||e===null)return r;let n=new Set(t.map(o=>o.toLowerCase())),s=F(e,n);return JSON.stringify(s)}function F(r,t){if(Array.isArray(r))return r.map(e=>F(e,t));if(typeof r=="object"&&r!==null){let e={};for(let n of Object.keys(r)){if(!Object.hasOwn(r,n))continue;let s=r[n];t.has(n.toLowerCase())?e[n]=z:e[n]=F(s,t);}return e}return r}var yt=new Set(["access_token","api_key","token","sig"]);function E(r){if(!r)return r;let t;try{t=new URL(r);}catch{return r}let e=false;for(let n of [...t.searchParams.keys()])yt.has(n.toLowerCase())&&(t.searchParams.delete(n),e=true);return e?t.toString():r}function K(r,t,e){if(e.length>0){for(let n of e)if(V(r,n))return false}if(t.length>0){for(let n of t)if(V(r,n))return true;return false}return true}function V(r,t){try{return t instanceof RegExp?t.test(r):wt(t).test(r)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(t)}`),false}}function wt(r){let t="",e=0;for(;e<r.length;){let n=r[e];n==="*"&&r[e+1]==="*"?(t+=".*",e+=2,r[e]==="/"&&e++):n==="*"?(t+="[^/]*",e++):n==="?"?(t+="[^/]",e++):".+^${}()|[]\\".includes(n)?(t+="\\"+n,e++):(t+=n,e++);}return new RegExp(t)}var kt=["get","post","put","patch","delete","head","fetch"],mt=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Ct(r){let t=r.toLowerCase();return mt.some(e=>t.includes(e))}function Rt(r){if(!r)return null;if(r.data!==void 0&&r.data!==null){let t=r.data;return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("base64"):JSON.stringify(t)}if(r.form!==void 0&&r.form!==null)return JSON.stringify(r.form);if(r.multipart!==void 0&&r.multipart!==null){let t=r.multipart,e={};for(let[n,s]of Object.entries(t))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?e[n]=String(s):s&&typeof s=="object"&&"name"in s?e[n]=`[file: ${s.name}]`:e[n]="[binary]";return JSON.stringify(e)}return null}function Q(r){return r?"\u2022\u2022\u2022\u2022":""}function Tt(r){if(!r)return [];let t;for(let[n,s]of Object.entries(r))if(n.toLowerCase()==="cookie"){t=s;break}if(!t)return [];let e=[];for(let n of t.split(";")){let s=n.trim();if(!s)continue;let o=s.indexOf("="),p=o===-1?s:s.slice(0,o).trim(),u=o===-1?"":s.slice(o+1).trim();p&&e.push({name:p,value:Q(u)});}return e}function At(r){let t=[];for(let e of r)for(let n of e.split(/,(?=\s*[A-Za-z0-9_.\-]+=)/)){let s=n.trim();if(!s)continue;let o=s.split(";"),p=o[0].indexOf("=");if(p===-1)continue;let u=o[0].slice(0,p).trim(),d=o[0].slice(p+1).trim(),l=o.slice(1).map(i=>i.trim()).filter(Boolean).join(" \xB7 ")||void 0;u&&t.push({name:u,value:Q(d),attributes:l});}return t}var P=class P{constructor(t,e,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=t,this.assertionTracker=e??null,this.apiConfig=n??P.DEFAULT_API_CONFIG;try{this.apiCallWriter=new h("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(t){return t!=null&&typeof t=="object"?C.get(t)??null:this.primitiveCallIds.get(t)??null}intercept(){for(let e of kt){let n=this.context[e].bind(this.context);this.originals.set(e,n),this.context[e]=this.createWrapper(e,n);}let t=this.context.dispose.bind(this.context);this.originals.set("dispose",t),this.context.dispose=async e=>(this.disposed=true,t(e));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(t){}dispose(){for(let[t,e]of this.originals)this.context[t]=e;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(t,e){let n=this,s=t.headers.bind(t);t.headers=function(){let a=s();return C.set(a,e),a};let o=t.headersArray.bind(t);t.headersArray=function(){let a=o();return C.set(a,e),a};let p=t.json.bind(t);t.json=async function(){let a=await p();return a!=null&&typeof a=="object"&&C.set(a,e),a};let u=t.status.bind(t);t.status=function(){let a=u();return n.primitiveCallIds.set(a,e),a};let d=t.statusText.bind(t);t.statusText=function(){let a=d();return n.primitiveCallIds.set(a,e),a};let l=t.ok.bind(t);t.ok=function(){let a=l();return n.primitiveCallIds.set(a,e),a};let i=t.text.bind(t);t.text=async function(){let a=await i();return n.primitiveCallIds.set(a,e),a};let g=t.body.bind(t);t.body=async function(){let a=await g();return C.set(a,e),a};}createWrapper(t,e){let n=this;return async function(o,p){if(!K(o,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return e(o,p);let u=`api-call-${n.callCounter++}`,d=new Date().toISOString(),l=t==="fetch"?(p?.method??"GET").toUpperCase():t.toUpperCase(),i=Rt(p),g=perf_hooks.performance.now();n._lastCallId=u,n.assertionTracker&&n.assertionTracker.setCurrentCallId(u);let c;try{c=await e(o,p);}catch(a){let y=perf_hooks.performance.now();try{let R=n.apiConfig.captureRequestBody?q(i,n.apiConfig.redactBodyFields):null,m={id:u,timestamp:d,method:l,url:E(o),requestHeaders:null,requestBody:R,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((y-g)*100)/100,isBinary:!1,error:a instanceof Error?a.message:String(a)};n.apiCallWriter&&(n.apiCallWriter.append(m),n.apiCallCount++);}catch{}throw a}try{let a=perf_hooks.performance.now(),y=c.headers(),R=y["content-type"]??null,m=R?!Ct(R):!1,T=null;n.apiConfig.captureRequestHeaders&&p?.headers&&(T=p.headers);let f=null;n.apiConfig.captureResponseHeaders&&(f=y);let w=n.apiConfig.captureRequestBody?i:null,k=null;if(n.apiConfig.captureResponseBody)try{m?k=(await c.body()).toString("base64"):k=await c.text();}catch{}let x=[],_=[];try{if(n.apiConfig.captureRequestHeaders&&(x=Tt(p?.headers)),n.apiConfig.captureResponseHeaders){let M=c.headersArray().filter(I=>I.name.toLowerCase()==="set-cookie").map(I=>I.value);_=At(M);}}catch{}T=O(T,n.apiConfig.redactHeaders),f=O(f,n.apiConfig.redactHeaders),w=q(w,n.apiConfig.redactBodyFields),k=q(k,n.apiConfig.redactBodyFields);let et={id:u,timestamp:d,method:l,url:E(c.url()),requestHeaders:T,requestBody:w,responseStatusCode:c.status(),responseStatusText:c.statusText(),responseHeaders:f,responseBody:k,requestCookies:x.length?x:null,responseCookies:_.length?_:null,responseTimeMs:Math.round((a-g)*100)/100,isBinary:m,error:null};n.apiCallWriter&&(n.apiCallWriter.append(et),n.apiCallCount++);}catch{}try{c[B]=u,n.tagResponseMethods(c,u);}catch{}return c}}};P.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 b=P;var vt=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function bt(r){let t=r.toLowerCase();return vt.some(e=>t.includes(e))}var N=class r{constructor(t,e){this.page=t;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=e?.includeNetworkStats??true,this.origGoto=t.goto.bind(t),this.origGoBack=t.goBack.bind(t),this.origGoForward=t.goForward.bind(t),this.origReload=t.reload.bind(t);try{this.includeNetworkStats&&(this.networkWriter=new h("network")),this.consoleWriter=new h("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,t]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:t.url,method:t.method,resourceType:t.resourceType,statusCode:0,responseTimeMs:Date.now()-t.startTimeMs,startedAt:t.startedAt,requestHeaders:t.headers,requestBody:t.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:t.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(t){switch(t){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.assembleNetworkStats();let t=this.records.map(e=>({url:e.url,navigationType:e.navigationType,timestamp:e.timestamp,domContentLoadedAt:e.domContentLoadedAt,networkIdleAt:e.networkIdleAt,networkStats:e.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:t,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(t){}dispose(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:t,handler:e}of this.listeners)this.page.off(t,e);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.assembleNetworkStats(),this.records}interceptMethods(){let t=this,e=this.page;e.goto=async function(n,s){return t.recordNavigation(n,"goto"),t.origGoto(n,s)},e.goBack=async function(n){let s=await t.origGoBack(n);return t.recordNavigation(e.url(),"back"),s},e.goForward=async function(n){let s=await t.origGoForward(n);return t.recordNavigation(e.url(),"forward"),s},e.reload=async function(n){return t.recordNavigation(e.url(),"refresh"),t.origReload(n)};}attachListeners(){let t=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",t),this.listeners.push({event:"domcontentloaded",handler:t});let e=s=>{try{let o=s;if(typeof o.parentFrame=="function"&&o.parentFrame()!==null)return;let p=o.url(),u=this.records[this.records.length-1];if(u&&Date.now()-new Date(u.timestamp).getTime()<50&&u.url===p)return;this.recordNavigation(p,"navigation");}catch{}};this.page.on("framenavigated",e),this.listeners.push({event:"framenavigated",handler:e});let n=s=>{try{let o=s,p=o.type(),u=o.text();if(p==="debug"&&u.startsWith("__testrelic_nav:")){try{let d=JSON.parse(u.slice(16));d.type&&d.url&&this.recordNavigation(d.url,d.type);}catch{}return}{let d=null;try{let i=o.location();i&&i.url&&(d=`${i.url}:${i.lineNumber}:${i.columnNumber}`);}catch{}let l=r.mapConsoleType(p);this.consoleWriter&&(this.consoleWriter.append({level:l,text:u,timestamp:new Date().toISOString(),location:d}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=u=>{let d=this.records.length-1,l=this.counterForNav(d);l&&l.totalRequests++;try{let i=u,g=String(this.requestIdCounter++),c=i.postData()??null,a={url:i.url(),method:i.method(),resourceType:this.mapResourceType(i.resourceType()),headers:i.headers(),postData:c,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now(),navIndex:d};this.pendingRequests.set(g,a),u.__testrelic_id=g;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let o=u=>{try{let d=u,l=d.request().__testrelic_id,i=l?this.pendingRequests.get(l):void 0,g=this.counterForNav(i?i.navIndex:this.records.length-1);if(g){let f=d.status();f>=400&&(g.failedRequests++,g.failedRequestUrls.push(f+" "+d.url()));let w=d.headers()["content-length"];w&&(g.totalBytes+=parseInt(w,10)||0);let k=d.request().resourceType(),x=this.mapResourceType(k);g.byType[x]++;}if(!l||!i)return;this.pendingRequests.delete(l);let c=Date.now()-i.startTimeMs,a=d.headers(),y=a["content-type"]??null,R=parseInt(a["content-length"]??"0",10)||0,m=y?!bt(y):!1,T=(async()=>{let f=null;if(!m)try{f=(await d.body()).toString("utf-8");}catch{}let w={url:i.url,method:i.method,resourceType:i.resourceType,statusCode:d.status(),responseTimeMs:c,startedAt:i.startedAt,requestHeaders:i.headers,requestBody:i.postData,responseBody:f,responseHeaders:a,contentType:y,responseSize:R,requestBodyTruncated:i.postDataTruncated,responseBodyTruncated:!1,isBinary:m,error:null};this.networkWriter&&(this.networkWriter.append(w),this.networkRequestCount++);})();this.pendingBodyReads.push(T);}catch{}};this.page.on("response",o),this.listeners.push({event:"response",handler:o});let p=u=>{let d=u.__testrelic_id,l=d?this.pendingRequests.get(d):void 0,i=this.counterForNav(l?l.navIndex:this.records.length-1);if(i){i.failedRequests++;try{let g=u;i.failedRequestUrls.push("ERR "+g.url());}catch{}}try{let g=u;if(!d||!l)return;this.pendingRequests.delete(d);let c={url:l.url,method:l.method,resourceType:l.resourceType,statusCode:0,responseTimeMs:Date.now()-l.startTimeMs,startedAt:l.startedAt,requestHeaders:l.headers,requestBody:l.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:l.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:g.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(c),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",p),this.listeners.push({event:"requestfailed",handler:p});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let t=history.pushState.bind(history),e=history.replaceState.bind(history);history.pushState=function(...n){t(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(t,e){this.records.push({url:t,navigationType:e,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(t){return t>=0?this.navCounters[t]:void 0}assembleNetworkStats(){if(this.includeNetworkStats)for(let t=0;t<this.records.length;t++){let e=this.navCounters[t];e&&(this.records[t].networkStats={totalRequests:e.totalRequests,failedRequests:e.failedRequests,failedRequestUrls:[...e.failedRequestUrls],totalBytes:e.totalBytes,byType:{...e.byType}});}}mapResourceType(t){switch(t){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};S(test.expect);var qt="__testrelic_api_config",Pt="__testrelic_config_trackApiCalls";function W(r){let t=r.annotations.find(n=>n.type===qt&&n.description!==void 0);if(t)try{return JSON.parse(t.description,Nt)}catch{}let e=r.annotations.find(n=>n.type===Pt&&n.description!==void 0);return e?{trackApiCalls:e.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 Nt(r,t){if(typeof t=="object"&&t!==null&&t.__regexp===true&&typeof t.source=="string"){let{source:e,flags:n}=t;return new RegExp(e,n)}return t}var _t={page:async({page:r},t,e)=>{let n=new N(r);try{await n.init();}catch{}await t(r);try{let{navigations:s,networkRequestsFile:o,networkRequestsCount:p,consoleLogsFile:u,consoleLogsCount:d}=await n.getFileData(),l={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:o,networkRequestsCount:p,consoleLogsFile:u,consoleLogsCount:d,apiCallsFile:null,apiCallsCount:0};await e.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(l)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:r},t,e)=>{let n=W(e);if(!n.trackApiCalls){await t(r);return}let s=new A,o=new b(r,s,n);o.intercept(),v(s,o);try{await t(r);}finally{v(null,null);}try{let{apiCallsFile:p,apiCallsCount:u}=o.getFileData(),d=n.captureAssertions?s.getData():[],l={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:d,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:p,apiCallsCount:u};await e.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(l)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}o.dispose(),s.dispose();}};test.test.extend(_t);var we=S(test.expect),ke={request:async({request:r},t,e)=>{let n=W(e);if(!n.trackApiCalls){await t(r);return}let s=new A,o=new b(r,s,n);o.intercept(),v(s,o);let p=null;try{p=new h("api-console");}catch{}let u=0,d=process.stdout.write,l=process.stderr.write;process.stdout.write=function(i,...g){try{let c=typeof i=="string"?i:Buffer.isBuffer(i)?i.toString("utf-8"):String(i);!c.startsWith("[testrelic]")&&!c.startsWith("\u2139 TestRelic")&&!c.startsWith("\u2713 TestRelic")&&!c.startsWith("\u26A0 TestRelic")&&p&&(p.append({level:"stdout",text:c.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),u++);}catch{}return d.apply(process.stdout,[i,...g])},process.stderr.write=function(i,...g){try{let c=typeof i=="string"?i:Buffer.isBuffer(i)?i.toString("utf-8"):String(i);!c.startsWith("[testrelic]")&&!c.startsWith("\u26A0 TestRelic")&&p&&(p.append({level:"stderr",text:c.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),u++);}catch{}return l.apply(process.stderr,[i,...g])};try{await t(r);}finally{process.stdout.write=d,process.stderr.write=l,v(null,null);}try{p?.close();let{apiCallsFile:i,apiCallsCount:g}=o.getFileData(),c=n.captureAssertions?s.getData():[],a={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:c,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:u>0?p?.getPath()??null:null,consoleLogsCount:u,apiCallsFile:i,apiCallsCount:g};await e.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(a)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}o.dispose(),s.dispose();}};exports.expect=we;exports.testRelicApiFixture=ke;//# sourceMappingURL=api-fixture.cjs.map
5
5
  //# sourceMappingURL=api-fixture.cjs.map