@immense/vue-pom-generator 1.0.95 → 1.0.97

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 (38) hide show
  1. package/README.md +124 -0
  2. package/RELEASE_NOTES.md +68 -18
  3. package/class-generation/base-page.ts +18 -2
  4. package/class-generation/index.ts +564 -48
  5. package/class-generation/vue-test-utils-pom.ts +112 -0
  6. package/dist/class-generation/base-page.d.ts +6 -0
  7. package/dist/class-generation/base-page.d.ts.map +1 -1
  8. package/dist/class-generation/index.d.ts +2 -0
  9. package/dist/class-generation/index.d.ts.map +1 -1
  10. package/dist/class-generation/vue-test-utils-pom.d.ts +28 -0
  11. package/dist/class-generation/vue-test-utils-pom.d.ts.map +1 -0
  12. package/dist/index.cjs +625 -48
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.mjs +626 -49
  15. package/dist/index.mjs.map +1 -1
  16. package/dist/playwright/runtime.cjs +12 -2
  17. package/dist/playwright/runtime.cjs.map +1 -1
  18. package/dist/playwright/runtime.mjs +12 -2
  19. package/dist/playwright/runtime.mjs.map +1 -1
  20. package/dist/plugin/create-vue-pom-generator-plugins.d.ts.map +1 -1
  21. package/dist/plugin/internal/build-plugin.d.ts.map +1 -1
  22. package/dist/plugin/internal/dev-plugin.d.ts.map +1 -1
  23. package/dist/plugin/resolved-generation-options.d.ts +1 -0
  24. package/dist/plugin/resolved-generation-options.d.ts.map +1 -1
  25. package/dist/plugin/types.d.ts +9 -0
  26. package/dist/plugin/types.d.ts.map +1 -1
  27. package/dist/tests/fixtures/generated-tsc/base-page.full.d.ts +2 -0
  28. package/dist/tests/fixtures/generated-tsc/base-page.full.d.ts.map +1 -1
  29. package/dist/tests/fixtures/generated-tsc/base-page.minimal.d.ts +2 -0
  30. package/dist/tests/fixtures/generated-tsc/base-page.minimal.d.ts.map +1 -1
  31. package/dist/tests/semantic-component-instances.test.d.ts +2 -0
  32. package/dist/tests/semantic-component-instances.test.d.ts.map +1 -0
  33. package/dist/tests/vue-test-utils-pom.test.d.ts +2 -0
  34. package/dist/tests/vue-test-utils-pom.test.d.ts.map +1 -0
  35. package/dist/transform.d.ts.map +1 -1
  36. package/dist/utils.d.ts +40 -12
  37. package/dist/utils.d.ts.map +1 -1
  38. package/package.json +4 -1
package/dist/index.mjs CHANGED
@@ -7,7 +7,7 @@ import * as compilerDom from "@vue/compiler-dom";
7
7
  import { parse as parse$2, NodeTypes as NodeTypes$1 } from "@vue/compiler-dom";
8
8
  import { parse as parse$1, compileScript } from "@vue/compiler-sfc";
9
9
  import { parseExpression, parse } from "@babel/parser";
10
- import { NodeTypes, stringifyExpression, ConstantTypes, createSimpleExpression, ElementTypes } from "@vue/compiler-core";
10
+ import { NodeTypes, stringifyExpression, createSimpleExpression, ConstantTypes, ElementTypes } from "@vue/compiler-core";
11
11
  import { Project, QuoteKind, NewLineKind, IndentationText, CodeBlockWriter, StructureKind, VariableDeclarationKind } from "ts-morph";
12
12
  import { isIdentifier, isObjectPattern, isRestElement, isObjectProperty, isArrayExpression, isStringLiteral, isTemplateLiteral, isArrowFunctionExpression, isExpressionStatement, isAssignmentPattern, isMemberExpression, isOptionalMemberExpression, isCallExpression, isOptionalCallExpression, isAssignmentExpression, isObjectExpression, isFile, isBlockStatement, isLogicalExpression, isConditionalExpression, isSequenceExpression, isProgram, VISITOR_KEYS, isBooleanLiteral, isNumericLiteral, isNullLiteral, isImportDeclaration, isImportSpecifier, isExportDefaultDeclaration, isExpression, isVariableDeclaration, isFunctionDeclaration, isFunctionExpression, isReturnStatement, isTSAsExpression, isTSTypeAssertion, isTSNonNullExpression, isForInStatement, isIfStatement } from "@babel/types";
13
13
  import { POM_ROUTER_GLOBAL_NAME } from "./router.mjs";
@@ -213,6 +213,7 @@ function resolveGenerationSupportOptions(options) {
213
213
  typescriptOutputStructure: options.typescriptOutputStructure ?? "aggregated",
214
214
  csharp: options.csharp,
215
215
  generateFixtures: options.generateFixtures,
216
+ vueTestUtilsOutDir: options.vueTestUtilsOutDir?.trim() || void 0,
216
217
  customPomAttachments: options.customPomAttachments ?? [],
217
218
  customPomDir: options.customPomDir ?? "tests/playwright/pom/custom",
218
219
  requireCustomPomDir: options.requireCustomPomDir ?? false,
@@ -2901,18 +2902,18 @@ function safeMethodNameFromParts(parts) {
2901
2902
  }
2902
2903
  return name;
2903
2904
  }
2904
- function toPomKeyPattern(templateValue) {
2905
+ function toPomKeyPattern(templateValue, parameterName = "key") {
2905
2906
  const { templateLiteral } = templateValue.parsedTemplate;
2906
2907
  let out = "";
2907
2908
  let hasExpression = false;
2908
2909
  for (let i = 0; i < templateLiteral.quasis.length; i += 1) {
2909
2910
  out += templateLiteral.quasis[i]?.value.raw ?? "";
2910
2911
  if (templateLiteral.expressions[i]) {
2911
- out += "${key}";
2912
+ out += `\${${parameterName}}`;
2912
2913
  hasExpression = true;
2913
2914
  }
2914
2915
  }
2915
- return { formatted: out, templateVariables: hasExpression ? ["key"] : [] };
2916
+ return { formatted: out, templateVariables: hasExpression ? [parameterName] : [] };
2916
2917
  }
2917
2918
  function applyResolvedDataTestId(args) {
2918
2919
  const addHtmlAttribute = args.addHtmlAttribute ?? true;
@@ -3037,7 +3038,8 @@ Fix: either (1) include ${bestKeyPreservePlaceholder} in your :${attrLabel} temp
3037
3038
  };
3038
3039
  const normalizedRole = normalizeNativeRole(args.nativeRole) ?? "button";
3039
3040
  const targetPageObjectModelClass = entryOverrides.targetPageObjectModelClass;
3040
- const pomKeyPattern = dataTestId.kind === "template" ? toPomKeyPattern(dataTestId) : null;
3041
+ const selectorParameterName = args.selectorParameterName?.trim() || "key";
3042
+ const pomKeyPattern = dataTestId.kind === "template" ? toPomKeyPattern(dataTestId, selectorParameterName) : null;
3041
3043
  const formattedDataTestIdForPom = dataTestId.kind === "template" ? pomKeyPattern.formatted : dataTestId.value;
3042
3044
  const selectorPatternKind = dataTestId.kind === "template" ? "parameterized" : "static";
3043
3045
  const selectorTemplateVariables = dataTestId.kind === "template" ? pomKeyPattern.templateVariables : [];
@@ -3183,8 +3185,11 @@ Fix: either (1) include ${bestKeyPreservePlaceholder} in your :${attrLabel} temp
3183
3185
  existingPom.alternateSelectors.push(selectorPattern);
3184
3186
  }
3185
3187
  }
3186
- if (selectorIsParameterized && !existingPom.parameters.some((param) => param.name === "key")) {
3187
- existingPom.parameters = [createPomParameterSpec("key", keyTypeFromValues), ...existingPom.parameters];
3188
+ if (selectorIsParameterized && !existingPom.parameters.some((param) => param.name === selectorParameterName)) {
3189
+ existingPom.parameters = [
3190
+ createPomParameterSpec(selectorParameterName, keyTypeFromValues),
3191
+ ...existingPom.parameters
3192
+ ];
3188
3193
  }
3189
3194
  return true;
3190
3195
  };
@@ -3198,7 +3203,8 @@ Fix: either (1) include ${bestKeyPreservePlaceholder} in your :${attrLabel} temp
3198
3203
  let suffix = 1;
3199
3204
  while (true) {
3200
3205
  const baseWithSuffix = suffix === 1 ? base : `${base}${suffix}`;
3201
- const candidate = selectorIsParameterized ? `${baseWithSuffix}ByKey` : baseWithSuffix;
3206
+ const parameterizedSuffix = `By${upperFirst(selectorParameterName)}`;
3207
+ const candidate = selectorIsParameterized ? normalizedRole === "radio" && selectorParameterName !== "key" ? parameterizedSuffix : `${baseWithSuffix}${parameterizedSuffix}` : baseWithSuffix;
3202
3208
  const actionName = getPrimaryActionMethodName(candidate);
3203
3209
  const getterCandidates = getPrimaryGetterNameCandidates(candidate);
3204
3210
  let chosenGetterName = getterCandidates.primary;
@@ -3224,7 +3230,7 @@ Fix: either (1) include ${bestKeyPreservePlaceholder} in your :${attrLabel} temp
3224
3230
  const baseNameUpper = upperFirst(baseWithSuffix);
3225
3231
  if (!hasRoleSuffix(baseNameUpper, roleSuffix)) {
3226
3232
  const baseWithRoleSuffix = `${baseWithSuffix}${roleSuffix}`;
3227
- const candidateWithRoleSuffix = selectorIsParameterized ? `${baseWithRoleSuffix}ByKey` : baseWithRoleSuffix;
3233
+ const candidateWithRoleSuffix = selectorIsParameterized ? `${baseWithRoleSuffix}By${upperFirst(selectorParameterName)}` : baseWithRoleSuffix;
3228
3234
  const actionNameWithRoleSuffix = getPrimaryActionMethodName(candidateWithRoleSuffix);
3229
3235
  const getterCandidatesWithRoleSuffix = getPrimaryGetterNameCandidates(candidateWithRoleSuffix);
3230
3236
  let chosenGetterNameWithRoleSuffix = getterCandidatesWithRoleSuffix.primary;
@@ -3292,7 +3298,7 @@ Conflicts: getter=${last.getterName}, method=${last.actionName}
3292
3298
  Fix: make the element identifiable (e.g. add id/name/inner text or use a more specific click handler name), or switch generation.nameCollisionBehavior to "warn"/"suffix".`
3293
3299
  );
3294
3300
  }
3295
- let parameters = selectorIsParameterized ? [createPomParameterSpec("key", keyTypeFromValues)] : [];
3301
+ let parameters = selectorIsParameterized ? [createPomParameterSpec(selectorParameterName, keyTypeFromValues)] : [];
3296
3302
  switch (normalizedRole) {
3297
3303
  case "input":
3298
3304
  parameters = setPomParameter(parameters, "text", "string");
@@ -3311,7 +3317,7 @@ Fix: make the element identifiable (e.g. add id/name/inner text or use a more sp
3311
3317
  parameters = setPomParameter(parameters, "annotationText", 'string = ""');
3312
3318
  break;
3313
3319
  }
3314
- const normalizedParameters = selectorIsParameterized ? setPomParameter(parameters, "key", keyTypeFromValues) : removePomParameter(parameters, "key");
3320
+ const normalizedParameters = selectorIsParameterized ? setPomParameter(parameters, selectorParameterName, keyTypeFromValues) : removePomParameter(parameters, selectorParameterName);
3315
3321
  if (addHtmlAttribute && !fromExisting) {
3316
3322
  upsertAttribute(args.element, testIdAttribute, dataTestId);
3317
3323
  }
@@ -5520,11 +5526,11 @@ function generateMethodMembersFromPom(componentName, primary, targetPageObjectMo
5520
5526
  primary.parameters
5521
5527
  );
5522
5528
  }
5523
- function generateMethodsContentForDependencies(componentName, dependencies) {
5529
+ function getUniquePrimaryPomSpecs(dependencies) {
5524
5530
  const entries = Array.from(dependencies.dataTestIdSet ?? []);
5525
5531
  const primarySpecsAll = entries.map((e) => ({ pom: e.pom, target: e.targetPageObjectModelClass })).filter((x) => !!x.pom).sort((a, b) => a.pom.methodName.localeCompare(b.pom.methodName));
5526
5532
  const seenPrimaryKeys = /* @__PURE__ */ new Set();
5527
- const primarySpecs = primarySpecsAll.filter(({ pom, target }) => {
5533
+ return primarySpecsAll.filter(({ pom, target }) => {
5528
5534
  const alternates = (pom.alternateSelectors ?? []).slice().sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
5529
5535
  const key = JSON.stringify({
5530
5536
  role: pom.nativeRole,
@@ -5542,6 +5548,9 @@ function generateMethodsContentForDependencies(componentName, dependencies) {
5542
5548
  seenPrimaryKeys.add(key);
5543
5549
  return true;
5544
5550
  });
5551
+ }
5552
+ function generateMethodsContentForDependencies(componentName, dependencies) {
5553
+ const primarySpecs = getUniquePrimaryPomSpecs(dependencies);
5545
5554
  const extras = (dependencies.pomExtraMethods ?? []).slice().sort((a, b) => a.name.localeCompare(b.name));
5546
5555
  const members = [];
5547
5556
  for (const { pom, target } of primarySpecs) {
@@ -5556,6 +5565,7 @@ async function generateFiles(componentHierarchyMap, vueFilesPathMap, basePageCla
5556
5565
  const {
5557
5566
  outDir: outDirOverride,
5558
5567
  generateFixtures,
5568
+ vueTestUtilsOutDir,
5559
5569
  customPomAttachments = [],
5560
5570
  projectRoot,
5561
5571
  customPomDir,
@@ -5577,6 +5587,9 @@ async function generateFiles(componentHierarchyMap, vueFilesPathMap, basePageCla
5577
5587
  } = options;
5578
5588
  const emitLanguages = emitLanguagesOverride?.length ? emitLanguagesOverride : ["ts"];
5579
5589
  const outDir = outDirOverride ?? "./pom";
5590
+ if (vueTestUtilsOutDir && path.resolve(vueTestUtilsOutDir) === path.resolve(outDir)) {
5591
+ throw new Error("[vue-pom-generator] generation.vueTestUtils.outDir must differ from generation.outDir.");
5592
+ }
5580
5593
  const routeMetaByComponent = routeMetaByComponentOverride ?? (vueRouterFluentChaining ? await getRouteMetaByComponent(projectRoot, routerEntry, routerType, {
5581
5594
  pageDirs,
5582
5595
  componentDirs,
@@ -5635,11 +5648,247 @@ async function generateFiles(componentHierarchyMap, vueFilesPathMap, basePageCla
5635
5648
  writeGeneratedFile(file);
5636
5649
  }
5637
5650
  }
5651
+ if (vueTestUtilsOutDir) {
5652
+ const vueTestUtilsFiles = generateVueTestUtilsFiles(
5653
+ emittableComponentHierarchyMap,
5654
+ vueTestUtilsOutDir,
5655
+ { testIdAttribute }
5656
+ );
5657
+ for (const file of vueTestUtilsFiles) {
5658
+ writeGeneratedFile(file);
5659
+ }
5660
+ }
5638
5661
  const gitattributesFiles = buildGeneratedGitAttributesFiles(generatedFilePaths);
5639
5662
  for (const file of gitattributesFiles) {
5640
5663
  createFile(file.filePath, file.content);
5641
5664
  }
5642
5665
  }
5666
+ const VUE_TEST_UTILS_OMITTED_PARAMETERS = /* @__PURE__ */ new Set(["annotationText", "timeOut", "timeout", "wait"]);
5667
+ function getVueTestUtilsParameters(parameters, patterns, options = {}) {
5668
+ return orderPomPatternParameters(parameters, patterns, options).filter((parameter) => !VUE_TEST_UTILS_OMITTED_PARAMETERS.has(parameter.name));
5669
+ }
5670
+ function getVueTestUtilsPrimaryMembers(primary) {
5671
+ if (primary.emitPrimary === false) {
5672
+ return [];
5673
+ }
5674
+ const selectors = uniquePomStringPatterns(primary.selector, primary.alternateSelectors);
5675
+ const parameters = getVueTestUtilsParameters(primary.parameters, selectors);
5676
+ const actionName = buildPomGeneratedActionName(primary);
5677
+ const selectorExpressions = selectors.map((selector) => toTypeScriptPomPatternExpression(selector));
5678
+ const targetExpression = selectorExpressions.length === 1 ? `this.getByTestId(${selectorExpressions[0]})` : `this.getByAnyTestId([${selectorExpressions.join(", ")}])`;
5679
+ let actionStatement;
5680
+ switch (primary.nativeRole) {
5681
+ case "input":
5682
+ actionStatement = `await ${targetExpression}.setValue(text);`;
5683
+ break;
5684
+ case "select":
5685
+ actionStatement = `await ${targetExpression}.setValue(value);`;
5686
+ break;
5687
+ case "vselect":
5688
+ actionStatement = selectors.length === 1 ? `await this.selectVSelectByTestId(${selectorExpressions[0]}, value);` : `await this.selectVSelectByAnyTestId([${selectorExpressions.join(", ")}], value);`;
5689
+ break;
5690
+ case "radio":
5691
+ actionStatement = `await ${targetExpression}.setValue();`;
5692
+ break;
5693
+ default:
5694
+ actionStatement = `await ${targetExpression}.trigger("click");`;
5695
+ break;
5696
+ }
5697
+ return [createClassMethod({
5698
+ name: actionName,
5699
+ isAsync: true,
5700
+ parameters: toTypeScriptPomParameterStructures(parameters),
5701
+ statements: [actionStatement]
5702
+ })];
5703
+ }
5704
+ function getVueTestUtilsExtraMembers(extra) {
5705
+ if (extra.kind !== "click") {
5706
+ return [];
5707
+ }
5708
+ const patterns = extra.selector.kind === "testId" ? [extra.selector.testId] : [extra.selector.rootTestId, extra.selector.label];
5709
+ const parameters = getVueTestUtilsParameters(extra.parameters, patterns, {
5710
+ omit: extra.keyLiteral === void 0 ? [] : ["key"]
5711
+ });
5712
+ return [createClassMethod({
5713
+ name: extra.name,
5714
+ isAsync: true,
5715
+ parameters: toTypeScriptPomParameterStructures(parameters),
5716
+ statements: (writer) => {
5717
+ if (extra.keyLiteral !== void 0) {
5718
+ writer.writeLine(`const key = ${JSON.stringify(extra.keyLiteral)};`);
5719
+ }
5720
+ if (extra.selector.kind === "testId") {
5721
+ writer.writeLine(`await this.clickByTestId(${toTypeScriptPomPatternExpression(extra.selector.testId)});`);
5722
+ return;
5723
+ }
5724
+ writer.writeLine(
5725
+ `await this.clickWithinTestIdByLabel(${toTypeScriptPomPatternExpression(extra.selector.rootTestId)}, ${toTypeScriptPomPatternExpression(extra.selector.label)}, ${extra.selector.exact ?? false});`
5726
+ );
5727
+ }
5728
+ })];
5729
+ }
5730
+ function getVueTestUtilsComponentMembers(componentInstances, projectedComponentInstances, testIdAttribute) {
5731
+ const members = [];
5732
+ for (const instance of componentInstances) {
5733
+ if (instance.parameters.length === 0) {
5734
+ members.push(createClassGetter({
5735
+ name: instance.instanceName,
5736
+ returnType: instance.className,
5737
+ statements: [
5738
+ `return new ${instance.className}(this.getComponentInstance(${toTypeScriptPomPatternExpression(instance.selector)}));`
5739
+ ]
5740
+ }));
5741
+ continue;
5742
+ }
5743
+ members.push(createClassMethod({
5744
+ name: instance.instanceName,
5745
+ parameters: toTypeScriptPomParameterStructures(instance.parameters),
5746
+ returnType: instance.className,
5747
+ statements: [
5748
+ `return new ${instance.className}(this.getComponentInstance(${toTypeScriptPomPatternExpression(instance.selector)}));`
5749
+ ]
5750
+ }));
5751
+ }
5752
+ for (const projection of projectedComponentInstances) {
5753
+ const projectedPropertiesType = projection.contents.length > 0 ? ` & { ${projection.contents.map((content) => `readonly ${content.instanceName}: ${content.className}`).join("; ")} }` : "";
5754
+ const statements = (writer) => {
5755
+ writer.writeLine(`const ownerRoot = this.getComponentInstance(${toTypeScriptPomPatternExpression(projection.owner.selector)});`);
5756
+ writer.writeLine(`const root = this.getComponentInstance(${toTypeScriptPomPatternExpression(projection.target.selector)}, ownerRoot);`);
5757
+ writer.writeLine(`const instance = new ${projection.target.className}(root);`);
5758
+ if (projection.contents.length === 0) {
5759
+ writer.writeLine("return instance;");
5760
+ return;
5761
+ }
5762
+ writer.writeLine("return Object.assign(instance, {");
5763
+ writer.indent(() => {
5764
+ for (const content of projection.contents) {
5765
+ writer.writeLine(
5766
+ `${content.instanceName}: new ${content.className}(this.getComponentInstance(${toTypeScriptPomPatternExpression(content.selector)}, root)),`
5767
+ );
5768
+ }
5769
+ });
5770
+ writer.writeLine("});");
5771
+ };
5772
+ const returnType = `${projection.target.className}${projectedPropertiesType}`;
5773
+ members.push(projection.target.parameters.length > 0 ? createClassMethod({
5774
+ name: projection.target.instanceName,
5775
+ parameters: toTypeScriptPomParameterStructures(projection.target.parameters),
5776
+ returnType,
5777
+ statements
5778
+ }) : createClassGetter({
5779
+ name: projection.target.instanceName,
5780
+ returnType,
5781
+ statements
5782
+ }));
5783
+ }
5784
+ members.push(createClassConstructor({
5785
+ parameters: [{ name: "wrapper", type: "VueTestUtilsPomRoot" }],
5786
+ statements: (writer) => {
5787
+ writer.writeLine(`super(wrapper, { testIdAttribute: ${JSON.stringify(testIdAttribute)} });`);
5788
+ }
5789
+ }));
5790
+ return members;
5791
+ }
5792
+ function generateVueTestUtilsContent(componentName, dependencies, componentHierarchyMap, outputDir, runtimePath, generatedFilePathByComponent, testIdAttribute) {
5793
+ const prepared = prepareViewObjectModelClass(componentName, dependencies, componentHierarchyMap, {
5794
+ testIdAttribute
5795
+ });
5796
+ const runtimeImport = stripExtension(toPosixRelativePath(outputDir, runtimePath));
5797
+ const sourceRel = toPosixRelativePath(outputDir, dependencies.filePath);
5798
+ const componentImports = Array.from(prepared.componentRefsForInstances).map((componentRef) => {
5799
+ const className = componentRef.endsWith(".vue") ? componentRef.slice(0, -4) : componentRef;
5800
+ const filePath = generatedFilePathByComponent.get(className);
5801
+ return filePath ? { className, moduleSpecifier: stripExtension(toPosixRelativePath(outputDir, filePath)) } : null;
5802
+ }).filter((value) => !!value).sort((left, right) => left.className.localeCompare(right.className));
5803
+ const members = [
5804
+ ...getVueTestUtilsComponentMembers(
5805
+ prepared.directComponentInstances,
5806
+ prepared.projectedComponentInstances,
5807
+ testIdAttribute
5808
+ ),
5809
+ ...getUniquePrimaryPomSpecs(dependencies).flatMap(({ pom }) => getVueTestUtilsPrimaryMembers(pom)),
5810
+ ...(dependencies.pomExtraMethods ?? []).flatMap(getVueTestUtilsExtraMembers)
5811
+ ];
5812
+ return renderSourceFile(`${componentName}.vtu.g.ts`, (sourceFile) => {
5813
+ addNamedImport(sourceFile, {
5814
+ moduleSpecifier: runtimeImport,
5815
+ namedImports: ["VueTestUtilsPom"]
5816
+ });
5817
+ addNamedImport(sourceFile, {
5818
+ moduleSpecifier: runtimeImport,
5819
+ namedImports: ["VueTestUtilsPomRoot"],
5820
+ isTypeOnly: true
5821
+ });
5822
+ for (const componentImport of componentImports) {
5823
+ addNamedImport(sourceFile, {
5824
+ moduleSpecifier: componentImport.moduleSpecifier,
5825
+ namedImports: [componentImport.className]
5826
+ });
5827
+ }
5828
+ const declaration = sourceFile.addClass({
5829
+ name: prepared.className,
5830
+ isExported: true,
5831
+ extends: "VueTestUtilsPom",
5832
+ docs: [`Vue Test Utils object for ${componentName} (source: ${sourceRel}).`]
5833
+ });
5834
+ for (const member of members) {
5835
+ addClassMember(declaration, member);
5836
+ }
5837
+ }, {
5838
+ prefixText: buildFilePrefix({ eslintDisableSortImports: true })
5839
+ });
5840
+ }
5841
+ function generateVueTestUtilsFiles(componentHierarchyMap, outDir, options = {}) {
5842
+ const base = ensureDir(outDir);
5843
+ const testIdAttribute = options.testIdAttribute?.trim() || "data-testid";
5844
+ const entries = Array.from(componentHierarchyMap.entries()).sort((left, right) => left[0].localeCompare(right[0]));
5845
+ const generatedFilePathByComponent = new Map(
5846
+ entries.map(([componentName]) => [componentName, path.join(base, `${componentName}.vtu.g.ts`)])
5847
+ );
5848
+ const runtimePath = path.join(base, "_pom-runtime", "vue-test-utils-pom.ts");
5849
+ const files = entries.map(([componentName, dependencies]) => {
5850
+ const filePath = generatedFilePathByComponent.get(componentName);
5851
+ return {
5852
+ filePath,
5853
+ content: generateVueTestUtilsContent(
5854
+ componentName,
5855
+ dependencies,
5856
+ componentHierarchyMap,
5857
+ path.dirname(filePath),
5858
+ runtimePath,
5859
+ generatedFilePathByComponent,
5860
+ testIdAttribute
5861
+ )
5862
+ };
5863
+ });
5864
+ const [runtimeFile] = buildRuntimeGeneratedFilesFromSpecs([{
5865
+ absolutePath: resolvePluginAsset("../class-generation/vue-test-utils-pom.ts"),
5866
+ description: "vue-test-utils-pom.ts",
5867
+ outputPath: runtimePath
5868
+ }]);
5869
+ if (!runtimeFile) {
5870
+ throw new Error("[vue-pom-generator] Failed to generate the Vue Test Utils runtime.");
5871
+ }
5872
+ const indexContent = renderSourceFile("index.ts", (sourceFile) => {
5873
+ addExportAll(sourceFile, stripExtension(toPosixRelativePath(base, runtimePath)));
5874
+ for (const [, filePath] of generatedFilePathByComponent) {
5875
+ addExportAll(sourceFile, `./${stripExtension(path.basename(filePath))}`);
5876
+ }
5877
+ }, {
5878
+ prefixText: buildFilePrefix({
5879
+ eslintDisableSortImports: true,
5880
+ commentLines: [
5881
+ "Vue Test Utils POM exports",
5882
+ "DO NOT MODIFY BY HAND"
5883
+ ]
5884
+ })
5885
+ });
5886
+ return [
5887
+ ...files,
5888
+ { filePath: path.join(base, "index.ts"), content: indexContent },
5889
+ runtimeFile
5890
+ ];
5891
+ }
5643
5892
  async function generateSplitTypeScriptFiles(componentHierarchyMap, vueFilesPathMap, basePageClassPath, outDir, options = {}) {
5644
5893
  const projectRoot = options.projectRoot ?? process.cwd();
5645
5894
  const entries = Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0]));
@@ -6468,21 +6717,116 @@ function prepareViewObjectModelClass(componentName, dependencies, componentHiera
6468
6717
  const nestedRefs = resolvedDependencies.usedComponentSet?.size ? resolvedDependencies.usedComponentSet : resolvedDependencies.childrenComponentSet;
6469
6718
  return Array.from(nestedRefs).some((child) => hasGeneratedPomSurface(child, nextSeen));
6470
6719
  };
6471
- const rawComponentRefsForInstances = usedComponentSet?.size ? usedComponentSet : childrenComponentSet;
6472
6720
  const ownClassName = toPascalCaseLocal(componentName);
6473
6721
  const isSelfReference = (ref) => {
6474
6722
  return toPascalCaseLocal(normalizeTrackedComponentRef(ref)) === ownClassName && ownClassName.length > 0;
6475
6723
  };
6476
- const componentRefsForInstances = /* @__PURE__ */ new Set();
6477
- for (const ref of rawComponentRefsForInstances) {
6478
- const resolvedRef = resolveTrackedComponentRef(ref) ?? normalizeTrackedComponentRef(ref);
6479
- if (isSelfReference(resolvedRef)) {
6480
- continue;
6724
+ const resolveComponentInstance = (spec) => {
6725
+ const componentRef = resolveTrackedComponentRef(spec.componentName);
6726
+ if (!componentRef || isSelfReference(componentRef) || !hasGeneratedPomSurface(componentRef, /* @__PURE__ */ new Set([componentName]))) {
6727
+ return null;
6728
+ }
6729
+ return {
6730
+ ...spec,
6731
+ componentRef,
6732
+ className: normalizeTrackedComponentRef(componentRef)
6733
+ };
6734
+ };
6735
+ const uniqueInstances = (instances, ownerName) => {
6736
+ const byPublicName = /* @__PURE__ */ new Map();
6737
+ for (const instance of instances) {
6738
+ const existing = byPublicName.get(instance.instanceName);
6739
+ if (!existing) {
6740
+ byPublicName.set(instance.instanceName, instance);
6741
+ continue;
6742
+ }
6743
+ const sameInvocationShape = existing.componentRef === instance.componentRef && JSON.stringify(existing.selector) === JSON.stringify(instance.selector) && JSON.stringify(existing.parameters) === JSON.stringify(instance.parameters);
6744
+ if (sameInvocationShape) {
6745
+ continue;
6746
+ }
6747
+ throw new VuePomGeneratorError(
6748
+ `Semantic component instance name ${JSON.stringify(instance.instanceName)} is ambiguous in ${ownerName}.
6749
+ It refers to both <${existing.componentName}> and <${instance.componentName}>.
6750
+
6751
+ Fix: give the invocations distinct accessible names or distinct semantic model/options bindings.`
6752
+ );
6481
6753
  }
6482
- if (!hasGeneratedPomSurface(resolvedRef, /* @__PURE__ */ new Set([componentName]))) {
6754
+ return Array.from(byPublicName.values());
6755
+ };
6756
+ const allInvocationSpecs = dependencies.componentInstances ?? [];
6757
+ const directComponentInstances = uniqueInstances(
6758
+ allInvocationSpecs.filter((spec) => !spec.suppliedSlot).map(resolveComponentInstance).filter((instance) => !!instance),
6759
+ componentName
6760
+ );
6761
+ const projectedComponentInstances = [];
6762
+ for (const owner of directComponentInstances) {
6763
+ const ownerDependencies = componentHierarchyMap.get(owner.componentRef);
6764
+ if (!ownerDependencies?.slotOutlets?.length) {
6483
6765
  continue;
6484
6766
  }
6485
- componentRefsForInstances.add(resolvedRef);
6767
+ const suppliedBySlot = /* @__PURE__ */ new Map();
6768
+ for (const suppliedSpec of allInvocationSpecs) {
6769
+ if (suppliedSpec.suppliedSlot?.ownerSourceId !== owner.sourceId) {
6770
+ continue;
6771
+ }
6772
+ const supplied = resolveComponentInstance(suppliedSpec);
6773
+ if (!supplied) {
6774
+ continue;
6775
+ }
6776
+ const values = suppliedBySlot.get(suppliedSpec.suppliedSlot.name) ?? [];
6777
+ values.push(supplied);
6778
+ suppliedBySlot.set(suppliedSpec.suppliedSlot.name, values);
6779
+ }
6780
+ for (const [slotName, rawContents] of suppliedBySlot) {
6781
+ const outletTargetIds = new Set(
6782
+ ownerDependencies.slotOutlets.filter((outlet) => outlet.name === slotName).map((outlet) => outlet.targetSourceId)
6783
+ );
6784
+ const targetInstances = uniqueInstances(
6785
+ (ownerDependencies.componentInstances ?? []).filter((spec) => outletTargetIds.has(spec.sourceId)).map(resolveComponentInstance).filter((instance) => !!instance),
6786
+ `${owner.className} slot ${JSON.stringify(slotName)}`
6787
+ );
6788
+ const contents = uniqueInstances(rawContents, `${componentName} slot ${JSON.stringify(slotName)}`);
6789
+ for (const target of targetInstances) {
6790
+ if (owner.parameters.length > 0) {
6791
+ throw new VuePomGeneratorError(
6792
+ `Cannot project slot ${JSON.stringify(slotName)} through keyed component instance ${owner.instanceName} in ${componentName}.
6793
+ The owner and projected target require distinct key scopes, which cannot be represented by one unambiguous generated accessor.`
6794
+ );
6795
+ }
6796
+ const keyedContent = contents.find((content) => content.parameters.length > 0);
6797
+ if (keyedContent) {
6798
+ throw new VuePomGeneratorError(
6799
+ `Cannot attach keyed slot content ${keyedContent.instanceName} as a property of ${target.instanceName} in ${componentName}.
6800
+ Move the repetition to the receiving component boundary so the generator can expose it as a keyed accessor.`
6801
+ );
6802
+ }
6803
+ const existingProjection = projectedComponentInstances.find((projection) => {
6804
+ return projection.owner.sourceId === owner.sourceId && projection.target.instanceName === target.instanceName && projection.target.componentRef === target.componentRef && JSON.stringify(projection.target.selector) === JSON.stringify(target.selector);
6805
+ });
6806
+ if (existingProjection) {
6807
+ existingProjection.contents = uniqueInstances(
6808
+ [...existingProjection.contents, ...contents],
6809
+ `${componentName} projected ${target.instanceName}`
6810
+ );
6811
+ continue;
6812
+ }
6813
+ projectedComponentInstances.push({ owner, target, contents });
6814
+ }
6815
+ }
6816
+ }
6817
+ const rawComponentRefsForInstances = usedComponentSet?.size ? usedComponentSet : childrenComponentSet;
6818
+ const componentRefsForInstances = /* @__PURE__ */ new Set();
6819
+ for (const instance of directComponentInstances) {
6820
+ if (!isSelfReference(instance.componentRef)) {
6821
+ componentRefsForInstances.add(instance.componentRef);
6822
+ }
6823
+ }
6824
+ for (const projection of projectedComponentInstances) {
6825
+ for (const instance of [projection.owner, projection.target, ...projection.contents]) {
6826
+ if (!isSelfReference(instance.componentRef)) {
6827
+ componentRefsForInstances.add(instance.componentRef);
6828
+ }
6829
+ }
6486
6830
  }
6487
6831
  const hasChildComponent = (needle) => {
6488
6832
  const normalizedNeedle = normalizeTrackedComponentRef(needle);
@@ -6523,7 +6867,19 @@ function prepareViewObjectModelClass(componentName, dependencies, componentHiera
6523
6867
  }));
6524
6868
  const widgetInstances = isView ? getWidgetInstancesForView(componentName, dependencies.dataTestIdSet, customPomAvailableClassIdentifiers) : [];
6525
6869
  const className = toPascalCaseLocal(componentName);
6526
- const childInstancePropertyNames = Array.from(componentRefsForInstances).map((child) => child.split(".vue")[0]);
6870
+ const childInstancePropertyNames = [
6871
+ ...directComponentInstances.map((instance) => instance.instanceName),
6872
+ ...projectedComponentInstances.map((projection) => projection.target.instanceName)
6873
+ ];
6874
+ const duplicateChildInstanceName = childInstancePropertyNames.find((name, index) => {
6875
+ return childInstancePropertyNames.indexOf(name) !== index;
6876
+ });
6877
+ if (duplicateChildInstanceName) {
6878
+ throw new VuePomGeneratorError(
6879
+ `Semantic component instance ${JSON.stringify(duplicateChildInstanceName)} would be emitted more than once in ${componentName}.
6880
+ Fix: give direct and slot-projected instances distinct accessible names or semantic bindings.`
6881
+ );
6882
+ }
6527
6883
  const blockedViewPassthroughMethodNames = new Set(
6528
6884
  attachmentsForThisClass.filter((a) => a.flatten).flatMap((a) => Array.from(a.methodSignatures.keys()))
6529
6885
  );
@@ -6534,22 +6890,22 @@ function prepareViewObjectModelClass(componentName, dependencies, componentHiera
6534
6890
  ]);
6535
6891
  const members = [];
6536
6892
  if (isView && (componentRefsForInstances.size > 0 || attachmentsForThisClass.length > 0 || widgetInstances.length > 0)) {
6537
- members.push(...getComponentInstances(componentRefsForInstances, componentHierarchyMap, attachmentsForThisClass, widgetInstances));
6538
- members.push(getConstructor(componentRefsForInstances, componentHierarchyMap, attachmentsForThisClass, widgetInstances, { testIdAttribute }));
6893
+ members.push(...getComponentInstances(directComponentInstances, projectedComponentInstances, attachmentsForThisClass, widgetInstances));
6894
+ members.push(getConstructor(directComponentInstances, attachmentsForThisClass, widgetInstances, { testIdAttribute }));
6539
6895
  }
6540
6896
  if (!isView && (componentRefsForInstances.size > 0 || attachmentsForThisClass.length > 0)) {
6541
- members.push(...getComponentInstances(componentRefsForInstances, componentHierarchyMap, attachmentsForThisClass));
6542
- members.push(getConstructor(componentRefsForInstances, componentHierarchyMap, attachmentsForThisClass, [], { testIdAttribute }));
6897
+ members.push(...getComponentInstances(directComponentInstances, projectedComponentInstances, attachmentsForThisClass));
6898
+ members.push(getConstructor(directComponentInstances, attachmentsForThisClass, [], { testIdAttribute }));
6543
6899
  }
6544
6900
  members.push(
6545
6901
  ...getAttachmentPassthroughMethods(componentName, dependencies, attachmentsForThisClass, reservedAttachmentPassthroughNames)
6546
6902
  );
6547
- if (isView && componentRefsForInstances.size === 1) {
6903
+ if (isView && directComponentInstances.length === 1) {
6548
6904
  members.push(
6549
6905
  ...getViewPassthroughMethods(
6550
6906
  componentName,
6551
6907
  dependencies,
6552
- componentRefsForInstances,
6908
+ directComponentInstances,
6553
6909
  componentHierarchyMap,
6554
6910
  blockedViewPassthroughMethodNames
6555
6911
  )
@@ -6564,6 +6920,8 @@ function prepareViewObjectModelClass(componentName, dependencies, componentHiera
6564
6920
  return {
6565
6921
  className,
6566
6922
  componentRefsForInstances,
6923
+ directComponentInstances,
6924
+ projectedComponentInstances,
6567
6925
  attachmentsForThisClass,
6568
6926
  widgetInstances,
6569
6927
  isView,
@@ -6639,7 +6997,10 @@ function generateViewObjectModelContent(componentName, dependencies, componentHi
6639
6997
  addNamedImport(sourceFile, {
6640
6998
  moduleSpecifier: "@playwright/test",
6641
6999
  isTypeOnly: true,
6642
- namedImports: [{ name: "Page", alias: "PwPage" }]
7000
+ namedImports: [
7001
+ { name: "Locator", alias: "PwLocator" },
7002
+ { name: "Page", alias: "PwPage" }
7003
+ ]
6643
7004
  });
6644
7005
  }
6645
7006
  addNamedImport(sourceFile, {
@@ -6668,17 +7029,17 @@ function generateViewObjectModelContent(componentName, dependencies, componentHi
6668
7029
  }
6669
7030
  }, { prefixText });
6670
7031
  }
6671
- function getViewPassthroughMethods(viewName, viewDependencies, childrenComponentSet, componentHierarchyMap, blockedMethodNames = /* @__PURE__ */ new Set()) {
7032
+ function getViewPassthroughMethods(viewName, viewDependencies, componentInstances, componentHierarchyMap, blockedMethodNames = /* @__PURE__ */ new Set()) {
6672
7033
  const existingOnView = viewDependencies.generatedMethods ?? /* @__PURE__ */ new Map();
6673
7034
  const methodToChildren = /* @__PURE__ */ new Map();
6674
- for (const child of childrenComponentSet) {
6675
- const childDeps = componentHierarchyMap.get(child);
7035
+ for (const instance of componentInstances) {
7036
+ const childDeps = componentHierarchyMap.get(instance.componentRef);
6676
7037
  if (!childDeps || !childDeps.dataTestIdSet?.size)
6677
7038
  continue;
6678
7039
  const methods = childDeps.generatedMethods;
6679
7040
  if (!methods)
6680
7041
  continue;
6681
- const childProp = child.endsWith(".vue") ? child.slice(0, -4) : child;
7042
+ const childProp = instance.instanceName;
6682
7043
  for (const [name, sig] of methods.entries()) {
6683
7044
  if (!sig)
6684
7045
  continue;
@@ -6964,7 +7325,7 @@ function getRuntimeGeneratedAssetSpecs(baseDir, basePageClassPath) {
6964
7325
  const runtimeDirAbs = path.join(baseDir, "_pom-runtime");
6965
7326
  const runtimeClassGenAbs = path.join(runtimeDirAbs, "class-generation");
6966
7327
  const runtimeClassGenSourceDir = resolvePluginAsset("../class-generation");
6967
- 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));
7328
+ const runtimeClassGenFiles = fs.readdirSync(runtimeClassGenSourceDir).filter((file) => file.endsWith(".ts")).filter((file) => !["base-page.ts", "diagnostics.ts", "index.ts", "vue-test-utils-pom.ts"].includes(file)).sort((left, right) => left.localeCompare(right));
6968
7329
  return [
6969
7330
  {
6970
7331
  absolutePath: resolvePluginAsset("../click-instrumentation.ts"),
@@ -7368,7 +7729,7 @@ function getWidgetInstancesForView(componentName, dataTestIdSet, availableClassI
7368
7729
  }
7369
7730
  return out;
7370
7731
  }
7371
- function getComponentInstances(childrenComponent, componentHierarchyMap, attachmentsForThisView = [], widgetInstances = []) {
7732
+ function getComponentInstances(componentInstances, projectedComponentInstances, attachmentsForThisView = [], widgetInstances = []) {
7372
7733
  const declarations = [];
7373
7734
  for (const a of attachmentsForThisView) {
7374
7735
  declarations.push(createClassProperty({
@@ -7382,35 +7743,80 @@ function getComponentInstances(childrenComponent, componentHierarchyMap, attachm
7382
7743
  type: w.className
7383
7744
  }));
7384
7745
  }
7385
- childrenComponent.forEach((child) => {
7386
- if (componentHierarchyMap.has(child)) {
7387
- const childName = child.split(".vue")[0];
7746
+ for (const instance of componentInstances) {
7747
+ if (instance.parameters.length === 0) {
7388
7748
  declarations.push(createClassProperty({
7389
- name: childName,
7390
- type: childName
7749
+ name: instance.instanceName,
7750
+ type: instance.className
7391
7751
  }));
7752
+ continue;
7392
7753
  }
7393
- });
7754
+ declarations.push(createClassMethod({
7755
+ name: instance.instanceName,
7756
+ parameters: toTypeScriptPomParameterStructures(instance.parameters),
7757
+ returnType: instance.className,
7758
+ statements: (writer) => {
7759
+ writer.writeLine(`const root = this.componentInstanceLocator(${toTypeScriptPomPatternExpression(instance.selector)});`);
7760
+ writer.writeLine(`return new ${instance.className}(this.page, root);`);
7761
+ }
7762
+ }));
7763
+ }
7764
+ for (const projection of projectedComponentInstances) {
7765
+ const projectedPropertiesType = projection.contents.length > 0 ? ` & { ${projection.contents.map((content) => `readonly ${content.instanceName}: ${content.className}`).join("; ")} }` : "";
7766
+ const statements = (writer) => {
7767
+ const ownerSelector = toTypeScriptPomPatternExpression(projection.owner.selector);
7768
+ const targetSelector = toTypeScriptPomPatternExpression(projection.target.selector);
7769
+ writer.writeLine(`const ownerRoot = this.componentInstanceLocator(${ownerSelector});`);
7770
+ writer.writeLine(`const root = this.componentInstanceLocator(${targetSelector}, ownerRoot);`);
7771
+ writer.writeLine(`const instance = new ${projection.target.className}(this.page, root);`);
7772
+ if (projection.contents.length === 0) {
7773
+ writer.writeLine("return instance;");
7774
+ return;
7775
+ }
7776
+ writer.writeLine("return Object.assign(instance, {");
7777
+ writer.indent(() => {
7778
+ for (const content of projection.contents) {
7779
+ const contentSelector = toTypeScriptPomPatternExpression(content.selector);
7780
+ writer.writeLine(`${content.instanceName}: new ${content.className}(this.page, this.componentInstanceLocator(${contentSelector}, root)),`);
7781
+ }
7782
+ });
7783
+ writer.writeLine("});");
7784
+ };
7785
+ const returnType = `${projection.target.className}${projectedPropertiesType}`;
7786
+ declarations.push(projection.target.parameters.length > 0 ? createClassMethod({
7787
+ name: projection.target.instanceName,
7788
+ parameters: toTypeScriptPomParameterStructures(projection.target.parameters),
7789
+ returnType,
7790
+ statements
7791
+ }) : createClassGetter({
7792
+ name: projection.target.instanceName,
7793
+ returnType,
7794
+ statements
7795
+ }));
7796
+ }
7394
7797
  return declarations;
7395
7798
  }
7396
- function getConstructor(childrenComponent, componentHierarchyMap, attachmentsForThisView = [], widgetInstances = [], options) {
7799
+ function getConstructor(componentInstances, attachmentsForThisView = [], widgetInstances = [], options) {
7397
7800
  const attr = (options?.testIdAttribute ?? "data-testid").trim() || "data-testid";
7398
7801
  return createClassConstructor({
7399
- parameters: [{ name: "page", type: "PwPage" }],
7802
+ parameters: [
7803
+ { name: "page", type: "PwPage" },
7804
+ { name: "root", type: "PwLocator", hasQuestionToken: true }
7805
+ ],
7400
7806
  statements: (writer) => {
7401
- writer.writeLine(`super(page, { testIdAttribute: ${JSON.stringify(attr)} });`);
7807
+ writer.writeLine(`super(page, { root, testIdAttribute: ${JSON.stringify(attr)} });`);
7402
7808
  for (const a of attachmentsForThisView) {
7403
7809
  writer.writeLine(`this.${a.propertyName} = new ${a.className}(this.page, this);`);
7404
7810
  }
7405
7811
  for (const w of widgetInstances) {
7406
7812
  writer.writeLine(`this.${w.propertyName} = new ${w.className}(this.page, ${JSON.stringify(w.testId)});`);
7407
7813
  }
7408
- childrenComponent.forEach((child) => {
7409
- if (componentHierarchyMap.has(child)) {
7410
- const childName = child.split(".vue")[0];
7411
- writer.writeLine(`this.${childName} = new ${childName}(page);`);
7814
+ for (const instance of componentInstances) {
7815
+ if (instance.parameters.length === 0) {
7816
+ const selector = toTypeScriptPomPatternExpression(instance.selector);
7817
+ writer.writeLine(`this.${instance.instanceName} = new ${instance.className}(page, this.componentInstanceLocator(${selector}));`);
7412
7818
  }
7413
- });
7819
+ }
7414
7820
  }
7415
7821
  });
7416
7822
  }
@@ -8186,6 +8592,92 @@ function resolveWrapperContractForTag(options) {
8186
8592
  return resolveTag(options.tag);
8187
8593
  }
8188
8594
  const CLICK_EVENT_NAME = TESTID_CLICK_EVENT_NAME;
8595
+ const POM_INSTANCE_ATTRIBUTE = "data-pom-instance";
8596
+ function getLastSemanticIdentifier(node) {
8597
+ if (!node) {
8598
+ return null;
8599
+ }
8600
+ if (node.type === "Identifier") {
8601
+ return node.name?.trim() || null;
8602
+ }
8603
+ if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
8604
+ if (!node.computed && node.property?.type === "Identifier") {
8605
+ return node.property.name?.trim() || null;
8606
+ }
8607
+ if (node.computed && node.property?.type === "StringLiteral") {
8608
+ return node.property.value?.trim() || null;
8609
+ }
8610
+ return getLastSemanticIdentifier(node.object);
8611
+ }
8612
+ if (node.type === "CallExpression" || node.type === "OptionalCallExpression") {
8613
+ return getLastSemanticIdentifier(node.callee);
8614
+ }
8615
+ if (node.type === "TSAsExpression" || node.type === "TSTypeAssertion" || node.type === "TSNonNullExpression" || node.type === "ChainExpression") {
8616
+ return getLastSemanticIdentifier(node.expression);
8617
+ }
8618
+ return null;
8619
+ }
8620
+ function getBoundSemanticName(element, attributeName) {
8621
+ const directive = element.props.find((prop) => {
8622
+ return prop.type === NodeTypes.DIRECTIVE && prop.name === "bind" && prop.arg?.type === NodeTypes.SIMPLE_EXPRESSION && prop.arg.content === attributeName && !!prop.exp;
8623
+ });
8624
+ if (!directive?.exp) {
8625
+ return null;
8626
+ }
8627
+ const source = getVueExpressionSource(
8628
+ directive.exp,
8629
+ "loc",
8630
+ "content",
8631
+ "compiled"
8632
+ );
8633
+ if (!source) {
8634
+ return null;
8635
+ }
8636
+ try {
8637
+ const identifier = getLastSemanticIdentifier(parseExpression(source, { plugins: ["typescript"] }));
8638
+ return identifier ? toPascalCase(identifier) : null;
8639
+ } catch {
8640
+ return null;
8641
+ }
8642
+ }
8643
+ function getComponentInstanceNameCandidates(element) {
8644
+ const explicitAccessibleNames = ["aria-label", "label", "title", "name"].map((attributeName) => getStaticAttributeContent(element, attributeName)).filter((value) => !!value).map(toPascalCase);
8645
+ const optionsName = getBoundSemanticName(element, "options");
8646
+ const { vModel, modelValue } = getModelBindingValues(element);
8647
+ const modelName = modelValue || vModel;
8648
+ const candidates = [
8649
+ ...explicitAccessibleNames,
8650
+ optionsName && optionsName !== "Options" ? optionsName : null,
8651
+ modelName && !(/* @__PURE__ */ new Set(["Data", "Item", "ModelValue", "Value"])).has(modelName) ? toPascalCase(modelName) : null,
8652
+ toPascalCase(element.tag)
8653
+ ].filter((value) => !!value);
8654
+ return Array.from(new Set(candidates));
8655
+ }
8656
+ function getElementSourceId(element) {
8657
+ return `${element.tag}:${element.loc.start.offset}:${element.loc.end.offset}`;
8658
+ }
8659
+ function getNearestComponentAncestor(element, hierarchyMap2, isComponentLikeTag2) {
8660
+ let parent = hierarchyMap2.get(element) ?? null;
8661
+ while (parent) {
8662
+ if (isComponentLikeTag2(parent.tag)) {
8663
+ return parent;
8664
+ }
8665
+ parent = hierarchyMap2.get(parent) ?? null;
8666
+ }
8667
+ return null;
8668
+ }
8669
+ function getSlotNameFromTemplate(element) {
8670
+ const directive = element.props.find((prop) => {
8671
+ return prop.type === NodeTypes.DIRECTIVE && prop.name === "slot";
8672
+ });
8673
+ if (!directive) {
8674
+ return null;
8675
+ }
8676
+ if (!directive.arg) {
8677
+ return "default";
8678
+ }
8679
+ return directive.arg.type === NodeTypes.SIMPLE_EXPRESSION ? directive.arg.content.trim() || "default" : null;
8680
+ }
8189
8681
  function getStaticAttributeContent(element, name) {
8190
8682
  const attr = element.props.find((prop) => {
8191
8683
  return prop.type === NodeTypes.ATTRIBUTE && prop.name === name;
@@ -8524,6 +9016,7 @@ function createTestIdTransform(componentName, componentHierarchyMap, nativeWrapp
8524
9016
  Object.entries(nativeWrappers).map(([tag, config]) => [tag, { ...config }])
8525
9017
  );
8526
9018
  const wrapperContractByTag = /* @__PURE__ */ new Map();
9019
+ const instanceWrapperContractByTag = /* @__PURE__ */ new Map();
8527
9020
  const getWrapperContract = (tag) => {
8528
9021
  if (!wrapperContractByTag.has(tag)) {
8529
9022
  wrapperContractByTag.set(tag, resolveWrapperContractForTag({
@@ -8535,6 +9028,17 @@ function createTestIdTransform(componentName, componentHierarchyMap, nativeWrapp
8535
9028
  }
8536
9029
  return wrapperContractByTag.get(tag) ?? null;
8537
9030
  };
9031
+ const getInstanceWrapperContract = (tag) => {
9032
+ if (!instanceWrapperContractByTag.has(tag)) {
9033
+ instanceWrapperContractByTag.set(tag, resolveWrapperContractForTag({
9034
+ tag,
9035
+ vueFilesPathMap,
9036
+ wrapperSearchRoots,
9037
+ testIdAttribute: POM_INSTANCE_ATTRIBUTE
9038
+ }));
9039
+ }
9040
+ return instanceWrapperContractByTag.get(tag) ?? null;
9041
+ };
8538
9042
  const safeRealpath2 = (p) => {
8539
9043
  try {
8540
9044
  return fs.existsSync(p) ? fs.realpathSync(p) : p;
@@ -8551,6 +9055,7 @@ function createTestIdTransform(componentName, componentHierarchyMap, nativeWrapp
8551
9055
  const conditionalMergeGroupByElement = /* @__PURE__ */ new WeakMap();
8552
9056
  const conditionalMergeGroupByElementLoc = /* @__PURE__ */ new Map();
8553
9057
  const conditionalMergeGroupByIfBranch = /* @__PURE__ */ new WeakMap();
9058
+ const componentInstanceNameOwnerByName = /* @__PURE__ */ new Map();
8554
9059
  let conditionalMergeGroupCounter = 0;
8555
9060
  const getElementLocationKey = (element) => {
8556
9061
  const startOffset = element.loc?.start.offset;
@@ -8644,6 +9149,8 @@ function createTestIdTransform(componentName, componentHierarchyMap, nativeWrapp
8644
9149
  childrenComponentSet: /* @__PURE__ */ new Set(),
8645
9150
  usedComponentSet: /* @__PURE__ */ new Set(),
8646
9151
  dataTestIdSet: /* @__PURE__ */ new Set(),
9152
+ componentInstances: [],
9153
+ slotOutlets: [],
8647
9154
  isView,
8648
9155
  methodsContent: ""
8649
9156
  };
@@ -8657,6 +9164,17 @@ function createTestIdTransform(componentName, componentHierarchyMap, nativeWrapp
8657
9164
  const isUpper = isAsciiUppercaseLetterCode$1(first);
8658
9165
  return isUpper || tag.includes("-");
8659
9166
  };
9167
+ if (element.tag === "slot") {
9168
+ const slotName = getStaticAttributeContent(element, "name") ?? "default";
9169
+ const target = getNearestComponentAncestor(element, hierarchyMap, isComponentLikeTag2);
9170
+ if (target) {
9171
+ dependencies.slotOutlets ??= [];
9172
+ const outlet = { name: slotName, targetSourceId: getElementSourceId(target) };
9173
+ if (!dependencies.slotOutlets.some((existing) => existing.name === outlet.name && existing.targetSourceId === outlet.targetSourceId)) {
9174
+ dependencies.slotOutlets.push(outlet);
9175
+ }
9176
+ }
9177
+ }
8660
9178
  if (isComponentLikeTag2(element.tag)) {
8661
9179
  dependencies.usedComponentSet.add(element.tag);
8662
9180
  if (crossFileKeyRegistry && context.scopes.vSlot > 0) {
@@ -8719,6 +9237,7 @@ Fix: set \`role\` explicitly in nativeWrappers (e.g. { "${element.tag}": { role:
8719
9237
  role: contract.role
8720
9238
  };
8721
9239
  }
9240
+ let selectorParameterName = "key";
8722
9241
  const getBestAvailableKeyInfo = () => {
8723
9242
  const parentNode = context.parent && typeof context.parent === "object" ? context.parent : null;
8724
9243
  const isDirectVForChild = parentNode?.type === NodeTypes.FOR;
@@ -8726,6 +9245,7 @@ Fix: set \`role\` explicitly in nativeWrappers (e.g. { "${element.tag}": { role:
8726
9245
  if (configuredAttrName && configuredAttrName !== "key") {
8727
9246
  const bindingKeyInfo = getBindingKeyInfo(element, configuredAttrName);
8728
9247
  if (bindingKeyInfo) {
9248
+ selectorParameterName = configuredAttrName === "value" ? "value" : "key";
8729
9249
  return bindingKeyInfo;
8730
9250
  }
8731
9251
  }
@@ -8752,6 +9272,50 @@ Fix: set \`role\` explicitly in nativeWrappers (e.g. { "${element.tag}": { role:
8752
9272
  const bestKeyInfo = getBestAvailableKeyInfo();
8753
9273
  const bestKeyPlaceholder = bestKeyInfo?.selectorFragment ?? null;
8754
9274
  const bestRuntimeKeyPlaceholder = bestKeyInfo?.runtimeFragment ?? null;
9275
+ if (isComponentLikeTag2(element.tag)) {
9276
+ const componentInstanceKeyInfo = getKeyDirectiveInfo(element) || getContainedInVForDirectiveKeyInfo(context, element, hierarchyMap);
9277
+ const instanceContract = getInstanceWrapperContract(element.tag);
9278
+ if ((instanceContract?.forwardedTestIdTargetOffsets.size ?? 0) > 0) {
9279
+ if (tryGetExistingElementDataTestId(element, POM_INSTANCE_ATTRIBUTE)) {
9280
+ const loc = element.loc.start;
9281
+ throw new Error(
9282
+ `[vue-pom-generator] ${POM_INSTANCE_ATTRIBUTE} is generator-owned and cannot be authored manually.
9283
+ Component: ${componentName}
9284
+ File: ${context.filename ?? "unknown"}:${loc.line}:${loc.column}`
9285
+ );
9286
+ }
9287
+ const sourceId = getElementSourceId(element);
9288
+ const semanticNameCandidates = getComponentInstanceNameCandidates(element);
9289
+ const componentTypeName = toPascalCase(element.tag);
9290
+ const instanceNameCandidates = componentInstanceKeyInfo ? [componentTypeName, ...semanticNameCandidates.filter((candidate) => candidate !== componentTypeName)] : semanticNameCandidates;
9291
+ const instanceName = instanceNameCandidates.find((candidate) => {
9292
+ const owner = componentInstanceNameOwnerByName.get(candidate);
9293
+ return !owner || !!componentInstanceKeyInfo && owner.keyed && owner.componentName === element.tag;
9294
+ });
9295
+ if (instanceName) {
9296
+ componentInstanceNameOwnerByName.set(instanceName, {
9297
+ componentName: element.tag,
9298
+ keyed: !!componentInstanceKeyInfo,
9299
+ sourceId
9300
+ });
9301
+ const runtimeMarker = componentInstanceKeyInfo ? templateAttributeValue(`${componentName}-${componentInstanceKeyInfo.runtimeFragment}-${instanceName}-component`) : staticAttributeValue(`${componentName}-${instanceName}-component`);
9302
+ const selector = componentInstanceKeyInfo ? createPomStringPattern(`${componentName}-\${key}-${instanceName}-component`, "parameterized", ["key"]) : createPomStringPattern(`${componentName}-${instanceName}-component`, "static", []);
9303
+ upsertAttribute(element, POM_INSTANCE_ATTRIBUTE, runtimeMarker);
9304
+ const slotTemplate = getContainedInSlotTemplateNode(element, hierarchyMap);
9305
+ const slotName = slotTemplate ? getSlotNameFromTemplate(slotTemplate) : null;
9306
+ const slotOwner = slotTemplate ? getNearestComponentAncestor(slotTemplate, hierarchyMap, isComponentLikeTag2) : null;
9307
+ dependencies.componentInstances ??= [];
9308
+ dependencies.componentInstances.push({
9309
+ sourceId,
9310
+ componentName: element.tag,
9311
+ instanceName,
9312
+ selector,
9313
+ parameters: componentInstanceKeyInfo ? [createPomParameterSpec("key", "string")] : [],
9314
+ suppliedSlot: slotName && slotOwner ? { ownerSourceId: getElementSourceId(slotOwner), name: slotName } : void 0
9315
+ });
9316
+ }
9317
+ }
9318
+ }
8755
9319
  const keyValuesOverride = tryGetContainedInStaticVForSourceLiteralValues(context);
8756
9320
  const parentKey = context?.parent ? context.parent : null;
8757
9321
  const conditional = getConditionalDirectiveInfo(element);
@@ -8860,6 +9424,7 @@ Fix: set \`role\` explicitly in nativeWrappers (e.g. { "${element.tag}": { role:
8860
9424
  preferredGeneratedValue: args.preferredGeneratedValue,
8861
9425
  preferredRuntimeValue: args.preferredRuntimeValue,
8862
9426
  keyInfo: bestKeyInfo,
9427
+ selectorParameterName,
8863
9428
  keyValuesOverride,
8864
9429
  entryOverrides: args.entryOverrides,
8865
9430
  semanticNameHint: args.semanticNameHint,
@@ -9554,6 +10119,7 @@ function createBuildProcessorPlugin(options) {
9554
10119
  typescriptOutputStructure,
9555
10120
  csharp,
9556
10121
  generateFixtures,
10122
+ vueTestUtilsOutDir,
9557
10123
  customPomAttachments,
9558
10124
  customPomDir,
9559
10125
  requireCustomPomDir,
@@ -9770,6 +10336,7 @@ function createBuildProcessorPlugin(options) {
9770
10336
  typescriptOutputStructure,
9771
10337
  csharp,
9772
10338
  generateFixtures,
10339
+ vueTestUtilsOutDir,
9773
10340
  customPomAttachments,
9774
10341
  projectRoot: projectRootRef.current,
9775
10342
  customPomDir,
@@ -9818,6 +10385,7 @@ function createDevProcessorPlugin(options) {
9818
10385
  typescriptOutputStructure,
9819
10386
  csharp,
9820
10387
  generateFixtures,
10388
+ vueTestUtilsOutDir,
9821
10389
  customPomAttachments,
9822
10390
  customPomDir,
9823
10391
  requireCustomPomDir,
@@ -10076,6 +10644,7 @@ function createDevProcessorPlugin(options) {
10076
10644
  typescriptOutputStructure,
10077
10645
  csharp,
10078
10646
  generateFixtures,
10647
+ vueTestUtilsOutDir,
10079
10648
  customPomAttachments,
10080
10649
  projectRoot: projectRootRef.current,
10081
10650
  customPomDir,
@@ -10712,6 +11281,7 @@ function createVuePomGeneratorPlugins(options = {}) {
10712
11281
  typescriptOutputStructure: generationOptions?.playwright?.outputStructure,
10713
11282
  csharp: generationOptions?.csharp,
10714
11283
  generateFixtures,
11284
+ vueTestUtilsOutDir: generationOptions?.vueTestUtils ? generationOptions.vueTestUtils.outDir ?? "tests/unit/__generated__" : void 0,
10715
11285
  customPomAttachments: resolvedCustomPomAttachments,
10716
11286
  customPomDir: customPoms?.dir,
10717
11287
  requireCustomPomDir,
@@ -10746,6 +11316,7 @@ function createVuePomGeneratorPlugins(options = {}) {
10746
11316
  layoutDirs: isNuxt ? null : getLayoutDirs(),
10747
11317
  wrapperSearchRoots: isNuxt ? null : getWrapperSearchRoots(),
10748
11318
  outDir: resolvedGenerationOptions.outDir,
11319
+ vueTestUtilsOutDir: resolvedGenerationOptions.vueTestUtilsOutDir,
10749
11320
  testIdAttribute,
10750
11321
  routerType: resolvedGenerationOptions.routerType,
10751
11322
  vuePluginOwnership
@@ -10784,6 +11355,12 @@ function createVuePomGeneratorPlugins(options = {}) {
10784
11355
  }
10785
11356
  if (generationEnabled) {
10786
11357
  assertNonEmptyString(resolvedGenerationOptions.outDir, "[vue-pom-generator] generation.outDir");
11358
+ if (generationOptions?.vueTestUtils) {
11359
+ assertNonEmptyString(resolvedGenerationOptions.vueTestUtilsOutDir, "[vue-pom-generator] generation.vueTestUtils.outDir");
11360
+ if (path.resolve(projectRootRef.current, resolvedGenerationOptions.vueTestUtilsOutDir) === path.resolve(projectRootRef.current, resolvedGenerationOptions.outDir)) {
11361
+ throw new Error("[vue-pom-generator] generation.vueTestUtils.outDir must differ from generation.outDir.");
11362
+ }
11363
+ }
10787
11364
  assertOneOf(resolvedGenerationOptions.typescriptOutputStructure, ["aggregated", "split"], "[vue-pom-generator] generation.playwright.outputStructure");
10788
11365
  assertRouterModuleShims(resolvedGenerationOptions.routerModuleShims, "[vue-pom-generator] generation.router.moduleShims");
10789
11366
  if (!isNuxt && vueGenerationOptions?.router && resolvedGenerationOptions.routerType === "vue-router") {