@immense/vue-pom-generator 1.0.91 → 1.0.93

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 (66) hide show
  1. package/README.md +76 -2
  2. package/RELEASE_NOTES.md +22 -22
  3. package/class-generation/base-page.ts +141 -59
  4. package/class-generation/diagnostics.ts +559 -0
  5. package/class-generation/index.ts +123 -21
  6. package/class-generation/playwright-types.ts +7 -11
  7. package/class-generation/pointer.ts +65 -18
  8. package/dist/class-generation/base-page.d.ts +19 -4
  9. package/dist/class-generation/base-page.d.ts.map +1 -1
  10. package/dist/class-generation/diagnostics.d.ts +110 -0
  11. package/dist/class-generation/diagnostics.d.ts.map +1 -0
  12. package/dist/class-generation/index.d.ts +3 -0
  13. package/dist/class-generation/index.d.ts.map +1 -1
  14. package/dist/class-generation/playwright-types.d.ts +3 -39
  15. package/dist/class-generation/playwright-types.d.ts.map +1 -1
  16. package/dist/class-generation/pointer.d.ts +10 -1
  17. package/dist/class-generation/pointer.d.ts.map +1 -1
  18. package/dist/eslint/index.cjs +52 -9
  19. package/dist/eslint/index.cjs.map +1 -1
  20. package/dist/eslint/index.d.ts +16 -7
  21. package/dist/eslint/index.d.ts.map +1 -1
  22. package/dist/eslint/index.mjs +52 -9
  23. package/dist/eslint/index.mjs.map +1 -1
  24. package/dist/index.cjs +419 -298
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.mjs +419 -298
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/manifest-generator.d.ts +10 -5
  29. package/dist/manifest-generator.d.ts.map +1 -1
  30. package/dist/method-generation.d.ts.map +1 -1
  31. package/dist/playwright/reporter.cjs +174 -0
  32. package/dist/playwright/reporter.cjs.map +1 -0
  33. package/dist/playwright/reporter.d.ts +13 -0
  34. package/dist/playwright/reporter.d.ts.map +1 -0
  35. package/dist/playwright/reporter.mjs +174 -0
  36. package/dist/playwright/reporter.mjs.map +1 -0
  37. package/dist/playwright/runtime.cjs +945 -0
  38. package/dist/playwright/runtime.cjs.map +1 -0
  39. package/dist/playwright/runtime.mjs +945 -0
  40. package/dist/playwright/runtime.mjs.map +1 -0
  41. package/dist/plugin/internal/build-plugin.d.ts +2 -0
  42. package/dist/plugin/internal/build-plugin.d.ts.map +1 -1
  43. package/dist/plugin/internal/dev-plugin.d.ts +2 -0
  44. package/dist/plugin/internal/dev-plugin.d.ts.map +1 -1
  45. package/dist/plugin/internal-plugins.d.ts.map +1 -1
  46. package/dist/route-navigation-codegen.d.ts +3 -1
  47. package/dist/route-navigation-codegen.d.ts.map +1 -1
  48. package/dist/router-bridge.d.ts +14 -0
  49. package/dist/router-bridge.d.ts.map +1 -1
  50. package/dist/router.cjs +41 -1
  51. package/dist/router.cjs.map +1 -1
  52. package/dist/router.mjs +41 -1
  53. package/dist/router.mjs.map +1 -1
  54. package/dist/tests/broad/helpers/fake-runtime.d.ts +27 -3
  55. package/dist/tests/broad/helpers/fake-runtime.d.ts.map +1 -1
  56. package/dist/tests/fixtures/generated-tsc/base-page.full.d.ts +16 -3
  57. package/dist/tests/fixtures/generated-tsc/base-page.full.d.ts.map +1 -1
  58. package/dist/tests/method-generation.test.d.ts +2 -0
  59. package/dist/tests/method-generation.test.d.ts.map +1 -0
  60. package/dist/tests/playwright-diagnostics.test.d.ts +2 -0
  61. package/dist/tests/playwright-diagnostics.test.d.ts.map +1 -0
  62. package/dist/tests/playwright-reporter.test.d.ts +2 -0
  63. package/dist/tests/playwright-reporter.test.d.ts.map +1 -0
  64. package/dist/transform.d.ts.map +1 -1
  65. package/dist/vite.config.d.ts.map +1 -1
  66. package/package.json +13 -1
@@ -0,0 +1,559 @@
1
+ import { writeFile } from "node:fs/promises";
2
+ import type { TestInfo } from "@playwright/test";
3
+ import type { BrowserContext, Page } from "playwright";
4
+
5
+ export const POM_FAILURE_ATTACHMENT_NAME = "vue-pom-generator.failure";
6
+ export const POM_FAILURE_SCREENSHOT_ATTACHMENT_NAME = "vue-pom-generator.screenshot";
7
+
8
+ const DEFAULT_CAPTURE_BUDGET_MS = 5_000;
9
+ const MAX_BUFFERED_EVENTS = 100;
10
+ const MAX_TEXT_LENGTH = 2_000;
11
+ const MAX_HTTP_FAILURES = 20;
12
+ const MAX_HTTP_FAILURE_BODY_LENGTH = 8_000;
13
+ const HTTP_FAILURE_BODY_SETTLE_BUDGET_MS = 500;
14
+ const POM_ACTIVE_ACTION_REGISTRY = Symbol.for("@immense/vue-pom-generator.active-action-registry");
15
+
16
+ export interface PomManifestParameter {
17
+ name: string;
18
+ typeExpression?: string;
19
+ type?: string;
20
+ initializer?: string;
21
+ hasQuestionToken?: boolean;
22
+ isRestParameter?: boolean;
23
+ }
24
+
25
+ export interface PomManifestMethod {
26
+ name: string;
27
+ kind: "action" | "locator";
28
+ parameters: readonly PomManifestParameter[];
29
+ }
30
+
31
+ export interface PomManifestEntry {
32
+ testId: string;
33
+ selectorPatternKind: "static" | "parameterized";
34
+ generatedMethods: readonly PomManifestMethod[];
35
+ targetPageObjectModelClass?: string;
36
+ }
37
+
38
+ export interface PomManifestComponent {
39
+ componentName: string;
40
+ className: string;
41
+ sourceFile: string;
42
+ kind: "component" | "view";
43
+ entries: readonly PomManifestEntry[];
44
+ }
45
+
46
+ export type PomManifest = Readonly<Record<string, PomManifestComponent>>;
47
+
48
+ export interface PomActiveAction {
49
+ componentName?: string;
50
+ methodName: string;
51
+ expectedTestIds: readonly string[];
52
+ }
53
+
54
+ export interface PomRenderedElement {
55
+ testId: string;
56
+ tag: string;
57
+ role: string | null;
58
+ name: string | null;
59
+ visible: boolean;
60
+ enabled: boolean;
61
+ }
62
+
63
+ export interface PomMethodAvailability {
64
+ methodName: string;
65
+ kind: "action" | "locator";
66
+ signature: string;
67
+ expectedTestIds: string[];
68
+ state: "present" | "hidden" | "disabled" | "absent";
69
+ }
70
+
71
+ export interface PomComponentAvailability {
72
+ componentName: string;
73
+ className: string;
74
+ sourceFile: string;
75
+ matchedTestIds: number;
76
+ methods: PomMethodAvailability[];
77
+ }
78
+
79
+ export interface PomPageFailureSnapshot {
80
+ url: string;
81
+ title: string | null;
82
+ closed: boolean;
83
+ ariaSnapshot: string | null;
84
+ ariaSnapshotError?: string;
85
+ renderedElements: PomRenderedElement[];
86
+ component: PomComponentAvailability | null;
87
+ routerNavigation?: PomRouterNavigationSnapshot | null;
88
+ screenshotPath?: string;
89
+ captureErrors: string[];
90
+ }
91
+
92
+ export interface PomRouterNavigationSnapshot {
93
+ id: number;
94
+ status: "pending" | "succeeded" | "failed";
95
+ stage: "waiting-for-router-ready" | "pushing-route" | "complete";
96
+ targetName: string;
97
+ error?: string;
98
+ }
99
+
100
+ export interface PomFailureDiagnostics {
101
+ schemaVersion: 1;
102
+ capturedAt: string;
103
+ captureBudgetMs: number;
104
+ activeAction: PomActiveAction | null;
105
+ pages: PomPageFailureSnapshot[];
106
+ console: string[];
107
+ pageErrors: string[];
108
+ networkFailures: string[];
109
+ httpFailures?: PomHttpFailure[];
110
+ pendingRequests?: string[];
111
+ jsonPath: string;
112
+ }
113
+
114
+ export interface PomHttpFailure {
115
+ status: number;
116
+ method: string;
117
+ url: string;
118
+ contentType: string | null;
119
+ body?: string;
120
+ bodyCaptureError?: string;
121
+ }
122
+
123
+ export type PomDiagnosticsTestInfo = Pick<TestInfo, "attach" | "outputPath">;
124
+
125
+ export interface PomFailureDiagnosticsOptions {
126
+ captureBudgetMs?: number;
127
+ testIdAttribute?: string;
128
+ }
129
+
130
+ export interface PomFailureDiagnosticsCapture {
131
+ capture: () => Promise<PomFailureDiagnostics>;
132
+ }
133
+
134
+ interface EventBuffers {
135
+ console: string[];
136
+ pageErrors: string[];
137
+ networkFailures: string[];
138
+ httpFailures: PomHttpFailure[];
139
+ httpFailureBodyCaptures: Set<Promise<void>>;
140
+ pendingRequests: Map<object, { method: string; resourceType: string; startedAt: number; url: string }>;
141
+ }
142
+
143
+ function pushBounded(buffer: string[], value: string): void {
144
+ buffer.push(value.slice(0, MAX_TEXT_LENGTH));
145
+ if (buffer.length > MAX_BUFFERED_EVENTS) {
146
+ buffer.splice(0, buffer.length - MAX_BUFFERED_EVENTS);
147
+ }
148
+ }
149
+
150
+ function pushHttpFailureBounded(buffer: PomHttpFailure[], value: PomHttpFailure): void {
151
+ buffer.push(value);
152
+ if (buffer.length > MAX_HTTP_FAILURES) {
153
+ buffer.splice(0, buffer.length - MAX_HTTP_FAILURES);
154
+ }
155
+ }
156
+
157
+ function truncateText(value: string, maximum: number): string {
158
+ if (value.length <= maximum) return value;
159
+ return `${value.slice(0, maximum)}\n… truncated ${value.length - maximum} characters …`;
160
+ }
161
+
162
+ function formatNetworkUrl(value: string): string {
163
+ if (value.length <= 500) return value;
164
+
165
+ try {
166
+ const parsed = new URL(value);
167
+ return `${parsed.origin}${parsed.pathname}${parsed.search ? "?…" : ""}`;
168
+ }
169
+ catch {
170
+ return `${value.slice(0, 497)}…`;
171
+ }
172
+ }
173
+
174
+ function errorMessage<T>(error: T): string {
175
+ return error instanceof Error ? error.message : String(error);
176
+ }
177
+
178
+ function patternToRegExp(pattern: string): RegExp {
179
+ const escaped = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
180
+ return new RegExp(`^${escaped.replace(/\\\$\\\{[^}]+\\\}/g, ".+")}$`);
181
+ }
182
+
183
+ function matchesTestId(pattern: string, actual: string): boolean {
184
+ return pattern.includes("${") ? patternToRegExp(pattern).test(actual) : pattern === actual;
185
+ }
186
+
187
+ function formatMethodSignature(method: PomManifestMethod): string {
188
+ const parameters = method.parameters.map((parameter) => {
189
+ const rest = parameter.isRestParameter ? "..." : "";
190
+ const optional = parameter.hasQuestionToken ? "?" : "";
191
+ // Normalized manifest parameters retain the original typeExpression for
192
+ // provenance, but it may also contain the initializer (for example
193
+ // `string = ""`). Prefer the split type to avoid printing it twice.
194
+ const type = parameter.type ?? parameter.typeExpression ?? "unknown";
195
+ const initializer = parameter.initializer === undefined ? "" : ` = ${parameter.initializer}`;
196
+ return `${rest}${parameter.name}${optional}: ${type}${initializer}`;
197
+ });
198
+ return `${method.name}(${parameters.join(", ")})`;
199
+ }
200
+
201
+ function availabilityState(elements: readonly PomRenderedElement[]): PomMethodAvailability["state"] {
202
+ if (!elements.length) return "absent";
203
+ if (!elements.some(element => element.visible)) return "hidden";
204
+ if (!elements.some(element => element.visible && element.enabled)) return "disabled";
205
+ return "present";
206
+ }
207
+
208
+ function buildComponentAvailability(
209
+ manifest: PomManifest,
210
+ renderedElements: readonly PomRenderedElement[],
211
+ activeComponentName?: string,
212
+ ): PomComponentAvailability | null {
213
+ const renderedTestIds = Array.from(new Set(renderedElements.map(element => element.testId)));
214
+ const candidates = Object.values(manifest).map((component) => ({
215
+ component,
216
+ matchedTestIds: renderedTestIds.filter(actual => component.entries.some(entry => matchesTestId(entry.testId, actual))).length,
217
+ }));
218
+ candidates.sort((a, b) => b.matchedTestIds - a.matchedTestIds
219
+ || Number(b.component.kind === "view") - Number(a.component.kind === "view")
220
+ || a.component.componentName.localeCompare(b.component.componentName));
221
+
222
+ const activeCandidate = candidates.find(candidate => candidate.component.componentName === activeComponentName);
223
+ const selected = activeCandidate ?? candidates[0];
224
+ if (!selected || (selected.matchedTestIds === 0 && !activeCandidate)) return null;
225
+
226
+ const methods = new Map<string, { method: PomManifestMethod; testIds: Set<string> }>();
227
+ for (const entry of selected.component.entries) {
228
+ for (const method of entry.generatedMethods) {
229
+ const key = `${method.kind}:${method.name}`;
230
+ const current = methods.get(key) ?? { method, testIds: new Set<string>() };
231
+ current.testIds.add(entry.testId);
232
+ methods.set(key, current);
233
+ }
234
+ }
235
+
236
+ return {
237
+ componentName: selected.component.componentName,
238
+ className: selected.component.className,
239
+ sourceFile: selected.component.sourceFile,
240
+ matchedTestIds: selected.matchedTestIds,
241
+ methods: Array.from(methods.values())
242
+ .map(({ method, testIds }) => {
243
+ const expectedTestIds = Array.from(testIds).sort((a, b) => a.localeCompare(b));
244
+ const matchingElements = renderedElements.filter(element => expectedTestIds.some(pattern => matchesTestId(pattern, element.testId)));
245
+ return {
246
+ methodName: method.name,
247
+ kind: method.kind,
248
+ signature: formatMethodSignature(method),
249
+ expectedTestIds,
250
+ state: availabilityState(matchingElements),
251
+ } satisfies PomMethodAvailability;
252
+ })
253
+ .sort((a, b) => a.methodName.localeCompare(b.methodName)),
254
+ };
255
+ }
256
+
257
+ function remainingMilliseconds(deadline: number): number {
258
+ return Math.max(0, deadline - Date.now());
259
+ }
260
+
261
+ async function withinBudget<T>(deadline: number, operation: () => Promise<T>): Promise<T> {
262
+ const remaining = remainingMilliseconds(deadline);
263
+ if (remaining <= 0) throw new Error("diagnostic capture budget exhausted");
264
+
265
+ let timer: ReturnType<typeof setTimeout> | undefined;
266
+ try {
267
+ return await Promise.race([
268
+ operation(),
269
+ new Promise<T>((_resolve, reject) => {
270
+ timer = setTimeout(() => reject(new Error("diagnostic capture budget exhausted")), remaining);
271
+ }),
272
+ ]);
273
+ }
274
+ finally {
275
+ if (timer) clearTimeout(timer);
276
+ }
277
+ }
278
+
279
+ function installPageListeners(page: Page, buffers: EventBuffers): void {
280
+ page.on("console", message => pushBounded(buffers.console, `[${message.type()}] ${message.text()}`));
281
+ page.on("pageerror", error => pushBounded(buffers.pageErrors, errorMessage(error)));
282
+ page.on("request", (request) => {
283
+ buffers.pendingRequests.set(request, {
284
+ method: request.method(),
285
+ resourceType: request.resourceType(),
286
+ startedAt: Date.now(),
287
+ url: request.url(),
288
+ });
289
+ });
290
+ page.on("requestfinished", request => buffers.pendingRequests.delete(request));
291
+ page.on("requestfailed", (request) => {
292
+ buffers.pendingRequests.delete(request);
293
+ const failure = request.failure()?.errorText ?? "request failed";
294
+ pushBounded(buffers.networkFailures, `${request.method()} ${formatNetworkUrl(request.url())} — ${failure}`);
295
+ });
296
+ page.on("response", (response) => {
297
+ if (response.status() >= 400) {
298
+ pushBounded(buffers.networkFailures, `${response.status()} ${response.request().method()} ${formatNetworkUrl(response.url())}`);
299
+ const failure: PomHttpFailure = {
300
+ status: response.status(),
301
+ method: response.request().method(),
302
+ url: formatNetworkUrl(response.url()),
303
+ contentType: response.headers()["content-type"] ?? null,
304
+ };
305
+ pushHttpFailureBounded(buffers.httpFailures, failure);
306
+
307
+ const capture: Promise<void> = response.text()
308
+ .then((body) => {
309
+ if (body) failure.body = truncateText(body, MAX_HTTP_FAILURE_BODY_LENGTH);
310
+ })
311
+ .catch((error) => {
312
+ failure.bodyCaptureError = errorMessage(error);
313
+ })
314
+ .finally(() => buffers.httpFailureBodyCaptures.delete(capture));
315
+ buffers.httpFailureBodyCaptures.add(capture);
316
+ }
317
+ });
318
+ }
319
+
320
+ async function settleHttpFailureBodies(buffers: EventBuffers, deadline: number): Promise<void> {
321
+ const captures = Array.from(buffers.httpFailureBodyCaptures);
322
+ if (!captures.length) return;
323
+
324
+ const waitMs = Math.min(HTTP_FAILURE_BODY_SETTLE_BUDGET_MS, remainingMilliseconds(deadline));
325
+ if (waitMs <= 0) return;
326
+
327
+ let timer: ReturnType<typeof setTimeout> | undefined;
328
+ try {
329
+ await Promise.race([
330
+ Promise.allSettled(captures),
331
+ new Promise<void>((resolve) => {
332
+ timer = setTimeout(resolve, waitMs);
333
+ }),
334
+ ]);
335
+ }
336
+ finally {
337
+ if (timer) clearTimeout(timer);
338
+ }
339
+ }
340
+
341
+ async function captureRenderedElements(
342
+ page: Page,
343
+ testIdAttribute: string,
344
+ ): Promise<{ title: string; elements: PomRenderedElement[]; routerNavigation: PomRouterNavigationSnapshot | null }> {
345
+ return page.evaluate(({ attribute, routerGlobalName }) => {
346
+ const elements = Array.from(document.querySelectorAll(`[${CSS.escape(attribute)}]`));
347
+ const isVisibleElement = (candidate: HTMLElement) => {
348
+ const style = getComputedStyle(candidate);
349
+ const rect = candidate.getBoundingClientRect();
350
+ return style.display !== "none"
351
+ && style.visibility !== "hidden"
352
+ && Number.parseFloat(style.opacity || "1") > 0
353
+ && rect.width > 0
354
+ && rect.height > 0;
355
+ };
356
+ const rendered = elements.map((element) => {
357
+ const htmlElement = element as HTMLElement;
358
+ const disabled = ("disabled" in htmlElement && Boolean((htmlElement as HTMLButtonElement).disabled))
359
+ || htmlElement.getAttribute("aria-disabled") === "true";
360
+ const text = htmlElement.textContent?.replace(/\s+/g, " ").trim();
361
+ const inputType = htmlElement instanceof HTMLInputElement ? htmlElement.type.toLowerCase() : "";
362
+ const labels = htmlElement instanceof HTMLInputElement ? Array.from(htmlElement.labels ?? []) : [];
363
+ const labelText = labels.length
364
+ ? labels
365
+ .map(label => label.textContent?.replace(/\s+/g, " ").trim())
366
+ .filter((value): value is string => Boolean(value))
367
+ .join(" ")
368
+ : "";
369
+ const visible = isVisibleElement(htmlElement)
370
+ || ((inputType === "checkbox" || inputType === "radio") && labels.some(label => isVisibleElement(label)));
371
+ const role = htmlElement.getAttribute("role")
372
+ ?? (htmlElement.tagName === "BUTTON" ? "button" : null)
373
+ ?? (htmlElement.tagName === "A" && htmlElement.hasAttribute("href") ? "link" : null)
374
+ ?? (inputType === "checkbox" || inputType === "radio" ? inputType : null)
375
+ ?? (htmlElement.tagName === "TEXTAREA" || (htmlElement.tagName === "INPUT" && inputType !== "hidden") ? "textbox" : null)
376
+ ?? (htmlElement.tagName === "SELECT" ? "combobox" : null);
377
+ const name = htmlElement.getAttribute("aria-label")
378
+ ?? htmlElement.getAttribute("title")
379
+ ?? (labelText || null)
380
+ ?? (text ? text.slice(0, 160) : null);
381
+ return {
382
+ testId: htmlElement.getAttribute(attribute) ?? "",
383
+ tag: htmlElement.tagName.toLowerCase(),
384
+ role,
385
+ name,
386
+ visible,
387
+ enabled: !disabled,
388
+ };
389
+ }).filter(element => element.testId.length > 0);
390
+
391
+ const routerBridge = Reflect.get(globalThis, routerGlobalName) as
392
+ | { navigation?: PomRouterNavigationSnapshot }
393
+ | undefined;
394
+ const rawNavigation = routerBridge?.navigation;
395
+ const routerNavigation = rawNavigation
396
+ ? {
397
+ id: rawNavigation.id,
398
+ status: rawNavigation.status,
399
+ stage: rawNavigation.stage,
400
+ targetName: rawNavigation.targetName,
401
+ ...(rawNavigation.error ? { error: rawNavigation.error } : {}),
402
+ }
403
+ : null;
404
+
405
+ return { title: document.title, elements: rendered, routerNavigation };
406
+ }, { attribute: testIdAttribute, routerGlobalName: "__vuePomGeneratorRouter" });
407
+ }
408
+
409
+ async function capturePage(
410
+ page: Page,
411
+ pageIndex: number,
412
+ manifest: PomManifest,
413
+ testInfo: PomDiagnosticsTestInfo,
414
+ testIdAttribute: string,
415
+ deadline: number,
416
+ activeAction: PomActiveAction | null,
417
+ ): Promise<PomPageFailureSnapshot> {
418
+ const captureErrors: string[] = [];
419
+ const snapshot: PomPageFailureSnapshot = {
420
+ url: page.url(),
421
+ title: null,
422
+ closed: page.isClosed(),
423
+ ariaSnapshot: null,
424
+ renderedElements: [],
425
+ component: null,
426
+ routerNavigation: null,
427
+ captureErrors,
428
+ };
429
+ if (snapshot.closed) return snapshot;
430
+
431
+ try {
432
+ const rendered = await withinBudget(deadline, () => captureRenderedElements(page, testIdAttribute));
433
+ snapshot.title = rendered.title;
434
+ snapshot.renderedElements = rendered.elements;
435
+ snapshot.component = buildComponentAvailability(manifest, rendered.elements, activeAction?.componentName);
436
+ snapshot.routerNavigation = rendered.routerNavigation;
437
+ }
438
+ catch (error) {
439
+ captureErrors.push(`DOM inventory: ${errorMessage(error)}`);
440
+ }
441
+
442
+ try {
443
+ snapshot.ariaSnapshot = await withinBudget(deadline, () => page.locator("body").ariaSnapshot({
444
+ timeout: remainingMilliseconds(deadline),
445
+ }));
446
+ }
447
+ catch (error) {
448
+ snapshot.ariaSnapshotError = errorMessage(error);
449
+ }
450
+
451
+ if (pageIndex === 0 && remainingMilliseconds(deadline) > 0) {
452
+ const screenshotPath = testInfo.outputPath("vue-pom-generator-failure.png");
453
+ try {
454
+ await withinBudget(deadline, () => page.screenshot({
455
+ path: screenshotPath,
456
+ fullPage: true,
457
+ timeout: remainingMilliseconds(deadline),
458
+ }));
459
+ await testInfo.attach(POM_FAILURE_SCREENSHOT_ATTACHMENT_NAME, { path: screenshotPath, contentType: "image/png" });
460
+ snapshot.screenshotPath = screenshotPath;
461
+ }
462
+ catch (error) {
463
+ captureErrors.push(`Screenshot: ${errorMessage(error)}`);
464
+ }
465
+ }
466
+
467
+ return snapshot;
468
+ }
469
+
470
+ export function recordPomAction(page: object, action: PomActiveAction): void {
471
+ const globalRecord = globalThis as typeof globalThis & {
472
+ [POM_ACTIVE_ACTION_REGISTRY]?: WeakMap<object, PomActiveAction>;
473
+ };
474
+ const registry = globalRecord[POM_ACTIVE_ACTION_REGISTRY] ?? new WeakMap<object, PomActiveAction>();
475
+ globalRecord[POM_ACTIVE_ACTION_REGISTRY] = registry;
476
+ registry.set(page, {
477
+ ...action,
478
+ expectedTestIds: [...action.expectedTestIds],
479
+ });
480
+ }
481
+
482
+ export function getActivePomAction(page: object): PomActiveAction | null {
483
+ const globalRecord = globalThis as typeof globalThis & {
484
+ [POM_ACTIVE_ACTION_REGISTRY]?: WeakMap<object, PomActiveAction>;
485
+ };
486
+ return globalRecord[POM_ACTIVE_ACTION_REGISTRY]?.get(page) ?? null;
487
+ }
488
+
489
+ export function installPomFailureDiagnostics(
490
+ page: Page,
491
+ manifest: PomManifest,
492
+ testInfo: PomDiagnosticsTestInfo,
493
+ options: PomFailureDiagnosticsOptions = {},
494
+ ): PomFailureDiagnosticsCapture {
495
+ const context: BrowserContext = page.context();
496
+ const pages = new Set<Page>();
497
+ const buffers: EventBuffers = {
498
+ console: [],
499
+ pageErrors: [],
500
+ networkFailures: [],
501
+ httpFailures: [],
502
+ httpFailureBodyCaptures: new Set(),
503
+ pendingRequests: new Map(),
504
+ };
505
+ let captured: Promise<PomFailureDiagnostics> | null = null;
506
+
507
+ const registerPage = (candidate: Page) => {
508
+ if (pages.has(candidate)) return;
509
+ pages.add(candidate);
510
+ installPageListeners(candidate, buffers);
511
+ };
512
+ for (const existingPage of context.pages()) registerPage(existingPage);
513
+ context.on("page", registerPage);
514
+
515
+ return {
516
+ capture() {
517
+ if (captured) return captured;
518
+ captured = (async () => {
519
+ const captureBudgetMs = options.captureBudgetMs ?? DEFAULT_CAPTURE_BUDGET_MS;
520
+ const deadline = Date.now() + captureBudgetMs;
521
+ await settleHttpFailureBodies(buffers, deadline);
522
+ const activeAction = getActivePomAction(page);
523
+ const pageSnapshots: PomPageFailureSnapshot[] = [];
524
+ for (const [index, candidate] of Array.from(pages).entries()) {
525
+ pageSnapshots.push(await capturePage(
526
+ candidate,
527
+ index,
528
+ manifest,
529
+ testInfo,
530
+ options.testIdAttribute ?? "data-testid",
531
+ deadline,
532
+ activeAction,
533
+ ));
534
+ }
535
+
536
+ const jsonPath = testInfo.outputPath("vue-pom-generator-failure.json");
537
+ const diagnostics: PomFailureDiagnostics = {
538
+ schemaVersion: 1,
539
+ capturedAt: new Date().toISOString(),
540
+ captureBudgetMs,
541
+ activeAction,
542
+ pages: pageSnapshots,
543
+ console: [...buffers.console],
544
+ pageErrors: [...buffers.pageErrors],
545
+ networkFailures: [...buffers.networkFailures],
546
+ httpFailures: buffers.httpFailures.map(failure => ({ ...failure })),
547
+ pendingRequests: Array.from(buffers.pendingRequests.values())
548
+ .map(request => `${request.method} ${request.resourceType} ${formatNetworkUrl(request.url)} — pending ${Date.now() - request.startedAt}ms`)
549
+ .slice(-MAX_BUFFERED_EVENTS),
550
+ jsonPath,
551
+ };
552
+ await writeFile(jsonPath, `${JSON.stringify(diagnostics, null, 2)}\n`, "utf8");
553
+ await testInfo.attach(POM_FAILURE_ATTACHMENT_NAME, { path: jsonPath, contentType: "application/json" });
554
+ return diagnostics;
555
+ })();
556
+ return captured;
557
+ },
558
+ };
559
+ }