@testrelic/playwright-analytics 2.2.6 → 2.2.7

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,2 +1,2 @@
1
- import {performance}from'perf_hooks';import'fs';import {PAYLOAD_VERSION,ATTACHMENT_NAME,ATTACHMENT_CONTENT_TYPE}from'@testrelic/core';import {test}from'@playwright/test';var P=Symbol.for("__testrelic_call_id"),F="__testrelic_api_assertions",T=new WeakMap,C=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:F,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}};var L="[REDACTED]";function x(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())?L:r[s]);return n}function v(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=_(e,n);return JSON.stringify(s)}function _(r,t){if(Array.isArray(r))return r.map(e=>_(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]=L:e[n]=_(s,t);}return e}return r}function O(r,t,e){if(e.length>0){for(let n of e)if(E(r,n))return false}if(t.length>0){for(let n of t)if(E(r,n))return true;return false}return true}function E(r,t){try{return t instanceof RegExp?t.test(r):U(t).test(r)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(t)}`),false}}function U(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 J=["get","post","put","patch","delete","head","fetch"],G=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"],W="__testrelic_api_calls";function Y(r){let t=r.toLowerCase();return G.some(e=>t.includes(e))}function $(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}var N=class N{constructor(t,e,n){this.originals=new Map;this.capturedCalls=[];this.callCounter=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=t,this.assertionTracker=e??null,this.apiConfig=n??N.DEFAULT_API_CONFIG;}get lastCallId(){return this._lastCallId}getCallIdForValue(t){return t!=null&&typeof t=="object"?T.get(t)??null:this.primitiveCallIds.get(t)??null}intercept(){for(let e of J){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));}getData(){return [...this.capturedCalls]}flushLegacyAnnotations(t){this.capturedCalls.length!==0&&t.annotations.push({type:W,description:JSON.stringify(this.capturedCalls)});}dispose(){for(let[t,e]of this.originals)this.context[t]=e;this.originals.clear(),this.capturedCalls=[],this.callCounter=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCalls(){return this.capturedCalls}tagResponseMethods(t,e){let n=this,s=t.headers.bind(t);t.headers=function(){let i=s();return T.set(i,e),i};let l=t.headersArray.bind(t);t.headersArray=function(){let i=l();return T.set(i,e),i};let d=t.json.bind(t);t.json=async function(){let i=await d();return i!=null&&typeof i=="object"&&T.set(i,e),i};let c=t.status.bind(t);t.status=function(){let i=c();return n.primitiveCallIds.set(i,e),i};let a=t.statusText.bind(t);t.statusText=function(){let i=a();return n.primitiveCallIds.set(i,e),i};let u=t.ok.bind(t);t.ok=function(){let i=u();return n.primitiveCallIds.set(i,e),i};let o=t.text.bind(t);t.text=async function(){let i=await o();return n.primitiveCallIds.set(i,e),i};let g=t.body.bind(t);t.body=async function(){let i=await g();return T.set(i,e),i};}createWrapper(t,e){let n=this;return async function(l,d){if(!O(l,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return e(l,d);let c=`api-call-${n.callCounter++}`,a=new Date().toISOString(),u=t==="fetch"?(d?.method??"GET").toUpperCase():t.toUpperCase(),o=$(d),g=performance.now();n._lastCallId=c,n.assertionTracker&&n.assertionTracker.setCurrentCallId(c);let p;try{p=await e(l,d);}catch(i){let m=performance.now();try{let w=n.apiConfig.captureRequestBody?v(o,n.apiConfig.redactBodyFields):null,R={id:c,timestamp:a,method:u,url:l,requestHeaders:null,requestBody:w,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((m-g)*100)/100,isBinary:!1,error:i instanceof Error?i.message:String(i)};n.capturedCalls.push(R);}catch{}throw i}try{let i=performance.now(),m=p.headers(),w=m["content-type"]??null,R=w?!Y(w):!1,f=null;n.apiConfig.captureRequestHeaders&&d?.headers&&(f=d.headers);let h=null;n.apiConfig.captureResponseHeaders&&(h=m);let k=n.apiConfig.captureRequestBody?o:null,y=null;if(n.apiConfig.captureResponseBody)try{R?y=(await p.body()).toString("base64"):y=await p.text();}catch{}f=x(f,n.apiConfig.redactHeaders),h=x(h,n.apiConfig.redactHeaders),k=v(k,n.apiConfig.redactBodyFields),y=v(y,n.apiConfig.redactBodyFields);let b={id:c,timestamp:a,method:u,url:p.url(),requestHeaders:f,requestBody:k,responseStatusCode:p.status(),responseStatusText:p.statusText(),responseHeaders:h,responseBody:y,responseTimeMs:Math.round((i-g)*100)/100,isBinary:R,error:null};n.capturedCalls.push(b);}catch{}try{p[P]=c,n.tagResponseMethods(p,c);}catch{}return p}}};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 A=N;var z=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function X(r){let t=r.toLowerCase();return z.some(e=>t.includes(e))}function D(r,t){let e=new TextEncoder().encode(r);return e.length<=t?{text:r,truncated:false}:{text:new TextDecoder().decode(e.slice(0,t)),truncated:true}}var q=class r{constructor(t,e){this.page=t;this.records=[];this.listeners=[];this.currentNetworkCounter=null;this.pendingRequests=new Map;this.capturedRequests=[];this.pendingBodyReads=[];this.requestIdCounter=0;this.requestCaptureCount=0;this.consoleLogs=[];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),this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async getCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[t,e]of this.pendingRequests)this.capturedRequests.push({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.pendingRequests.delete(t);return [...this.capturedRequests].sort((t,e)=>t.startedAt.localeCompare(e.startedAt))}static mapConsoleType(t){switch(t){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getData(){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});let t=this.records.map(n=>({url:n.url,navigationType:n.navigationType,timestamp:n.timestamp,domContentLoadedAt:n.domContentLoadedAt,networkIdleAt:n.networkIdleAt,networkStats:n.networkStats})),e=this.includeNetworkStats?await this.getCapturedRequests():[];return {navigations:t,networkRequests:e,consoleLogs:[...this.consoleLogs]}}async flushLegacyAnnotations(t){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});for(let e of this.records){let n={url:e.url,navigationType:e.navigationType,timestamp:e.timestamp,domContentLoadedAt:e.domContentLoadedAt,networkIdleAt:e.networkIdleAt,networkStats:e.networkStats};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}if(this.includeNetworkStats){let e=await this.getCapturedRequests();e.length>0&&t.annotations.push({type:"__testrelic_network_requests",description:JSON.stringify(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:t,handler:e}of this.listeners)this.page.off(t,e);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.capturedRequests=[],this.pendingBodyReads=[],this.requestCaptureCount=0;}getRecords(){return 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 l=s;if(typeof l.parentFrame=="function"&&l.parentFrame()!==null)return;let d=l.url(),c=this.records[this.records.length-1];if(c&&Date.now()-new Date(c.timestamp).getTime()<50&&c.url===d)return;this.recordNavigation(d,"navigation");}catch{}};this.page.on("framenavigated",e),this.listeners.push({event:"framenavigated",handler:e});let n=s=>{try{let l=s,d=l.type(),c=l.text();if(d==="debug"&&c.startsWith("__testrelic_nav:")){try{let a=JSON.parse(c.slice(16));a.type&&a.url&&this.recordNavigation(a.url,a.type);}catch{}return}{let a=null;try{let o=l.location();o&&o.url&&(a=`${o.url}:${o.lineNumber}:${o.columnNumber}`);}catch{}let u=r.mapConsoleType(d);this.consoleLogs.push({level:u,text:c,timestamp:new Date().toISOString(),location:a});}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=c=>{if(this.currentNetworkCounter&&this.currentNetworkCounter.totalRequests++,!(this.requestCaptureCount>=500)){this.requestCaptureCount++;try{let a=c,u=String(this.requestIdCounter++),o=a.postData()??null,g=!1;if(o!==null){let i=D(o,10240);o=i.text,g=i.truncated;}let p={url:a.url(),method:a.method(),resourceType:this.mapResourceType(a.resourceType()),headers:a.headers(),postData:o,postDataTruncated:g,startedAt:new Date().toISOString(),startTimeMs:Date.now()};this.pendingRequests.set(u,p),c.__testrelic_id=u;}catch{}}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let l=c=>{try{let a=c;if(this.currentNetworkCounter){let f=a.status();f>=400&&(this.currentNetworkCounter.failedRequests++,this.currentNetworkCounter.failedRequestUrls.push(f+" "+a.url()));let h=a.headers()["content-length"];h&&(this.currentNetworkCounter.totalBytes+=parseInt(h,10)||0);let k=a.request().resourceType(),y=this.mapResourceType(k);this.currentNetworkCounter.byType[y]++;}let u=a.request().__testrelic_id;if(!u)return;let o=this.pendingRequests.get(u);if(!o)return;this.pendingRequests.delete(u);let g=Date.now()-o.startTimeMs,p=a.headers(),i=p["content-type"]??null,m=parseInt(p["content-length"]??"0",10)||0,w=i?!X(i):!1,R=(async()=>{let f=null,h=!1;if(!w)try{let b=(await a.body()).toString("utf-8"),S=D(b,10240);f=S.text,h=S.truncated;}catch{}let k={url:o.url,method:o.method,resourceType:o.resourceType,statusCode:a.status(),responseTimeMs:g,startedAt:o.startedAt,requestHeaders:o.headers,requestBody:o.postData,responseBody:f,responseHeaders:p,contentType:i,responseSize:m,requestBodyTruncated:o.postDataTruncated,responseBodyTruncated:h,isBinary:w,error:null};this.capturedRequests.push(k);})();this.pendingBodyReads.push(R);}catch{}};this.page.on("response",l),this.listeners.push({event:"response",handler:l});let d=c=>{if(this.currentNetworkCounter){this.currentNetworkCounter.failedRequests++;try{let a=c;this.currentNetworkCounter.failedRequestUrls.push("ERR "+a.url());}catch{}}try{let a=c,u=a.__testrelic_id;if(!u)return;let o=this.pendingRequests.get(u);if(!o)return;this.pendingRequests.delete(u);let g={url:o.url,method:o.method,resourceType:o.resourceType,statusCode:0,responseTimeMs:Date.now()-o.startTimeMs,startedAt:o.startedAt,requestHeaders:o.headers,requestBody:o.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:o.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:a.failure()?.errorText??"Unknown error"};this.capturedRequests.push(g);}catch{}};this.page.on("requestfailed",d),this.listeners.push({event:"requestfailed",handler:d});}}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.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}}),this.records.push({url:t,navigationType:e,timestamp:new Date().toISOString()}),this.includeNetworkStats&&(this.currentNetworkCounter=this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}mapResourceType(t){switch(t){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var V="__testrelic_api_config",Z="__testrelic_config_trackApiCalls";function I(r){let t=r.annotations.find(n=>n.type===V&&n.description!==void 0);if(t)try{return JSON.parse(t.description,Q)}catch{}let e=r.annotations.find(n=>n.type===Z&&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 Q(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 tt={page:async({page:r},t,e)=>{let n=new q(r);try{await n.init();}catch{}await t(r);try{let{navigations:s,networkRequests:l,consoleLogs:d}=await n.getData(),c={testRelicData:!0,version:PAYLOAD_VERSION,navigations:s,networkRequests:l,apiCalls:[],apiAssertions:[],consoleLogs:d};await e.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{await n.flushLegacyAnnotations(e);}catch{}n.dispose();},request:async({request:r},t,e)=>{let n=I(e);if(!n.trackApiCalls){await t(r);return}let s=new C,l=new A(r,s,n);l.intercept(),await t(r);try{let d=l.getData(),c=n.captureAssertions?s.getData():[],a={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:d,apiAssertions:c,consoleLogs:[]};await e.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(a)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{l.flushLegacyAnnotations(e);}catch{}try{s.flushLegacyAnnotations(e);}catch{}l.dispose(),s.dispose();}};test.extend(tt);var St={request:async({request:r},t,e)=>{let n=I(e);if(!n.trackApiCalls){await t(r);return}let s=new C,l=new A(r,s,n);l.intercept();let d=[],c=process.stdout.write,a=process.stderr.write;process.stdout.write=function(u,...o){try{let g=typeof u=="string"?u:Buffer.isBuffer(u)?u.toString("utf-8"):String(u);!g.startsWith("[testrelic]")&&!g.startsWith("\u2139 TestRelic")&&!g.startsWith("\u2713 TestRelic")&&!g.startsWith("\u26A0 TestRelic")&&d.push({level:"stdout",text:g.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null});}catch{}return c.apply(process.stdout,[u,...o])},process.stderr.write=function(u,...o){try{let g=typeof u=="string"?u:Buffer.isBuffer(u)?u.toString("utf-8"):String(u);!g.startsWith("[testrelic]")&&!g.startsWith("\u26A0 TestRelic")&&d.push({level:"stderr",text:g.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null});}catch{}return a.apply(process.stderr,[u,...o])};try{await t(r);}finally{process.stdout.write=c,process.stderr.write=a;}try{let u=l.getData(),o=n.captureAssertions?s.getData():[],g={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:u,apiAssertions:o,consoleLogs:d};await e.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(g)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{l.flushLegacyAnnotations(e);}catch{}try{s.flushLegacyAnnotations(e);}catch{}l.dispose(),s.dispose();}};export{St as testRelicApiFixture};//# sourceMappingURL=api-fixture.js.map
1
+ import {performance}from'perf_hooks';import'fs';import {PAYLOAD_VERSION,ATTACHMENT_NAME,ATTACHMENT_CONTENT_TYPE}from'@testrelic/core';import {test}from'@playwright/test';var B=Symbol.for("__testrelic_call_id"),H="__testrelic_api_assertions",T=new WeakMap,C=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:H,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}};var I="[REDACTED]";function S(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())?I:r[s]);return n}function v(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=b(e,n);return JSON.stringify(s)}function b(r,t){if(Array.isArray(r))return r.map(e=>b(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]=I:e[n]=b(s,t);}return e}return r}function L(r,t,e){if(e.length>0){for(let n of e)if(P(r,n))return false}if(t.length>0){for(let n of t)if(P(r,n))return true;return false}return true}function P(r,t){try{return t instanceof RegExp?t.test(r):j(t).test(r)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(t)}`),false}}function j(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 F=["get","post","put","patch","delete","head","fetch"],U=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"],J="__testrelic_api_calls";function G(r){let t=r.toLowerCase();return U.some(e=>t.includes(e))}function W(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}var N=class N{constructor(t,e,n){this.originals=new Map;this.capturedCalls=[];this.callCounter=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=t,this.assertionTracker=e??null,this.apiConfig=n??N.DEFAULT_API_CONFIG;}get lastCallId(){return this._lastCallId}getCallIdForValue(t){return t!=null&&typeof t=="object"?T.get(t)??null:this.primitiveCallIds.get(t)??null}intercept(){for(let e of F){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));}getData(){return [...this.capturedCalls]}flushLegacyAnnotations(t){this.capturedCalls.length!==0&&t.annotations.push({type:J,description:JSON.stringify(this.capturedCalls)});}dispose(){for(let[t,e]of this.originals)this.context[t]=e;this.originals.clear(),this.capturedCalls=[],this.callCounter=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCalls(){return this.capturedCalls}tagResponseMethods(t,e){let n=this,s=t.headers.bind(t);t.headers=function(){let a=s();return T.set(a,e),a};let l=t.headersArray.bind(t);t.headersArray=function(){let a=l();return T.set(a,e),a};let d=t.json.bind(t);t.json=async function(){let a=await d();return a!=null&&typeof a=="object"&&T.set(a,e),a};let c=t.status.bind(t);t.status=function(){let a=c();return n.primitiveCallIds.set(a,e),a};let o=t.statusText.bind(t);t.statusText=function(){let a=o();return n.primitiveCallIds.set(a,e),a};let u=t.ok.bind(t);t.ok=function(){let a=u();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 p=t.body.bind(t);t.body=async function(){let a=await p();return T.set(a,e),a};}createWrapper(t,e){let n=this;return async function(l,d){if(!L(l,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return e(l,d);let c=`api-call-${n.callCounter++}`,o=new Date().toISOString(),u=t==="fetch"?(d?.method??"GET").toUpperCase():t.toUpperCase(),i=W(d),p=performance.now();n._lastCallId=c,n.assertionTracker&&n.assertionTracker.setCurrentCallId(c);let g;try{g=await e(l,d);}catch(a){let k=performance.now();try{let y=n.apiConfig.captureRequestBody?v(i,n.apiConfig.redactBodyFields):null,m={id:c,timestamp:o,method:u,url:l,requestHeaders:null,requestBody:y,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((k-p)*100)/100,isBinary:!1,error:a instanceof Error?a.message:String(a)};n.capturedCalls.push(m);}catch{}throw a}try{let a=performance.now(),k=g.headers(),y=k["content-type"]??null,m=y?!G(y):!1,f=null;n.apiConfig.captureRequestHeaders&&d?.headers&&(f=d.headers);let h=null;n.apiConfig.captureResponseHeaders&&(h=k);let R=n.apiConfig.captureRequestBody?i:null,w=null;if(n.apiConfig.captureResponseBody)try{m?w=(await g.body()).toString("base64"):w=await g.text();}catch{}f=S(f,n.apiConfig.redactHeaders),h=S(h,n.apiConfig.redactHeaders),R=v(R,n.apiConfig.redactBodyFields),w=v(w,n.apiConfig.redactBodyFields);let M={id:c,timestamp:o,method:u,url:g.url(),requestHeaders:f,requestBody:R,responseStatusCode:g.status(),responseStatusText:g.statusText(),responseHeaders:h,responseBody:w,responseTimeMs:Math.round((a-p)*100)/100,isBinary:m,error:null};n.capturedCalls.push(M);}catch{}try{g[B]=c,n.tagResponseMethods(g,c);}catch{}return g}}};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 A=N;var Y=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function $(r){let t=r.toLowerCase();return Y.some(e=>t.includes(e))}var q=class r{constructor(t,e){this.page=t;this.records=[];this.listeners=[];this.currentNetworkCounter=null;this.pendingRequests=new Map;this.capturedRequests=[];this.pendingBodyReads=[];this.requestIdCounter=0;this.consoleLogs=[];this.includeNetworkStats=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),this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async getCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[t,e]of this.pendingRequests)this.capturedRequests.push({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.pendingRequests.delete(t);return [...this.capturedRequests].sort((t,e)=>t.startedAt.localeCompare(e.startedAt))}static mapConsoleType(t){switch(t){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getData(){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});let t=this.records.map(n=>({url:n.url,navigationType:n.navigationType,timestamp:n.timestamp,domContentLoadedAt:n.domContentLoadedAt,networkIdleAt:n.networkIdleAt,networkStats:n.networkStats})),e=this.includeNetworkStats?await this.getCapturedRequests():[];return {navigations:t,networkRequests:e,consoleLogs:[...this.consoleLogs]}}async flushLegacyAnnotations(t){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});for(let e of this.records){let n={url:e.url,navigationType:e.navigationType,timestamp:e.timestamp,domContentLoadedAt:e.domContentLoadedAt,networkIdleAt:e.networkIdleAt,networkStats:e.networkStats};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}if(this.includeNetworkStats){let e=await this.getCapturedRequests();e.length>0&&t.annotations.push({type:"__testrelic_network_requests",description:JSON.stringify(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:t,handler:e}of this.listeners)this.page.off(t,e);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.capturedRequests=[],this.pendingBodyReads=[];}getRecords(){return 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 l=s;if(typeof l.parentFrame=="function"&&l.parentFrame()!==null)return;let d=l.url(),c=this.records[this.records.length-1];if(c&&Date.now()-new Date(c.timestamp).getTime()<50&&c.url===d)return;this.recordNavigation(d,"navigation");}catch{}};this.page.on("framenavigated",e),this.listeners.push({event:"framenavigated",handler:e});let n=s=>{try{let l=s,d=l.type(),c=l.text();if(d==="debug"&&c.startsWith("__testrelic_nav:")){try{let o=JSON.parse(c.slice(16));o.type&&o.url&&this.recordNavigation(o.url,o.type);}catch{}return}{let o=null;try{let i=l.location();i&&i.url&&(o=`${i.url}:${i.lineNumber}:${i.columnNumber}`);}catch{}let u=r.mapConsoleType(d);this.consoleLogs.push({level:u,text:c,timestamp:new Date().toISOString(),location:o});}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=c=>{this.currentNetworkCounter&&this.currentNetworkCounter.totalRequests++;try{let o=c,u=String(this.requestIdCounter++),i=o.postData()??null,p={url:o.url(),method:o.method(),resourceType:this.mapResourceType(o.resourceType()),headers:o.headers(),postData:i,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now()};this.pendingRequests.set(u,p),c.__testrelic_id=u;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let l=c=>{try{let o=c;if(this.currentNetworkCounter){let f=o.status();f>=400&&(this.currentNetworkCounter.failedRequests++,this.currentNetworkCounter.failedRequestUrls.push(f+" "+o.url()));let h=o.headers()["content-length"];h&&(this.currentNetworkCounter.totalBytes+=parseInt(h,10)||0);let R=o.request().resourceType(),w=this.mapResourceType(R);this.currentNetworkCounter.byType[w]++;}let u=o.request().__testrelic_id;if(!u)return;let i=this.pendingRequests.get(u);if(!i)return;this.pendingRequests.delete(u);let p=Date.now()-i.startTimeMs,g=o.headers(),a=g["content-type"]??null,k=parseInt(g["content-length"]??"0",10)||0,y=a?!$(a):!1,m=(async()=>{let f=null;if(!y)try{f=(await o.body()).toString("utf-8");}catch{}let h={url:i.url,method:i.method,resourceType:i.resourceType,statusCode:o.status(),responseTimeMs:p,startedAt:i.startedAt,requestHeaders:i.headers,requestBody:i.postData,responseBody:f,responseHeaders:g,contentType:a,responseSize:k,requestBodyTruncated:i.postDataTruncated,responseBodyTruncated:!1,isBinary:y,error:null};this.capturedRequests.push(h);})();this.pendingBodyReads.push(m);}catch{}};this.page.on("response",l),this.listeners.push({event:"response",handler:l});let d=c=>{if(this.currentNetworkCounter){this.currentNetworkCounter.failedRequests++;try{let o=c;this.currentNetworkCounter.failedRequestUrls.push("ERR "+o.url());}catch{}}try{let o=c,u=o.__testrelic_id;if(!u)return;let i=this.pendingRequests.get(u);if(!i)return;this.pendingRequests.delete(u);let p={url:i.url,method:i.method,resourceType:i.resourceType,statusCode:0,responseTimeMs:Date.now()-i.startTimeMs,startedAt:i.startedAt,requestHeaders:i.headers,requestBody:i.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:i.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:o.failure()?.errorText??"Unknown error"};this.capturedRequests.push(p);}catch{}};this.page.on("requestfailed",d),this.listeners.push({event:"requestfailed",handler:d});}}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.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}}),this.records.push({url:t,navigationType:e,timestamp:new Date().toISOString()}),this.includeNetworkStats&&(this.currentNetworkCounter=this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}mapResourceType(t){switch(t){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var K="__testrelic_api_config",V="__testrelic_config_trackApiCalls";function x(r){let t=r.annotations.find(n=>n.type===K&&n.description!==void 0);if(t)try{return JSON.parse(t.description,X)}catch{}let e=r.annotations.find(n=>n.type===V&&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 X(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 Q={page:async({page:r},t,e)=>{let n=new q(r);try{await n.init();}catch{}await t(r);try{let{navigations:s,networkRequests:l,consoleLogs:d}=await n.getData(),c={testRelicData:!0,version:PAYLOAD_VERSION,navigations:s,networkRequests:l,apiCalls:[],apiAssertions:[],consoleLogs:d};await e.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{await n.flushLegacyAnnotations(e);}catch{}n.dispose();},request:async({request:r},t,e)=>{let n=x(e);if(!n.trackApiCalls){await t(r);return}let s=new C,l=new A(r,s,n);l.intercept(),await t(r);try{let d=l.getData(),c=n.captureAssertions?s.getData():[],o={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:d,apiAssertions:c,consoleLogs:[]};await e.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(o)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{l.flushLegacyAnnotations(e);}catch{}try{s.flushLegacyAnnotations(e);}catch{}l.dispose(),s.dispose();}};test.extend(Q);var bt={request:async({request:r},t,e)=>{let n=x(e);if(!n.trackApiCalls){await t(r);return}let s=new C,l=new A(r,s,n);l.intercept();let d=[],c=process.stdout.write,o=process.stderr.write;process.stdout.write=function(u,...i){try{let p=typeof u=="string"?u:Buffer.isBuffer(u)?u.toString("utf-8"):String(u);!p.startsWith("[testrelic]")&&!p.startsWith("\u2139 TestRelic")&&!p.startsWith("\u2713 TestRelic")&&!p.startsWith("\u26A0 TestRelic")&&d.push({level:"stdout",text:p.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null});}catch{}return c.apply(process.stdout,[u,...i])},process.stderr.write=function(u,...i){try{let p=typeof u=="string"?u:Buffer.isBuffer(u)?u.toString("utf-8"):String(u);!p.startsWith("[testrelic]")&&!p.startsWith("\u26A0 TestRelic")&&d.push({level:"stderr",text:p.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null});}catch{}return o.apply(process.stderr,[u,...i])};try{await t(r);}finally{process.stdout.write=c,process.stderr.write=o;}try{let u=l.getData(),i=n.captureAssertions?s.getData():[],p={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:u,apiAssertions:i,consoleLogs:d};await e.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(p)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{l.flushLegacyAnnotations(e);}catch{}try{s.flushLegacyAnnotations(e);}catch{}l.dispose(),s.dispose();}};export{bt as testRelicApiFixture};//# sourceMappingURL=api-fixture.js.map
2
2
  //# sourceMappingURL=api-fixture.js.map