-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathhelpers.ts
More file actions
574 lines (491 loc) · 15.6 KB
/
helpers.ts
File metadata and controls
574 lines (491 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/* eslint-disable max-lines */
import type { Page, Request } from '@playwright/test';
import type {
ClientReport,
Envelope,
EnvelopeItem,
EnvelopeItemType,
Event as SentryEvent,
EventEnvelope,
EventEnvelopeHeaders,
SerializedMetric,
SerializedMetricContainer,
SerializedSession,
TransactionEvent,
} from '@sentry/core';
import { parseEnvelope } from '@sentry/core';
export const envelopeUrlRegex = /\.sentry\.io\/api\/\d+\/envelope\//;
export const envelopeParser = (request: Request | null): unknown[] => {
// https://develop.sentry.dev/sdk/envelopes/
const envelope = request?.postData() || '';
// Third row of the envelop is the event payload.
return envelope.split('\n').map(line => {
try {
return JSON.parse(line);
} catch {
return line;
}
});
};
// Rather use the `properEnvelopeRequestParser`, as the `envelopeParser` does not follow the envelope spec.
export const envelopeRequestParser = <T = SentryEvent>(request: Request | null, envelopeIndex = 2): T => {
return envelopeParser(request)[envelopeIndex] as T;
};
/**
* The above envelope parser does not follow the envelope spec...
* ...but modifying it to follow the spec breaks a lot of the test which rely on the current indexing behavior.
*
* This parser is a temporary solution to allow us to test metrics with statsd envelopes.
*
* Eventually, all the tests should be migrated to use this 'proper' envelope parser!
*/
export const properEnvelopeParser = (request: Request | null): EnvelopeItem[] => {
// https://develop.sentry.dev/sdk/envelopes/
const envelope = request?.postData() || '';
const [, items] = parseEnvelope(envelope);
return items;
};
export type EventAndTraceHeader = [SentryEvent, EventEnvelopeHeaders['trace']];
/**
* Returns the first event item and `trace` envelope header from an envelope.
* This is particularly helpful if you want to test dynamic sampling and trace propagation-related cases.
*/
export const eventAndTraceHeaderRequestParser = (request: Request | null): EventAndTraceHeader => {
const envelope = properFullEnvelopeParser<EventEnvelope>(request);
return getEventAndTraceHeader(envelope);
};
const properFullEnvelopeParser = <T extends Envelope>(request: Request | null): T => {
// https://develop.sentry.dev/sdk/envelopes/
const envelope = request?.postData() || '';
return parseEnvelope(envelope) as T;
};
function getEventAndTraceHeader(envelope: EventEnvelope): EventAndTraceHeader {
const event = envelope[1][0]?.[1] as SentryEvent | undefined;
const trace = envelope[0]?.trace;
if (!event || !trace) {
throw new Error('Could not get event or trace from envelope');
}
return [event, trace];
}
export const properEnvelopeRequestParser = <T = SentryEvent>(
request: Request | null,
envelopeItemIndex: number,
envelopeIndex = 1, // 1 is usually the payload of the envelope (0 is the header)
): T => {
return properEnvelopeParser(request)[envelopeItemIndex]?.[envelopeIndex] as T;
};
export const properFullEnvelopeRequestParser = <T extends Envelope>(request: Request | null): T => {
// https://develop.sentry.dev/sdk/envelopes/
const envelope = request?.postData() || '';
return parseEnvelope(envelope) as T;
};
export const envelopeHeaderRequestParser = (request: Request | null): EventEnvelopeHeaders => {
// https://develop.sentry.dev/sdk/envelopes/
const envelope = request?.postData() || '';
// First row of the envelop is the event payload.
return envelope.split('\n').map(line => JSON.parse(line))[0];
};
export const getEnvelopeType = (request: Request | null): EnvelopeItemType => {
const envelope = request?.postData() || '';
return (envelope.split('\n').map(line => JSON.parse(line))[1] as Record<string, unknown>).type as EnvelopeItemType;
};
export const countEnvelopes = async (
page: Page,
options?: {
url?: string;
timeout?: number;
envelopeType: EnvelopeItemType | EnvelopeItemType[];
},
): Promise<number> => {
const countPromise = new Promise<number>((resolve, reject) => {
let reqCount = 0;
const requestHandler = (request: Request): void => {
if (envelopeUrlRegex.test(request.url())) {
try {
if (options?.envelopeType) {
const envelopeTypeArray = options
? typeof options.envelopeType === 'string'
? [options.envelopeType]
: options.envelopeType || (['event'] as EnvelopeItemType[])
: (['event'] as EnvelopeItemType[]);
if (envelopeTypeArray.includes(getEnvelopeType(request))) {
reqCount++;
}
}
} catch (e) {
reject(e);
}
}
};
page.on('request', requestHandler);
setTimeout(() => {
page.off('request', requestHandler);
resolve(reqCount);
}, options?.timeout || 1000);
});
if (options?.url) {
await page.goto(options.url);
}
return countPromise;
};
/**
* Run script inside the test environment.
* This is useful for throwing errors in the test environment.
*
* Errors thrown from this function are not guaranteed to be captured by Sentry, especially in Webkit.
*
* @param {Page} page
* @param {{ path?: string; content?: string }} impl
* @return {*} {Promise<void>}
*/
export async function runScriptInSandbox(
page: Page,
impl: {
path?: string;
content?: string;
},
): Promise<void> {
try {
await page.addScriptTag({ path: impl.path, content: impl.content });
} catch {
// no-op
}
}
/**
* Get Sentry events at the given URL, or the current page.
*
* @param {Page} page
* @param {string} [url]
* @return {*} {Promise<Array<SentryEvent>>}
*/
export async function getSentryEvents(page: Page, url?: string): Promise<Array<SentryEvent>> {
if (url) {
await page.goto(url);
}
const eventsHandle = await page.evaluateHandle<Array<SentryEvent>>('window.events');
return eventsHandle.jsonValue();
}
export async function waitForErrorRequestOnUrl(page: Page, url: string): Promise<Request> {
const [req] = await Promise.all([waitForErrorRequest(page), page.goto(url)]);
return req;
}
export async function waitForTransactionRequestOnUrl(page: Page, url: string): Promise<Request> {
const [req] = await Promise.all([waitForTransactionRequest(page), page.goto(url)]);
return req;
}
export function waitForErrorRequest(page: Page, callback?: (event: SentryEvent) => boolean): Promise<Request> {
return page.waitForRequest(req => {
const postData = req.postData();
if (!postData) {
return false;
}
try {
const event = envelopeRequestParser(req);
if (event.type) {
return false;
}
if (callback) {
return callback(event);
}
return true;
} catch {
return false;
}
});
}
export function waitForTransactionRequest(
page: Page,
callback?: (event: TransactionEvent) => boolean,
): Promise<Request> {
return page.waitForRequest(req => {
const postData = req.postData();
if (!postData) {
return false;
}
try {
const event = envelopeRequestParser(req);
if (event.type !== 'transaction') {
return false;
}
if (callback) {
return callback(event as TransactionEvent);
}
return true;
} catch {
return false;
}
});
}
export function waitForClientReportRequest(page: Page, callback?: (report: ClientReport) => boolean): Promise<Request> {
return page.waitForRequest(req => {
const postData = req.postData();
if (!postData) {
return false;
}
try {
const maybeReport = envelopeRequestParser<Partial<ClientReport>>(req);
if (typeof maybeReport.discarded_events !== 'object') {
return false;
}
if (callback) {
return callback(maybeReport as ClientReport);
}
return true;
} catch {
return false;
}
});
}
/**
* Wait for metric requests. Accumulates metrics across all matching requests
* and resolves when the callback returns true for the full set of collected metrics.
* If no callback is provided, resolves on the first request containing metrics.
*/
export function waitForMetrics(
page: Page,
callback?: (metrics: SerializedMetric[]) => boolean,
): Promise<SerializedMetric[]> {
const collected: SerializedMetric[] = [];
return page
.waitForRequest(req => {
const postData = req.postData();
if (!postData) {
return false;
}
try {
const envelope = properFullEnvelopeRequestParser<Envelope>(req);
const items = envelope[1];
const metrics: SerializedMetric[] = [];
for (const item of items) {
const [header] = item;
if (header.type === 'trace_metric') {
const payload = item[1] as SerializedMetricContainer;
if (payload.items) {
metrics.push(...payload.items);
}
}
}
if (metrics.length === 0) {
return false;
}
collected.push(...metrics);
if (callback) {
return callback(collected);
}
return true;
} catch {
return false;
}
})
.then(() => collected);
}
export async function waitForSession(
page: Page,
callback?: (session: SerializedSession) => boolean,
): Promise<SerializedSession> {
const req = await page.waitForRequest(req => {
const postData = req.postData();
if (!postData) {
return false;
}
try {
const event = envelopeRequestParser<SerializedSession>(req);
if (callback) {
return callback(event);
}
return typeof event.init === 'boolean' && event.started !== undefined;
} catch {
return false;
}
});
return envelopeRequestParser<SerializedSession>(req);
}
/**
* We can only test tracing tests in certain bundles/packages:
* - NPM (ESM, CJS)
* - CDN bundles that contain Tracing
*
* @returns `true` if we should skip the tracing test
*/
export function shouldSkipTracingTest(): boolean {
const bundle = process.env.PW_BUNDLE;
return bundle != null && !bundle.includes('tracing') && !bundle.includes('esm') && !bundle.includes('cjs');
}
/**
* We can only test metrics tests in certain bundles/packages:
* - NPM (ESM, CJS)
* - CDN bundles that contain metrics
*
* @returns `true` if we should skip the metrics test
*/
export function shouldSkipMetricsTest(): boolean {
const bundle = process.env.PW_BUNDLE;
return bundle != null && !bundle.includes('metrics') && !bundle.includes('esm') && !bundle.includes('cjs');
}
/**
* We can only test logs tests in certain bundles/packages:
* - NPM (ESM, CJS)
* - CDN bundles that contain logs
*
* @returns `true` if we should skip the logs test
*/
export function shouldSkipLogsTest(): boolean {
const bundle = process.env.PW_BUNDLE;
return bundle != null && !bundle.includes('logs') && !bundle.includes('esm') && !bundle.includes('cjs');
}
/**
* @returns `true` if we are testing a CDN bundle
*/
export function testingCdnBundle(): boolean {
const bundle = process.env.PW_BUNDLE;
return bundle != null && (bundle.startsWith('bundle') || bundle.startsWith('loader'));
}
/**
* Today we always run feedback tests, but this can be used to guard this if we ever need to.
*/
export function shouldSkipFeedbackTest(): boolean {
// We always run these, in bundles the pluggable integration is automatically added
return false;
}
/**
* We only test feature flags integrations in certain bundles/packages:
* - NPM (ESM, CJS)
* - Not CDNs.
*
* @returns `true` if we should skip the feature flags test
*/
export function shouldSkipFeatureFlagsTest(): boolean {
const bundle = process.env.PW_BUNDLE;
return bundle != null && !bundle.includes('esm') && !bundle.includes('cjs');
}
/**
* Returns true if the current bundle has debug logs.
*/
export function hasDebugLogs(): boolean {
const bundle = process.env.PW_BUNDLE;
return !bundle?.includes('min');
}
/**
* Waits until a number of requests matching urlRgx at the given URL arrive.
* If the timeout option is configured, this function will abort waiting, even if it hasn't received the configured
* amount of requests, and returns all the events received up to that point in time.
*/
async function getMultipleRequests<T>(
page: Page,
count: number,
urlRgx: RegExp,
requestParser: (req: Request) => T,
options?: {
url?: string;
timeout?: number;
envelopeType?: EnvelopeItemType | EnvelopeItemType[];
},
): Promise<T[]> {
const requests: Promise<T[]> = new Promise((resolve, reject) => {
let reqCount = count;
const requestData: T[] = [];
let timeoutId: NodeJS.Timeout | undefined = undefined;
function requestHandler(request: Request): void {
if (urlRgx.test(request.url())) {
try {
if (options?.envelopeType) {
const envelopeTypeArray = options
? typeof options.envelopeType === 'string'
? [options.envelopeType]
: options.envelopeType || (['event'] as EnvelopeItemType[])
: (['event'] as EnvelopeItemType[]);
if (!envelopeTypeArray.includes(getEnvelopeType(request))) {
return;
}
}
reqCount--;
requestData.push(requestParser(request));
if (reqCount === 0) {
if (timeoutId) {
clearTimeout(timeoutId);
}
page.off('request', requestHandler);
resolve(requestData);
}
} catch (err) {
reject(err);
}
}
}
page.on('request', requestHandler);
if (options?.timeout) {
timeoutId = setTimeout(() => {
resolve(requestData);
}, options.timeout);
}
});
if (options?.url) {
await page.goto(options.url);
}
return requests;
}
/**
* Wait and get multiple envelope requests at the given URL, or the current page
*/
export async function getMultipleSentryEnvelopeRequests<T>(
page: Page,
count: number,
options?: {
url?: string;
timeout?: number;
envelopeType?: EnvelopeItemType | EnvelopeItemType[];
},
requestParser: (req: Request) => T = envelopeRequestParser as (req: Request) => T,
): Promise<T[]> {
return getMultipleRequests<T>(page, count, envelopeUrlRegex, requestParser, options);
}
/**
* Wait and get the first envelope request at the given URL, or the current page
*
* @template T
* @param {Page} page
* @param {string} [url]
* @return {*} {Promise<T>}
*/
export async function getFirstSentryEnvelopeRequest<T>(
page: Page,
url?: string,
requestParser: (req: Request) => T = envelopeRequestParser as (req: Request) => T,
): Promise<T> {
const reqs = await getMultipleSentryEnvelopeRequests<T>(page, 1, { url }, requestParser);
const req = reqs[0];
if (!req) {
throw new Error('No request found');
}
return req;
}
export async function hidePage(page: Page): Promise<void> {
await page.evaluate(() => {
Object.defineProperty(document, 'visibilityState', {
configurable: true,
get: function () {
return 'hidden';
},
});
// Dispatch the visibilitychange event to notify listeners
document.dispatchEvent(new Event('visibilitychange'));
});
}
export async function waitForTracingHeadersOnUrl(
page: Page,
url: string,
): Promise<{ baggage: string; sentryTrace: string }> {
return new Promise<{ baggage: string; sentryTrace: string }>(resolve => {
page
.route(url, (route, req) => {
const baggage = req.headers()['baggage'];
const sentryTrace = req.headers()['sentry-trace'];
resolve({ baggage, sentryTrace });
return route.fulfill({ status: 200, body: 'ok' });
})
.catch(error => {
// Handle any routing setup errors
throw error;
});
});
}