playwright-opentelemetry 0.5.0 → 0.6.1

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.
Files changed (37) hide show
  1. package/dist/config-B9i3jm5s.d.cts +15 -0
  2. package/dist/config-B9i3jm5s.d.mts +15 -0
  3. package/dist/fixture/factory.cjs +2 -2
  4. package/dist/fixture/factory.d.cts +1 -5
  5. package/dist/fixture/factory.d.mts +1 -5
  6. package/dist/fixture/factory.mjs +1 -1
  7. package/dist/fixture-1Zc7Gp0b.d.cts +61 -0
  8. package/dist/{factory-Df7HwxXO.mjs → fixture-C3xMi3bo.mjs} +192 -99
  9. package/dist/fixture-IJvYGCtD.d.mts +61 -0
  10. package/dist/{factory-kMxwg_DI.cjs → fixture-KBHTI5WC.cjs} +193 -100
  11. package/dist/fixture.cjs +3 -3
  12. package/dist/fixture.d.cts +13 -3
  13. package/dist/fixture.d.mts +13 -3
  14. package/dist/fixture.mjs +1 -1
  15. package/dist/index.cjs +1 -1
  16. package/dist/index.d.cts +3 -2
  17. package/dist/index.d.mts +3 -2
  18. package/dist/index.mjs +1 -1
  19. package/dist/otel-B-kvMiiq.d.cts +18 -0
  20. package/dist/otel-B-kvMiiq.d.mts +18 -0
  21. package/dist/reporter-D-ONZUZE.mjs +429 -0
  22. package/dist/reporter-DaCojFom.d.cts +25 -0
  23. package/dist/reporter-DaCojFom.d.mts +25 -0
  24. package/dist/reporter-pVDPoXTx.cjs +436 -0
  25. package/dist/reporter.cjs +1 -1
  26. package/dist/reporter.d.cts +2 -2
  27. package/dist/reporter.d.mts +2 -2
  28. package/dist/reporter.mjs +1 -1
  29. package/dist/trace-context-Cck0LEoL.mjs +205 -0
  30. package/dist/trace-context-Dd2Fmx9q.cjs +286 -0
  31. package/package.json +1 -1
  32. package/dist/index-BNfDd8Mg.d.cts +0 -45
  33. package/dist/index-BNfDd8Mg.d.mts +0 -45
  34. package/dist/reporter-BE9S9CtV.mjs +0 -461
  35. package/dist/reporter-BzHSG-gx.cjs +0 -468
  36. package/dist/trace-files-B6bmvwUq.mjs +0 -218
  37. package/dist/trace-files-DTK0XBIq.cjs +0 -325
@@ -1,468 +0,0 @@
1
- const require_trace_files = require("./trace-files-DTK0XBIq.cjs");
2
- let node_fs = require("node:fs");
3
- let node_path = require("node:path");
4
- node_path = require_trace_files.__toESM(node_path, 1);
5
- let node_fs_promises = require("node:fs/promises");
6
- node_fs_promises = require_trace_files.__toESM(node_fs_promises, 1);
7
- let _zip_js_zip_js = require("@zip.js/zip.js");
8
- //#region src/reporter/otel-attributes.ts
9
- const ATTR_CODE_FILE_PATH = "code.file.path";
10
- const ATTR_CODE_LINE_NUMBER = "code.line.number";
11
- const ATTR_TEST_CASE_NAME = "test.case.name";
12
- const ATTR_TEST_CASE_TITLE = "test.case.title";
13
- const ATTR_TEST_CASE_RESULT_STATUS = "test.case.result.status";
14
- //#endregion
15
- //#region src/reporter/reporter-attributes.ts
16
- const TEST_SPAN_NAME = "playwright.test";
17
- const TEST_STEP_SPAN_NAME = "playwright.test.step";
18
- const ATTR_TEST_STEP_NAME = "test.step.name";
19
- const ATTR_TEST_STEP_TITLE = "test.step.title";
20
- const ATTR_TEST_STEP_CATEGORY = "test.step.category";
21
- //#endregion
22
- //#region package.json
23
- var version = "0.5.0";
24
- //#endregion
25
- //#region src/reporter/sender.ts
26
- function dateToNanoseconds(date) {
27
- return (BigInt(date.getTime()) * BigInt(1e6)).toString();
28
- }
29
- function toOtlpAttributes(attributes) {
30
- return Object.entries(attributes).map(([key, value]) => {
31
- if (Array.isArray(value)) return {
32
- key,
33
- value: { arrayValue: { values: value.map((item) => ({ stringValue: item })) } }
34
- };
35
- else if (typeof value === "number") return {
36
- key,
37
- value: Number.isInteger(value) ? { intValue: value } : { doubleValue: value }
38
- };
39
- else if (typeof value === "boolean") return {
40
- key,
41
- value: { boolValue: value }
42
- };
43
- else return {
44
- key,
45
- value: { stringValue: value }
46
- };
47
- });
48
- }
49
- const SPAN_KIND_INTERNAL = 1;
50
- function buildResourceSpan(spans, serviceName, playwrightVersion) {
51
- const otlpSpans = spans.map((span) => ({
52
- traceId: span.traceId,
53
- spanId: span.spanId,
54
- parentSpanId: span.parentSpanId || void 0,
55
- name: span.name,
56
- kind: span.kind ?? SPAN_KIND_INTERNAL,
57
- startTimeUnixNano: dateToNanoseconds(span.startTime),
58
- endTimeUnixNano: dateToNanoseconds(span.endTime),
59
- attributes: toOtlpAttributes(span.attributes),
60
- droppedAttributesCount: 0,
61
- events: [],
62
- droppedEventsCount: 0,
63
- status: span.status,
64
- links: [],
65
- droppedLinksCount: 0
66
- }));
67
- return {
68
- resource: { attributes: [
69
- {
70
- key: "service.name",
71
- value: { stringValue: serviceName }
72
- },
73
- {
74
- key: "service.namespace",
75
- value: { stringValue: "playwright" }
76
- },
77
- {
78
- key: "service.version",
79
- value: { stringValue: playwrightVersion }
80
- }
81
- ] },
82
- scopeSpans: [{
83
- scope: {
84
- name: "playwright-opentelemetry",
85
- version
86
- },
87
- spans: otlpSpans
88
- }]
89
- };
90
- }
91
- function buildOtlpRequest(spans, serviceName, playwrightVersion) {
92
- const spansByService = /* @__PURE__ */ new Map();
93
- for (const span of spans) {
94
- const spanServiceName = span.serviceName ?? serviceName;
95
- const serviceSpans = spansByService.get(spanServiceName);
96
- if (serviceSpans) serviceSpans.push(span);
97
- else spansByService.set(spanServiceName, [span]);
98
- }
99
- const resourceSpans = [];
100
- for (const [svcName, svcSpans] of spansByService) resourceSpans.push(buildResourceSpan(svcSpans, svcName, playwrightVersion));
101
- return { resourceSpans };
102
- }
103
- async function sendSpans(spans, options) {
104
- if (spans.length === 0) return;
105
- const endpoint = options.tracesEndpoint;
106
- const headers = options.headers || {};
107
- const body = JSON.stringify(buildOtlpRequest(spans, options.serviceName, options.playwrightVersion));
108
- if (options.debug) console.log("Sending spans to", endpoint);
109
- const response = await fetch(endpoint, {
110
- method: "POST",
111
- body,
112
- headers: {
113
- "content-type": "application/json",
114
- ...headers
115
- }
116
- });
117
- if (!response.ok) {
118
- const error = await response.text();
119
- throw new Error(`Failed to send spans: ${response.status} ${response.statusText}, ${error}`);
120
- }
121
- }
122
- //#endregion
123
- //#region src/reporter/trace-zip-builder.ts
124
- /**
125
- * Get the zip filename based on test location and ID.
126
- * Format: {basename(file)}:{line}-{testId}-pw-otel.zip
127
- * Fallback: {testId}-pw-otel.zip (if no location info)
128
- */
129
- function getZipFilename(test, testId) {
130
- if (test.location) return `${node_path.default.basename(test.location.file)}:${test.location.line}-${testId}-pw-otel.zip`;
131
- return `${testId}-pw-otel.zip`;
132
- }
133
- const PLAYWRIGHT_TRACE_RESOURCES_DIR = "resources/";
134
- /**
135
- * Pattern to match Playwright screenshot filenames: {name}@{hex-hash}-{timestamp}.jpeg
136
- * Examples: page@f06f11f7c14d6ce1060d47d79f05c154-1766833384425.jpeg
137
- */
138
- const PLAYWRIGHT_SCREENSHOT_PATTERN = /^.+@[a-f0-9]+-\d+\.jpe?g$/i;
139
- /**
140
- * Extract screenshots from a Playwright trace ZIP file.
141
- * Screenshots are stored in the resources/ directory with names like:
142
- * {pageGuid}-{timestamp}.jpeg (e.g., page@abc123-1766929201038.jpeg)
143
- *
144
- * @param traceZipPath - Path to the Playwright trace.zip file
145
- * @returns Map of filename (without resources/ prefix) to Blob
146
- */
147
- async function extractScreenshotsFromPlaywrightTrace(traceZipPath) {
148
- const screenshots = /* @__PURE__ */ new Map();
149
- try {
150
- const zipBuffer = await node_fs_promises.default.readFile(traceZipPath);
151
- const zipReader = new _zip_js_zip_js.ZipReader(new _zip_js_zip_js.BlobReader(new Blob([zipBuffer])));
152
- const entries = await zipReader.getEntries();
153
- await Promise.all(entries.filter((entry) => {
154
- if (!isFileEntry(entry)) return false;
155
- if (!entry.filename.startsWith(PLAYWRIGHT_TRACE_RESOURCES_DIR)) return false;
156
- const name = entry.filename.slice(10);
157
- return PLAYWRIGHT_SCREENSHOT_PATTERN.test(name);
158
- }).map(async (entry) => {
159
- const filename = entry.filename.slice(10);
160
- const blob = await entry.getData(new _zip_js_zip_js.BlobWriter("image/jpeg"));
161
- screenshots.set(filename, blob);
162
- }));
163
- await zipReader.close();
164
- } catch (err) {
165
- if (err.code !== "ENOENT") console.warn(`Warning: Could not extract screenshots from trace ZIP: ${err}`);
166
- }
167
- return screenshots;
168
- }
169
- /**
170
- * Create a zip file containing the OTLP trace JSON and screenshots for a test.
171
- */
172
- async function createTraceZip(options) {
173
- const { outputDir, test, spans, serviceName, playwrightVersion, screenshots } = options;
174
- const otlpRequest = buildOtlpRequest(spans, serviceName, playwrightVersion);
175
- const traceJson = JSON.stringify(otlpRequest, null, 2);
176
- const zipWriter = new _zip_js_zip_js.ZipWriter(new _zip_js_zip_js.BlobWriter("application/zip"));
177
- await zipWriter.add("traces/playwright-opentelemetry.json", new Blob([traceJson]).stream());
178
- await Promise.all(Array.from(screenshots.entries()).map(([filename, blob]) => zipWriter.add(`screenshots/${filename}`, blob.stream())));
179
- const zipBlob = await zipWriter.close();
180
- const zipFilename = getZipFilename(test, test.id);
181
- const zipPath = node_path.default.join(outputDir, zipFilename);
182
- const arrayBuffer = await zipBlob.arrayBuffer();
183
- await node_fs_promises.default.writeFile(zipPath, Buffer.from(arrayBuffer));
184
- }
185
- function isFileEntry(entry) {
186
- return !entry.directory;
187
- }
188
- //#endregion
189
- //#region src/reporter/reporter.ts
190
- var PlaywrightOpentelemetryReporter = class {
191
- options;
192
- spans = [];
193
- rootDir;
194
- playwrightVersion;
195
- resolvedEndpoint;
196
- resolvedHeaders;
197
- resolvedTraceApiEndpoint;
198
- resolvedTraceApiHeaders;
199
- resolvedServiceName;
200
- /** Maps test.id to its project's outputDir */
201
- testOutputDirs = /* @__PURE__ */ new Map();
202
- testSpans = /* @__PURE__ */ new Map();
203
- testTraceIds = /* @__PURE__ */ new Map();
204
- stepSpanIds = /* @__PURE__ */ new Map();
205
- /** Tracks the span context stack per test for append-only file writes */
206
- spanContextStacks = /* @__PURE__ */ new Map();
207
- constructor(options = {}) {
208
- this.options = options;
209
- this.resolvedEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || options.otlpEndpoint || "";
210
- const envHeaders = process.env.OTEL_EXPORTER_OTLP_HEADERS ? parseOtlpHeaders(process.env.OTEL_EXPORTER_OTLP_HEADERS) : {};
211
- this.resolvedHeaders = {
212
- ...options.otlpHeaders,
213
- ...envHeaders
214
- };
215
- this.resolvedTraceApiEndpoint = options.playwrightTraceApiEndpoint || "";
216
- this.resolvedTraceApiHeaders = options.playwrightTraceApiHeaders || {};
217
- this.resolvedServiceName = process.env.OTEL_SERVICE_NAME || options.serviceName || "playwright-tests";
218
- if (!this.resolvedEndpoint && !this.resolvedTraceApiEndpoint && !this.options.storeTraceZip) throw new Error(getConfigurationErrorMessage());
219
- }
220
- onBegin(config, suite) {
221
- this.rootDir = config.rootDir;
222
- this.playwrightVersion = config.version;
223
- for (const test of suite.allTests()) {
224
- const project = test.parent.project();
225
- if (project?.outputDir) {
226
- this.testOutputDirs.set(test.id, project.outputDir);
227
- (0, node_fs.mkdirSync)(node_path.default.join(project.outputDir, require_trace_files.PW_OTEL_DIR), { recursive: true });
228
- }
229
- }
230
- }
231
- onTestBegin(test, result) {
232
- const testId = test.id;
233
- const outputDir = this.getOutputDir(testId);
234
- const traceId = require_trace_files.getOrCreateTraceId(outputDir, testId);
235
- this.testTraceIds.set(testId, traceId);
236
- const testSpanId = require_trace_files.generateSpanId();
237
- this.testSpans.set(testId, testSpanId);
238
- this.spanContextStacks.set(testId, [testSpanId]);
239
- require_trace_files.writeCurrentSpanId(outputDir, testId, testSpanId);
240
- require_trace_files.createNetworkDirs(outputDir, testId);
241
- }
242
- async onStepBegin(test, _result, step) {
243
- const testId = test.id;
244
- const outputDir = this.getOutputDir(testId);
245
- const stepId = getStepId(test, step);
246
- const stepSpanId = require_trace_files.generateSpanId();
247
- this.stepSpanIds.set(stepId, stepSpanId);
248
- const stack = this.spanContextStacks.get(testId);
249
- if (stack) {
250
- stack.push(stepSpanId);
251
- require_trace_files.writeCurrentSpanId(outputDir, testId, stepSpanId);
252
- }
253
- }
254
- onStepEnd(test, _result, _step) {
255
- const testId = test.id;
256
- const outputDir = this.getOutputDir(testId);
257
- const stack = this.spanContextStacks.get(testId);
258
- if (stack && stack.length > 1) {
259
- stack.pop();
260
- const currentParent = stack[stack.length - 1];
261
- require_trace_files.writeCurrentSpanId(outputDir, testId, currentParent);
262
- }
263
- }
264
- async onTestEnd(test, result) {
265
- const testId = test.id;
266
- const outputDir = this.getOutputDir(testId);
267
- const traceId = this.testTraceIds.get(testId);
268
- const testSpanId = this.testSpans.get(testId);
269
- if (!traceId || !testSpanId) throw new Error(`Test ${testId} not found`);
270
- const traceAttachment = result.attachments.find((attachment) => attachment.name === "trace" && attachment.contentType === "application/zip" && attachment.path);
271
- if (!traceAttachment?.path) return;
272
- result.attachments.push({
273
- name: "playwright-opentelemetry-trace-id",
274
- contentType: "text/plain",
275
- body: Buffer.from(traceId, "utf-8")
276
- });
277
- const attributes = {};
278
- const titlePath = test.titlePath();
279
- if (titlePath.length >= 3) attributes[ATTR_TEST_CASE_NAME] = titlePath.slice(3).join(" > ");
280
- const describes = titlePath.length > 4 ? titlePath.slice(3, -1) : [];
281
- attributes[ATTR_TEST_CASE_TITLE] = test.title;
282
- attributes[ATTR_TEST_CASE_RESULT_STATUS] = result.status === "passed" ? "pass" : "fail";
283
- attributes["playwright.test.status"] = result.status;
284
- attributes["playwright.test.describes"] = describes;
285
- if (test.location) {
286
- const { file, line } = test.location;
287
- attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? node_path.default.relative(this.rootDir, file) : file;
288
- attributes[ATTR_CODE_LINE_NUMBER] = line;
289
- }
290
- const processedSteps = /* @__PURE__ */ new Map();
291
- if (result.steps && result.steps.length > 0) for (const step of result.steps) this.processTestStep(test, step, testSpanId, traceId, [], processedSteps);
292
- const stepSpans = [];
293
- for (const [key, stepSpan] of processedSteps.entries()) if (!key.startsWith("__skip__")) stepSpans.push(stepSpan);
294
- const networkSpans = await require_trace_files.collectNetworkSpans(outputDir, testId);
295
- const browserPageSpans = await require_trace_files.collectBrowserPageSpans(outputDir, testId, networkSpans, new Date(result.startTime.getTime() + result.duration));
296
- let minStartTime = result.startTime;
297
- let maxEndTime = new Date(result.startTime.getTime() + result.duration);
298
- for (const stepSpan of stepSpans) {
299
- if (stepSpan.startTime < minStartTime) minStartTime = stepSpan.startTime;
300
- if (stepSpan.endTime > maxEndTime) maxEndTime = stepSpan.endTime;
301
- }
302
- for (const browserSpan of [...browserPageSpans, ...networkSpans]) {
303
- if (browserSpan.startTime < minStartTime) minStartTime = browserSpan.startTime;
304
- if (browserSpan.endTime > maxEndTime) maxEndTime = browserSpan.endTime;
305
- }
306
- const testSpans = [
307
- {
308
- traceId,
309
- spanId: testSpanId,
310
- name: TEST_SPAN_NAME,
311
- startTime: minStartTime,
312
- endTime: maxEndTime,
313
- attributes,
314
- status: { code: result.status === test.expectedStatus ? 1 : 2 }
315
- },
316
- ...stepSpans,
317
- ...browserPageSpans,
318
- ...networkSpans
319
- ];
320
- this.spans.push(...testSpans);
321
- const relativeFilePath = test.location && this.rootDir ? node_path.default.relative(this.rootDir, test.location.file) : test.location?.file ?? "";
322
- const computedDuration = maxEndTime.getTime() - minStartTime.getTime();
323
- const screenshots = await extractScreenshotsFromPlaywrightTrace(traceAttachment.path);
324
- if (this.options.storeTraceZip) await createTraceZip({
325
- outputDir,
326
- testId,
327
- test,
328
- spans: testSpans,
329
- serviceName: this.resolvedServiceName,
330
- playwrightVersion: this.playwrightVersion || "unknown",
331
- relativeFilePath,
332
- status: result.status,
333
- startTime: minStartTime,
334
- duration: computedDuration,
335
- screenshots
336
- });
337
- if (this.resolvedTraceApiEndpoint) await this.sendScreenshotsToTraceApi({
338
- traceId,
339
- screenshots
340
- });
341
- }
342
- async onEnd(_result) {
343
- if (this.resolvedEndpoint && this.spans.length > 0) await sendSpans(this.spans, {
344
- tracesEndpoint: this.resolvedEndpoint,
345
- headers: this.resolvedHeaders,
346
- serviceName: this.resolvedServiceName,
347
- playwrightVersion: this.playwrightVersion || "unknown",
348
- debug: this.options.debug ?? false
349
- });
350
- if (this.resolvedTraceApiEndpoint && this.spans.length > 0) await sendSpans(this.spans, {
351
- tracesEndpoint: `${this.resolvedTraceApiEndpoint}/v1/traces`,
352
- headers: this.resolvedTraceApiHeaders,
353
- serviceName: this.resolvedServiceName,
354
- playwrightVersion: this.playwrightVersion || "unknown",
355
- debug: this.options.debug ?? false
356
- });
357
- for (const [testId, outputDir] of this.testOutputDirs.entries()) await require_trace_files.cleanupTestFiles(outputDir, testId);
358
- }
359
- processTestStep(test, step, parentSpanId, traceId, parentTitlePath, processedSteps) {
360
- const isInternalFixture = step.category === "fixture" && step.location?.file.includes("playwright-opentelemetry") && (step.location?.file.endsWith("fixture.mjs") || step.location?.file.endsWith("fixture/index.ts"));
361
- const stepId = getStepId(test, step);
362
- if (isInternalFixture) {
363
- processedSteps.set(`__skip__${stepId}`, {});
364
- if (processedSteps.has(stepId)) processedSteps.delete(stepId);
365
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps);
366
- return;
367
- }
368
- if (processedSteps.has(`__skip__${stepId}`)) {
369
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps);
370
- return;
371
- }
372
- const currentTitlePath = [...parentTitlePath, step.title];
373
- const stepSpanId = this.stepSpanIds.get(stepId) ?? require_trace_files.generateSpanId();
374
- const existingSpan = processedSteps.get(stepId);
375
- if (existingSpan) {
376
- if (step.location && !existingSpan.attributes["code.file.path"]) {
377
- const { file, line } = step.location;
378
- const relativePath = this.rootDir ? node_path.default.relative(this.rootDir, file) : file;
379
- existingSpan.attributes[ATTR_CODE_FILE_PATH] = relativePath;
380
- existingSpan.attributes[ATTR_CODE_LINE_NUMBER] = line;
381
- }
382
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, existingSpan.spanId, traceId, currentTitlePath, processedSteps);
383
- return;
384
- }
385
- const attributes = {};
386
- attributes[ATTR_TEST_STEP_NAME] = currentTitlePath.join(" > ");
387
- attributes[ATTR_TEST_STEP_TITLE] = step.title;
388
- attributes[ATTR_TEST_STEP_CATEGORY] = step.category;
389
- if (step.location) {
390
- const { file, line } = step.location;
391
- attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? node_path.default.relative(this.rootDir, file) : file;
392
- attributes[ATTR_CODE_LINE_NUMBER] = line;
393
- }
394
- const stepSpan = {
395
- traceId,
396
- spanId: stepSpanId,
397
- parentSpanId,
398
- name: TEST_STEP_SPAN_NAME,
399
- startTime: step.startTime,
400
- endTime: new Date(step.startTime.getTime() + step.duration),
401
- attributes,
402
- status: { code: step.error ? 2 : 1 }
403
- };
404
- processedSteps.set(stepId, stepSpan);
405
- if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, stepSpan.spanId, traceId, currentTitlePath, processedSteps);
406
- }
407
- onStdOut(chunk, _test, _result) {
408
- if (this.options.debug) console.log(chunk.toString().slice(0, -1));
409
- }
410
- onStdErr(chunk, _test, _result) {
411
- if (this.options.debug) console.log(chunk.toString().slice(0, -1));
412
- }
413
- printsToStdio() {
414
- return this.options.debug ?? false;
415
- }
416
- getOutputDir(testId) {
417
- const outputDir = this.testOutputDirs.get(testId);
418
- if (!outputDir) throw new Error(`No outputDir found for test "${testId}" - onBegin must be called first and test must exist in suite`);
419
- return outputDir;
420
- }
421
- async sendScreenshotsToTraceApi(params) {
422
- const { traceId, screenshots } = params;
423
- await Promise.all(Array.from(screenshots.entries()).map(async ([filename, blob]) => {
424
- const screenshotUrl = `${this.resolvedTraceApiEndpoint}/playwright-otel-reporter/v1/screenshots/${filename}`;
425
- const response = await fetch(screenshotUrl, {
426
- method: "PUT",
427
- headers: {
428
- "content-type": "image/jpeg",
429
- "x-trace-id": traceId,
430
- ...this.resolvedTraceApiHeaders
431
- },
432
- body: blob
433
- });
434
- if (!response.ok) {
435
- const error = await response.text();
436
- throw new Error(`Failed to send screenshot ${filename}: ${response.status} ${response.statusText}, ${error}`);
437
- }
438
- }));
439
- }
440
- };
441
- function parseOtlpHeaders(headersString) {
442
- const headers = {};
443
- const pairs = headersString.split(",");
444
- for (const pair of pairs) {
445
- const [key, ...valueParts] = pair.split("=");
446
- if (key && valueParts.length > 0) headers[key.trim()] = valueParts.join("=").trim();
447
- }
448
- return headers;
449
- }
450
- function getConfigurationErrorMessage() {
451
- return "playwright-opentelemetry reporter requires an OTLP endpoint to be configured.\n\nYou can configure it using environment variables:\n\n export OTEL_EXPORTER_OTLP_ENDPOINT=\"https://api.honeycomb.io\"\n export OTEL_EXPORTER_OTLP_HEADERS=\"x-honeycomb-team=YOUR_API_KEY\"\n export OTEL_SERVICE_NAME=\"my-service\"\n\nOr via playwright.config.ts:\n\nimport { defineConfig } from '@playwright/test';\nimport type { PlaywrightOpentelemetryReporterOptions } from 'playwright-opentelemetry';\n\nexport default defineConfig({\n reporter: [\n [\n 'playwright-opentelemetry/reporter',\n {\n otlpEndpoint: 'http://localhost:4317/v1/traces',\n otlpHeaders: {\n Authorization: 'Bearer YOUR_TOKEN',\n },\n serviceName: 'my-service',\n } satisfies PlaywrightOpentelemetryReporterOptions,\n ],\n ],\n});\n\nNote: Environment variables take precedence over config file options.\n";
452
- }
453
- function getStepId(test, step) {
454
- const startTimeMs = step.startTime.getTime();
455
- return [
456
- test.id,
457
- step.category,
458
- startTimeMs,
459
- ...step.titlePath()
460
- ].join(" > ");
461
- }
462
- //#endregion
463
- Object.defineProperty(exports, "PlaywrightOpentelemetryReporter", {
464
- enumerable: true,
465
- get: function() {
466
- return PlaywrightOpentelemetryReporter;
467
- }
468
- });
@@ -1,218 +0,0 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import path from "node:path";
3
- import fs from "node:fs/promises";
4
- //#region src/shared/trace-files.ts
5
- const PW_OTEL_DIR = "playwright-opentelemetry";
6
- function getOrCreateTraceId(outputDir, testId) {
7
- const tracePath = getTracePath(outputDir, testId);
8
- if (existsSync(tracePath)) return readFileSync(tracePath, "utf-8");
9
- const traceId = generateTraceId();
10
- writeFileSync(tracePath, traceId);
11
- return traceId;
12
- }
13
- /**
14
- * Write the current span ID to the span context file.
15
- * This is an append-only operation - the file maintains a log of all span context changes.
16
- * The fixture reads the last line to get the current parent span ID.
17
- */
18
- function writeCurrentSpanId(outputDir, testId, spanId) {
19
- writeFileSync(getSpanPath(outputDir, testId), `${spanId}\n`, { flag: "a" });
20
- }
21
- function getCurrentSpanId(outputDir, testId) {
22
- const lines = readFileSync(getSpanPath(outputDir, testId), "utf-8").trim().split("\n").filter((line) => line.length > 0);
23
- if (lines.length === 0) throw new Error(`No span context found for test ${testId}`);
24
- const lastLine = lines[lines.length - 1];
25
- if (!lastLine) throw new Error(`No span context found for test ${testId}`);
26
- return lastLine;
27
- }
28
- function createNetworkDirs(outputDir, testId) {
29
- mkdirSync(getNetworkParentDir(outputDir, testId), { recursive: true });
30
- mkdirSync(getNetworkSpanDir(outputDir, testId), { recursive: true });
31
- mkdirSync(getBrowserPageSpanDir(outputDir, testId), { recursive: true });
32
- }
33
- function writeNetworkSpanParent({ outputDir, testId, parentSpanId, traceHeader }) {
34
- writeFileSync(getNetworkParentPath(outputDir, testId, traceHeader), parentSpanId);
35
- }
36
- function readNetworkSpanParent(outputDir, testId, traceHeader) {
37
- const parentPath = getNetworkParentPath(outputDir, testId, traceHeader);
38
- try {
39
- return readFileSync(parentPath, "utf-8");
40
- } catch (err) {
41
- if (err.code === "ENOENT") return;
42
- throw err;
43
- }
44
- }
45
- function writeNetworkSpan(outputDir, testId, traceHeader, span) {
46
- const networkSpanPath = getNetworkSpanPath(outputDir, testId, traceHeader);
47
- const serialized = {
48
- ...span,
49
- startTime: span.startTime.toISOString(),
50
- endTime: span.endTime.toISOString()
51
- };
52
- writeFileSync(networkSpanPath, JSON.stringify(serialized));
53
- }
54
- function writeBrowserPageSpan(outputDir, testId, span) {
55
- const pageSpanPath = getBrowserPageSpanPath(outputDir, testId, span.spanId);
56
- const serialized = {
57
- ...span,
58
- startTime: span.startTime.toISOString(),
59
- endTime: span.endTime.toISOString()
60
- };
61
- writeFileSync(pageSpanPath, JSON.stringify(serialized));
62
- }
63
- async function collectBrowserPageSpans(outputDir, testId, networkSpans, fallbackEndTime) {
64
- const pageSpanDir = getBrowserPageSpanDir(outputDir, testId);
65
- try {
66
- const files = await fs.readdir(pageSpanDir);
67
- const spans = [];
68
- for (const file of files) {
69
- const content = await fs.readFile(path.join(pageSpanDir, file), "utf-8");
70
- const parsed = JSON.parse(content);
71
- spans.push({
72
- ...parsed,
73
- startTime: new Date(parsed.startTime),
74
- endTime: new Date(parsed.endTime)
75
- });
76
- }
77
- return finalizeBrowserPageSpanEndTimes(spans, networkSpans, fallbackEndTime);
78
- } catch (err) {
79
- if (err.code === "ENOENT") return [];
80
- throw err;
81
- }
82
- }
83
- function finalizeBrowserPageSpanEndTimes(spans, networkSpans, fallbackEndTime) {
84
- const spansByPageId = /* @__PURE__ */ new Map();
85
- const nextSpanBySpanId = /* @__PURE__ */ new Map();
86
- for (const span of spans) {
87
- const pageId = span.attributes["browser.page.id"];
88
- if (typeof pageId !== "string") {
89
- span.endTime = fallbackEndTime;
90
- continue;
91
- }
92
- const pageSpans = spansByPageId.get(pageId) ?? [];
93
- pageSpans.push(span);
94
- spansByPageId.set(pageId, pageSpans);
95
- }
96
- for (const pageSpans of spansByPageId.values()) {
97
- pageSpans.sort((a, b) => a.startTime.getTime() - b.startTime.getTime());
98
- for (let i = 0; i < pageSpans.length; i++) {
99
- const span = pageSpans[i];
100
- const nextSpan = pageSpans[i + 1];
101
- if (nextSpan) nextSpanBySpanId.set(span.spanId, nextSpan);
102
- span.endTime = nextSpan?.startTime ?? fallbackEndTime;
103
- }
104
- }
105
- for (const networkSpan of networkSpans) {
106
- const parentPageSpan = spans.find((span) => span.spanId === networkSpan.parentSpanId);
107
- if (parentPageSpan && !nextSpanBySpanId.has(parentPageSpan.spanId) && networkSpan.endTime > parentPageSpan.endTime) parentPageSpan.endTime = networkSpan.endTime;
108
- }
109
- return spans.sort((a, b) => a.startTime.getTime() - b.startTime.getTime());
110
- }
111
- /**
112
- * Collect all network spans for a test.
113
- * Called by the reporter at onTestEnd to gather HTTP client spans.
114
- * Reads all files from the network spans directory.
115
- *
116
- * @param outputDir - The Playwright output directory
117
- * @param testId - The unique test identifier
118
- * @returns Array of network spans
119
- */
120
- async function collectNetworkSpans(outputDir, testId) {
121
- const networkSpanDir = getNetworkSpanDir(outputDir, testId);
122
- try {
123
- const files = await fs.readdir(networkSpanDir);
124
- const spans = [];
125
- for (const file of files) {
126
- const content = await fs.readFile(path.join(networkSpanDir, file), "utf-8");
127
- const parsed = JSON.parse(content);
128
- spans.push({
129
- ...parsed,
130
- startTime: new Date(parsed.startTime),
131
- endTime: new Date(parsed.endTime)
132
- });
133
- }
134
- return spans;
135
- } catch (err) {
136
- if (err.code === "ENOENT") return [];
137
- throw err;
138
- }
139
- }
140
- /**
141
- * Cleanup all trace files for a test.
142
- * Called by the reporter after onTestEnd has processed the spans.
143
- *
144
- * @param outputDir - The Playwright output directory
145
- * @param testId - The unique test identifier
146
- */
147
- async function cleanupTestFiles(outputDir, testId) {
148
- try {
149
- await fs.unlink(getTracePath(outputDir, testId));
150
- } catch (err) {
151
- if (err.code !== "ENOENT") throw err;
152
- }
153
- try {
154
- await fs.unlink(getSpanPath(outputDir, testId));
155
- } catch (err) {
156
- if (err.code !== "ENOENT") throw err;
157
- }
158
- try {
159
- await fs.rm(getNetworkParentDir(outputDir, testId), { recursive: true });
160
- } catch (err) {
161
- if (err.code !== "ENOENT") throw err;
162
- }
163
- try {
164
- await fs.rm(getNetworkSpanDir(outputDir, testId), { recursive: true });
165
- } catch (err) {
166
- if (err.code !== "ENOENT") throw err;
167
- }
168
- try {
169
- await fs.rm(getBrowserPageSpanDir(outputDir, testId), { recursive: true });
170
- } catch (err) {
171
- if (err.code !== "ENOENT") throw err;
172
- }
173
- }
174
- function getTracePath(outputDir, testId) {
175
- return path.join(outputDir, PW_OTEL_DIR, `${sanitizeTestId(testId)}.trace`);
176
- }
177
- function getSpanPath(outputDir, testId) {
178
- return path.join(outputDir, PW_OTEL_DIR, `${sanitizeTestId(testId)}.span`);
179
- }
180
- function getNetworkParentDir(outputDir, testId) {
181
- return path.join(outputDir, PW_OTEL_DIR, `${sanitizeTestId(testId)}-network-parents`);
182
- }
183
- function getNetworkSpanDir(outputDir, testId) {
184
- return path.join(outputDir, PW_OTEL_DIR, `${sanitizeTestId(testId)}-network-spans`);
185
- }
186
- function getBrowserPageSpanDir(outputDir, testId) {
187
- return path.join(outputDir, PW_OTEL_DIR, `${sanitizeTestId(testId)}-browser-page-spans`);
188
- }
189
- function getNetworkParentPath(outputDir, testId, traceHeader) {
190
- return path.join(getNetworkParentDir(outputDir, testId), traceHeader);
191
- }
192
- function getNetworkSpanPath(outputDir, testId, traceHeader) {
193
- return path.join(getNetworkSpanDir(outputDir, testId), traceHeader);
194
- }
195
- function getBrowserPageSpanPath(outputDir, testId, spanId) {
196
- return path.join(getBrowserPageSpanDir(outputDir, testId), spanId);
197
- }
198
- /**
199
- * Sanitize test ID for use as filename.
200
- * Replaces characters that are invalid in filenames.
201
- */
202
- function sanitizeTestId(testId) {
203
- return testId.replace(/[<>:"/\\|?*]/g, "_");
204
- }
205
- /**
206
- * Generate a random 32-character hex trace ID.
207
- */
208
- function generateTraceId() {
209
- return Array.from({ length: 32 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
210
- }
211
- /**
212
- * Generate a random 16-character hex span ID.
213
- */
214
- function generateSpanId() {
215
- return Array.from({ length: 16 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
216
- }
217
- //#endregion
218
- export { createNetworkDirs as a, getOrCreateTraceId as c, writeCurrentSpanId as d, writeNetworkSpan as f, collectNetworkSpans as i, readNetworkSpanParent as l, cleanupTestFiles as n, generateSpanId as o, writeNetworkSpanParent as p, collectBrowserPageSpans as r, getCurrentSpanId as s, PW_OTEL_DIR as t, writeBrowserPageSpan as u };