playwright-opentelemetry 0.8.0 → 0.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.
@@ -1,483 +0,0 @@
1
- import { a as flushFixtureSpans, c as generateSpanId, i as createTestTraceContext, t as resolvePlaywrightOpentelemetryConfig } from "./config-BltzmZgg.mjs";
2
- import path from "node:path";
3
- //#region src/fixture/browser-page-tracker.ts
4
- const BROWSER_PAGE_SPAN_NAME = "browser.page";
5
- const BROWSER_ROUTE_SPAN_NAME = "browser.route";
6
- const BROWSER_SERVICE_NAME = "playwright-browser";
7
- const SPAN_STATUS_CODE_UNSET$1 = 0;
8
- var BrowserPageTracker = class {
9
- traceContext;
10
- nextPageId = 1;
11
- pageStates = /* @__PURE__ */ new WeakMap();
12
- pages = /* @__PURE__ */ new Set();
13
- constructor(traceContext) {
14
- this.traceContext = traceContext;
15
- }
16
- registerPage(page) {
17
- this.stateFor(page);
18
- this.pages.add(page);
19
- }
20
- unregisterPage(page, endTime = /* @__PURE__ */ new Date()) {
21
- this.finishPageSpans(page, endTime);
22
- this.pages.delete(page);
23
- }
24
- finishAll(endTime = /* @__PURE__ */ new Date()) {
25
- for (const page of this.pages) this.finishPageSpans(page, endTime);
26
- this.pages.clear();
27
- }
28
- startDocumentNavigation(request) {
29
- if (!isMainFrameNavigationRequest(request)) return;
30
- const page = pageForRequest(request);
31
- if (!page) return;
32
- this.startDocumentPageSpan(page, request.url(), /* @__PURE__ */ new Date());
33
- }
34
- handleFrameNavigated(page, url) {
35
- const state = this.stateFor(page);
36
- const previousUrl = state.lastUrl;
37
- state.lastUrl = url;
38
- if (!previousUrl || previousUrl === "about:blank") return;
39
- if (!shouldCreateSameDocumentPageSpan(previousUrl, url, state.activeRouteSpan?.url)) return;
40
- this.startRouteSpan(page, url, previousUrl, /* @__PURE__ */ new Date());
41
- }
42
- getNetworkParent(request) {
43
- const page = pageForRequest(request);
44
- if (!page) return {
45
- spanId: this.traceContext.rootSpanId,
46
- routeAssociation: "root"
47
- };
48
- const state = this.stateFor(page);
49
- if (state.activeRouteSpan) return {
50
- spanId: state.activeRouteSpan.span.spanId,
51
- routeAssociation: "active-route"
52
- };
53
- if (state.activeDocumentSpan) return {
54
- spanId: state.activeDocumentSpan.span.spanId,
55
- routeAssociation: "active-page"
56
- };
57
- return {
58
- spanId: this.traceContext.rootSpanId,
59
- routeAssociation: "root"
60
- };
61
- }
62
- recordConsoleMessage(page, message, time = /* @__PURE__ */ new Date()) {
63
- const activeSpan = this.getActiveBrowserSpan(page);
64
- if (!activeSpan) return;
65
- const type = message.type();
66
- const attributes = {
67
- message: message.text(),
68
- "browser.console.type": type,
69
- "severity.text": consoleSeverityText(type)
70
- };
71
- const location = message.location();
72
- if (location.url) attributes["code.file.path"] = location.url;
73
- const line = consoleLocationLine(location);
74
- if (line !== void 0) attributes["code.line.number"] = line + 1;
75
- activeSpan.events.push({
76
- name: "log",
77
- time,
78
- attributes
79
- });
80
- }
81
- recordPageError(page, error, time = /* @__PURE__ */ new Date()) {
82
- const activeSpan = this.getActiveBrowserSpan(page);
83
- if (!activeSpan) return;
84
- const attributes = {};
85
- if (error.name) attributes["exception.type"] = error.name;
86
- if (error.message) attributes["exception.message"] = error.message;
87
- if (error.stack) attributes["exception.stacktrace"] = error.stack;
88
- activeSpan.events.push({
89
- name: "exception",
90
- time,
91
- attributes
92
- });
93
- }
94
- startDocumentPageSpan(page, url, startTime) {
95
- const state = this.stateFor(page);
96
- this.finishPageSpans(page, startTime);
97
- const span = this.createBrowserSpan({
98
- pageId: state.pageId,
99
- name: BROWSER_PAGE_SPAN_NAME,
100
- url,
101
- navigationType: "document",
102
- parentSpanId: this.traceContext.rootSpanId,
103
- startTime
104
- });
105
- state.activeDocumentSpan = {
106
- span,
107
- url
108
- };
109
- state.documentUrl = url;
110
- state.lastUrl = url;
111
- this.traceContext.addSpan(span);
112
- }
113
- startRouteSpan(page, url, previousUrl, startTime) {
114
- const state = this.stateFor(page);
115
- this.finishRouteSpan(state, startTime);
116
- const span = this.createBrowserSpan({
117
- pageId: state.pageId,
118
- name: BROWSER_ROUTE_SPAN_NAME,
119
- url,
120
- navigationType: "same-document",
121
- parentSpanId: state.activeDocumentSpan?.span.spanId ?? this.traceContext.rootSpanId,
122
- startTime,
123
- previousUrl,
124
- documentUrl: state.documentUrl
125
- });
126
- state.activeRouteSpan = {
127
- span,
128
- url
129
- };
130
- this.traceContext.addSpan(span);
131
- }
132
- finishPageSpans(page, endTime) {
133
- const state = this.pageStates.get(page);
134
- if (!state) return;
135
- this.finishRouteSpan(state, endTime);
136
- if (state.activeDocumentSpan) {
137
- state.activeDocumentSpan.span.endTime = endTime;
138
- state.activeDocumentSpan = void 0;
139
- }
140
- }
141
- finishRouteSpan(state, endTime) {
142
- if (state.activeRouteSpan) {
143
- state.activeRouteSpan.span.endTime = endTime;
144
- state.activeRouteSpan = void 0;
145
- }
146
- }
147
- getActiveBrowserSpan(page) {
148
- const state = this.pageStates.get(page);
149
- return state?.activeRouteSpan?.span ?? state?.activeDocumentSpan?.span;
150
- }
151
- stateFor(page) {
152
- const existing = this.pageStates.get(page);
153
- if (existing) return existing;
154
- const state = {
155
- pageId: `page-${this.nextPageId++}`,
156
- lastUrl: page.url()
157
- };
158
- this.pageStates.set(page, state);
159
- return state;
160
- }
161
- createBrowserSpan({ pageId, name, url, navigationType, parentSpanId, startTime, previousUrl, documentUrl }) {
162
- return {
163
- traceId: this.traceContext.traceId,
164
- spanId: generateSpanId(),
165
- parentSpanId,
166
- name,
167
- startTime,
168
- endTime: startTime,
169
- status: { code: SPAN_STATUS_CODE_UNSET$1 },
170
- attributes: pageAttributes({
171
- pageId,
172
- url,
173
- navigationType,
174
- previousUrl,
175
- documentUrl
176
- }),
177
- events: [],
178
- serviceName: BROWSER_SERVICE_NAME
179
- };
180
- }
181
- };
182
- function consoleSeverityText(type) {
183
- switch (type) {
184
- case "debug": return "DEBUG";
185
- case "warning": return "WARN";
186
- case "error":
187
- case "assert": return "ERROR";
188
- case "trace": return "TRACE";
189
- default: return "INFO";
190
- }
191
- }
192
- function consoleLocationLine(location) {
193
- return location.line ?? location.lineNumber;
194
- }
195
- function pageAttributes({ pageId, url, navigationType, previousUrl, documentUrl }) {
196
- const attributes = {
197
- "browser.resource.type": navigationType === "document" ? "page" : "route",
198
- "browser.page.id": pageId,
199
- "browser.page.navigation.type": navigationType,
200
- "url.full": url
201
- };
202
- try {
203
- const parsedUrl = new URL(url);
204
- attributes["url.path"] = parsedUrl.pathname;
205
- if (parsedUrl.search) attributes["url.query"] = parsedUrl.search.slice(1);
206
- } catch {}
207
- if (previousUrl) attributes["browser.route.previous_url"] = previousUrl;
208
- if (documentUrl) attributes["browser.document.url"] = documentUrl;
209
- return attributes;
210
- }
211
- function isMainFrameNavigationRequest(request) {
212
- if (!request.isNavigationRequest()) return false;
213
- try {
214
- const frame = request.frame();
215
- return frame === frame.page().mainFrame();
216
- } catch {
217
- return false;
218
- }
219
- }
220
- function pageForRequest(request) {
221
- try {
222
- return request.frame().page();
223
- } catch {
224
- return;
225
- }
226
- }
227
- function stripHash(url) {
228
- try {
229
- const parsed = new URL(url);
230
- parsed.hash = "";
231
- return parsed.toString();
232
- } catch {
233
- return url.split("#")[0] ?? url;
234
- }
235
- }
236
- function shouldCreateSameDocumentPageSpan(previousUrl, nextUrl, activePageUrl) {
237
- if (activePageUrl && stripHash(activePageUrl) === stripHash(nextUrl)) return false;
238
- return stripHash(previousUrl) !== stripHash(nextUrl);
239
- }
240
- //#endregion
241
- //#region src/fixture/network-propagator.ts
242
- function storeRequestTraceContext({ request, traceContext, parentSpanId, routeAssociation }) {
243
- const spanId = generateSpanId();
244
- traceContext.requestContexts.set(request, {
245
- traceId: traceContext.traceId,
246
- spanId,
247
- parentSpanId,
248
- routeAssociation
249
- });
250
- return spanId;
251
- }
252
- /**
253
- * Intercepts network requests to propagate trace context via traceparent header.
254
- * @param options - The propagator options
255
- */
256
- async function propagateRouteTraceHeaders({ route, request, traceId, spanId }) {
257
- const traceHeader = `00-${traceId}-${spanId}-01`;
258
- await route.fallback({ headers: {
259
- ...request.headers(),
260
- traceparent: traceHeader
261
- } });
262
- }
263
- //#endregion
264
- //#region src/fixture/reporter-config.ts
265
- const PLAYWRIGHT_OPENTELEMETRY_REPORTER_NAMES = new Set(["playwright-opentelemetry", "playwright-opentelemetry/reporter"]);
266
- const PLAYWRIGHT_OPENTELEMETRY_REPORTER_PATHS = ["dist/reporter.mjs", "dist/reporter.cjs"];
267
- const MISSING_PLAYWRIGHT_OPENTELEMETRY_REPORTER_ERROR = `playwright-opentelemetry fixture is enabled, but the reporter is missing.
268
-
269
- Add it to playwright.config.ts:
270
-
271
- reporter: [["playwright-opentelemetry/reporter"]]`;
272
- function hasPlaywrightOpentelemetryReporter(reporter) {
273
- return reporter.some(([reporterName]) => isPlaywrightOpentelemetryReporterName(reporterName));
274
- }
275
- function isPlaywrightOpentelemetryReporterName(reporterName) {
276
- if (PLAYWRIGHT_OPENTELEMETRY_REPORTER_NAMES.has(reporterName)) return true;
277
- const normalizedReporterName = reporterName.replace(/\\/g, "/");
278
- return PLAYWRIGHT_OPENTELEMETRY_REPORTER_PATHS.some((reporterPath) => normalizedReporterName === reporterPath || normalizedReporterName.endsWith(`/${reporterPath}`));
279
- }
280
- //#endregion
281
- //#region src/fixture/request-response-capture.ts
282
- /**
283
- * Detects the resource type based on Content-Type header with URL extension fallback.
284
- * This categorization mirrors Chrome DevTools Network tab behavior.
285
- *
286
- * @param contentType - The Content-Type response header value (may be null)
287
- * @param url - The request URL (used as fallback)
288
- * @returns The detected resource type
289
- */
290
- function detectResourceType(contentType, url) {
291
- if (contentType) {
292
- const mimeType = contentType.split(";")[0].trim().toLowerCase();
293
- if (mimeType !== "application/octet-stream") {
294
- if (mimeType === "text/html" || mimeType === "application/xhtml+xml") return "document";
295
- if (mimeType === "application/javascript" || mimeType === "text/javascript" || mimeType === "application/x-javascript" || mimeType === "application/ecmascript" || mimeType === "text/ecmascript" || mimeType === "module" || mimeType === "application/wasm") return "script";
296
- if (mimeType === "text/css") return "stylesheet";
297
- if (mimeType.startsWith("image/")) return "image";
298
- if (mimeType.startsWith("font/") || mimeType === "application/font-woff" || mimeType === "application/font-woff2" || mimeType === "application/x-font-ttf" || mimeType === "application/x-font-opentype") return "font";
299
- if (mimeType.startsWith("video/") || mimeType.startsWith("audio/")) return "media";
300
- if (mimeType === "application/json" || mimeType === "text/plain" || mimeType === "application/xml" || mimeType === "text/xml" || mimeType.endsWith("+json") || mimeType.endsWith("+xml")) return "fetch";
301
- }
302
- }
303
- const resourceType = detectResourceTypeFromUrl(url);
304
- if (resourceType) return resourceType;
305
- return "other";
306
- }
307
- /**
308
- * Detects resource type from URL file extension.
309
- * Used as fallback when Content-Type header is missing or generic.
310
- */
311
- function detectResourceTypeFromUrl(url) {
312
- try {
313
- const lastSegment = new URL(url).pathname.toLowerCase().split("/").pop() || "";
314
- const dotIndex = lastSegment.lastIndexOf(".");
315
- if (dotIndex === -1) return null;
316
- const extension = lastSegment.slice(dotIndex + 1);
317
- if (extension === "html" || extension === "htm" || extension === "xhtml") return "document";
318
- if (extension === "js" || extension === "mjs" || extension === "cjs" || extension === "jsx" || extension === "ts" || extension === "tsx" || extension === "wasm") return "script";
319
- if (extension === "css") return "stylesheet";
320
- if (extension === "png" || extension === "jpg" || extension === "jpeg" || extension === "gif" || extension === "svg" || extension === "webp" || extension === "ico" || extension === "bmp" || extension === "avif") return "image";
321
- if (extension === "woff" || extension === "woff2" || extension === "ttf" || extension === "otf" || extension === "eot") return "font";
322
- if (extension === "mp4" || extension === "webm" || extension === "ogg" || extension === "mp3" || extension === "wav" || extension === "m4a" || extension === "aac" || extension === "flac" || extension === "avi" || extension === "mov") return "media";
323
- if (extension === "json" || extension === "xml") return "fetch";
324
- return null;
325
- } catch {
326
- return null;
327
- }
328
- }
329
- /**
330
- * OpenTelemetry SpanKind values
331
- * @see https://opentelemetry.io/docs/specs/otel/trace/api/#spankind
332
- */
333
- const SPAN_KIND_CLIENT = 3;
334
- /**
335
- * OpenTelemetry SpanStatusCode values
336
- * @see https://opentelemetry.io/docs/specs/otel/trace/api/#set-status
337
- */
338
- const SPAN_STATUS_CODE_UNSET = 0;
339
- const SPAN_STATUS_CODE_ERROR = 2;
340
- /**
341
- * Captures request/response data and stores the complete network span in the
342
- * current test trace context. Called after the request has completed.
343
- *
344
- * @param options - The capture options
345
- */
346
- async function fixtureCaptureRequestResponse({ request, response, traceContext }) {
347
- const url = request.url();
348
- const method = request.method();
349
- const statusCode = response.status();
350
- const requestTraceContext = traceContext.requestContexts.get(request);
351
- if (!requestTraceContext) return;
352
- const timing = request.timing();
353
- const startTime = new Date(timing.startTime);
354
- const endTime = timing.responseEnd >= 0 ? new Date(timing.startTime + timing.responseEnd) : new Date(timing.startTime);
355
- const parsedUrl = new URL(url);
356
- const serverAddress = parsedUrl.hostname;
357
- const serverPort = parsedUrl.port !== "" ? Number.parseInt(parsedUrl.port, 10) : parsedUrl.protocol === "https:" ? 443 : 80;
358
- let statusCodeValue = SPAN_STATUS_CODE_UNSET;
359
- if (statusCode >= 400) statusCodeValue = SPAN_STATUS_CODE_ERROR;
360
- const resourceType = detectResourceType(await getResponseHeaderValue(response, "content-type"), url);
361
- const attributes = {
362
- "http.request.method": method,
363
- "url.full": url,
364
- "url.path": parsedUrl.pathname,
365
- "server.address": serverAddress,
366
- "server.port": serverPort,
367
- "http.response.status_code": statusCode,
368
- "http.resource.type": resourceType,
369
- "browser.request.route_association": requestTraceContext.routeAssociation
370
- };
371
- if (parsedUrl.search) attributes["url.query"] = parsedUrl.search.slice(1);
372
- if (statusCodeValue === SPAN_STATUS_CODE_ERROR) attributes["error.type"] = statusCode.toString();
373
- const networkSpan = {
374
- traceId: requestTraceContext.traceId,
375
- spanId: requestTraceContext.spanId,
376
- parentSpanId: requestTraceContext.parentSpanId,
377
- name: `HTTP ${method}`,
378
- kind: SPAN_KIND_CLIENT,
379
- startTime,
380
- endTime,
381
- status: { code: statusCodeValue },
382
- attributes,
383
- events: [],
384
- serviceName: "playwright-browser"
385
- };
386
- traceContext.addSpan(networkSpan);
387
- }
388
- async function getResponseHeaderValue(response, name) {
389
- try {
390
- return await response.headerValue(name);
391
- } catch {
392
- return null;
393
- }
394
- }
395
- //#endregion
396
- //#region src/fixture/playwright-opentelemetry-fixture.ts
397
- function createPlaywrightOtelTest(testBase) {
398
- return testBase.extend({
399
- playwrightOpentelemetry: [void 0, { option: true }],
400
- _playwrightOpentelemetryReporterCheck: [async ({}, use, workerInfo) => {
401
- if (!hasPlaywrightOpentelemetryReporter(workerInfo.config.reporter)) throw new Error(MISSING_PLAYWRIGHT_OPENTELEMETRY_REPORTER_ERROR);
402
- await use();
403
- }, {
404
- scope: "worker",
405
- auto: true
406
- }],
407
- testTraceInfo: [async ({ playwright }, use, testInfo) => {
408
- const outputDir = path.dirname(testInfo.outputDir);
409
- await use({
410
- testId: testInfo.testId,
411
- outputDir
412
- });
413
- }, { auto: true }],
414
- testTraceContext: [async ({ playwrightOpentelemetry, trace }, use, testInfo) => {
415
- const config = resolvePlaywrightOpentelemetryConfig(playwrightOpentelemetry);
416
- const traceContext = await createTestTraceContext(testInfo);
417
- await use(traceContext);
418
- await flushFixtureSpans(traceContext, config, {
419
- trace: config.trace ?? trace,
420
- testInfo
421
- });
422
- }, { auto: true }],
423
- browserPageTracker: [async ({ testTraceContext }, use) => {
424
- const tracker = new BrowserPageTracker(testTraceContext);
425
- await use(tracker);
426
- tracker.finishAll();
427
- }, { auto: true }],
428
- context: async ({ context, playwrightOpentelemetry, testTraceContext, browserPageTracker }, use) => {
429
- const config = resolvePlaywrightOpentelemetryConfig(playwrightOpentelemetry);
430
- context.route("**", async (route, request) => {
431
- browserPageTracker.startDocumentNavigation(request);
432
- const networkParent = browserPageTracker.getNetworkParent(request);
433
- const spanId = storeRequestTraceContext({
434
- request,
435
- traceContext: testTraceContext,
436
- parentSpanId: networkParent.spanId,
437
- routeAssociation: networkParent.routeAssociation
438
- });
439
- if (config.propagateTraceHeaders) {
440
- await propagateRouteTraceHeaders({
441
- route,
442
- request,
443
- traceId: testTraceContext.traceId,
444
- spanId
445
- });
446
- return;
447
- }
448
- await route.fallback();
449
- });
450
- await use(context);
451
- },
452
- page: async ({ page, testTraceContext, browserPageTracker }, use) => {
453
- browserPageTracker.registerPage(page);
454
- page.on("close", () => browserPageTracker.unregisterPage(page));
455
- page.on("console", (message) => {
456
- browserPageTracker.recordConsoleMessage(page, message);
457
- });
458
- page.on("pageerror", (error) => {
459
- browserPageTracker.recordPageError(page, error);
460
- });
461
- page.on("framenavigated", (frame) => {
462
- if (frame === page.mainFrame()) browserPageTracker.handleFrameNavigated(page, frame.url());
463
- });
464
- const pendingRequests = /* @__PURE__ */ new Map();
465
- page.on("response", (response) => {
466
- pendingRequests.set(response.request(), response);
467
- });
468
- page.on("requestfinished", async (request) => {
469
- const response = pendingRequests.get(request);
470
- pendingRequests.delete(request);
471
- if (!response) return;
472
- await fixtureCaptureRequestResponse({
473
- request,
474
- response,
475
- traceContext: testTraceContext
476
- });
477
- });
478
- await use(page);
479
- }
480
- });
481
- }
482
- //#endregion
483
- export { createPlaywrightOtelTest as t };
@@ -1,67 +0,0 @@
1
- import { n as PlaywrightOpentelemetryUseOptions } from "./config-Db932l_s.mjs";
2
- import { n as SpanEvent, t as Span } from "./otel-D0ztpic2.mjs";
3
- import { ConsoleMessage, Page, Request, test } from "@playwright/test";
4
-
5
- //#region src/fixture/trace-context.d.ts
6
- interface PlaywrightOtelTraceContextAttachment {
7
- traceId: string;
8
- rootSpanId: string;
9
- }
10
- type FixtureSpan = Omit<Span, "events"> & {
11
- events: SpanEvent[];
12
- };
13
- interface NetworkRequestTraceContext {
14
- traceId: string;
15
- spanId: string;
16
- parentSpanId: string;
17
- routeAssociation: "active-route" | "active-page" | "root";
18
- }
19
- interface TestTraceContext extends PlaywrightOtelTraceContextAttachment {
20
- spans: FixtureSpan[];
21
- requestContexts: WeakMap<object, NetworkRequestTraceContext>;
22
- addSpan(span: FixtureSpan): void;
23
- }
24
- //#endregion
25
- //#region src/fixture/browser-page-tracker.d.ts
26
- declare class BrowserPageTracker {
27
- private readonly traceContext;
28
- private nextPageId;
29
- private pageStates;
30
- private pages;
31
- constructor(traceContext: TestTraceContext);
32
- registerPage(page: Page): void;
33
- unregisterPage(page: Page, endTime?: Date): void;
34
- finishAll(endTime?: Date): void;
35
- startDocumentNavigation(request: Request): void;
36
- handleFrameNavigated(page: Page, url: string): void;
37
- getNetworkParent(request: Request): {
38
- spanId: string;
39
- routeAssociation: "active-route" | "active-page" | "root";
40
- };
41
- recordConsoleMessage(page: Page, message: ConsoleMessage, time?: Date): void;
42
- recordPageError(page: Page, error: Error, time?: Date): void;
43
- private startDocumentPageSpan;
44
- private startRouteSpan;
45
- private finishPageSpans;
46
- private finishRouteSpan;
47
- private getActiveBrowserSpan;
48
- private stateFor;
49
- private createBrowserSpan;
50
- }
51
- //#endregion
52
- //#region src/fixture/playwright-opentelemetry-fixture.d.ts
53
- type TestTraceInfo = {
54
- testId: string;
55
- outputDir: string;
56
- };
57
- type PlaywrightOpentelemetryFixtures = {
58
- testTraceInfo: TestTraceInfo;
59
- testTraceContext: TestTraceContext;
60
- browserPageTracker: BrowserPageTracker;
61
- };
62
- type PlaywrightOpentelemetryWorkerFixtures = {
63
- _playwrightOpentelemetryReporterCheck: void;
64
- };
65
- declare function createPlaywrightOtelTest<T extends typeof test>(testBase: T): import("@playwright/test").TestType<import("@playwright/test").PlaywrightTestArgs & import("@playwright/test").PlaywrightTestOptions & PlaywrightOpentelemetryUseOptions & PlaywrightOpentelemetryFixtures, import("@playwright/test").PlaywrightWorkerArgs & import("@playwright/test").PlaywrightWorkerOptions & PlaywrightOpentelemetryWorkerFixtures>;
66
- //#endregion
67
- export { BrowserPageTracker as n, TestTraceContext as r, createPlaywrightOtelTest as t };