@testrelic/playwright-analytics 2.9.0-next.67 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api-fixture.cjs +1 -1
- package/dist/api-fixture.cjs.map +1 -1
- package/dist/api-fixture.js +1 -1
- package/dist/api-fixture.js.map +1 -1
- package/dist/fixture.cjs +2 -2
- package/dist/fixture.cjs.map +1 -1
- package/dist/fixture.js +2 -2
- package/dist/fixture.js.map +1 -1
- package/dist/index.cjs +11 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +11 -11
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/fixture.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import {test,expect}from'@playwright/test';import {mkdirSync,openSync,writeSync,closeSync,unlinkSync,readFileSync}from'fs';import {join}from'path';import {tmpdir}from'os';import {randomUUID}from'crypto';import'readline';import {performance}from'perf_hooks';import {fileURLToPath}from'url';import {PAYLOAD_VERSION,ATTACHMENT_NAME,ATTACHMENT_CONTENT_TYPE}from'@testrelic/core';var j=join(tmpdir(),"testrelic-data"),m=class{constructor(e){this.count=0;this.closed=false;mkdirSync(j,{recursive:true}),this.filePath=join(j,`${e}-${randomUUID().substring(0,8)}.jsonl`),this.fd=openSync(this.filePath,"w");}append(e){if(this.closed)return;let t=JSON.stringify(e)+`
|
|
2
|
-
`;writeSync(this.fd,t),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{closeSync(this.fd);}catch{}}}cleanup(){try{unlinkSync(this.filePath);}catch{}}};var ae=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function ue(r){let e=r.toLowerCase();return ae.some(t=>e.includes(t))}var A=class r{constructor(e,t){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=t?.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 m("network")),this.consoleWriter=new m("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(t=>({url:t.url,navigationType:t.navigationType,timestamp:t.timestamp,domContentLoadedAt:t.domContentLoadedAt,networkIdleAt:t.networkIdleAt,networkStats:t.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:t}of this.listeners)this.page.off(e,t);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,t=this.page;t.goto=async function(n,s){return e.recordNavigation(n,"goto"),e.origGoto(n,s)},t.goBack=async function(n){let s=await e.origGoBack(n);return e.recordNavigation(t.url(),"back"),s},t.goForward=async function(n){let s=await e.origGoForward(n);return e.recordNavigation(t.url(),"forward"),s},t.reload=async function(n){return e.recordNavigation(t.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 t=s=>{try{let o=s;if(typeof o.parentFrame=="function"&&o.parentFrame()!==null)return;let p=o.url(),l=this.records[this.records.length-1];if(l&&Date.now()-new Date(l.timestamp).getTime()<50&&l.url===p)return;this.recordNavigation(p,"navigation");}catch{}};this.page.on("framenavigated",t),this.listeners.push({event:"framenavigated",handler:t});let n=s=>{try{let o=s,p=o.type(),l=o.text();if(p==="debug"&&l.startsWith("__testrelic_nav:")){try{let
|
|
2
|
+
`;writeSync(this.fd,t),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{closeSync(this.fd);}catch{}}}cleanup(){try{unlinkSync(this.filePath);}catch{}}};var ae=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function ue(r){let e=r.toLowerCase();return ae.some(t=>e.includes(t))}var A=class r{constructor(e,t){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=t?.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 m("network")),this.consoleWriter=new m("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(t=>({url:t.url,navigationType:t.navigationType,timestamp:t.timestamp,domContentLoadedAt:t.domContentLoadedAt,networkIdleAt:t.networkIdleAt,networkStats:t.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:t}of this.listeners)this.page.off(e,t);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,t=this.page;t.goto=async function(n,s){return e.recordNavigation(n,"goto"),e.origGoto(n,s)},t.goBack=async function(n){let s=await e.origGoBack(n);return e.recordNavigation(t.url(),"back"),s},t.goForward=async function(n){let s=await e.origGoForward(n);return e.recordNavigation(t.url(),"forward"),s},t.reload=async function(n){return e.recordNavigation(t.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 t=s=>{try{let o=s;if(typeof o.parentFrame=="function"&&o.parentFrame()!==null)return;let p=o.url(),l=this.records[this.records.length-1];if(l&&Date.now()-new Date(l.timestamp).getTime()<50&&l.url===p)return;this.recordNavigation(p,"navigation");}catch{}};this.page.on("framenavigated",t),this.listeners.push({event:"framenavigated",handler:t});let n=s=>{try{let o=s,p=o.type(),l=o.text();if(p==="debug"&&l.startsWith("__testrelic_nav:")){try{let c=JSON.parse(l.slice(16));c.type&&c.url&&this.recordNavigation(c.url,c.type);}catch{}return}{let c=null;try{let u=o.location();u&&u.url&&(c=`${u.url}:${u.lineNumber}:${u.columnNumber}`);}catch{}let a=r.mapConsoleType(p);this.consoleWriter&&(this.consoleWriter.append({level:a,text:l,timestamp:new Date().toISOString(),location:c}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=l=>{let c=this.records.length-1,a=this.counterForNav(c);a&&a.totalRequests++;try{let u=l,g=String(this.requestIdCounter++),d=u.postData()??null,i={url:u.url(),method:u.method(),resourceType:this.mapResourceType(u.resourceType()),headers:u.headers(),postData:d,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now(),navIndex:c};this.pendingRequests.set(g,i),l.__testrelic_id=g;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let o=l=>{try{let c=l,a=c.request().__testrelic_id,u=a?this.pendingRequests.get(a):void 0,g=this.counterForNav(u?u.navIndex:this.records.length-1);if(g){let f=c.status();f>=400&&(g.failedRequests++,g.failedRequestUrls.push(f+" "+c.url()));let y=c.headers()["content-length"];y&&(g.totalBytes+=parseInt(y,10)||0);let k=c.request().resourceType(),v=this.mapResourceType(k);g.byType[v]++;}if(!a||!u)return;this.pendingRequests.delete(a);let d=Date.now()-u.startTimeMs,i=c.headers(),h=i["content-type"]??null,R=parseInt(i["content-length"]??"0",10)||0,w=h?!ue(h):!1,T=(async()=>{let f=null;if(!w)try{f=(await c.body()).toString("utf-8");}catch{}let y={url:u.url,method:u.method,resourceType:u.resourceType,statusCode:c.status(),responseTimeMs:d,startedAt:u.startedAt,requestHeaders:u.headers,requestBody:u.postData,responseBody:f,responseHeaders:i,contentType:h,responseSize:R,requestBodyTruncated:u.postDataTruncated,responseBodyTruncated:!1,isBinary:w,error:null};this.networkWriter&&(this.networkWriter.append(y),this.networkRequestCount++);})();this.pendingBodyReads.push(T);}catch{}};this.page.on("response",o),this.listeners.push({event:"response",handler:o});let p=l=>{let c=l.__testrelic_id,a=c?this.pendingRequests.get(c):void 0,u=this.counterForNav(a?a.navIndex:this.records.length-1);if(u){u.failedRequests++;try{let g=l;u.failedRequestUrls.push("ERR "+g.url());}catch{}}try{let g=l;if(!c||!a)return;this.pendingRequests.delete(c);let d={url:a.url,method:a.method,resourceType:a.resourceType,statusCode:0,responseTimeMs:Date.now()-a.startTimeMs,startedAt:a.startedAt,requestHeaders:a.headers,requestBody:a.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:a.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:g.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(d),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",p),this.listeners.push({event:"requestfailed",handler:p});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let e=history.pushState.bind(history),t=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){t(...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,t){this.records.push({url:e,navigationType:t,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 t=this.navCounters[e];t&&(this.records[e].networkStats={totalRequests:t.totalRequests,failedRequests:t.failedRequests,failedRequestUrls:[...t.failedRequestUrls],totalBytes:t.totalBytes,byType:{...t.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 P=Symbol.for("__testrelic_call_id"),de="__testrelic_api_assertions",C=new WeakMap,b=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:de,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}},J=new Map;function pe(r){let e=J.get(r);if(e)return e;try{let t=r.startsWith("file://")?fileURLToPath(r):r,s=readFileSync(t,"utf-8").split(`
|
|
3
3
|
`);return J.set(r,s),s}catch{return null}}function ge(){let e=new Error().stack;if(!e)return null;let t=e.split(`
|
|
4
|
-
`);for(let n of t){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 fe(r,e){if(!r)return "custom";let t=r.toLowerCase();return t.includes(".status()")&&!t.includes(".statustext()")?t.includes(".ok()")?"statusOk":"status":t.includes(".ok()")?"statusOk":t.includes(".headers()")||t.includes(".headersarray()")?"header":t.includes("tomatchobject")||t.includes("toequal")?"bodyMatch":t.includes("tocontain")||t.includes("tostringcontaining")?"bodyContains":t.includes(".json()")||t.includes(".text()")?"bodyField":"custom"}function he(r,e,t){let n=function(o,...p){let l=r(),u=e();if(!l||!u)return t(o,...p);let a=null;if(o!=null&&typeof o=="object"){let i=o[P];typeof i=="string"&&(a=i);}if(!a&&o!==null&&o!==void 0&&typeof o=="object"&&(a=C.get(o)??null),a||(a=u.getCallIdForValue(o)),a||(a=l.getCurrentCallId()),!a)return t(o,...p);let c=ge(),g;if(c){let i=pe(c.file);i&&c.line>0&&c.line<=i.length&&(g=i[c.line-1].trim());}let d=t(o,...p);return a?z(d,{tracker:l,callId:a,received:o,location:c??{file:"unknown",line:0},expression:g}):d};for(let s of Object.keys(t))n[s]=t[s];return n}var G=null,$=null;function L(r,e){G=r,$=e;}function Y(r){return he(()=>G,()=>$,r)}function z(r,e){return new Proxy(r,{get(t,n,s){let o=Reflect.get(t,n,s);return typeof o!="function"||typeof n=="symbol"?o:n==="not"?z(o,e):function(...l){let u=l[0],a="passed",c=e.received,g=null;try{let d=o.apply(this??t,l);return d&&typeof d=="object"&&typeof d.then=="function"?d.then(()=>{_(e,n,u,c,"passed");},i=>{throw _(e,n,u,c,"failed"),i}):d}catch(d){if(a="failed",g=d,d instanceof Error&&d.message){let i=d.message.match(/Received:\s*(.+)/);i&&(c=i[1]);}throw d}finally{(g!==null||a==="passed")&&_(e,n,u,c,a);}}}})}function _(r,e,t,n,s){let o=fe(r.expression,r.received),p={callId:r.callId,type:o,expected:U(t),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 V="[REDACTED]";function F(r,e){if(r===null||e.length===0)return r;let t=new Set(e.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(r))Object.hasOwn(r,s)&&(n[s]=t.has(s.toLowerCase())?V:r[s]);return n}function q(r,e){if(r===null||e.length===0)return r;let t;try{t=JSON.parse(r);}catch{return r}if(typeof t!="object"||t===null)return r;let n=new Set(e),s=B(t,n);return JSON.stringify(s)}function B(r,e){if(Array.isArray(r))return r.map(t=>B(t,e));if(typeof r=="object"&&r!==null){let t={};for(let n of Object.keys(r)){if(!Object.hasOwn(r,n))continue;let s=r[n];e.has(n)?t[n]=V:t[n]=B(s,e);}return t}return r}function X(r,e,t){if(t.length>0){for(let n of t)if(K(r,n))return false}if(e.length>0){for(let n of e)if(K(r,n))return true;return false}return true}function K(r,e){try{return e instanceof RegExp?e.test(r):ye(e).test(r)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(e)}`),false}}function ye(r){let e="",t=0;for(;t<r.length;){let n=r[t];n==="*"&&r[t+1]==="*"?(e+=".*",t+=2,r[t]==="/"&&t++):n==="*"?(e+="[^/]*",t++):n==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(n)?(e+="\\"+n,t++):(e+=n,t++);}return new RegExp(e)}var we=["get","post","put","patch","delete","head","fetch"],ke=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function me(r){let e=r.toLowerCase();return ke.some(t=>e.includes(t))}function Ce(r){if(!r)return null;if(r.data!==void 0&&r.data!==null){let e=r.data;return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):JSON.stringify(e)}if(r.form!==void 0&&r.form!==null)return JSON.stringify(r.form);if(r.multipart!==void 0&&r.multipart!==null){let e=r.multipart,t={};for(let[n,s]of Object.entries(e))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?t[n]=String(s):s&&typeof s=="object"&&"name"in s?t[n]=`[file: ${s.name}]`:t[n]="[binary]";return JSON.stringify(t)}return null}function Q(r){return r?"\u2022\u2022\u2022\u2022":""}function Re(r){if(!r)return [];let e;for(let[n,s]of Object.entries(r))if(n.toLowerCase()==="cookie"){e=s;break}if(!e)return [];let t=[];for(let n of e.split(";")){let s=n.trim();if(!s)continue;let o=s.indexOf("="),p=o===-1?s:s.slice(0,o).trim(),l=o===-1?"":s.slice(o+1).trim();p&&t.push({name:p,value:Q(l)});}return t}function Te(r){let e=[];for(let t of r){let n=t.trim();if(!n)continue;let s=n.split(";"),o=s[0].indexOf("=");if(o===-1)continue;let p=s[0].slice(0,o).trim(),l=s[0].slice(o+1).trim(),u=s.slice(1).map(a=>a.trim()).filter(Boolean).join(" \xB7 ")||void 0;p&&e.push({name:p,value:Q(l),attributes:u});}return e}var S=class S{constructor(e,t,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=t??null,this.apiConfig=n??S.DEFAULT_API_CONFIG;try{this.apiCallWriter=new m("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?C.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let t of we){let n=this.context[t].bind(this.context);this.originals.set(t,n),this.context[t]=this.createWrapper(t,n);}let e=this.context.dispose.bind(this.context);this.originals.set("dispose",e),this.context.dispose=async t=>(this.disposed=true,e(t));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(e){}dispose(){for(let[e,t]of this.originals)this.context[e]=t;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,t){let n=this,s=e.headers.bind(e);e.headers=function(){let i=s();return C.set(i,t),i};let o=e.headersArray.bind(e);e.headersArray=function(){let i=o();return C.set(i,t),i};let p=e.json.bind(e);e.json=async function(){let i=await p();return i!=null&&typeof i=="object"&&C.set(i,t),i};let l=e.status.bind(e);e.status=function(){let i=l();return n.primitiveCallIds.set(i,t),i};let u=e.statusText.bind(e);e.statusText=function(){let i=u();return n.primitiveCallIds.set(i,t),i};let a=e.ok.bind(e);e.ok=function(){let i=a();return n.primitiveCallIds.set(i,t),i};let c=e.text.bind(e);e.text=async function(){let i=await c();return n.primitiveCallIds.set(i,t),i};let g=e.body.bind(e);e.body=async function(){let i=await g();return C.set(i,t),i};}createWrapper(e,t){let n=this;return async function(o,p){if(!X(o,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return t(o,p);let l=`api-call-${n.callCounter++}`,u=new Date().toISOString(),a=e==="fetch"?(p?.method??"GET").toUpperCase():e.toUpperCase(),c=Ce(p),g=performance.now();n._lastCallId=l,n.assertionTracker&&n.assertionTracker.setCurrentCallId(l);let d;try{d=await t(o,p);}catch(i){let h=performance.now();try{let R=n.apiConfig.captureRequestBody?q(c,n.apiConfig.redactBodyFields):null,k={id:l,timestamp:u,method:a,url:o,requestHeaders:null,requestBody:R,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((h-g)*100)/100,isBinary:!1,error:i instanceof Error?i.message:String(i)};n.apiCallWriter&&(n.apiCallWriter.append(k),n.apiCallCount++);}catch{}throw i}try{let i=performance.now(),h=d.headers(),R=h["content-type"]??null,k=R?!me(R):!1,T=null;n.apiConfig.captureRequestHeaders&&p?.headers&&(T=p.headers);let f=null;n.apiConfig.captureResponseHeaders&&(f=h);let y=n.apiConfig.captureRequestBody?c:null,w=null;if(n.apiConfig.captureResponseBody)try{k?w=(await d.body()).toString("base64"):w=await d.text();}catch{}let v=[],N=[];try{if(n.apiConfig.captureRequestHeaders&&(v=Re(p?.headers)),n.apiConfig.captureResponseHeaders){let W=d.headersArray().filter(I=>I.name.toLowerCase()==="set-cookie").map(I=>I.value);N=Te(W);}}catch{}T=F(T,n.apiConfig.redactHeaders),f=F(f,n.apiConfig.redactHeaders),y=q(y,n.apiConfig.redactBodyFields),w=q(w,n.apiConfig.redactBodyFields);let Z={id:l,timestamp:u,method:a,url:d.url(),requestHeaders:T,requestBody:y,responseStatusCode:d.status(),responseStatusText:d.statusText(),responseHeaders:f,responseBody:w,requestCookies:v.length?v:null,responseCookies:N.length?N:null,responseTimeMs:Math.round((i-g)*100)/100,isBinary:k,error:null};n.apiCallWriter&&(n.apiCallWriter.append(Z),n.apiCallCount++);}catch{}try{d[P]=l,n.tagResponseMethods(d,l);}catch{}return d}}};S.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 x=S;var nt=Y(expect),be="__testrelic_api_config",qe="__testrelic_config_trackApiCalls";function xe(r){let e=r.annotations.find(n=>n.type===be&&n.description!==void 0);if(e)try{return JSON.parse(e.description,Se)}catch{}let t=r.annotations.find(n=>n.type===qe&&n.description!==void 0);return t?{trackApiCalls:t.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 Se(r,e){if(typeof e=="object"&&e!==null&&e.__regexp===true&&typeof e.source=="string"){let{source:t,flags:n}=e;return new RegExp(t,n)}return e}var Ne={page:async({page:r},e,t)=>{let n=new A(r);try{await n.init();}catch{}await e(r);try{let{navigations:s,networkRequestsFile:o,networkRequestsCount:p,consoleLogsFile:l,consoleLogsCount:u}=await n.getFileData(),a={testRelicData:!0,version:PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:o,networkRequestsCount:p,consoleLogsFile:l,consoleLogsCount:u,apiCallsFile:null,apiCallsCount:0};await t.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(a)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:r},e,t)=>{let n=xe(t);if(!n.trackApiCalls){await e(r);return}let s=new b,o=new x(r,s,n);o.intercept(),L(s,o);try{await e(r);}finally{L(null,null);}try{let{apiCallsFile:p,apiCallsCount:l}=o.getFileData(),u=n.captureAssertions?s.getData():[],a={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],apiAssertions:u,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:p,apiCallsCount:l};await t.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(a)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}o.dispose(),s.dispose();}};async function rt(r,e){let t=new A(r);try{await t.init();}catch{}return async()=>{try{let{navigations:n,networkRequestsFile:s,networkRequestsCount:o,consoleLogsFile:p,consoleLogsCount:l}=await t.getFileData(),u={testRelicData:!0,version:PAYLOAD_VERSION,navigations:n,apiAssertions:[],networkRequestsFile:s,networkRequestsCount:o,consoleLogsFile:p,consoleLogsCount:l,apiCallsFile:null,apiCallsCount:0};await e.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(u)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}t.dispose();}}var st=test.extend(Ne);export{nt as expect,xe as readApiConfig,st as test,Ne as testRelicFixture,rt as trackPage};//# sourceMappingURL=fixture.js.map
|
|
4
|
+
`);for(let n of t){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 fe(r,e){if(!r)return "custom";let t=r.toLowerCase();return t.includes(".status()")&&!t.includes(".statustext()")?t.includes(".ok()")?"statusOk":"status":t.includes(".ok()")?"statusOk":t.includes(".headers()")||t.includes(".headersarray()")?"header":t.includes("tomatchobject")||t.includes("toequal")?"bodyMatch":t.includes("tocontain")||t.includes("tostringcontaining")?"bodyContains":t.includes(".json()")||t.includes(".text()")?"bodyField":"custom"}function he(r,e,t){let n=function(o,...p){let l=r(),c=e();if(!l||!c)return t(o,...p);let a=null;if(o!=null&&typeof o=="object"){let i=o[P];typeof i=="string"&&(a=i);}if(!a&&o!==null&&o!==void 0&&typeof o=="object"&&(a=C.get(o)??null),a||(a=c.getCallIdForValue(o)),a||(a=l.getCurrentCallId()),!a)return t(o,...p);let u=ge(),g;if(u){let i=pe(u.file);i&&u.line>0&&u.line<=i.length&&(g=i[u.line-1].trim());}let d=t(o,...p);return a?Y(d,{tracker:l,callId:a,received:o,location:u??{file:"unknown",line:0},expression:g}):d};for(let s of Object.keys(t))n[s]=t[s];return n}var G=null,$=null;function L(r,e){G=r,$=e;}function z(r){return he(()=>G,()=>$,r)}function Y(r,e){return new Proxy(r,{get(t,n,s){let o=Reflect.get(t,n,s);return typeof o!="function"||typeof n=="symbol"?o:n==="not"?Y(o,e):function(...l){let c=l[0],a="passed",u=e.received,g=null;try{let d=o.apply(this??t,l);return d&&typeof d=="object"&&typeof d.then=="function"?d.then(()=>{I(e,n,c,u,"passed");},i=>{throw I(e,n,c,u,"failed"),i}):d}catch(d){if(a="failed",g=d,d instanceof Error&&d.message){let i=d.message.match(/Received:\s*(.+)/);i&&(u=i[1]);}throw d}finally{(g!==null||a==="passed")&&I(e,n,c,u,a);}}}})}function I(r,e,t,n,s){let o=fe(r.expression,r.received),p={callId:r.callId,type:o,expected:U(t),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 V="[REDACTED]";function F(r,e){if(r===null||e.length===0)return r;let t=new Set(e.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(r))Object.hasOwn(r,s)&&(n[s]=t.has(s.toLowerCase())?V:r[s]);return n}function q(r,e){if(r===null||e.length===0)return r;let t;try{t=JSON.parse(r);}catch{return r}if(typeof t!="object"||t===null)return r;let n=new Set(e),s=B(t,n);return JSON.stringify(s)}function B(r,e){if(Array.isArray(r))return r.map(t=>B(t,e));if(typeof r=="object"&&r!==null){let t={};for(let n of Object.keys(r)){if(!Object.hasOwn(r,n))continue;let s=r[n];e.has(n)?t[n]=V:t[n]=B(s,e);}return t}return r}function X(r,e,t){if(t.length>0){for(let n of t)if(K(r,n))return false}if(e.length>0){for(let n of e)if(K(r,n))return true;return false}return true}function K(r,e){try{return e instanceof RegExp?e.test(r):ye(e).test(r)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(e)}`),false}}function ye(r){let e="",t=0;for(;t<r.length;){let n=r[t];n==="*"&&r[t+1]==="*"?(e+=".*",t+=2,r[t]==="/"&&t++):n==="*"?(e+="[^/]*",t++):n==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(n)?(e+="\\"+n,t++):(e+=n,t++);}return new RegExp(e)}var ke=["get","post","put","patch","delete","head","fetch"],we=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function me(r){let e=r.toLowerCase();return we.some(t=>e.includes(t))}function Ce(r){if(!r)return null;if(r.data!==void 0&&r.data!==null){let e=r.data;return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):JSON.stringify(e)}if(r.form!==void 0&&r.form!==null)return JSON.stringify(r.form);if(r.multipart!==void 0&&r.multipart!==null){let e=r.multipart,t={};for(let[n,s]of Object.entries(e))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?t[n]=String(s):s&&typeof s=="object"&&"name"in s?t[n]=`[file: ${s.name}]`:t[n]="[binary]";return JSON.stringify(t)}return null}function Z(r){return r?"\u2022\u2022\u2022\u2022":""}function Re(r){if(!r)return [];let e;for(let[n,s]of Object.entries(r))if(n.toLowerCase()==="cookie"){e=s;break}if(!e)return [];let t=[];for(let n of e.split(";")){let s=n.trim();if(!s)continue;let o=s.indexOf("="),p=o===-1?s:s.slice(0,o).trim(),l=o===-1?"":s.slice(o+1).trim();p&&t.push({name:p,value:Z(l)});}return t}function Te(r){let e=[];for(let t of r)for(let n of t.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 l=o[0].slice(0,p).trim(),c=o[0].slice(p+1).trim(),a=o.slice(1).map(u=>u.trim()).filter(Boolean).join(" \xB7 ")||void 0;l&&e.push({name:l,value:Z(c),attributes:a});}return e}var S=class S{constructor(e,t,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=t??null,this.apiConfig=n??S.DEFAULT_API_CONFIG;try{this.apiCallWriter=new m("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?C.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let t of ke){let n=this.context[t].bind(this.context);this.originals.set(t,n),this.context[t]=this.createWrapper(t,n);}let e=this.context.dispose.bind(this.context);this.originals.set("dispose",e),this.context.dispose=async t=>(this.disposed=true,e(t));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(e){}dispose(){for(let[e,t]of this.originals)this.context[e]=t;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,t){let n=this,s=e.headers.bind(e);e.headers=function(){let i=s();return C.set(i,t),i};let o=e.headersArray.bind(e);e.headersArray=function(){let i=o();return C.set(i,t),i};let p=e.json.bind(e);e.json=async function(){let i=await p();return i!=null&&typeof i=="object"&&C.set(i,t),i};let l=e.status.bind(e);e.status=function(){let i=l();return n.primitiveCallIds.set(i,t),i};let c=e.statusText.bind(e);e.statusText=function(){let i=c();return n.primitiveCallIds.set(i,t),i};let a=e.ok.bind(e);e.ok=function(){let i=a();return n.primitiveCallIds.set(i,t),i};let u=e.text.bind(e);e.text=async function(){let i=await u();return n.primitiveCallIds.set(i,t),i};let g=e.body.bind(e);e.body=async function(){let i=await g();return C.set(i,t),i};}createWrapper(e,t){let n=this;return async function(o,p){if(!X(o,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return t(o,p);let l=`api-call-${n.callCounter++}`,c=new Date().toISOString(),a=e==="fetch"?(p?.method??"GET").toUpperCase():e.toUpperCase(),u=Ce(p),g=performance.now();n._lastCallId=l,n.assertionTracker&&n.assertionTracker.setCurrentCallId(l);let d;try{d=await t(o,p);}catch(i){let h=performance.now();try{let R=n.apiConfig.captureRequestBody?q(u,n.apiConfig.redactBodyFields):null,w={id:l,timestamp:c,method:a,url:o,requestHeaders:null,requestBody:R,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((h-g)*100)/100,isBinary:!1,error:i instanceof Error?i.message:String(i)};n.apiCallWriter&&(n.apiCallWriter.append(w),n.apiCallCount++);}catch{}throw i}try{let i=performance.now(),h=d.headers(),R=h["content-type"]??null,w=R?!me(R):!1,T=null;n.apiConfig.captureRequestHeaders&&p?.headers&&(T=p.headers);let f=null;n.apiConfig.captureResponseHeaders&&(f=h);let y=n.apiConfig.captureRequestBody?u:null,k=null;if(n.apiConfig.captureResponseBody)try{w?k=(await d.body()).toString("base64"):k=await d.text();}catch{}let v=[],N=[];try{if(n.apiConfig.captureRequestHeaders&&(v=Re(p?.headers)),n.apiConfig.captureResponseHeaders){let W=d.headersArray().filter(_=>_.name.toLowerCase()==="set-cookie").map(_=>_.value);N=Te(W);}}catch{}T=F(T,n.apiConfig.redactHeaders),f=F(f,n.apiConfig.redactHeaders),y=q(y,n.apiConfig.redactBodyFields),k=q(k,n.apiConfig.redactBodyFields);let Q={id:l,timestamp:c,method:a,url:d.url(),requestHeaders:T,requestBody:y,responseStatusCode:d.status(),responseStatusText:d.statusText(),responseHeaders:f,responseBody:k,requestCookies:v.length?v:null,responseCookies:N.length?N:null,responseTimeMs:Math.round((i-g)*100)/100,isBinary:w,error:null};n.apiCallWriter&&(n.apiCallWriter.append(Q),n.apiCallCount++);}catch{}try{d[P]=l,n.tagResponseMethods(d,l);}catch{}return d}}};S.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 x=S;var nt=z(expect),be="__testrelic_api_config",qe="__testrelic_config_trackApiCalls";function xe(r){let e=r.annotations.find(n=>n.type===be&&n.description!==void 0);if(e)try{return JSON.parse(e.description,Se)}catch{}let t=r.annotations.find(n=>n.type===qe&&n.description!==void 0);return t?{trackApiCalls:t.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 Se(r,e){if(typeof e=="object"&&e!==null&&e.__regexp===true&&typeof e.source=="string"){let{source:t,flags:n}=e;return new RegExp(t,n)}return e}var Ne={page:async({page:r},e,t)=>{let n=new A(r);try{await n.init();}catch{}await e(r);try{let{navigations:s,networkRequestsFile:o,networkRequestsCount:p,consoleLogsFile:l,consoleLogsCount:c}=await n.getFileData(),a={testRelicData:!0,version:PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:o,networkRequestsCount:p,consoleLogsFile:l,consoleLogsCount:c,apiCallsFile:null,apiCallsCount:0};await t.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(a)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:r},e,t)=>{let n=xe(t);if(!n.trackApiCalls){await e(r);return}let s=new b,o=new x(r,s,n);o.intercept(),L(s,o);try{await e(r);}finally{L(null,null);}try{let{apiCallsFile:p,apiCallsCount:l}=o.getFileData(),c=n.captureAssertions?s.getData():[],a={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],apiAssertions:c,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:p,apiCallsCount:l};await t.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(a)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}o.dispose(),s.dispose();}};async function rt(r,e){let t=new A(r);try{await t.init();}catch{}return async()=>{try{let{navigations:n,networkRequestsFile:s,networkRequestsCount:o,consoleLogsFile:p,consoleLogsCount:l}=await t.getFileData(),c={testRelicData:!0,version:PAYLOAD_VERSION,navigations:n,apiAssertions:[],networkRequestsFile:s,networkRequestsCount:o,consoleLogsFile:p,consoleLogsCount:l,apiCallsFile:null,apiCallsCount:0};await e.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}t.dispose();}}var st=test.extend(Ne);export{nt as expect,xe as readApiConfig,st as test,Ne as testRelicFixture,rt as trackPage};//# sourceMappingURL=fixture.js.map
|
|
5
5
|
//# sourceMappingURL=fixture.js.map
|