@immense/vue-pom-generator 1.0.90 → 1.0.92

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 (62) hide show
  1. package/README.md +88 -10
  2. package/RELEASE_NOTES.md +95 -62
  3. package/class-generation/base-page.ts +141 -59
  4. package/class-generation/diagnostics.ts +559 -0
  5. package/class-generation/index.ts +247 -128
  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 +4 -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 +728 -324
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.mjs +728 -324
  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/plugin/internal/build-plugin.d.ts +2 -0
  38. package/dist/plugin/internal/build-plugin.d.ts.map +1 -1
  39. package/dist/plugin/internal/dev-plugin.d.ts +2 -0
  40. package/dist/plugin/internal/dev-plugin.d.ts.map +1 -1
  41. package/dist/plugin/internal-plugins.d.ts.map +1 -1
  42. package/dist/route-navigation-codegen.d.ts +40 -0
  43. package/dist/route-navigation-codegen.d.ts.map +1 -0
  44. package/dist/router-bridge.d.ts +15 -0
  45. package/dist/router-bridge.d.ts.map +1 -1
  46. package/dist/router.cjs +41 -1
  47. package/dist/router.cjs.map +1 -1
  48. package/dist/router.mjs +41 -1
  49. package/dist/router.mjs.map +1 -1
  50. package/dist/tests/broad/helpers/fake-runtime.d.ts +27 -3
  51. package/dist/tests/broad/helpers/fake-runtime.d.ts.map +1 -1
  52. package/dist/tests/fixtures/generated-tsc/base-page.full.d.ts +16 -3
  53. package/dist/tests/fixtures/generated-tsc/base-page.full.d.ts.map +1 -1
  54. package/dist/tests/method-generation.test.d.ts +2 -0
  55. package/dist/tests/method-generation.test.d.ts.map +1 -0
  56. package/dist/tests/playwright-diagnostics.test.d.ts +2 -0
  57. package/dist/tests/playwright-diagnostics.test.d.ts.map +1 -0
  58. package/dist/tests/playwright-reporter.test.d.ts +2 -0
  59. package/dist/tests/playwright-reporter.test.d.ts.map +1 -0
  60. package/dist/transform.d.ts.map +1 -1
  61. package/dist/vite.config.d.ts.map +1 -1
  62. package/package.json +8 -1
package/dist/index.mjs CHANGED
@@ -624,6 +624,10 @@ function upperFirst$1(value) {
624
624
  }
625
625
  return value.charAt(0).toUpperCase() + value.slice(1);
626
626
  }
627
+ function generatedActionMetadata(componentName, methodName, options = {}) {
628
+ const preferAssociatedLabel = options.preferAssociatedLabel ? ", preferAssociatedLabel: true" : "";
629
+ return `{ componentName: ${JSON.stringify(componentName)}, methodName: ${JSON.stringify(methodName)}${preferAssociatedLabel} }`;
630
+ }
627
631
  function createParameters(params) {
628
632
  return toTypeScriptPomParameterStructures(params);
629
633
  }
@@ -649,7 +653,7 @@ function createAsyncMethod(name, parameters, statements) {
649
653
  statements
650
654
  });
651
655
  }
652
- function generateClickMethod(componentName, methodName, selector, alternateSelectors, parameters) {
656
+ function generateClickMethod(componentName, methodName, nativeRole, selector, alternateSelectors, parameters) {
653
657
  const name = `click${methodName}`;
654
658
  const noWaitName = `${name}NoWait`;
655
659
  const locatorDescription = JSON.stringify(buildPomLocatorDescription({
@@ -663,6 +667,9 @@ function generateClickMethod(componentName, methodName, selector, alternateSelec
663
667
  const argsForForward = getPomParameterNames(selectorParams).join(", ");
664
668
  const alternates = uniquePomStringPatterns(selector, alternateSelectors).slice(1);
665
669
  const primaryTestIdExpr = toTypeScriptPomPatternExpression(selector);
670
+ const actionMetadata = generatedActionMetadata(componentName, name, {
671
+ preferAssociatedLabel: nativeRole === "checkbox"
672
+ });
666
673
  if (alternates.length > 0) {
667
674
  const candidatesExpr = [primaryTestIdExpr, ...alternates.map((id) => toTypeScriptPomPatternExpression(id))].join(", ");
668
675
  const clickMethod = createAsyncMethod(
@@ -677,20 +684,8 @@ function generateClickMethod(componentName, methodName, selector, alternateSelec
677
684
  ],
678
685
  (writer) => {
679
686
  writer.writeLine(`const candidates = [${candidatesExpr}] as const;`);
680
- writer.writeLine("let lastError: unknown;");
681
- writer.write("for (const testId of candidates) ").block(() => {
682
- writer.writeLine(`const locator = this.locatorByTestId(testId, ${locatorDescription});`);
683
- writer.write("try ").block(() => {
684
- writer.write("if (await locator.count()) ").block(() => {
685
- writer.writeLine("await this.clickLocator(locator, annotationText, wait);");
686
- writer.writeLine("return;");
687
- });
688
- });
689
- writer.write("catch (e) ").block(() => {
690
- writer.writeLine("lastError = e;");
691
- });
692
- });
693
- writer.writeLine(`throw (lastError instanceof Error) ? lastError : new Error("[pom] Failed to click any candidate locator for ${name}.");`);
687
+ writer.writeLine(`const locator = await this.resolveVisibleTestIdLocator(candidates, ${locatorDescription}, ${JSON.stringify(name)}, ${JSON.stringify(componentName)});`);
688
+ writer.writeLine("await this.clickLocator(locator, annotationText, wait);");
694
689
  }
695
690
  );
696
691
  const noWaitArgs = argsForForward ? `${argsForForward}, false, annotationText` : "false, annotationText";
@@ -713,7 +708,7 @@ function generateClickMethod(componentName, methodName, selector, alternateSelec
713
708
  createInlineParameter("annotationText", { type: "string", initializer: '""' })
714
709
  ],
715
710
  (writer) => {
716
- writer.writeLine(`await this.clickByTestId(${primaryTestIdExpr}, annotationText, wait, ${locatorDescription});`);
711
+ writer.writeLine(`await this.clickByTestId(${primaryTestIdExpr}, annotationText, wait, ${locatorDescription}, ${actionMetadata});`);
717
712
  }
718
713
  ),
719
714
  createAsyncMethod(
@@ -733,7 +728,7 @@ function generateClickMethod(componentName, methodName, selector, alternateSelec
733
728
  createInlineParameter("annotationText", { type: "string", initializer: '""' })
734
729
  ],
735
730
  (writer) => {
736
- writer.writeLine(`await this.clickByTestId(${primaryTestIdExpr}, annotationText, wait, ${locatorDescription});`);
731
+ writer.writeLine(`await this.clickByTestId(${primaryTestIdExpr}, annotationText, wait, ${locatorDescription}, ${actionMetadata});`);
737
732
  }
738
733
  ),
739
734
  createAsyncMethod(
@@ -757,7 +752,7 @@ function generateRadioMethod(componentName, methodName, selector, parameters) {
757
752
  const testIdExpr = toTypeScriptPomPatternExpression(selector);
758
753
  return [
759
754
  createAsyncMethod(name, methodParameters, (writer) => {
760
- writer.writeLine(`await this.clickByTestId(${testIdExpr}, annotationText, true, ${locatorDescription});`);
755
+ writer.writeLine(`await this.clickByTestId(${testIdExpr}, annotationText, true, ${locatorDescription}, ${generatedActionMetadata(componentName, name, { preferAssociatedLabel: true })});`);
761
756
  })
762
757
  ];
763
758
  }
@@ -776,7 +771,8 @@ function generateSelectMethod(componentName, methodName, selector, parameters) {
776
771
  createParameters(selectorParams),
777
772
  (writer) => {
778
773
  writer.writeLine(`const testId = ${testIdExpr};`);
779
- writer.writeLine(`const locator = this.locatorByTestId(testId, ${locatorDescription});`);
774
+ writer.writeLine(`this.recordPomAction(${JSON.stringify(componentName)}, ${JSON.stringify(name)}, [testId]);`);
775
+ writer.writeLine(`const locator = this.locatorByTestId(testId, ${locatorDescription}).filter({ visible: true }).first();`);
780
776
  writer.writeLine("await this.animateCursorToElement(locator, false, 500, annotationText);");
781
777
  writer.writeLine("await locator.selectOption(value);");
782
778
  }
@@ -790,13 +786,13 @@ function generateVSelectMethod(componentName, methodName, selector, parameters)
790
786
  methodName,
791
787
  nativeRole: "vselect"
792
788
  }));
793
- const selectorParams = orderPomPatternParameters(parameters, [selector]);
789
+ const selectorParams = orderPomPatternParameters(parameters, [selector]).filter((parameter) => parameter.name !== "timeOut" && parameter.name !== "timeout");
794
790
  return [
795
791
  createAsyncMethod(
796
792
  name,
797
793
  createParameters(selectorParams),
798
794
  (writer) => {
799
- writer.writeLine(`await this.selectVSelectByTestId(${toTypeScriptPomPatternExpression(selector)}, value, timeOut, annotationText, ${locatorDescription});`);
795
+ writer.writeLine(`await this.selectVSelectByTestId(${toTypeScriptPomPatternExpression(selector)}, value, annotationText, ${locatorDescription}, ${generatedActionMetadata(componentName, name)});`);
800
796
  }
801
797
  )
802
798
  ];
@@ -814,7 +810,7 @@ function generateTypeMethod(componentName, methodName, selector, parameters) {
814
810
  name,
815
811
  createParameters(selectorParams),
816
812
  (writer) => {
817
- writer.writeLine(`await this.fillInputByTestId(${toTypeScriptPomPatternExpression(selector)}, text, annotationText, ${locatorDescription});`);
813
+ writer.writeLine(`await this.fillInputByTestId(${toTypeScriptPomPatternExpression(selector)}, text, annotationText, ${locatorDescription}, ${generatedActionMetadata(componentName, name)});`);
818
814
  }
819
815
  )
820
816
  ];
@@ -894,20 +890,9 @@ function generateNavigationMethod(args) {
894
890
  statements: (writer) => {
895
891
  writer.write("return this.fluent(async () => ").block(() => {
896
892
  writer.writeLine(`const candidates = [${candidatesExpr}] as const;`);
897
- writer.writeLine("let lastError: unknown;");
898
- writer.write("for (const testId of candidates) ").block(() => {
899
- writer.writeLine(`const locator = this.locatorByTestId(testId, ${locatorDescription});`);
900
- writer.write("try ").block(() => {
901
- writer.write("if (await locator.count()) ").block(() => {
902
- writer.writeLine("await this.clickLocator(locator);");
903
- writer.writeLine(`return new ${target}(this.page);`);
904
- });
905
- });
906
- writer.write("catch (e) ").block(() => {
907
- writer.writeLine("lastError = e;");
908
- });
909
- });
910
- writer.writeLine(`throw (lastError instanceof Error) ? lastError : new Error("[pom] Failed to navigate using any candidate locator for ${methodName}.");`);
893
+ writer.writeLine(`const locator = await this.resolveVisibleTestIdLocator(candidates, ${locatorDescription}, ${JSON.stringify(methodName)}, ${JSON.stringify(componentName)});`);
894
+ writer.writeLine("await this.clickLocator(locator);");
895
+ writer.writeLine(`return new ${target}(this.page);`);
911
896
  });
912
897
  writer.writeLine(");");
913
898
  }
@@ -922,6 +907,7 @@ function generateNavigationMethod(args) {
922
907
  statements: (writer) => {
923
908
  writer.write("return this.fluent(async () => ").block(() => {
924
909
  writer.writeLine(`const locator = this.locatorByTestId(${toTypeScriptPomPatternExpression(selector)}, ${locatorDescription});`);
910
+ writer.writeLine(`this.recordPomAction(${JSON.stringify(componentName)}, ${JSON.stringify(methodName)}, [${toTypeScriptPomPatternExpression(selector)}]);`);
925
911
  writer.writeLine("await this.clickLocator(locator);");
926
912
  writer.writeLine(`return new ${target}(this.page);`);
927
913
  });
@@ -966,7 +952,60 @@ function generateViewObjectModelMembers(componentName, targetPageObjectModelClas
966
952
  if (nativeRole === "radio") {
967
953
  return [...members, ...generateRadioMethod(componentName, baseMethodName || "Radio", selector, parameters)];
968
954
  }
969
- return [...members, ...generateClickMethod(componentName, baseMethodName, selector, alternateSelectors, parameters)];
955
+ return [...members, ...generateClickMethod(componentName, baseMethodName, nativeRole, selector, alternateSelectors, parameters)];
956
+ }
957
+ function supportsInlineTextAccessibleName(role) {
958
+ return role === "button" || role === "radio";
959
+ }
960
+ function buildAccessibilityAudit(metadata, inferredRole) {
961
+ if (!metadata || !inferredRole) {
962
+ return void 0;
963
+ }
964
+ const role = normalizePomRoleLabel(inferredRole).toLowerCase();
965
+ const dynamicProps = new Set(metadata.dynamicProps ?? []);
966
+ const hasDynamicAccessibleNameSignal = dynamicProps.has("aria-label") || dynamicProps.has("title") || !!metadata.hasDynamicText;
967
+ let accessibleNameSource;
968
+ const reasons = [];
969
+ if (metadata.staticAriaLabel) {
970
+ accessibleNameSource = "aria-label";
971
+ } else if (supportsInlineTextAccessibleName(role) && metadata.staticTextContent) {
972
+ accessibleNameSource = "text";
973
+ } else if (metadata.staticTitle) {
974
+ accessibleNameSource = "title";
975
+ } else if (hasDynamicAccessibleNameSignal) {
976
+ accessibleNameSource = "dynamic";
977
+ } else if (role === "input" || role === "select") {
978
+ accessibleNameSource = "unknown";
979
+ reasons.push("No inline accessible-name signal was found; the element may rely on external markup such as a separate <label>.");
980
+ } else {
981
+ accessibleNameSource = "missing";
982
+ reasons.push("No compile-time accessible-name signal was found.");
983
+ }
984
+ return {
985
+ needsReview: accessibleNameSource === "unknown" || accessibleNameSource === "missing",
986
+ accessibleNameSource,
987
+ reasons,
988
+ ...metadata.staticAriaLabel ? { staticAriaLabel: metadata.staticAriaLabel } : {},
989
+ ...metadata.staticRole ? { staticRole: metadata.staticRole } : {},
990
+ ...metadata.staticTitle ? { staticTitle: metadata.staticTitle } : {},
991
+ ...metadata.staticTextContent ? { staticTextContent: metadata.staticTextContent } : {}
992
+ };
993
+ }
994
+ function collectAccessibilityReviewWarnings(manifest) {
995
+ const warnings = [];
996
+ for (const [componentName, component] of Object.entries(manifest)) {
997
+ for (const entry of component.entries) {
998
+ if (!entry.accessibility?.needsReview) {
999
+ continue;
1000
+ }
1001
+ const entryLabel = entry.generatedPropertyName ?? entry.testId;
1002
+ const reasonText = entry.accessibility.reasons.join(" ");
1003
+ warnings.push(
1004
+ `[vue-pom-generator] Accessibility review suggested for ${componentName}.${entryLabel} (role=${entry.inferredRole ?? "unknown"}, testId=${JSON.stringify(entry.testId)}): ${reasonText}`
1005
+ );
1006
+ }
1007
+ }
1008
+ return warnings;
970
1009
  }
971
1010
  function isSimpleExpressionNode(value) {
972
1011
  return value !== null && "type" in value && value.type === NodeTypes.SIMPLE_EXPRESSION;
@@ -1312,7 +1351,7 @@ function findTemplateSlotScopeExpression(node) {
1312
1351
  return slotProp?.exp && (slotProp.exp.type === NodeTypes.SIMPLE_EXPRESSION || slotProp.exp.type === NodeTypes.COMPOUND_EXPRESSION) ? slotProp.exp : null;
1313
1352
  }
1314
1353
  function buildSlotScopeFallbackKeyExpression(identifier) {
1315
- return `${identifier}.key ?? ${identifier}.data?.id ?? ${identifier}.id ?? ${identifier}.value ?? ${identifier}`;
1354
+ return `${identifier}.key ?? ${identifier}.data?.id ?? ${identifier}.id ?? ${identifier}.value ?? ${identifier}.url ?? ${identifier}`;
1316
1355
  }
1317
1356
  function tryGetBindingIdentifierName(node) {
1318
1357
  if (!node) {
@@ -3604,6 +3643,157 @@ function buildPomGeneratedPropertyName(pom) {
3604
3643
  function buildPomGeneratedActionName(pom) {
3605
3644
  return requireStructuredPomName(pom.generatedActionName, "generatedActionName", pom);
3606
3645
  }
3646
+ function matchesPrimarySelector(extraMethod, pom) {
3647
+ if (extraMethod.selector.kind !== "testId") {
3648
+ return false;
3649
+ }
3650
+ return extraMethod.selector.testId.formatted === pom.selector.formatted && extraMethod.selector.testId.patternKind === pom.selector.patternKind;
3651
+ }
3652
+ function getManifestEntry(componentName, entry, componentMetadata, extraMethods) {
3653
+ const testId = entry.selectorValue.formatted;
3654
+ const metadata = componentMetadata?.get(testId);
3655
+ const pom = entry.pom;
3656
+ const generatedActionName = pom ? buildPomGeneratedActionName(pom) : null;
3657
+ const extraActionNames = pom ? extraMethods.filter((extraMethod) => matchesPrimarySelector(extraMethod, pom)).map((extraMethod) => extraMethod.name).sort((a, b) => a.localeCompare(b)) : [];
3658
+ const generatedActionNames = Array.from(/* @__PURE__ */ new Set([
3659
+ ...generatedActionName ? [generatedActionName] : [],
3660
+ ...extraActionNames.filter((name) => name !== generatedActionName)
3661
+ ]));
3662
+ const generatedMethods = [
3663
+ ...pom && generatedActionName ? [{ name: generatedActionName, kind: "action", parameters: pom.parameters }] : [],
3664
+ ...pom ? extraMethods.filter((extraMethod) => matchesPrimarySelector(extraMethod, pom)).map((extraMethod) => ({ name: extraMethod.name, kind: "action", parameters: extraMethod.parameters })) : [],
3665
+ ...pom ? [{ name: buildPomGeneratedPropertyName(pom), kind: "locator", parameters: pom.parameters }] : []
3666
+ ].filter((method, index, methods) => methods.findIndex((candidate) => candidate.name === method.name && candidate.kind === method.kind) === index);
3667
+ const accessibility = buildAccessibilityAudit(metadata, pom?.nativeRole ?? null);
3668
+ return {
3669
+ testId,
3670
+ selectorPatternKind: entry.selectorValue.patternKind,
3671
+ semanticName: metadata?.semanticName ?? (pom ? humanizePomMethodName(pom.methodName) : testId),
3672
+ locatorDescription: pom ? buildPomLocatorDescription({
3673
+ componentName,
3674
+ methodName: pom.methodName,
3675
+ nativeRole: pom.nativeRole
3676
+ }) : componentName,
3677
+ inferredRole: pom?.nativeRole ?? null,
3678
+ ...accessibility ? { accessibility } : {},
3679
+ generatedPropertyName: pom ? buildPomGeneratedPropertyName(pom) : null,
3680
+ generatedActionName,
3681
+ generatedActionNames,
3682
+ generatedMethods,
3683
+ emitPrimary: pom?.emitPrimary !== false,
3684
+ ...entry.targetPageObjectModelClass ? { targetPageObjectModelClass: entry.targetPageObjectModelClass } : {},
3685
+ ...metadata?.tag ? { sourceTag: metadata.tag } : {},
3686
+ ...metadata ? { sourceTagType: metadata.tagType } : {},
3687
+ ...metadata?.sourceLine !== void 0 ? { sourceLine: metadata.sourceLine } : {},
3688
+ ...metadata?.sourceColumn !== void 0 ? { sourceColumn: metadata.sourceColumn } : {},
3689
+ ...metadata?.patchFlag !== void 0 ? { patchFlag: metadata.patchFlag } : {},
3690
+ ...metadata?.dynamicProps?.length ? { dynamicProps: metadata.dynamicProps } : {},
3691
+ ...metadata?.hasClickHandler !== void 0 ? { hasClickHandler: metadata.hasClickHandler } : {},
3692
+ ...metadata?.hasDynamicClass !== void 0 ? { hasDynamicClass: metadata.hasDynamicClass } : {},
3693
+ ...metadata?.hasDynamicStyle !== void 0 ? { hasDynamicStyle: metadata.hasDynamicStyle } : {},
3694
+ ...metadata?.hasDynamicText !== void 0 ? { hasDynamicText: metadata.hasDynamicText } : {}
3695
+ };
3696
+ }
3697
+ function buildPomManifest(componentHierarchyMap, elementMetadata) {
3698
+ const manifestEntries = Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
3699
+ const entries = Array.from(dependencies.dataTestIdSet).sort((a, b) => a.selectorValue.formatted.localeCompare(b.selectorValue.formatted)).map((entry) => getManifestEntry(componentName, entry, elementMetadata.get(componentName), dependencies.pomExtraMethods ?? []));
3700
+ if (!entries.length) {
3701
+ return null;
3702
+ }
3703
+ return [componentName, {
3704
+ componentName,
3705
+ className: componentName,
3706
+ sourceFile: dependencies.filePath,
3707
+ kind: dependencies.isView ? "view" : "component",
3708
+ testIds: Array.from(new Set(entries.map((entry) => entry.testId))),
3709
+ entries
3710
+ }];
3711
+ }).filter((entry) => entry !== null);
3712
+ return Object.fromEntries(manifestEntries);
3713
+ }
3714
+ function buildTestIdManifest(componentHierarchyMap) {
3715
+ return Object.fromEntries(
3716
+ Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
3717
+ const testIds = Array.from(dependencies.dataTestIdSet).map((entry) => entry.selectorValue.formatted).filter(Boolean);
3718
+ if (!testIds.length) {
3719
+ return null;
3720
+ }
3721
+ return [componentName, Array.from(new Set(testIds)).sort((a, b) => a.localeCompare(b))];
3722
+ }).filter((entry) => entry !== null)
3723
+ );
3724
+ }
3725
+ function writeConstJson(value) {
3726
+ return (writer) => {
3727
+ writer.write(`${JSON.stringify(value, null, 2)} as const`);
3728
+ };
3729
+ }
3730
+ function generateTestIdsModule(componentHierarchyMap, elementMetadata) {
3731
+ const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
3732
+ const testIdManifest = buildTestIdManifest(componentHierarchyMap);
3733
+ return renderSourceFile("virtual-testids.ts", (sourceFile) => {
3734
+ sourceFile.addStatements("// Virtual module: test id manifest");
3735
+ sourceFile.addVariableStatement({
3736
+ declarationKind: VariableDeclarationKind.Const,
3737
+ isExported: true,
3738
+ declarations: [{
3739
+ name: "testIdManifest",
3740
+ initializer: writeConstJson(testIdManifest)
3741
+ }]
3742
+ });
3743
+ sourceFile.addVariableStatement({
3744
+ declarationKind: VariableDeclarationKind.Const,
3745
+ isExported: true,
3746
+ declarations: [{
3747
+ name: "pomManifest",
3748
+ initializer: writeConstJson(pomManifest)
3749
+ }]
3750
+ });
3751
+ sourceFile.addTypeAlias({
3752
+ isExported: true,
3753
+ name: "TestIdManifest",
3754
+ type: "typeof testIdManifest"
3755
+ });
3756
+ sourceFile.addTypeAlias({
3757
+ isExported: true,
3758
+ name: "ComponentName",
3759
+ type: "keyof TestIdManifest"
3760
+ });
3761
+ sourceFile.addTypeAlias({
3762
+ isExported: true,
3763
+ name: "PomManifest",
3764
+ type: "typeof pomManifest"
3765
+ });
3766
+ sourceFile.addTypeAlias({
3767
+ isExported: true,
3768
+ name: "PomManifestComponentName",
3769
+ type: "keyof PomManifest"
3770
+ });
3771
+ });
3772
+ }
3773
+ function generatePomManifestModule(componentHierarchyMap, elementMetadata, fileName = "virtual-pom-manifest.ts") {
3774
+ const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
3775
+ return renderSourceFile(fileName, (sourceFile) => {
3776
+ sourceFile.addStatements("// Rich POM discoverability manifest.");
3777
+ sourceFile.addVariableStatement({
3778
+ declarationKind: VariableDeclarationKind.Const,
3779
+ isExported: true,
3780
+ declarations: [{
3781
+ name: "pomManifest",
3782
+ initializer: writeConstJson(pomManifest)
3783
+ }]
3784
+ });
3785
+ sourceFile.addTypeAlias({
3786
+ isExported: true,
3787
+ name: "PomManifest",
3788
+ type: "typeof pomManifest"
3789
+ });
3790
+ sourceFile.addTypeAlias({
3791
+ isExported: true,
3792
+ name: "PomManifestComponentName",
3793
+ type: "keyof PomManifest"
3794
+ });
3795
+ });
3796
+ }
3607
3797
  function safeRealpath(value) {
3608
3798
  try {
3609
3799
  if (fs.existsSync(value)) {
@@ -4629,6 +4819,282 @@ async function parseRouterFileFromCwd(routerEntryPath, options = {}) {
4629
4819
  }
4630
4820
  });
4631
4821
  }
4822
+ function writeNavigationValue(writer, input, name) {
4823
+ writer.write(input.identifier);
4824
+ if (input.optional) {
4825
+ writer.write("?.");
4826
+ }
4827
+ writer.write(`[${JSON.stringify(name)}]`);
4828
+ }
4829
+ function writeFilteredNavigationRecord(writer, variableName, input, names) {
4830
+ writer.write(`const ${variableName} = `);
4831
+ if (!input || names.length === 0) {
4832
+ writer.write("{};").newLine();
4833
+ return;
4834
+ }
4835
+ writer.write("Object.fromEntries([");
4836
+ names.forEach((name, index) => {
4837
+ if (index > 0) {
4838
+ writer.write(", ");
4839
+ }
4840
+ writer.write(`[${JSON.stringify(name)}, `);
4841
+ writeNavigationValue(writer, input, name);
4842
+ writer.write("]");
4843
+ });
4844
+ writer.write("].filter(([, value]) => value !== undefined));").newLine();
4845
+ }
4846
+ function writeUnpartitionedRouteParams(writer, input) {
4847
+ writer.write("const routeParams = ");
4848
+ if (!input) {
4849
+ writer.write("{};").newLine();
4850
+ return;
4851
+ }
4852
+ writer.write("Object.fromEntries(Object.entries(");
4853
+ writer.write(input.identifier);
4854
+ if (input.optional) {
4855
+ writer.write(" ?? {}");
4856
+ }
4857
+ writer.write(").filter(([, v]) => v !== undefined));").newLine();
4858
+ }
4859
+ function writeRouterTargetType(writer, includeQuery) {
4860
+ writer.write("{ name: string; params: Record<string, unknown>");
4861
+ if (includeQuery) {
4862
+ writer.write("; query: Record<string, unknown>");
4863
+ }
4864
+ writer.write(" }");
4865
+ }
4866
+ function writeRouterType(writer, includeQuery) {
4867
+ writer.write(`{ ${POM_ROUTER_GLOBAL_NAME}?: { beginNavigation: (to: `);
4868
+ writeRouterTargetType(writer, includeQuery);
4869
+ writer.write(') => number; navigation?: { id: number; status: "pending" | "succeeded" | "failed"; stage: "waiting-for-router-ready" | "pushing-route" | "complete"; targetName: string; error?: string } } }');
4870
+ }
4871
+ function writeRouterBinding(writer, includeQuery) {
4872
+ writer.write("{ name, params");
4873
+ if (includeQuery) {
4874
+ writer.write(", query");
4875
+ }
4876
+ writer.write(" }");
4877
+ }
4878
+ function writeRouterTarget(writer, writeName, includeQuery, paramsExpression, queryExpression) {
4879
+ writer.write("{ name: ");
4880
+ writeName(writer);
4881
+ writer.write(`, params: ${paramsExpression}`);
4882
+ if (includeQuery) {
4883
+ writer.write(`, query: ${queryExpression}`);
4884
+ }
4885
+ writer.write(" }");
4886
+ }
4887
+ function writeRouterNavigation(writer, writeName, includeQuery) {
4888
+ writer.write("const navigationId = await this.page.evaluate((");
4889
+ writeRouterBinding(writer, includeQuery);
4890
+ writer.write(") => {").newLine();
4891
+ writer.indent(() => {
4892
+ writer.write("const router = (globalThis as ");
4893
+ writeRouterType(writer, includeQuery);
4894
+ writer.write(`).${POM_ROUTER_GLOBAL_NAME};`).newLine();
4895
+ writer.writeLine("if (!router) {");
4896
+ writer.indent(() => {
4897
+ writer.writeLine('throw new Error("[vue-pom-generator] Vue Router bridge is unavailable.");');
4898
+ });
4899
+ writer.writeLine("}");
4900
+ writer.write("return router.beginNavigation(");
4901
+ writeRouterBinding(writer, includeQuery);
4902
+ writer.write(");").newLine();
4903
+ });
4904
+ writer.write("}, ");
4905
+ writeRouterTarget(writer, writeName, includeQuery, "routeParams", "routeQuery");
4906
+ writer.write(");").newLine();
4907
+ writer.writeLine("try {");
4908
+ writer.indent(() => {
4909
+ writer.write("await this.page.waitForFunction((id) => {").newLine();
4910
+ writer.indent(() => {
4911
+ writer.write("const navigation = (globalThis as ");
4912
+ writeRouterType(writer, includeQuery);
4913
+ writer.write(`).${POM_ROUTER_GLOBAL_NAME}?.navigation;`).newLine();
4914
+ writer.writeLine('return navigation?.id === id && navigation.status !== "pending";');
4915
+ });
4916
+ writer.writeLine("}, navigationId, { timeout: 5000 });");
4917
+ });
4918
+ writer.writeLine("}");
4919
+ writer.writeLine("catch (error) {");
4920
+ writer.indent(() => {
4921
+ writer.write("const navigation = await this.page.evaluate((id) => {").newLine();
4922
+ writer.indent(() => {
4923
+ writer.write("const current = (globalThis as ");
4924
+ writeRouterType(writer, includeQuery);
4925
+ writer.write(`).${POM_ROUTER_GLOBAL_NAME}?.navigation;`).newLine();
4926
+ writer.writeLine("return current?.id === id ? current : undefined;");
4927
+ });
4928
+ writer.writeLine("}, navigationId).catch(() => undefined);");
4929
+ writer.writeLine("const detail = error instanceof Error ? error.message : String(error);");
4930
+ writer.writeLine('throw new Error(`[vue-pom-generator] Vue Router navigation timed out after 5000ms (stage: ${navigation?.stage ?? "unknown"}, target: ${navigation?.targetName ?? "unknown"}, current URL: ${this.page.url()}). ${detail}`);');
4931
+ });
4932
+ writer.writeLine("}");
4933
+ writer.write("const navigationError = await this.page.evaluate((id) => {").newLine();
4934
+ writer.indent(() => {
4935
+ writer.write("const navigation = (globalThis as ");
4936
+ writeRouterType(writer, includeQuery);
4937
+ writer.write(`).${POM_ROUTER_GLOBAL_NAME}?.navigation;`).newLine();
4938
+ writer.writeLine('return navigation?.id === id && navigation.status === "failed" ? navigation.error ?? "Unknown navigation error" : undefined;');
4939
+ });
4940
+ writer.writeLine("}, navigationId);");
4941
+ writer.writeLine("if (navigationError) {");
4942
+ writer.indent(() => {
4943
+ writer.writeLine("throw new Error(`[vue-pom-generator] Vue Router navigation failed: ${navigationError}`);");
4944
+ });
4945
+ writer.writeLine("}");
4946
+ }
4947
+ function requireNavigationInput(input, context) {
4948
+ if (!input) {
4949
+ throw new Error(`${context} requires a navigation input.`);
4950
+ }
4951
+ return input;
4952
+ }
4953
+ function writeParametrizedRouteSelector(writer, input, pathParamNames) {
4954
+ writer.write(`const useParametrizedRoute = ${input.identifier} !== undefined && [`);
4955
+ pathParamNames.forEach((name, index) => {
4956
+ if (index > 0) {
4957
+ writer.write(", ");
4958
+ }
4959
+ writer.write(JSON.stringify(name));
4960
+ });
4961
+ writer.write(`].some(key => Object.prototype.hasOwnProperty.call(${input.identifier}, key));`).newLine();
4962
+ }
4963
+ function writeSelectionPrelude(writer, selection, input, pathParamNames) {
4964
+ if (selection.kind === "dual" && selection.selectBy === "path-param-presence") {
4965
+ writeParametrizedRouteSelector(
4966
+ writer,
4967
+ requireNavigationInput(input, "Path-param route selection"),
4968
+ pathParamNames
4969
+ );
4970
+ }
4971
+ }
4972
+ function writeSelectedTarget(writer, selection, input) {
4973
+ if (selection.kind === "single") {
4974
+ writer.write(JSON.stringify(selection.target));
4975
+ return;
4976
+ }
4977
+ if (selection.selectBy === "path-param-presence") {
4978
+ writer.write("useParametrizedRoute");
4979
+ } else {
4980
+ writer.write(requireNavigationInput(input, "Input-presence route selection").identifier);
4981
+ }
4982
+ writer.write(` ? ${JSON.stringify(selection.parametrizedTarget)} : ${JSON.stringify(selection.paramlessTarget)}`);
4983
+ }
4984
+ function createRouterNavigationWriter(options) {
4985
+ return (writer) => {
4986
+ writer.writeLine(`this.recordPomAction(${JSON.stringify(options.componentName)}, "goTo", []);`);
4987
+ writeSelectionPrelude(writer, options.routeName, options.input, options.pathParamNames);
4988
+ const writeRouteName = (nameWriter) => writeSelectedTarget(nameWriter, options.routeName, options.input);
4989
+ const includeQuery = options.queryNames.length > 0;
4990
+ if (includeQuery) {
4991
+ writeFilteredNavigationRecord(writer, "routeParams", options.input, options.pathParamNames);
4992
+ writeFilteredNavigationRecord(writer, "routeQuery", options.input, options.queryNames);
4993
+ } else {
4994
+ writeUnpartitionedRouteParams(writer, options.input);
4995
+ }
4996
+ writer.writeLine(
4997
+ `const isCold = await this.page.evaluate(() => typeof (globalThis as { ${POM_ROUTER_GLOBAL_NAME}?: unknown }).${POM_ROUTER_GLOBAL_NAME} === "undefined");`
4998
+ );
4999
+ writer.writeLine("if (isCold) {");
5000
+ writer.indent(() => {
5001
+ writer.writeLine('await this.page.goto("/", { waitUntil: "commit" });');
5002
+ writer.writeLine(
5003
+ `await this.page.waitForFunction(() => typeof (globalThis as { ${POM_ROUTER_GLOBAL_NAME}?: unknown }).${POM_ROUTER_GLOBAL_NAME} !== "undefined", undefined, { timeout: 5000 });`
5004
+ );
5005
+ });
5006
+ writer.writeLine("}");
5007
+ writeRouterNavigation(writer, writeRouteName, includeQuery);
5008
+ };
5009
+ }
5010
+ function writePathParamAssignments(writer, input, pathParams) {
5011
+ for (const param of pathParams) {
5012
+ const token = getParamToken(param.name);
5013
+ if (param.optional) {
5014
+ writer.write("targetUrl = ");
5015
+ writeNavigationValue(writer, input, param.name);
5016
+ writer.write(` === undefined ? targetUrl.replaceAll(${JSON.stringify(`/${token}`)}, "") : targetUrl.replaceAll(${JSON.stringify(token)}, String(`);
5017
+ writeNavigationValue(writer, input, param.name);
5018
+ writer.write("));").newLine();
5019
+ } else {
5020
+ writer.write(`targetUrl = targetUrl.replaceAll(${JSON.stringify(token)}, String(`);
5021
+ writeNavigationValue(writer, input, param.name);
5022
+ writer.write("));").newLine();
5023
+ }
5024
+ }
5025
+ }
5026
+ function writeQueryString(writer, input, queryNames) {
5027
+ if (queryNames.length === 0) {
5028
+ return;
5029
+ }
5030
+ writer.writeLine("const routeQuery = new URLSearchParams();");
5031
+ for (const queryName of queryNames) {
5032
+ writer.write("if (");
5033
+ writeNavigationValue(writer, input, queryName);
5034
+ writer.write(" !== undefined) {").newLine();
5035
+ writer.indent(() => {
5036
+ writer.write(`routeQuery.set(${JSON.stringify(queryName)}, String(`);
5037
+ writeNavigationValue(writer, input, queryName);
5038
+ writer.write("));").newLine();
5039
+ });
5040
+ writer.writeLine("}");
5041
+ }
5042
+ writer.writeLine("const routeQueryString = routeQuery.toString();");
5043
+ writer.writeLine("if (routeQueryString) {");
5044
+ writer.indent(() => {
5045
+ writer.writeLine("targetUrl += `?${routeQueryString}`;");
5046
+ });
5047
+ writer.writeLine("}");
5048
+ }
5049
+ function writeRuntimeUrlNavigation(writer) {
5050
+ writer.writeLine(
5051
+ "const runtimeEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;"
5052
+ );
5053
+ writer.writeLine(
5054
+ "const runtimeBaseUrl = runtimeEnv?.PLAYWRIGHT_RUNTIME_BASE_URL ?? runtimeEnv?.PLAYWRIGHT_TEST_BASE_URL ?? runtimeEnv?.VITE_PLAYWRIGHT_BASE_URL;"
5055
+ );
5056
+ writer.writeLine("const resolvedUrl = runtimeBaseUrl ? new URL(targetUrl, runtimeBaseUrl).toString() : targetUrl;");
5057
+ writer.writeLine("await this.page.goto(resolvedUrl);");
5058
+ }
5059
+ function createUrlNavigationWriter(options) {
5060
+ return (writer) => {
5061
+ writer.writeLine(`this.recordPomAction(${JSON.stringify(options.componentName)}, "goTo", []);`);
5062
+ writeSelectionPrelude(writer, options.routeTemplate, options.input, options.pathParams.map((param) => param.name));
5063
+ if (options.routeTemplate.kind === "single") {
5064
+ writer.write(`let targetUrl = ${JSON.stringify(options.routeTemplate.target)};`).newLine();
5065
+ } else {
5066
+ writer.write("const template = ");
5067
+ writeSelectedTarget(writer, options.routeTemplate, options.input);
5068
+ writer.write(";").newLine();
5069
+ writer.writeLine("let targetUrl = template;");
5070
+ }
5071
+ if (options.pathParams.length > 0) {
5072
+ const input = requireNavigationInput(options.input, "URL navigation with path params");
5073
+ if (options.routeTemplate.kind === "dual") {
5074
+ writer.write("if (");
5075
+ writer.write(input.identifier);
5076
+ if (options.routeTemplate.selectBy === "path-param-presence") {
5077
+ writer.write(" && useParametrizedRoute");
5078
+ }
5079
+ writer.write(") {").newLine();
5080
+ writer.indent(() => {
5081
+ writePathParamAssignments(writer, input, options.pathParams);
5082
+ });
5083
+ writer.writeLine("}");
5084
+ } else {
5085
+ writePathParamAssignments(writer, input, options.pathParams);
5086
+ }
5087
+ }
5088
+ if (options.queryNames.length > 0) {
5089
+ writeQueryString(
5090
+ writer,
5091
+ requireNavigationInput(options.input, "URL navigation with query params"),
5092
+ options.queryNames
5093
+ );
5094
+ }
5095
+ writeRuntimeUrlNavigation(writer);
5096
+ };
5097
+ }
4632
5098
  const GENERATED_GITATTRIBUTES_BLOCK_START = "# BEGIN vue-pom-generator generated files";
4633
5099
  const GENERATED_GITATTRIBUTES_BLOCK_END = "# END vue-pom-generator generated files";
4634
5100
  const VUE_POM_GENERATOR_ERROR_PREFIX = "[vue-pom-generator]";
@@ -4759,7 +5225,7 @@ async function getRouteMetaByComponent(projectRoot, routerEntry, routerType, opt
4759
5225
  const map = /* @__PURE__ */ new Map();
4760
5226
  for (const entry of routeMetaEntries) {
4761
5227
  const list = map.get(entry.componentName) ?? [];
4762
- list.push({ name: entry.name, template: entry.pathTemplate, params: entry.params });
5228
+ list.push({ name: entry.name, template: entry.pathTemplate, params: entry.params, query: entry.query });
4763
5229
  map.set(entry.componentName, list);
4764
5230
  }
4765
5231
  const dedupeRoutes = (entries) => {
@@ -4798,8 +5264,37 @@ function generateRouteProperty(routeMeta) {
4798
5264
  })
4799
5265
  ];
4800
5266
  }
4801
- function buildParamTypeString(params) {
4802
- return `{ ${params.map((p) => `${p.name}${p.optional ? "?" : ""}: string | number`).join("; ")} }`;
5267
+ function formatNavigationFieldName(name) {
5268
+ return /^[$a-z_][$\w]*$/i.test(name) ? name : JSON.stringify(name);
5269
+ }
5270
+ function buildNavigationTypeString(route, requiredOptionalParamName) {
5271
+ const pathFields = route.params.map((param) => {
5272
+ const forcePresent = param.optional && param.name === requiredOptionalParamName;
5273
+ return `${formatNavigationFieldName(param.name)}${param.optional && !forcePresent ? "?" : ""}: string | number${forcePresent ? " | undefined" : ""}`;
5274
+ });
5275
+ const pathNames = new Set(route.params.map((param) => param.name));
5276
+ const queryFields = route.query.filter((query) => !pathNames.has(query)).map((query) => `${formatNavigationFieldName(query)}?: string | number`);
5277
+ return `{ ${[...pathFields, ...queryFields].join("; ")} }`;
5278
+ }
5279
+ function buildParametrizedRouteSelectionTypeString(route) {
5280
+ if (route.params.some((param) => !param.optional)) {
5281
+ return buildNavigationTypeString(route);
5282
+ }
5283
+ return route.params.map((param) => buildNavigationTypeString(route, param.name)).join(" | ");
5284
+ }
5285
+ function buildImplementationNavigationTypeString(routes) {
5286
+ const fields = /* @__PURE__ */ new Map();
5287
+ for (const route of routes) {
5288
+ for (const param of route.params) {
5289
+ fields.set(param.name, true);
5290
+ }
5291
+ for (const query of route.query) {
5292
+ if (!fields.has(query)) {
5293
+ fields.set(query, true);
5294
+ }
5295
+ }
5296
+ }
5297
+ return `{ ${Array.from(fields.keys()).map((name) => `${formatNavigationFieldName(name)}?: string | number`).join("; ")} }`;
4803
5298
  }
4804
5299
  function chooseParamlessRoute(routes) {
4805
5300
  const paramless = routes.filter((r) => r.params.length === 0);
@@ -4813,31 +5308,12 @@ function chooseParametrizedRoute(routes) {
4813
5308
  return null;
4814
5309
  return parametrized.slice().sort((a, b) => a.params.length - b.params.length || a.template.length - b.template.length || a.template.localeCompare(b.template))[0];
4815
5310
  }
4816
- const GOTO_RUNTIME_LINES = [
4817
- "const runtimeEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;",
4818
- "const runtimeBaseUrl = runtimeEnv?.PLAYWRIGHT_RUNTIME_BASE_URL ?? runtimeEnv?.PLAYWRIGHT_TEST_BASE_URL ?? runtimeEnv?.VITE_PLAYWRIGHT_BASE_URL;",
4819
- "const resolvedUrl = runtimeBaseUrl ? new URL(targetUrl, runtimeBaseUrl).toString() : targetUrl;",
4820
- "await this.page.goto(resolvedUrl);"
4821
- ];
4822
- const ROUTER_GLOBAL_NAME = POM_ROUTER_GLOBAL_NAME;
4823
- const pushBlock = (routeNameExpr, paramsExpr, nullable) => {
4824
- const routerType = `{ ${ROUTER_GLOBAL_NAME}?: { push: (to: { name: string; params: Record<string, unknown> }) => Promise<unknown>; resolve: (to: { name: string; params: Record<string, unknown> }) => { href: string } } }`;
4825
- const routeParamsLine = paramsExpr === "undefined" ? "const routeParams = {};" : nullable ? `const routeParams = Object.fromEntries(Object.entries(${paramsExpr} ?? {}).filter(([, v]) => v !== undefined));` : `const routeParams = Object.fromEntries(Object.entries(${paramsExpr}).filter(([, v]) => v !== undefined));`;
4826
- return [
4827
- routeParamsLine,
4828
- `const isCold = await this.page.evaluate(() => typeof (globalThis as { ${ROUTER_GLOBAL_NAME}?: unknown }).${ROUTER_GLOBAL_NAME} === "undefined");`,
4829
- `if (isCold) {`,
4830
- ` await this.page.goto("/", { waitUntil: "commit" });`,
4831
- ` await this.page.waitForFunction(() => typeof (globalThis as { ${ROUTER_GLOBAL_NAME}?: unknown }).${ROUTER_GLOBAL_NAME} !== "undefined", { timeout: 15000 });`,
4832
- ` const href = await this.page.evaluate(({ name, params }) => (globalThis as ${routerType}).${ROUTER_GLOBAL_NAME}?.resolve({ name, params })?.href, { name: ${routeNameExpr}, params: routeParams });`,
4833
- ` if (href) { await this.page.goto(href, { waitUntil: "domcontentloaded" }); }`,
4834
- `} else {`,
4835
- ` await this.page.evaluate(async ({ name, params }) => {`,
4836
- ` await (globalThis as ${routerType}).${ROUTER_GLOBAL_NAME}?.push({ name, params });`,
4837
- ` }, { name: ${routeNameExpr}, params: routeParams });`,
4838
- `}`
4839
- ];
4840
- };
5311
+ function requireRouteName(route) {
5312
+ if (route.name === null) {
5313
+ throw new VuePomGeneratorError(`Named navigation requires a route name for template "${route.template}".`);
5314
+ }
5315
+ return route.name;
5316
+ }
4841
5317
  function generateGoToMethod(componentName, routeMeta) {
4842
5318
  if (!routeMeta) {
4843
5319
  return [
@@ -4862,32 +5338,35 @@ function generateGoToMethod(componentName, routeMeta) {
4862
5338
  statements: [
4863
5339
  `throw new Error("[pom] No router path found for component/page-object '${componentName}'.");`
4864
5340
  ]
4865
- })
4866
- ];
4867
- }
4868
- const paramStatements = (entry) => {
4869
- const lines = [];
4870
- for (const param of entry.params) {
4871
- const token = getParamToken(param.name);
4872
- if (param.optional) {
4873
- lines.push(`targetUrl = params.${param.name} === undefined ? targetUrl.replaceAll(${JSON.stringify(`/${token}`)}, "") : targetUrl.replaceAll(${JSON.stringify(token)}, String(params.${param.name}));`);
4874
- } else {
4875
- lines.push(`targetUrl = targetUrl.replaceAll(${JSON.stringify(token)}, String(params.${param.name}));`);
4876
- }
4877
- }
4878
- return lines;
4879
- };
5341
+ })
5342
+ ];
5343
+ }
4880
5344
  if (hasParamless && !hasParametrized) {
4881
5345
  const route = paramless;
5346
+ const hasQuery2 = route.query.length > 0;
5347
+ const paramType2 = buildNavigationTypeString(route);
4882
5348
  return [
4883
5349
  createClassMethod({
4884
5350
  name: "goTo",
4885
5351
  isAsync: true,
4886
- statements: route.name !== null ? pushBlock(JSON.stringify(route.name), "undefined", false) : [`const targetUrl = ${JSON.stringify(route.template)};`, ...GOTO_RUNTIME_LINES]
5352
+ parameters: hasQuery2 ? [{ name: "params", type: paramType2, hasQuestionToken: true }] : [],
5353
+ statements: route.name !== null ? createRouterNavigationWriter({
5354
+ componentName,
5355
+ routeName: { kind: "single", target: route.name },
5356
+ input: hasQuery2 ? { identifier: "params", optional: true } : void 0,
5357
+ pathParamNames: [],
5358
+ queryNames: route.query
5359
+ }) : createUrlNavigationWriter({
5360
+ componentName,
5361
+ routeTemplate: { kind: "single", target: route.template },
5362
+ input: hasQuery2 ? { identifier: "params", optional: true } : void 0,
5363
+ pathParams: [],
5364
+ queryNames: route.query
5365
+ })
4887
5366
  })
4888
5367
  ];
4889
5368
  }
4890
- const paramType = buildParamTypeString(parametrized.params);
5369
+ const paramType = buildNavigationTypeString(parametrized);
4891
5370
  if (hasParametrized && !hasParamless) {
4892
5371
  const route = parametrized;
4893
5372
  const allOptional = route.params.every((p) => p.optional);
@@ -4896,34 +5375,65 @@ function generateGoToMethod(componentName, routeMeta) {
4896
5375
  name: "goTo",
4897
5376
  isAsync: true,
4898
5377
  parameters: [{ name: "params", type: paramType, hasQuestionToken: allOptional }],
4899
- statements: route.name !== null ? pushBlock(JSON.stringify(route.name), "params", allOptional) : [`let targetUrl = ${JSON.stringify(route.template)};`, ...paramStatements(route), ...GOTO_RUNTIME_LINES]
5378
+ statements: route.name !== null ? createRouterNavigationWriter({
5379
+ componentName,
5380
+ routeName: { kind: "single", target: route.name },
5381
+ input: { identifier: "params", optional: allOptional },
5382
+ pathParamNames: route.params.map((param) => param.name),
5383
+ queryNames: route.query
5384
+ }) : createUrlNavigationWriter({
5385
+ componentName,
5386
+ routeTemplate: { kind: "single", target: route.template },
5387
+ input: { identifier: "params", optional: allOptional },
5388
+ pathParams: route.params,
5389
+ queryNames: route.query
5390
+ })
4900
5391
  })
4901
5392
  ];
4902
5393
  }
4903
5394
  const paramlessRoute = paramless;
4904
5395
  const parametrizedRoute = parametrized;
4905
5396
  const usePush = paramlessRoute.name !== null && parametrizedRoute.name !== null;
5397
+ const paramlessType = buildNavigationTypeString(paramlessRoute);
5398
+ const parametrizedOverloadType = buildParametrizedRouteSelectionTypeString(parametrizedRoute);
5399
+ const queryNames = Array.from(/* @__PURE__ */ new Set([...paramlessRoute.query, ...parametrizedRoute.query]));
5400
+ const hasQuery = queryNames.length > 0;
5401
+ const implementationType = hasQuery ? buildImplementationNavigationTypeString([paramlessRoute, parametrizedRoute]) : paramType;
4906
5402
  return [
4907
5403
  createClassMethod({
4908
5404
  name: "goTo",
4909
5405
  isAsync: true,
4910
5406
  overloads: [
4911
- { parameters: [], returnType: "Promise<void>" },
4912
- { parameters: [{ name: "params", type: paramType }], returnType: "Promise<void>" }
5407
+ {
5408
+ parameters: paramlessRoute.query.length ? [{ name: "params", type: paramlessType, hasQuestionToken: true }] : [],
5409
+ returnType: "Promise<void>"
5410
+ },
5411
+ { parameters: [{ name: "params", type: parametrizedOverloadType }], returnType: "Promise<void>" }
4913
5412
  ],
4914
- parameters: [{ name: "params", type: paramType, hasQuestionToken: true }],
4915
- statements: usePush ? pushBlock(
4916
- `params ? ${JSON.stringify(parametrizedRoute.name)} : ${JSON.stringify(paramlessRoute.name)}`,
4917
- "params",
4918
- true
4919
- ) : [
4920
- `const template = params ? ${JSON.stringify(parametrizedRoute.template)} : ${JSON.stringify(paramlessRoute.template)};`,
4921
- "let targetUrl = template;",
4922
- `if (params) {`,
4923
- ...paramStatements(parametrizedRoute).map((line) => ` ${line}`),
4924
- "}",
4925
- ...GOTO_RUNTIME_LINES
4926
- ]
5413
+ parameters: [{ name: "params", type: implementationType, hasQuestionToken: true }],
5414
+ statements: usePush ? createRouterNavigationWriter({
5415
+ componentName,
5416
+ routeName: {
5417
+ kind: "dual",
5418
+ parametrizedTarget: requireRouteName(parametrizedRoute),
5419
+ paramlessTarget: requireRouteName(paramlessRoute),
5420
+ selectBy: hasQuery ? "path-param-presence" : "input-presence"
5421
+ },
5422
+ input: { identifier: "params", optional: true },
5423
+ pathParamNames: parametrizedRoute.params.map((param) => param.name),
5424
+ queryNames: hasQuery ? queryNames : []
5425
+ }) : createUrlNavigationWriter({
5426
+ componentName,
5427
+ routeTemplate: {
5428
+ kind: "dual",
5429
+ parametrizedTarget: parametrizedRoute.template,
5430
+ paramlessTarget: paramlessRoute.template,
5431
+ selectBy: hasQuery ? "path-param-presence" : "input-presence"
5432
+ },
5433
+ input: { identifier: "params", optional: true },
5434
+ pathParams: parametrizedRoute.params,
5435
+ queryNames: hasQuery ? queryNames : []
5436
+ })
4927
5437
  })
4928
5438
  ];
4929
5439
  }
@@ -4964,7 +5474,7 @@ function generateExtraClickMethodMembers(spec, componentName) {
4964
5474
  for (const statement of testIdBinding.setupStatements) {
4965
5475
  writer.writeLine(statement);
4966
5476
  }
4967
- writer.writeLine(`await this.clickByTestId(${testIdBinding.expression}, ${annotationArg}, ${waitArg}, ${locatorDescription});`);
5477
+ writer.writeLine(`await this.clickByTestId(${testIdBinding.expression}, ${annotationArg}, ${waitArg}, ${locatorDescription}, { componentName: ${JSON.stringify(componentName)}, methodName: ${JSON.stringify(spec.name)} });`);
4968
5478
  }
4969
5479
  })
4970
5480
  ];
@@ -4986,7 +5496,7 @@ function generateExtraClickMethodMembers(spec, componentName) {
4986
5496
  for (const statement of labelBinding.setupStatements) {
4987
5497
  writer.writeLine(statement);
4988
5498
  }
4989
- writer.writeLine(`await this.clickWithinTestIdByLabel(${rootBinding.expression}, ${labelBinding.expression}, ${annotationArg}, ${waitArg}, { description: ${locatorDescription} });`);
5499
+ writer.writeLine(`await this.clickWithinTestIdByLabel(${rootBinding.expression}, ${labelBinding.expression}, ${annotationArg}, ${waitArg}, { description: ${locatorDescription}, componentName: ${JSON.stringify(componentName)}, methodName: ${JSON.stringify(spec.name)} });`);
4990
5500
  }
4991
5501
  })
4992
5502
  ];
@@ -5058,7 +5568,8 @@ async function generateFiles(componentHierarchyMap, vueFilesPathMap, basePageCla
5058
5568
  pageDirs,
5059
5569
  componentDirs,
5060
5570
  layoutDirs,
5061
- routeMetaByComponent: routeMetaByComponentOverride
5571
+ routeMetaByComponent: routeMetaByComponentOverride,
5572
+ elementMetadata = /* @__PURE__ */ new Map()
5062
5573
  } = options;
5063
5574
  const emitLanguages = emitLanguagesOverride?.length ? emitLanguagesOverride : ["ts"];
5064
5575
  const outDir = outDirOverride ?? "./pom";
@@ -5099,13 +5610,15 @@ async function generateFiles(componentHierarchyMap, vueFilesPathMap, basePageCla
5099
5610
  for (const file of files) {
5100
5611
  writeGeneratedFile(file);
5101
5612
  }
5102
- const fixtureRegistryFile = maybeGenerateFixtureRegistry(emittableComponentHierarchyMap, {
5613
+ const fixtureRegistryFiles = maybeGenerateFixtureRegistry(emittableComponentHierarchyMap, {
5103
5614
  generateFixtures,
5104
5615
  pomOutDir: outDir,
5105
5616
  projectRoot,
5106
- customPomDir
5617
+ customPomDir,
5618
+ elementMetadata,
5619
+ testIdAttribute
5107
5620
  });
5108
- if (fixtureRegistryFile) {
5621
+ for (const fixtureRegistryFile of fixtureRegistryFiles) {
5109
5622
  writeGeneratedFile(fixtureRegistryFile);
5110
5623
  }
5111
5624
  }
@@ -5587,7 +6100,7 @@ function generateAggregatedCSharpFiles(componentHierarchyMap, outDir, options =
5587
6100
  function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5588
6101
  const { generateFixtures, pomOutDir } = options;
5589
6102
  if (!generateFixtures)
5590
- return null;
6103
+ return [];
5591
6104
  const defaultFixtureOutDirRel = pomOutDir;
5592
6105
  const fixtureOutRel = typeof generateFixtures === "string" ? generateFixtures : typeof generateFixtures === "object" && generateFixtures?.outDir ? generateFixtures.outDir : defaultFixtureOutDirRel;
5593
6106
  const looksLikeFilePath = fixtureOutRel.endsWith(".ts") || fixtureOutRel.endsWith(".tsx") || fixtureOutRel.endsWith(".mts") || fixtureOutRel.endsWith(".cts");
@@ -5600,6 +6113,10 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5600
6113
  const overridePomDirAbs = path.resolve(path.dirname(customPomDirAbs), "overrides");
5601
6114
  const pomDirAbs = path.isAbsolute(pomOutDir) ? pomOutDir : path.resolve(root, pomOutDir);
5602
6115
  const pomImport = toPosixRelativePath(fixtureOutDirAbs, pomDirAbs);
6116
+ const diagnosticsImport = stripExtension(toPosixRelativePath(
6117
+ fixtureOutDirAbs,
6118
+ path.join(pomDirAbs, "_pom-runtime", "class-generation", "diagnostics.ts")
6119
+ ));
5603
6120
  const viewClassNames = Array.from(componentHierarchyMap.entries()).filter(([, deps]) => !!deps.isView).map(([name]) => name).sort((a, b) => a.localeCompare(b));
5604
6121
  const reservedPlaywrightFixtureNames = /* @__PURE__ */ new Set([
5605
6122
  // Built-in Playwright fixtures
@@ -5609,7 +6126,8 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5609
6126
  "browserName",
5610
6127
  "request",
5611
6128
  // Our own fixtureOptions
5612
- "animation"
6129
+ "animation",
6130
+ "pomDiagnostics"
5613
6131
  ]);
5614
6132
  const viewFixtureNames = new Set(viewClassNames.map((name) => lowerFirst(name)));
5615
6133
  const componentClassNames = Array.from(componentHierarchyMap.entries()).filter(([, deps]) => !deps.isView).map(([name]) => name).filter((name) => {
@@ -5653,13 +6171,27 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5653
6171
  namedImports: [
5654
6172
  { name: "Page", alias: "PwPage" },
5655
6173
  "PlaywrightTestArgs",
6174
+ "TestInfo",
5656
6175
  "TestType"
5657
6176
  ]
5658
6177
  });
6178
+ addNamedImport(sourceFile, {
6179
+ moduleSpecifier: diagnosticsImport,
6180
+ namedImports: ["installPomFailureDiagnostics"]
6181
+ });
6182
+ addNamedImport(sourceFile, {
6183
+ moduleSpecifier: diagnosticsImport,
6184
+ isTypeOnly: true,
6185
+ namedImports: ["PomFailureDiagnosticsOptions"]
6186
+ });
5659
6187
  sourceFile.addImportDeclaration({
5660
6188
  namespaceImport: "Pom",
5661
6189
  moduleSpecifier: pomImport
5662
6190
  });
6191
+ addNamedImport(sourceFile, {
6192
+ moduleSpecifier: "./pom-manifest.g",
6193
+ namedImports: ["pomManifest"]
6194
+ });
5663
6195
  for (const entry of overrideCtorEntries) {
5664
6196
  addNamedImport(sourceFile, {
5665
6197
  moduleSpecifier: entry.importSpecifier,
@@ -5672,6 +6204,9 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5672
6204
  properties: [{
5673
6205
  name: "animation",
5674
6206
  type: "Pom.PlaywrightAnimationOptions"
6207
+ }, {
6208
+ name: "pomDiagnostics",
6209
+ type: "PomFailureDiagnosticsOptions"
5675
6210
  }]
5676
6211
  });
5677
6212
  sourceFile.addTypeAlias({
@@ -5698,6 +6233,10 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5698
6233
  name: "PomFactoryFixture",
5699
6234
  type: "{ pomFactory: PomFactory }"
5700
6235
  });
6236
+ sourceFile.addTypeAlias({
6237
+ name: "PomDiagnosticsSetupFixture",
6238
+ type: "{ pomDiagnosticsSetup: void }"
6239
+ });
5701
6240
  sourceFile.addVariableStatement({
5702
6241
  declarationKind: VariableDeclarationKind.Const,
5703
6242
  declarations: [{
@@ -5744,7 +6283,7 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5744
6283
  docs: [{
5745
6284
  description: "Every fixture contributed by the generator: the `animation` option, the internal\n`pomSetup`/`pomFactory` fixtures, and one fixture per generated page/component POM."
5746
6285
  }],
5747
- type: "PlaywrightOptions & PomSetupFixture & PomFactoryFixture & GeneratedPageFixtures & GeneratedComponentFixtures"
6286
+ type: "PlaywrightOptions & PomSetupFixture & PomFactoryFixture & PomDiagnosticsSetupFixture & GeneratedPageFixtures & GeneratedComponentFixtures"
5748
6287
  });
5749
6288
  sourceFile.addFunction({
5750
6289
  name: "makePomFixture",
@@ -5796,16 +6335,32 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5796
6335
  writer.block(() => {
5797
6336
  writer.writeLine("animation: [{");
5798
6337
  writer.indent(() => {
6338
+ writer.writeLine("enabled: false,");
5799
6339
  writer.writeLine('pointer: { durationMilliseconds: 250, transitionStyle: "ease-in-out", clickDelayMilliseconds: 0 },');
5800
6340
  writer.writeLine("keyboard: { typeDelayMilliseconds: 100 },");
5801
6341
  });
5802
6342
  writer.writeLine("}, { option: true }],");
6343
+ writer.writeLine(`pomDiagnostics: [{ captureBudgetMs: 5_000, testIdAttribute: ${JSON.stringify(options.testIdAttribute ?? "data-testid")} }, { option: true }],`);
5803
6344
  writer.writeLine("pomSetup: [async ({ animation }: PomFixtures, use: (r: void) => Promise<void>) => {");
5804
6345
  writer.indent(() => {
5805
6346
  writer.writeLine("Pom.setPlaywrightAnimationOptions(animation);");
5806
6347
  writer.writeLine("await use();");
5807
6348
  });
5808
6349
  writer.writeLine("}, { auto: true }],");
6350
+ writer.writeLine("pomDiagnosticsSetup: [async ({ page, pomDiagnostics }: { page: PwPage; pomDiagnostics: PomFailureDiagnosticsOptions }, use: (r: void) => Promise<void>, testInfo: TestInfo) => {");
6351
+ writer.indent(() => {
6352
+ writer.writeLine("const capture = installPomFailureDiagnostics(page, pomManifest, testInfo, pomDiagnostics);");
6353
+ writer.writeLine("try {");
6354
+ writer.indent(() => writer.writeLine("await use();"));
6355
+ writer.writeLine("} finally {");
6356
+ writer.indent(() => {
6357
+ writer.writeLine("if (testInfo.status !== undefined && testInfo.status !== testInfo.expectedStatus) {");
6358
+ writer.indent(() => writer.writeLine("await capture.capture().catch(() => undefined);"));
6359
+ writer.writeLine("}");
6360
+ });
6361
+ writer.writeLine("}");
6362
+ });
6363
+ writer.writeLine("}, { auto: true }],");
5809
6364
  writer.writeLine("pomFactory: async ({ page }: { page: PwPage }, use: (r: PomFactory) => Promise<void>) => {");
5810
6365
  writer.indent(() => {
5811
6366
  writer.writeLine("await use({");
@@ -5835,10 +6390,31 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5835
6390
  ]
5836
6391
  })
5837
6392
  });
5838
- return {
5839
- filePath: path.resolve(fixtureOutDirAbs, fixtureFileName),
5840
- content: fixturesContent
5841
- };
6393
+ const manifestFileName = "pom-manifest.g.ts";
6394
+ const manifestContent = generatePomManifestModule(
6395
+ componentHierarchyMap,
6396
+ options.elementMetadata,
6397
+ manifestFileName
6398
+ );
6399
+ const [diagnosticsRuntimeFile] = buildRuntimeGeneratedFilesFromSpecs([{
6400
+ absolutePath: resolvePluginAsset("../class-generation/diagnostics.ts"),
6401
+ description: "diagnostics.ts",
6402
+ outputPath: path.join(pomDirAbs, "_pom-runtime", "class-generation", "diagnostics.ts")
6403
+ }]);
6404
+ if (!diagnosticsRuntimeFile) {
6405
+ throw new Error("[vue-pom-generator] Failed to generate the Playwright diagnostics runtime.");
6406
+ }
6407
+ return [
6408
+ {
6409
+ filePath: path.resolve(fixtureOutDirAbs, fixtureFileName),
6410
+ content: fixturesContent
6411
+ },
6412
+ {
6413
+ filePath: path.resolve(fixtureOutDirAbs, manifestFileName),
6414
+ content: manifestContent
6415
+ },
6416
+ diagnosticsRuntimeFile
6417
+ ];
5842
6418
  }
5843
6419
  function prepareViewObjectModelClass(componentName, dependencies, componentHierarchyMap, options = {}) {
5844
6420
  const { isView, childrenComponentSet, usedComponentSet } = dependencies;
@@ -5871,6 +6447,23 @@ function prepareViewObjectModelClass(componentName, dependencies, componentHiera
5871
6447
  }
5872
6448
  return match;
5873
6449
  };
6450
+ const hasGeneratedPomSurface = (value, seen = /* @__PURE__ */ new Set()) => {
6451
+ const resolvedRef = resolveTrackedComponentRef(value);
6452
+ if (!resolvedRef || seen.has(resolvedRef)) {
6453
+ return false;
6454
+ }
6455
+ const resolvedDependencies = componentHierarchyMap.get(resolvedRef);
6456
+ if (!resolvedDependencies) {
6457
+ return false;
6458
+ }
6459
+ if (resolvedDependencies.dataTestIdSet.size > 0 || (resolvedDependencies.pomExtraMethods?.length ?? 0) > 0 || (resolvedDependencies.generatedMethods?.size ?? 0) > 0) {
6460
+ return true;
6461
+ }
6462
+ const nextSeen = new Set(seen);
6463
+ nextSeen.add(resolvedRef);
6464
+ const nestedRefs = resolvedDependencies.usedComponentSet?.size ? resolvedDependencies.usedComponentSet : resolvedDependencies.childrenComponentSet;
6465
+ return Array.from(nestedRefs).some((child) => hasGeneratedPomSurface(child, nextSeen));
6466
+ };
5874
6467
  const rawComponentRefsForInstances = usedComponentSet?.size ? usedComponentSet : childrenComponentSet;
5875
6468
  const ownClassName = toPascalCaseLocal(componentName);
5876
6469
  const isSelfReference = (ref) => {
@@ -5882,8 +6475,7 @@ function prepareViewObjectModelClass(componentName, dependencies, componentHiera
5882
6475
  if (isSelfReference(resolvedRef)) {
5883
6476
  continue;
5884
6477
  }
5885
- const resolvedDependencies = componentHierarchyMap.get(resolvedRef);
5886
- if (!resolvedDependencies?.dataTestIdSet.size) {
6478
+ if (!hasGeneratedPomSurface(resolvedRef, /* @__PURE__ */ new Set([componentName]))) {
5887
6479
  continue;
5888
6480
  }
5889
6481
  componentRefsForInstances.add(resolvedRef);
@@ -5927,7 +6519,7 @@ function prepareViewObjectModelClass(componentName, dependencies, componentHiera
5927
6519
  }));
5928
6520
  const widgetInstances = isView ? getWidgetInstancesForView(componentName, dependencies.dataTestIdSet, customPomAvailableClassIdentifiers) : [];
5929
6521
  const className = toPascalCaseLocal(componentName);
5930
- const childInstancePropertyNames = Array.from(componentRefsForInstances).filter((child) => componentHierarchyMap.has(child) && componentHierarchyMap.get(child)?.dataTestIdSet.size).map((child) => child.split(".vue")[0]);
6522
+ const childInstancePropertyNames = Array.from(componentRefsForInstances).map((child) => child.split(".vue")[0]);
5931
6523
  const blockedViewPassthroughMethodNames = new Set(
5932
6524
  attachmentsForThisClass.filter((a) => a.flatten).flatMap((a) => Array.from(a.methodSignatures.keys()))
5933
6525
  );
@@ -6025,10 +6617,7 @@ function generateViewObjectModelContent(componentName, dependencies, componentHi
6025
6617
  };
6026
6618
  for (const child of prepared.componentRefsForInstances) {
6027
6619
  const childName = child.endsWith(".vue") ? child.slice(0, -4) : child;
6028
- const childDeps = componentHierarchyMap.get(child) ?? componentHierarchyMap.get(childName);
6029
- if (childDeps?.dataTestIdSet.size) {
6030
- addGeneratedImport(childName);
6031
- }
6620
+ addGeneratedImport(childName);
6032
6621
  }
6033
6622
  const targetClassNames = Array.from(
6034
6623
  new Set(
@@ -6371,7 +6960,7 @@ function getRuntimeGeneratedAssetSpecs(baseDir, basePageClassPath) {
6371
6960
  const runtimeDirAbs = path.join(baseDir, "_pom-runtime");
6372
6961
  const runtimeClassGenAbs = path.join(runtimeDirAbs, "class-generation");
6373
6962
  const runtimeClassGenSourceDir = resolvePluginAsset("../class-generation");
6374
- const runtimeClassGenFiles = fs.readdirSync(runtimeClassGenSourceDir).filter((file) => file.endsWith(".ts")).filter((file) => file !== "base-page.ts" && file !== "index.ts").sort((left, right) => left.localeCompare(right));
6963
+ const runtimeClassGenFiles = fs.readdirSync(runtimeClassGenSourceDir).filter((file) => file.endsWith(".ts")).filter((file) => file !== "base-page.ts" && file !== "diagnostics.ts" && file !== "index.ts").sort((left, right) => left.localeCompare(right));
6375
6964
  return [
6376
6965
  {
6377
6966
  absolutePath: resolvePluginAsset("../click-instrumentation.ts"),
@@ -6790,7 +7379,7 @@ function getComponentInstances(childrenComponent, componentHierarchyMap, attachm
6790
7379
  }));
6791
7380
  }
6792
7381
  childrenComponent.forEach((child) => {
6793
- if (componentHierarchyMap.has(child) && componentHierarchyMap.get(child)?.dataTestIdSet.size) {
7382
+ if (componentHierarchyMap.has(child)) {
6794
7383
  const childName = child.split(".vue")[0];
6795
7384
  declarations.push(createClassProperty({
6796
7385
  name: childName,
@@ -6813,7 +7402,7 @@ function getConstructor(childrenComponent, componentHierarchyMap, attachmentsFor
6813
7402
  writer.writeLine(`this.${w.propertyName} = new ${w.className}(this.page, ${JSON.stringify(w.testId)});`);
6814
7403
  }
6815
7404
  childrenComponent.forEach((child) => {
6816
- if (componentHierarchyMap.has(child) && componentHierarchyMap.get(child)?.dataTestIdSet.size) {
7405
+ if (componentHierarchyMap.has(child)) {
6817
7406
  const childName = child.split(".vue")[0];
6818
7407
  writer.writeLine(`this.${childName} = new ${childName}(page);`);
6819
7408
  }
@@ -7213,6 +7802,13 @@ ${buildSearchRootsKey(normalizedSearchRoots)}`;
7213
7802
  }
7214
7803
  try {
7215
7804
  const ast = parse$2(template, { comments: false });
7805
+ const renderedRoots = ast.children.filter((child) => {
7806
+ return child.type !== NodeTypes.COMMENT && !(child.type === NodeTypes.TEXT && child.content.trim() === "");
7807
+ });
7808
+ if (renderedRoots.length !== 1) {
7809
+ inferredNativeWrapperConfigByLookup.set(cacheKey, { role: "" });
7810
+ return null;
7811
+ }
7216
7812
  const nextSeen = new Set(seenTags);
7217
7813
  nextSeen.add(tag);
7218
7814
  const isComponentLikeTag = (value) => {
@@ -7619,7 +8215,7 @@ function createTestIdTransform(componentName, componentHierarchyMap, nativeWrapp
7619
8215
  const inferred = tryInferNativeWrapperRoleFromSfc(element.tag, vueFilesPathMap, wrapperSearchRoots);
7620
8216
  if (inferred?.role) {
7621
8217
  nativeWrappers[element.tag] = { role: inferred.role, inferred: true };
7622
- } else if (element.tag.endsWith("Button")) {
8218
+ } else if (element.tag.endsWith("Button") && !tryResolveSfcPathForTag(element.tag, vueFilesPathMap, wrapperSearchRoots)) {
7623
8219
  nativeWrappers[element.tag] = { role: "button" };
7624
8220
  } else if (element.tag === "DxDataGrid") {
7625
8221
  nativeWrappers[element.tag] = { role: "grid" };
@@ -7922,7 +8518,7 @@ Fix: remove the explicit ${attrLabel}, or change existingIdBehavior to "overwrit
7922
8518
  });
7923
8519
  return;
7924
8520
  }
7925
- if (handlerInfo) {
8521
+ if (handlerInfo && nativeWrappers[element.tag]) {
7926
8522
  const testId = getHandlerAttributeValueDataTestId(handlerInfo.semanticNameHint);
7927
8523
  applyResolvedDataTestIdForElement({
7928
8524
  preferredGeneratedValue: testId,
@@ -7990,59 +8586,6 @@ Fix: remove the explicit ${attrLabel}, or change existingIdBehavior to "overwrit
7990
8586
  }
7991
8587
  };
7992
8588
  }
7993
- function supportsInlineTextAccessibleName(role) {
7994
- return role === "button" || role === "radio";
7995
- }
7996
- function buildAccessibilityAudit(metadata, inferredRole) {
7997
- if (!metadata || !inferredRole) {
7998
- return void 0;
7999
- }
8000
- const role = normalizePomRoleLabel(inferredRole).toLowerCase();
8001
- const dynamicProps = new Set(metadata.dynamicProps ?? []);
8002
- const hasDynamicAccessibleNameSignal = dynamicProps.has("aria-label") || dynamicProps.has("title") || !!metadata.hasDynamicText;
8003
- let accessibleNameSource;
8004
- const reasons = [];
8005
- if (metadata.staticAriaLabel) {
8006
- accessibleNameSource = "aria-label";
8007
- } else if (supportsInlineTextAccessibleName(role) && metadata.staticTextContent) {
8008
- accessibleNameSource = "text";
8009
- } else if (metadata.staticTitle) {
8010
- accessibleNameSource = "title";
8011
- } else if (hasDynamicAccessibleNameSignal) {
8012
- accessibleNameSource = "dynamic";
8013
- } else if (role === "input" || role === "select") {
8014
- accessibleNameSource = "unknown";
8015
- reasons.push("No inline accessible-name signal was found; the element may rely on external markup such as a separate <label>.");
8016
- } else {
8017
- accessibleNameSource = "missing";
8018
- reasons.push("No compile-time accessible-name signal was found.");
8019
- }
8020
- return {
8021
- needsReview: accessibleNameSource === "unknown" || accessibleNameSource === "missing",
8022
- accessibleNameSource,
8023
- reasons,
8024
- ...metadata.staticAriaLabel ? { staticAriaLabel: metadata.staticAriaLabel } : {},
8025
- ...metadata.staticRole ? { staticRole: metadata.staticRole } : {},
8026
- ...metadata.staticTitle ? { staticTitle: metadata.staticTitle } : {},
8027
- ...metadata.staticTextContent ? { staticTextContent: metadata.staticTextContent } : {}
8028
- };
8029
- }
8030
- function collectAccessibilityReviewWarnings(manifest) {
8031
- const warnings = [];
8032
- for (const [componentName, component] of Object.entries(manifest)) {
8033
- for (const entry of component.entries) {
8034
- if (!entry.accessibility?.needsReview) {
8035
- continue;
8036
- }
8037
- const entryLabel = entry.generatedPropertyName ?? entry.testId;
8038
- const reasonText = entry.accessibility.reasons.join(" ");
8039
- warnings.push(
8040
- `[vue-pom-generator] Accessibility review suggested for ${componentName}.${entryLabel} (role=${entry.inferredRole ?? "unknown"}, testId=${JSON.stringify(entry.testId)}): ${reasonText}`
8041
- );
8042
- }
8043
- }
8044
- return warnings;
8045
- }
8046
8589
  function findDataTestIdProp(element, attributeName = "data-testid") {
8047
8590
  return element.props.find(
8048
8591
  (prop) => prop.type === NodeTypes.ATTRIBUTE && prop.name === attributeName || prop.type === NodeTypes.DIRECTIVE && prop.name === "bind" && prop.arg?.type === NodeTypes.SIMPLE_EXPRESSION && prop.arg.content === attributeName
@@ -8167,151 +8710,6 @@ function tryCreateElementMetadata(args) {
8167
8710
  };
8168
8711
  return metadata;
8169
8712
  }
8170
- function matchesPrimarySelector(extraMethod, pom) {
8171
- if (extraMethod.selector.kind !== "testId") {
8172
- return false;
8173
- }
8174
- return extraMethod.selector.testId.formatted === pom.selector.formatted && extraMethod.selector.testId.patternKind === pom.selector.patternKind;
8175
- }
8176
- function getManifestEntry(componentName, entry, componentMetadata, extraMethods) {
8177
- const testId = entry.selectorValue.formatted;
8178
- const metadata = componentMetadata?.get(testId);
8179
- const pom = entry.pom;
8180
- const generatedActionName = pom ? buildPomGeneratedActionName(pom) : null;
8181
- const extraActionNames = pom ? extraMethods.filter((extraMethod) => matchesPrimarySelector(extraMethod, pom)).map((extraMethod) => extraMethod.name).sort((a, b) => a.localeCompare(b)) : [];
8182
- const generatedActionNames = Array.from(/* @__PURE__ */ new Set([
8183
- ...generatedActionName ? [generatedActionName] : [],
8184
- ...extraActionNames.filter((name) => name !== generatedActionName)
8185
- ]));
8186
- const accessibility = buildAccessibilityAudit(metadata, pom?.nativeRole ?? null);
8187
- return {
8188
- testId,
8189
- selectorPatternKind: entry.selectorValue.patternKind,
8190
- semanticName: metadata?.semanticName ?? (pom ? humanizePomMethodName(pom.methodName) : testId),
8191
- locatorDescription: pom ? buildPomLocatorDescription({
8192
- componentName,
8193
- methodName: pom.methodName,
8194
- nativeRole: pom.nativeRole
8195
- }) : componentName,
8196
- inferredRole: pom?.nativeRole ?? null,
8197
- ...accessibility ? { accessibility } : {},
8198
- generatedPropertyName: pom ? buildPomGeneratedPropertyName(pom) : null,
8199
- generatedActionName,
8200
- generatedActionNames,
8201
- emitPrimary: pom?.emitPrimary !== false,
8202
- ...entry.targetPageObjectModelClass ? { targetPageObjectModelClass: entry.targetPageObjectModelClass } : {},
8203
- ...metadata?.tag ? { sourceTag: metadata.tag } : {},
8204
- ...metadata ? { sourceTagType: metadata.tagType } : {},
8205
- ...metadata?.sourceLine !== void 0 ? { sourceLine: metadata.sourceLine } : {},
8206
- ...metadata?.sourceColumn !== void 0 ? { sourceColumn: metadata.sourceColumn } : {},
8207
- ...metadata?.patchFlag !== void 0 ? { patchFlag: metadata.patchFlag } : {},
8208
- ...metadata?.dynamicProps?.length ? { dynamicProps: metadata.dynamicProps } : {},
8209
- ...metadata?.hasClickHandler !== void 0 ? { hasClickHandler: metadata.hasClickHandler } : {},
8210
- ...metadata?.hasDynamicClass !== void 0 ? { hasDynamicClass: metadata.hasDynamicClass } : {},
8211
- ...metadata?.hasDynamicStyle !== void 0 ? { hasDynamicStyle: metadata.hasDynamicStyle } : {},
8212
- ...metadata?.hasDynamicText !== void 0 ? { hasDynamicText: metadata.hasDynamicText } : {}
8213
- };
8214
- }
8215
- function buildPomManifest(componentHierarchyMap, elementMetadata) {
8216
- const manifestEntries = Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8217
- const entries = Array.from(dependencies.dataTestIdSet).sort((a, b) => a.selectorValue.formatted.localeCompare(b.selectorValue.formatted)).map((entry) => getManifestEntry(componentName, entry, elementMetadata.get(componentName), dependencies.pomExtraMethods ?? []));
8218
- if (!entries.length) {
8219
- return null;
8220
- }
8221
- return [componentName, {
8222
- componentName,
8223
- className: componentName,
8224
- sourceFile: dependencies.filePath,
8225
- kind: dependencies.isView ? "view" : "component",
8226
- testIds: Array.from(new Set(entries.map((entry) => entry.testId))),
8227
- entries
8228
- }];
8229
- }).filter((entry) => entry !== null);
8230
- return Object.fromEntries(manifestEntries);
8231
- }
8232
- function buildTestIdManifest(componentHierarchyMap) {
8233
- return Object.fromEntries(
8234
- Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8235
- const testIds = Array.from(dependencies.dataTestIdSet).map((entry) => entry.selectorValue.formatted).filter(Boolean);
8236
- if (!testIds.length) {
8237
- return null;
8238
- }
8239
- return [componentName, Array.from(new Set(testIds)).sort((a, b) => a.localeCompare(b))];
8240
- }).filter((entry) => entry !== null)
8241
- );
8242
- }
8243
- function writeConstJson(value) {
8244
- return (writer) => {
8245
- writer.write(`${JSON.stringify(value, null, 2)} as const`);
8246
- };
8247
- }
8248
- function generateTestIdsModule(componentHierarchyMap, elementMetadata) {
8249
- const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8250
- const testIdManifest = buildTestIdManifest(componentHierarchyMap);
8251
- return renderSourceFile("virtual-testids.ts", (sourceFile) => {
8252
- sourceFile.addStatements("// Virtual module: test id manifest");
8253
- sourceFile.addVariableStatement({
8254
- declarationKind: VariableDeclarationKind.Const,
8255
- isExported: true,
8256
- declarations: [{
8257
- name: "testIdManifest",
8258
- initializer: writeConstJson(testIdManifest)
8259
- }]
8260
- });
8261
- sourceFile.addVariableStatement({
8262
- declarationKind: VariableDeclarationKind.Const,
8263
- isExported: true,
8264
- declarations: [{
8265
- name: "pomManifest",
8266
- initializer: writeConstJson(pomManifest)
8267
- }]
8268
- });
8269
- sourceFile.addTypeAlias({
8270
- isExported: true,
8271
- name: "TestIdManifest",
8272
- type: "typeof testIdManifest"
8273
- });
8274
- sourceFile.addTypeAlias({
8275
- isExported: true,
8276
- name: "ComponentName",
8277
- type: "keyof TestIdManifest"
8278
- });
8279
- sourceFile.addTypeAlias({
8280
- isExported: true,
8281
- name: "PomManifest",
8282
- type: "typeof pomManifest"
8283
- });
8284
- sourceFile.addTypeAlias({
8285
- isExported: true,
8286
- name: "PomManifestComponentName",
8287
- type: "keyof PomManifest"
8288
- });
8289
- });
8290
- }
8291
- function generatePomManifestModule(componentHierarchyMap, elementMetadata) {
8292
- const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8293
- return renderSourceFile("virtual-pom-manifest.ts", (sourceFile) => {
8294
- sourceFile.addStatements("// Virtual module: richer POM discoverability manifest");
8295
- sourceFile.addVariableStatement({
8296
- declarationKind: VariableDeclarationKind.Const,
8297
- isExported: true,
8298
- declarations: [{
8299
- name: "pomManifest",
8300
- initializer: writeConstJson(pomManifest)
8301
- }]
8302
- });
8303
- sourceFile.addTypeAlias({
8304
- isExported: true,
8305
- name: "PomManifest",
8306
- type: "typeof pomManifest"
8307
- });
8308
- sourceFile.addTypeAlias({
8309
- isExported: true,
8310
- name: "PomManifestComponentName",
8311
- type: "keyof PomManifest"
8312
- });
8313
- });
8314
- }
8315
8713
  function resolveExistingIdBehavior(config, componentName) {
8316
8714
  return typeof config === "string" ? config : config.components[componentName] ?? config.default;
8317
8715
  }
@@ -8640,6 +9038,7 @@ function isLessRich(candidate, previous) {
8640
9038
  function createBuildProcessorPlugin(options) {
8641
9039
  const {
8642
9040
  componentHierarchyMap,
9041
+ elementMetadata,
8643
9042
  crossFileKeyRegistry,
8644
9043
  vueFilesPathMap,
8645
9044
  getPageDirs,
@@ -8892,7 +9291,8 @@ function createBuildProcessorPlugin(options) {
8892
9291
  routerType,
8893
9292
  pageDirs: getPageDirs(),
8894
9293
  componentDirs: getComponentDirs(),
8895
- layoutDirs: getLayoutDirs()
9294
+ layoutDirs: getLayoutDirs(),
9295
+ elementMetadata
8896
9296
  });
8897
9297
  lastGeneratedMetrics = metrics;
8898
9298
  loggerRef.current.info(`generated POMs (${metrics.entryCount} entries, ${metrics.interactiveComponentCount} interactive components, ${metrics.dataTestIdCount} selectors)`);
@@ -8904,6 +9304,7 @@ function createBuildProcessorPlugin(options) {
8904
9304
  }
8905
9305
  function createDevProcessorPlugin(options) {
8906
9306
  const {
9307
+ elementMetadata,
8907
9308
  nativeWrappers,
8908
9309
  optionKeyAttribute,
8909
9310
  excludedComponents,
@@ -9196,7 +9597,8 @@ function createDevProcessorPlugin(options) {
9196
9597
  testIdAttribute,
9197
9598
  vueRouterFluentChaining: routerAwarePoms,
9198
9599
  routerEntry: getResolvedRouterEntry(),
9199
- routerType
9600
+ routerType,
9601
+ elementMetadata
9200
9602
  });
9201
9603
  const t1 = performance.now();
9202
9604
  logInfo(`generate(${logLabel}): components=${snapshotHierarchy.size} in ${formatMs(t1 - t0)}`);
@@ -9512,6 +9914,7 @@ function createInternalPlugins(options) {
9512
9914
  const normalizedBasePagePath = path.posix.normalize(basePageClassPath);
9513
9915
  const tsProcessor = createBuildProcessorPlugin({
9514
9916
  componentHierarchyMap,
9917
+ elementMetadata,
9515
9918
  crossFileKeyRegistry,
9516
9919
  vueFilesPathMap,
9517
9920
  getPageDirs,
@@ -9531,6 +9934,7 @@ function createInternalPlugins(options) {
9531
9934
  loggerRef
9532
9935
  });
9533
9936
  const devProcessor = createDevProcessorPlugin({
9937
+ elementMetadata,
9534
9938
  nativeWrappers,
9535
9939
  optionKeyAttribute,
9536
9940
  excludedComponents,