@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
@@ -26,6 +26,7 @@ import {
26
26
  isParameterizedPomPattern,
27
27
  orderPomPatternParameters,
28
28
  toCSharpPomPatternExpression,
29
+ toTypeScriptPomPatternExpression,
29
30
  uniquePomStringPatterns,
30
31
  type PomStringPattern,
31
32
  } from "../pom-patterns";
@@ -37,6 +38,7 @@ import {
37
38
  buildCommentBlock,
38
39
  buildFilePrefix,
39
40
  createClassConstructor,
41
+ createClassGetter,
40
42
  createClassMethod,
41
43
  createClassProperty,
42
44
  renderSourceFile,
@@ -49,13 +51,16 @@ import {
49
51
  type PropertyDeclarationStructure,
50
52
  type TypeScriptClassMember,
51
53
  type TypeScriptSourceFile,
54
+ type TypeScriptWriter,
52
55
  } from "../typescript-codegen";
53
56
  import {
54
57
  IComponentDependencies,
55
58
  IDataTestId,
59
+ PomComponentInstanceSpec,
56
60
  PomExtraClickMethodSpec,
57
61
  PomPrimarySpec,
58
62
  PomSelectorSpec,
63
+ buildPomGeneratedActionName,
59
64
  toPascalCase,
60
65
  upperFirst,
61
66
  } from "../utils";
@@ -70,6 +75,17 @@ import {
70
75
 
71
76
  void setPlaywrightAnimationOptions;
72
77
 
78
+ interface ResolvedComponentInstance extends PomComponentInstanceSpec {
79
+ componentRef: string;
80
+ className: string;
81
+ }
82
+
83
+ interface ResolvedProjectedComponentInstance {
84
+ owner: ResolvedComponentInstance;
85
+ target: ResolvedComponentInstance;
86
+ contents: ResolvedComponentInstance[];
87
+ }
88
+
73
89
  export { generateViewObjectModelMethodContent };
74
90
 
75
91
  const GENERATED_GITATTRIBUTES_BLOCK_START = "# BEGIN vue-pom-generator generated files";
@@ -669,7 +685,9 @@ function generateMethodMembersFromPom(
669
685
  );
670
686
  }
671
687
 
672
- function generateMethodsContentForDependencies(componentName: string, dependencies: IComponentDependencies): TypeScriptClassMember[] {
688
+ function getUniquePrimaryPomSpecs(
689
+ dependencies: IComponentDependencies,
690
+ ): Array<{ pom: PomPrimarySpec; target: string | undefined }> {
673
691
  const entries = Array.from(dependencies.dataTestIdSet ?? []);
674
692
  const primarySpecsAll = entries
675
693
  .map(e => ({ pom: e.pom, target: e.targetPageObjectModelClass }))
@@ -681,7 +699,7 @@ function generateMethodsContentForDependencies(componentName: string, dependenci
681
699
  // It's possible to end up with multiple IDataTestId entries that carry identical `pom` specs.
682
700
  // When we emit from IR, we must de-dupe here to avoid duplicate getters/methods.
683
701
  const seenPrimaryKeys = new Set<string>();
684
- const primarySpecs = primarySpecsAll.filter(({ pom, target }) => {
702
+ return primarySpecsAll.filter(({ pom, target }) => {
685
703
  const alternates = (pom.alternateSelectors ?? [])
686
704
  .slice()
687
705
  .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
@@ -701,6 +719,10 @@ function generateMethodsContentForDependencies(componentName: string, dependenci
701
719
  seenPrimaryKeys.add(key);
702
720
  return true;
703
721
  });
722
+ }
723
+
724
+ function generateMethodsContentForDependencies(componentName: string, dependencies: IComponentDependencies): TypeScriptClassMember[] {
725
+ const primarySpecs = getUniquePrimaryPomSpecs(dependencies);
704
726
 
705
727
  const extras = (dependencies.pomExtraMethods ?? [])
706
728
  .slice()
@@ -744,6 +766,9 @@ export interface GenerateFilesOptions {
744
766
  */
745
767
  generateFixtures?: boolean | string | { outDir?: string };
746
768
 
769
+ /** Generate Vue Test Utils component objects in this directory when set. */
770
+ vueTestUtilsOutDir?: string;
771
+
747
772
  /**
748
773
  * Project root used for resolving conventional paths (e.g. src/views, tests/playwright/pom/custom).
749
774
  * Defaults to process.cwd() for backwards compatibility.
@@ -866,6 +891,7 @@ export async function generateFiles(
866
891
  const {
867
892
  outDir: outDirOverride,
868
893
  generateFixtures,
894
+ vueTestUtilsOutDir,
869
895
  customPomAttachments = [],
870
896
  projectRoot,
871
897
  customPomDir,
@@ -891,6 +917,9 @@ export async function generateFiles(
891
917
  : ["ts"];
892
918
 
893
919
  const outDir = outDirOverride ?? "./pom";
920
+ if (vueTestUtilsOutDir && path.resolve(vueTestUtilsOutDir) === path.resolve(outDir)) {
921
+ throw new Error("[vue-pom-generator] generation.vueTestUtils.outDir must differ from generation.outDir.");
922
+ }
894
923
 
895
924
  const routeMetaByComponent = routeMetaByComponentOverride
896
925
  ?? (vueRouterFluentChaining
@@ -961,12 +990,310 @@ export async function generateFiles(
961
990
  }
962
991
  }
963
992
 
993
+ if (vueTestUtilsOutDir) {
994
+ const vueTestUtilsFiles = generateVueTestUtilsFiles(
995
+ emittableComponentHierarchyMap,
996
+ vueTestUtilsOutDir,
997
+ { testIdAttribute },
998
+ );
999
+ for (const file of vueTestUtilsFiles) {
1000
+ writeGeneratedFile(file);
1001
+ }
1002
+ }
1003
+
964
1004
  const gitattributesFiles = buildGeneratedGitAttributesFiles(generatedFilePaths);
965
1005
  for (const file of gitattributesFiles) {
966
1006
  createFile(file.filePath, file.content);
967
1007
  }
968
1008
  }
969
1009
 
1010
+ const VUE_TEST_UTILS_OMITTED_PARAMETERS = new Set(["annotationText", "timeOut", "timeout", "wait"]);
1011
+
1012
+ function getVueTestUtilsParameters(
1013
+ parameters: PomParameterSpec[],
1014
+ patterns: PomStringPattern[],
1015
+ options: { omit?: string[] } = {},
1016
+ ) {
1017
+ return orderPomPatternParameters(parameters, patterns, options)
1018
+ .filter(parameter => !VUE_TEST_UTILS_OMITTED_PARAMETERS.has(parameter.name));
1019
+ }
1020
+
1021
+ function getVueTestUtilsPrimaryMembers(primary: PomPrimarySpec): TypeScriptClassMember[] {
1022
+ if (primary.emitPrimary === false) {
1023
+ return [];
1024
+ }
1025
+
1026
+ const selectors = uniquePomStringPatterns(primary.selector, primary.alternateSelectors);
1027
+ const parameters = getVueTestUtilsParameters(primary.parameters, selectors);
1028
+ const actionName = buildPomGeneratedActionName(primary);
1029
+ const selectorExpressions = selectors.map(selector => toTypeScriptPomPatternExpression(selector));
1030
+ const targetExpression = selectorExpressions.length === 1
1031
+ ? `this.getByTestId(${selectorExpressions[0]})`
1032
+ : `this.getByAnyTestId([${selectorExpressions.join(", ")}])`;
1033
+
1034
+ let actionStatement: string;
1035
+ switch (primary.nativeRole) {
1036
+ case "input":
1037
+ actionStatement = `await ${targetExpression}.setValue(text);`;
1038
+ break;
1039
+ case "select":
1040
+ actionStatement = `await ${targetExpression}.setValue(value);`;
1041
+ break;
1042
+ case "vselect":
1043
+ actionStatement = selectors.length === 1
1044
+ ? `await this.selectVSelectByTestId(${selectorExpressions[0]}, value);`
1045
+ : `await this.selectVSelectByAnyTestId([${selectorExpressions.join(", ")}], value);`;
1046
+ break;
1047
+ case "radio":
1048
+ actionStatement = `await ${targetExpression}.setValue();`;
1049
+ break;
1050
+ default:
1051
+ actionStatement = `await ${targetExpression}.trigger("click");`;
1052
+ break;
1053
+ }
1054
+
1055
+ return [createClassMethod({
1056
+ name: actionName,
1057
+ isAsync: true,
1058
+ parameters: toTypeScriptPomParameterStructures(parameters),
1059
+ statements: [actionStatement],
1060
+ })];
1061
+ }
1062
+
1063
+ function getVueTestUtilsExtraMembers(extra: PomExtraClickMethodSpec): TypeScriptClassMember[] {
1064
+ if (extra.kind !== "click") {
1065
+ return [];
1066
+ }
1067
+
1068
+ const patterns = extra.selector.kind === "testId"
1069
+ ? [extra.selector.testId]
1070
+ : [extra.selector.rootTestId, extra.selector.label];
1071
+ const parameters = getVueTestUtilsParameters(extra.parameters, patterns, {
1072
+ omit: extra.keyLiteral === undefined ? [] : ["key"],
1073
+ });
1074
+
1075
+ return [createClassMethod({
1076
+ name: extra.name,
1077
+ isAsync: true,
1078
+ parameters: toTypeScriptPomParameterStructures(parameters),
1079
+ statements: (writer) => {
1080
+ if (extra.keyLiteral !== undefined) {
1081
+ writer.writeLine(`const key = ${JSON.stringify(extra.keyLiteral)};`);
1082
+ }
1083
+ if (extra.selector.kind === "testId") {
1084
+ writer.writeLine(`await this.clickByTestId(${toTypeScriptPomPatternExpression(extra.selector.testId)});`);
1085
+ return;
1086
+ }
1087
+ writer.writeLine(
1088
+ `await this.clickWithinTestIdByLabel(${toTypeScriptPomPatternExpression(extra.selector.rootTestId)}, `
1089
+ + `${toTypeScriptPomPatternExpression(extra.selector.label)}, ${extra.selector.exact ?? false});`,
1090
+ );
1091
+ },
1092
+ })];
1093
+ }
1094
+
1095
+ function getVueTestUtilsComponentMembers(
1096
+ componentInstances: ResolvedComponentInstance[],
1097
+ projectedComponentInstances: ResolvedProjectedComponentInstance[],
1098
+ testIdAttribute: string,
1099
+ ): TypeScriptClassMember[] {
1100
+ const members: TypeScriptClassMember[] = [];
1101
+
1102
+ for (const instance of componentInstances) {
1103
+ if (instance.parameters.length === 0) {
1104
+ members.push(createClassGetter({
1105
+ name: instance.instanceName,
1106
+ returnType: instance.className,
1107
+ statements: [
1108
+ `return new ${instance.className}(this.getComponentInstance(${toTypeScriptPomPatternExpression(instance.selector)}));`,
1109
+ ],
1110
+ }));
1111
+ continue;
1112
+ }
1113
+
1114
+ members.push(createClassMethod({
1115
+ name: instance.instanceName,
1116
+ parameters: toTypeScriptPomParameterStructures(instance.parameters),
1117
+ returnType: instance.className,
1118
+ statements: [
1119
+ `return new ${instance.className}(this.getComponentInstance(${toTypeScriptPomPatternExpression(instance.selector)}));`,
1120
+ ],
1121
+ }));
1122
+ }
1123
+
1124
+ for (const projection of projectedComponentInstances) {
1125
+ const projectedPropertiesType = projection.contents.length > 0
1126
+ ? ` & { ${projection.contents.map(content => `readonly ${content.instanceName}: ${content.className}`).join("; ")} }`
1127
+ : "";
1128
+ const statements = (writer: TypeScriptWriter) => {
1129
+ writer.writeLine(`const ownerRoot = this.getComponentInstance(${toTypeScriptPomPatternExpression(projection.owner.selector)});`);
1130
+ writer.writeLine(`const root = this.getComponentInstance(${toTypeScriptPomPatternExpression(projection.target.selector)}, ownerRoot);`);
1131
+ writer.writeLine(`const instance = new ${projection.target.className}(root);`);
1132
+ if (projection.contents.length === 0) {
1133
+ writer.writeLine("return instance;");
1134
+ return;
1135
+ }
1136
+ writer.writeLine("return Object.assign(instance, {");
1137
+ writer.indent(() => {
1138
+ for (const content of projection.contents) {
1139
+ writer.writeLine(
1140
+ `${content.instanceName}: new ${content.className}(this.getComponentInstance(`
1141
+ + `${toTypeScriptPomPatternExpression(content.selector)}, root)),`,
1142
+ );
1143
+ }
1144
+ });
1145
+ writer.writeLine("});");
1146
+ };
1147
+ const returnType = `${projection.target.className}${projectedPropertiesType}`;
1148
+ members.push(projection.target.parameters.length > 0
1149
+ ? createClassMethod({
1150
+ name: projection.target.instanceName,
1151
+ parameters: toTypeScriptPomParameterStructures(projection.target.parameters),
1152
+ returnType,
1153
+ statements,
1154
+ })
1155
+ : createClassGetter({
1156
+ name: projection.target.instanceName,
1157
+ returnType,
1158
+ statements,
1159
+ }));
1160
+ }
1161
+
1162
+ members.push(createClassConstructor({
1163
+ parameters: [{ name: "wrapper", type: "VueTestUtilsPomRoot" }],
1164
+ statements: (writer) => {
1165
+ writer.writeLine(`super(wrapper, { testIdAttribute: ${JSON.stringify(testIdAttribute)} });`);
1166
+ },
1167
+ }));
1168
+
1169
+ return members;
1170
+ }
1171
+
1172
+ function generateVueTestUtilsContent(
1173
+ componentName: string,
1174
+ dependencies: IComponentDependencies,
1175
+ componentHierarchyMap: Map<string, IComponentDependencies>,
1176
+ outputDir: string,
1177
+ runtimePath: string,
1178
+ generatedFilePathByComponent: Map<string, string>,
1179
+ testIdAttribute: string,
1180
+ ): string {
1181
+ const prepared = prepareViewObjectModelClass(componentName, dependencies, componentHierarchyMap, {
1182
+ outputStructure: "split",
1183
+ outputDir,
1184
+ testIdAttribute,
1185
+ });
1186
+ const runtimeImport = stripExtension(toPosixRelativePath(outputDir, runtimePath));
1187
+ const sourceRel = toPosixRelativePath(outputDir, dependencies.filePath);
1188
+ const componentImports = Array.from(prepared.componentRefsForInstances)
1189
+ .map((componentRef) => {
1190
+ const className = componentRef.endsWith(".vue") ? componentRef.slice(0, -4) : componentRef;
1191
+ const filePath = generatedFilePathByComponent.get(className);
1192
+ return filePath ? { className, moduleSpecifier: stripExtension(toPosixRelativePath(outputDir, filePath)) } : null;
1193
+ })
1194
+ .filter((value): value is { className: string; moduleSpecifier: string } => !!value)
1195
+ .sort((left, right) => left.className.localeCompare(right.className));
1196
+
1197
+ const members = [
1198
+ ...getVueTestUtilsComponentMembers(
1199
+ prepared.directComponentInstances,
1200
+ prepared.projectedComponentInstances,
1201
+ testIdAttribute,
1202
+ ),
1203
+ ...getUniquePrimaryPomSpecs(dependencies)
1204
+ .flatMap(({ pom }) => getVueTestUtilsPrimaryMembers(pom)),
1205
+ ...(dependencies.pomExtraMethods ?? []).flatMap(getVueTestUtilsExtraMembers),
1206
+ ];
1207
+
1208
+ return renderSourceFile(`${componentName}.vtu.g.ts`, (sourceFile) => {
1209
+ addNamedImport(sourceFile, {
1210
+ moduleSpecifier: runtimeImport,
1211
+ namedImports: ["VueTestUtilsPom"],
1212
+ });
1213
+ addNamedImport(sourceFile, {
1214
+ moduleSpecifier: runtimeImport,
1215
+ namedImports: ["VueTestUtilsPomRoot"],
1216
+ isTypeOnly: true,
1217
+ });
1218
+ for (const componentImport of componentImports) {
1219
+ addNamedImport(sourceFile, {
1220
+ moduleSpecifier: componentImport.moduleSpecifier,
1221
+ namedImports: [componentImport.className],
1222
+ });
1223
+ }
1224
+
1225
+ const declaration = sourceFile.addClass({
1226
+ name: prepared.className,
1227
+ isExported: true,
1228
+ extends: "VueTestUtilsPom",
1229
+ docs: [`Vue Test Utils object for ${componentName} (source: ${sourceRel}).`],
1230
+ });
1231
+ for (const member of members) {
1232
+ addClassMember(declaration, member);
1233
+ }
1234
+ }, {
1235
+ prefixText: buildFilePrefix({ eslintDisableSortImports: true }),
1236
+ });
1237
+ }
1238
+
1239
+ function generateVueTestUtilsFiles(
1240
+ componentHierarchyMap: Map<string, IComponentDependencies>,
1241
+ outDir: string,
1242
+ options: { testIdAttribute?: string } = {},
1243
+ ): GeneratedFileOutput[] {
1244
+ const base = ensureDir(outDir);
1245
+ const testIdAttribute = options.testIdAttribute?.trim() || "data-testid";
1246
+ const entries = Array.from(componentHierarchyMap.entries())
1247
+ .sort((left, right) => left[0].localeCompare(right[0]));
1248
+ const generatedFilePathByComponent = new Map(
1249
+ entries.map(([componentName]) => [componentName, path.join(base, `${componentName}.vtu.g.ts`)]),
1250
+ );
1251
+ const runtimePath = path.join(base, "_pom-runtime", "vue-test-utils-pom.ts");
1252
+ const files: GeneratedFileOutput[] = entries.map(([componentName, dependencies]) => {
1253
+ const filePath = generatedFilePathByComponent.get(componentName)!;
1254
+ return {
1255
+ filePath,
1256
+ content: generateVueTestUtilsContent(
1257
+ componentName,
1258
+ dependencies,
1259
+ componentHierarchyMap,
1260
+ path.dirname(filePath),
1261
+ runtimePath,
1262
+ generatedFilePathByComponent,
1263
+ testIdAttribute,
1264
+ ),
1265
+ };
1266
+ });
1267
+ const [runtimeFile] = buildRuntimeGeneratedFilesFromSpecs([{
1268
+ absolutePath: resolvePluginAsset("../class-generation/vue-test-utils-pom.ts"),
1269
+ description: "vue-test-utils-pom.ts",
1270
+ outputPath: runtimePath,
1271
+ }]);
1272
+ if (!runtimeFile) {
1273
+ throw new Error("[vue-pom-generator] Failed to generate the Vue Test Utils runtime.");
1274
+ }
1275
+ const indexContent = renderSourceFile("index.ts", (sourceFile) => {
1276
+ addExportAll(sourceFile, stripExtension(toPosixRelativePath(base, runtimePath)));
1277
+ for (const [, filePath] of generatedFilePathByComponent) {
1278
+ addExportAll(sourceFile, `./${stripExtension(path.basename(filePath))}`);
1279
+ }
1280
+ }, {
1281
+ prefixText: buildFilePrefix({
1282
+ eslintDisableSortImports: true,
1283
+ commentLines: [
1284
+ "Vue Test Utils POM exports",
1285
+ "DO NOT MODIFY BY HAND",
1286
+ ],
1287
+ }),
1288
+ });
1289
+
1290
+ return [
1291
+ ...files,
1292
+ { filePath: path.join(base, "index.ts"), content: indexContent },
1293
+ runtimeFile,
1294
+ ];
1295
+ }
1296
+
970
1297
  async function generateSplitTypeScriptFiles(
971
1298
  componentHierarchyMap: Map<string, IComponentDependencies>,
972
1299
  vueFilesPathMap: Map<string, string>,
@@ -2002,28 +2329,149 @@ function prepareViewObjectModelClass(
2002
2329
  return Array.from(nestedRefs).some(child => hasGeneratedPomSurface(child, nextSeen));
2003
2330
  };
2004
2331
 
2005
- const rawComponentRefsForInstances = usedComponentSet?.size
2006
- ? usedComponentSet
2007
- : childrenComponentSet;
2008
- // A component may render itself recursively (e.g. a tree/list that nests same-named
2009
- // children). Without this guard the generator emits `this.<SelfName> = new <SelfName>(page)`
2010
- // in the constructor, which infinitely recurses the moment any POM transitively
2011
- // instantiates this class. A self-reference is never a useful child instance (it would
2012
- // just re-wrap the same page), so drop it before it becomes a property + ctor assignment.
2332
+ // Recursive component invocations cannot become eager child POM instances without
2333
+ // infinitely constructing themselves.
2013
2334
  const ownClassName = toPascalCaseLocal(componentName);
2014
2335
  const isSelfReference = (ref: string): boolean => {
2015
2336
  return toPascalCaseLocal(normalizeTrackedComponentRef(ref)) === ownClassName && ownClassName.length > 0;
2016
2337
  };
2017
- const componentRefsForInstances = new Set<string>();
2018
- for (const ref of rawComponentRefsForInstances) {
2019
- const resolvedRef = resolveTrackedComponentRef(ref) ?? normalizeTrackedComponentRef(ref);
2020
- if (isSelfReference(resolvedRef)) {
2021
- continue;
2338
+
2339
+ const resolveComponentInstance = (spec: PomComponentInstanceSpec): ResolvedComponentInstance | null => {
2340
+ const componentRef = resolveTrackedComponentRef(spec.componentName);
2341
+ if (
2342
+ !componentRef
2343
+ || isSelfReference(componentRef)
2344
+ || !hasGeneratedPomSurface(componentRef, new Set([componentName]))
2345
+ ) {
2346
+ return null;
2022
2347
  }
2023
- if (!hasGeneratedPomSurface(resolvedRef, new Set([componentName]))) {
2348
+
2349
+ return {
2350
+ ...spec,
2351
+ componentRef,
2352
+ className: normalizeTrackedComponentRef(componentRef),
2353
+ };
2354
+ };
2355
+
2356
+ const uniqueInstances = (
2357
+ instances: ResolvedComponentInstance[],
2358
+ ownerName: string,
2359
+ ): ResolvedComponentInstance[] => {
2360
+ const byPublicName = new Map<string, ResolvedComponentInstance>();
2361
+ for (const instance of instances) {
2362
+ const existing = byPublicName.get(instance.instanceName);
2363
+ if (!existing) {
2364
+ byPublicName.set(instance.instanceName, instance);
2365
+ continue;
2366
+ }
2367
+
2368
+ const sameInvocationShape = existing.componentRef === instance.componentRef
2369
+ && JSON.stringify(existing.selector) === JSON.stringify(instance.selector)
2370
+ && JSON.stringify(existing.parameters) === JSON.stringify(instance.parameters);
2371
+ if (sameInvocationShape) {
2372
+ continue;
2373
+ }
2374
+
2375
+ throw new VuePomGeneratorError(
2376
+ `Semantic component instance name ${JSON.stringify(instance.instanceName)} is ambiguous in ${ownerName}.\n`
2377
+ + `It refers to both <${existing.componentName}> and <${instance.componentName}>.\n\n`
2378
+ + "Fix: give the invocations distinct accessible names or distinct semantic model/options bindings.",
2379
+ );
2380
+ }
2381
+ return Array.from(byPublicName.values());
2382
+ };
2383
+
2384
+ const allInvocationSpecs = dependencies.componentInstances ?? [];
2385
+ const directComponentInstances = uniqueInstances(
2386
+ allInvocationSpecs
2387
+ .filter(spec => !spec.suppliedSlot)
2388
+ .map(resolveComponentInstance)
2389
+ .filter((instance): instance is ResolvedComponentInstance => !!instance),
2390
+ componentName,
2391
+ );
2392
+
2393
+ const projectedComponentInstances: ResolvedProjectedComponentInstance[] = [];
2394
+ for (const owner of directComponentInstances) {
2395
+ const ownerDependencies = componentHierarchyMap.get(owner.componentRef);
2396
+ if (!ownerDependencies?.slotOutlets?.length) {
2024
2397
  continue;
2025
2398
  }
2026
- componentRefsForInstances.add(resolvedRef);
2399
+
2400
+ const suppliedBySlot = new Map<string, ResolvedComponentInstance[]>();
2401
+ for (const suppliedSpec of allInvocationSpecs) {
2402
+ if (suppliedSpec.suppliedSlot?.ownerSourceId !== owner.sourceId) {
2403
+ continue;
2404
+ }
2405
+ const supplied = resolveComponentInstance(suppliedSpec);
2406
+ if (!supplied) {
2407
+ continue;
2408
+ }
2409
+ const values = suppliedBySlot.get(suppliedSpec.suppliedSlot.name) ?? [];
2410
+ values.push(supplied);
2411
+ suppliedBySlot.set(suppliedSpec.suppliedSlot.name, values);
2412
+ }
2413
+
2414
+ for (const [slotName, rawContents] of suppliedBySlot) {
2415
+ const outletTargetIds = new Set(
2416
+ ownerDependencies.slotOutlets
2417
+ .filter(outlet => outlet.name === slotName)
2418
+ .map(outlet => outlet.targetSourceId),
2419
+ );
2420
+ const targetInstances = uniqueInstances(
2421
+ (ownerDependencies.componentInstances ?? [])
2422
+ .filter(spec => outletTargetIds.has(spec.sourceId))
2423
+ .map(resolveComponentInstance)
2424
+ .filter((instance): instance is ResolvedComponentInstance => !!instance),
2425
+ `${owner.className} slot ${JSON.stringify(slotName)}`,
2426
+ );
2427
+ const contents = uniqueInstances(rawContents, `${componentName} slot ${JSON.stringify(slotName)}`);
2428
+ for (const target of targetInstances) {
2429
+ if (owner.parameters.length > 0) {
2430
+ throw new VuePomGeneratorError(
2431
+ `Cannot project slot ${JSON.stringify(slotName)} through keyed component instance ${owner.instanceName} in ${componentName}.\n`
2432
+ + "The owner and projected target require distinct key scopes, which cannot be represented by one unambiguous generated accessor.",
2433
+ );
2434
+ }
2435
+ const keyedContent = contents.find(content => content.parameters.length > 0);
2436
+ if (keyedContent) {
2437
+ throw new VuePomGeneratorError(
2438
+ `Cannot attach keyed slot content ${keyedContent.instanceName} as a property of ${target.instanceName} in ${componentName}.\n`
2439
+ + "Move the repetition to the receiving component boundary so the generator can expose it as a keyed accessor.",
2440
+ );
2441
+ }
2442
+ const existingProjection = projectedComponentInstances.find((projection) => {
2443
+ return projection.owner.sourceId === owner.sourceId
2444
+ && projection.target.instanceName === target.instanceName
2445
+ && projection.target.componentRef === target.componentRef
2446
+ && JSON.stringify(projection.target.selector) === JSON.stringify(target.selector);
2447
+ });
2448
+ if (existingProjection) {
2449
+ existingProjection.contents = uniqueInstances(
2450
+ [...existingProjection.contents, ...contents],
2451
+ `${componentName} projected ${target.instanceName}`,
2452
+ );
2453
+ continue;
2454
+ }
2455
+ projectedComponentInstances.push({ owner, target, contents });
2456
+ }
2457
+ }
2458
+ }
2459
+
2460
+ const rawComponentRefsForInstances = usedComponentSet?.size
2461
+ ? usedComponentSet
2462
+ : childrenComponentSet;
2463
+ const componentRefsForInstances = new Set<string>();
2464
+ for (const instance of directComponentInstances) {
2465
+ if (!isSelfReference(instance.componentRef)) {
2466
+ componentRefsForInstances.add(instance.componentRef);
2467
+ }
2468
+ }
2469
+ for (const projection of projectedComponentInstances) {
2470
+ for (const instance of [projection.owner, projection.target, ...projection.contents]) {
2471
+ if (!isSelfReference(instance.componentRef)) {
2472
+ componentRefsForInstances.add(instance.componentRef);
2473
+ }
2474
+ }
2027
2475
  }
2028
2476
 
2029
2477
  const hasChildComponent = (needle: string) => {
@@ -2078,8 +2526,19 @@ function prepareViewObjectModelClass(
2078
2526
  : [];
2079
2527
 
2080
2528
  const className = toPascalCaseLocal(componentName);
2081
- const childInstancePropertyNames = Array.from(componentRefsForInstances)
2082
- .map(child => child.split(".vue")[0]);
2529
+ const childInstancePropertyNames = [
2530
+ ...directComponentInstances.map(instance => instance.instanceName),
2531
+ ...projectedComponentInstances.map(projection => projection.target.instanceName),
2532
+ ];
2533
+ const duplicateChildInstanceName = childInstancePropertyNames.find((name, index) => {
2534
+ return childInstancePropertyNames.indexOf(name) !== index;
2535
+ });
2536
+ if (duplicateChildInstanceName) {
2537
+ throw new VuePomGeneratorError(
2538
+ `Semantic component instance ${JSON.stringify(duplicateChildInstanceName)} would be emitted more than once in ${componentName}.\n`
2539
+ + "Fix: give direct and slot-projected instances distinct accessible names or semantic bindings.",
2540
+ );
2541
+ }
2083
2542
  const blockedViewPassthroughMethodNames = new Set(
2084
2543
  attachmentsForThisClass
2085
2544
  .filter(a => a.flatten)
@@ -2093,24 +2552,24 @@ function prepareViewObjectModelClass(
2093
2552
 
2094
2553
  const members: TypeScriptClassMember[] = [];
2095
2554
  if (isView && (componentRefsForInstances.size > 0 || attachmentsForThisClass.length > 0 || widgetInstances.length > 0)) {
2096
- members.push(...getComponentInstances(componentRefsForInstances, componentHierarchyMap, attachmentsForThisClass, widgetInstances));
2097
- members.push(getConstructor(componentRefsForInstances, componentHierarchyMap, attachmentsForThisClass, widgetInstances, { testIdAttribute }));
2555
+ members.push(...getComponentInstances(directComponentInstances, projectedComponentInstances, attachmentsForThisClass, widgetInstances));
2556
+ members.push(getConstructor(directComponentInstances, attachmentsForThisClass, widgetInstances, { testIdAttribute }));
2098
2557
  }
2099
2558
  if (!isView && (componentRefsForInstances.size > 0 || attachmentsForThisClass.length > 0)) {
2100
- members.push(...getComponentInstances(componentRefsForInstances, componentHierarchyMap, attachmentsForThisClass));
2101
- members.push(getConstructor(componentRefsForInstances, componentHierarchyMap, attachmentsForThisClass, [], { testIdAttribute }));
2559
+ members.push(...getComponentInstances(directComponentInstances, projectedComponentInstances, attachmentsForThisClass));
2560
+ members.push(getConstructor(directComponentInstances, attachmentsForThisClass, [], { testIdAttribute }));
2102
2561
  }
2103
2562
 
2104
2563
  members.push(
2105
2564
  ...getAttachmentPassthroughMethods(componentName, dependencies, attachmentsForThisClass, reservedAttachmentPassthroughNames),
2106
2565
  );
2107
2566
 
2108
- if (isView && componentRefsForInstances.size === 1) {
2567
+ if (isView && directComponentInstances.length === 1) {
2109
2568
  members.push(
2110
2569
  ...getViewPassthroughMethods(
2111
2570
  componentName,
2112
2571
  dependencies,
2113
- componentRefsForInstances,
2572
+ directComponentInstances,
2114
2573
  componentHierarchyMap,
2115
2574
  blockedViewPassthroughMethodNames,
2116
2575
  ),
@@ -2128,6 +2587,8 @@ function prepareViewObjectModelClass(
2128
2587
  return {
2129
2588
  className,
2130
2589
  componentRefsForInstances,
2590
+ directComponentInstances,
2591
+ projectedComponentInstances,
2131
2592
  attachmentsForThisClass,
2132
2593
  widgetInstances,
2133
2594
  isView,
@@ -2235,7 +2696,10 @@ function generateViewObjectModelContent(
2235
2696
  addNamedImport(sourceFile, {
2236
2697
  moduleSpecifier: "@playwright/test",
2237
2698
  isTypeOnly: true,
2238
- namedImports: [{ name: "Page", alias: "PwPage" }],
2699
+ namedImports: [
2700
+ { name: "Locator", alias: "PwLocator" },
2701
+ { name: "Page", alias: "PwPage" },
2702
+ ],
2239
2703
  });
2240
2704
  }
2241
2705
 
@@ -2273,7 +2737,7 @@ function generateViewObjectModelContent(
2273
2737
  function getViewPassthroughMethods(
2274
2738
  viewName: string,
2275
2739
  viewDependencies: IComponentDependencies,
2276
- childrenComponentSet: Set<string>,
2740
+ componentInstances: ResolvedComponentInstance[],
2277
2741
  componentHierarchyMap: Map<string, IComponentDependencies>,
2278
2742
  blockedMethodNames: Set<string> = new Set(),
2279
2743
  ) {
@@ -2282,8 +2746,8 @@ function getViewPassthroughMethods(
2282
2746
  // methodName -> candidates
2283
2747
  const methodToChildren = new Map<string, Array<{ childProp: string; signature: PomMethodSignature }>>();
2284
2748
 
2285
- for (const child of childrenComponentSet) {
2286
- const childDeps = componentHierarchyMap.get(child);
2749
+ for (const instance of componentInstances) {
2750
+ const childDeps = componentHierarchyMap.get(instance.componentRef);
2287
2751
  if (!childDeps || !childDeps.dataTestIdSet?.size)
2288
2752
  continue;
2289
2753
 
@@ -2292,7 +2756,7 @@ function getViewPassthroughMethods(
2292
2756
  continue;
2293
2757
 
2294
2758
  // Property name matches how we emit instance fields (strip .vue if present).
2295
- const childProp = child.endsWith(".vue") ? child.slice(0, -4) : child;
2759
+ const childProp = instance.instanceName;
2296
2760
 
2297
2761
  for (const [name, sig] of methods.entries()) {
2298
2762
  if (!sig)
@@ -2667,7 +3131,7 @@ function getRuntimeGeneratedAssetSpecs(baseDir: string, basePageClassPath: strin
2667
3131
  const runtimeClassGenSourceDir = resolvePluginAsset("../class-generation");
2668
3132
  const runtimeClassGenFiles = fs.readdirSync(runtimeClassGenSourceDir)
2669
3133
  .filter(file => file.endsWith(".ts"))
2670
- .filter(file => file !== "base-page.ts" && file !== "diagnostics.ts" && file !== "index.ts")
3134
+ .filter(file => !["base-page.ts", "diagnostics.ts", "index.ts", "vue-test-utils-pom.ts"].includes(file))
2671
3135
  .sort((left, right) => left.localeCompare(right));
2672
3136
 
2673
3137
  return [
@@ -3234,8 +3698,8 @@ function getWidgetInstancesForView(
3234
3698
  }
3235
3699
 
3236
3700
  function getComponentInstances(
3237
- childrenComponent: Set<string>,
3238
- componentHierarchyMap: Map<string, IComponentDependencies>,
3701
+ componentInstances: ResolvedComponentInstance[],
3702
+ projectedComponentInstances: ResolvedProjectedComponentInstance[],
3239
3703
  attachmentsForThisView: Array<{ className: string; propertyName: string }> = [],
3240
3704
  widgetInstances: WidgetInstance[] = [],
3241
3705
  ) {
@@ -3255,31 +3719,83 @@ function getComponentInstances(
3255
3719
  }));
3256
3720
  }
3257
3721
 
3258
- childrenComponent.forEach((child) => {
3259
- if (componentHierarchyMap.has(child)) {
3260
- const childName = child.split(".vue")[0];
3722
+ for (const instance of componentInstances) {
3723
+ if (instance.parameters.length === 0) {
3261
3724
  declarations.push(createClassProperty({
3262
- name: childName,
3263
- type: childName,
3725
+ name: instance.instanceName,
3726
+ type: instance.className,
3264
3727
  }));
3728
+ continue;
3265
3729
  }
3266
- });
3730
+
3731
+ declarations.push(createClassMethod({
3732
+ name: instance.instanceName,
3733
+ parameters: toTypeScriptPomParameterStructures(instance.parameters),
3734
+ returnType: instance.className,
3735
+ statements: (writer) => {
3736
+ writer.writeLine(`const root = this.componentInstanceLocator(${toTypeScriptPomPatternExpression(instance.selector)});`);
3737
+ writer.writeLine(`return new ${instance.className}(this.page, root);`);
3738
+ },
3739
+ }));
3740
+ }
3741
+
3742
+ for (const projection of projectedComponentInstances) {
3743
+ const projectedPropertiesType = projection.contents.length > 0
3744
+ ? ` & { ${projection.contents.map(content => `readonly ${content.instanceName}: ${content.className}`).join("; ")} }`
3745
+ : "";
3746
+ const statements = (writer: TypeScriptWriter) => {
3747
+ const ownerSelector = toTypeScriptPomPatternExpression(projection.owner.selector);
3748
+ const targetSelector = toTypeScriptPomPatternExpression(projection.target.selector);
3749
+ writer.writeLine(`const ownerRoot = this.componentInstanceLocator(${ownerSelector});`);
3750
+ writer.writeLine(`const root = this.componentInstanceLocator(${targetSelector}, ownerRoot);`);
3751
+ writer.writeLine(`const instance = new ${projection.target.className}(this.page, root);`);
3752
+ if (projection.contents.length === 0) {
3753
+ writer.writeLine("return instance;");
3754
+ return;
3755
+ }
3756
+
3757
+ writer.writeLine("return Object.assign(instance, {");
3758
+ writer.indent(() => {
3759
+ for (const content of projection.contents) {
3760
+ const contentSelector = toTypeScriptPomPatternExpression(content.selector);
3761
+ writer.writeLine(`${content.instanceName}: new ${content.className}(this.page, this.componentInstanceLocator(${contentSelector}, root)),`);
3762
+ }
3763
+ });
3764
+ writer.writeLine("});");
3765
+ };
3766
+ const returnType = `${projection.target.className}${projectedPropertiesType}`;
3767
+
3768
+ declarations.push(projection.target.parameters.length > 0
3769
+ ? createClassMethod({
3770
+ name: projection.target.instanceName,
3771
+ parameters: toTypeScriptPomParameterStructures(projection.target.parameters),
3772
+ returnType,
3773
+ statements,
3774
+ })
3775
+ : createClassGetter({
3776
+ name: projection.target.instanceName,
3777
+ returnType,
3778
+ statements,
3779
+ }));
3780
+ }
3267
3781
 
3268
3782
  return declarations;
3269
3783
  }
3270
3784
 
3271
3785
  function getConstructor(
3272
- childrenComponent: Set<string>,
3273
- componentHierarchyMap: Map<string, IComponentDependencies>,
3786
+ componentInstances: ResolvedComponentInstance[],
3274
3787
  attachmentsForThisView: Array<{ className: string; propertyName: string }> = [],
3275
3788
  widgetInstances: WidgetInstance[] = [],
3276
3789
  options?: { testIdAttribute?: string },
3277
3790
  ) {
3278
3791
  const attr = (options?.testIdAttribute ?? "data-testid").trim() || "data-testid";
3279
3792
  return createClassConstructor({
3280
- parameters: [{ name: "page", type: "PwPage" }],
3793
+ parameters: [
3794
+ { name: "page", type: "PwPage" },
3795
+ { name: "root", type: "PwLocator", hasQuestionToken: true },
3796
+ ],
3281
3797
  statements: (writer) => {
3282
- writer.writeLine(`super(page, { testIdAttribute: ${JSON.stringify(attr)} });`);
3798
+ writer.writeLine(`super(page, { root, testIdAttribute: ${JSON.stringify(attr)} });`);
3283
3799
 
3284
3800
  for (const a of attachmentsForThisView) {
3285
3801
  // Hand-written (custom) POMs are declared against Playwright's full `Page`.
@@ -3292,12 +3808,12 @@ function getConstructor(
3292
3808
  writer.writeLine(`this.${w.propertyName} = new ${w.className}(this.page, ${JSON.stringify(w.testId)});`);
3293
3809
  }
3294
3810
 
3295
- childrenComponent.forEach((child) => {
3296
- if (componentHierarchyMap.has(child)) {
3297
- const childName = child.split(".vue")[0];
3298
- writer.writeLine(`this.${childName} = new ${childName}(page);`);
3811
+ for (const instance of componentInstances) {
3812
+ if (instance.parameters.length === 0) {
3813
+ const selector = toTypeScriptPomPatternExpression(instance.selector);
3814
+ writer.writeLine(`this.${instance.instanceName} = new ${instance.className}(page, this.componentInstanceLocator(${selector}));`);
3299
3815
  }
3300
- });
3816
+ }
3301
3817
  },
3302
3818
  });
3303
3819
  }