@immense/vue-pom-generator 1.0.89 → 1.0.91

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 (43) hide show
  1. package/README.md +42 -10
  2. package/RELEASE_NOTES.md +22 -47
  3. package/class-generation/index.ts +124 -107
  4. package/dist/class-generation/index.d.ts +1 -0
  5. package/dist/class-generation/index.d.ts.map +1 -1
  6. package/dist/eslint/index.cjs +42 -0
  7. package/dist/eslint/index.cjs.map +1 -1
  8. package/dist/eslint/index.d.ts +3 -0
  9. package/dist/eslint/index.d.ts.map +1 -1
  10. package/dist/eslint/index.mjs +42 -0
  11. package/dist/eslint/index.mjs.map +1 -1
  12. package/dist/eslint/no-data-testid-in-specs.d.ts +3 -0
  13. package/dist/eslint/no-data-testid-in-specs.d.ts.map +1 -0
  14. package/dist/index.cjs +1824 -1537
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.mjs +1815 -1528
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/plugin/internal/build-plugin.d.ts.map +1 -1
  21. package/dist/plugin/internal/dev-plugin.d.ts.map +1 -1
  22. package/dist/plugin/resolved-generation-options.d.ts +2 -2
  23. package/dist/plugin/resolved-generation-options.d.ts.map +1 -1
  24. package/dist/plugin/resolved-injection-options.d.ts +3 -3
  25. package/dist/plugin/resolved-injection-options.d.ts.map +1 -1
  26. package/dist/plugin/types.d.ts +11 -3
  27. package/dist/plugin/types.d.ts.map +1 -1
  28. package/dist/plugin/vue-plugin.d.ts +3 -2
  29. package/dist/plugin/vue-plugin.d.ts.map +1 -1
  30. package/dist/route-navigation-codegen.d.ts +38 -0
  31. package/dist/route-navigation-codegen.d.ts.map +1 -0
  32. package/dist/router-bridge.d.ts +19 -0
  33. package/dist/router-bridge.d.ts.map +1 -0
  34. package/dist/router.cjs +9 -0
  35. package/dist/router.cjs.map +1 -0
  36. package/dist/router.mjs +9 -0
  37. package/dist/router.mjs.map +1 -0
  38. package/dist/tests/existing-id-behavior.test.d.ts +2 -0
  39. package/dist/tests/existing-id-behavior.test.d.ts.map +1 -0
  40. package/dist/tests/router-bridge.test.d.ts +2 -0
  41. package/dist/tests/router-bridge.test.d.ts.map +1 -0
  42. package/dist/vite.config.d.ts.map +1 -1
  43. package/package.json +6 -1
package/dist/index.mjs CHANGED
@@ -10,8 +10,9 @@ import { parseExpression, parse } from "@babel/parser";
10
10
  import { NodeTypes, stringifyExpression, ConstantTypes, createSimpleExpression, 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 } from "@babel/types";
13
- import { performance } from "node:perf_hooks";
13
+ import { POM_ROUTER_GLOBAL_NAME } from "./router.mjs";
14
14
  import vue from "@vitejs/plugin-vue";
15
+ import { performance } from "node:perf_hooks";
15
16
  import { autoUpdate, computePosition, offset, autoPlacement, shift, arrow } from "@floating-ui/dom";
16
17
  const VUE_POM_GENERATOR_LOG_PREFIX = "[vue-pom-generator]";
17
18
  function normalize(message) {
@@ -4628,6 +4629,251 @@ async function parseRouterFileFromCwd(routerEntryPath, options = {}) {
4628
4629
  }
4629
4630
  });
4630
4631
  }
4632
+ function writeNavigationValue(writer, input, name) {
4633
+ writer.write(input.identifier);
4634
+ if (input.optional) {
4635
+ writer.write("?.");
4636
+ }
4637
+ writer.write(`[${JSON.stringify(name)}]`);
4638
+ }
4639
+ function writeFilteredNavigationRecord(writer, variableName, input, names) {
4640
+ writer.write(`const ${variableName} = `);
4641
+ if (!input || names.length === 0) {
4642
+ writer.write("{};").newLine();
4643
+ return;
4644
+ }
4645
+ writer.write("Object.fromEntries([");
4646
+ names.forEach((name, index) => {
4647
+ if (index > 0) {
4648
+ writer.write(", ");
4649
+ }
4650
+ writer.write(`[${JSON.stringify(name)}, `);
4651
+ writeNavigationValue(writer, input, name);
4652
+ writer.write("]");
4653
+ });
4654
+ writer.write("].filter(([, value]) => value !== undefined));").newLine();
4655
+ }
4656
+ function writeUnpartitionedRouteParams(writer, input) {
4657
+ writer.write("const routeParams = ");
4658
+ if (!input) {
4659
+ writer.write("{};").newLine();
4660
+ return;
4661
+ }
4662
+ writer.write("Object.fromEntries(Object.entries(");
4663
+ writer.write(input.identifier);
4664
+ if (input.optional) {
4665
+ writer.write(" ?? {}");
4666
+ }
4667
+ writer.write(").filter(([, v]) => v !== undefined));").newLine();
4668
+ }
4669
+ function writeRouterTargetType(writer, includeQuery) {
4670
+ writer.write("{ name: string; params: Record<string, unknown>");
4671
+ if (includeQuery) {
4672
+ writer.write("; query: Record<string, unknown>");
4673
+ }
4674
+ writer.write(" }");
4675
+ }
4676
+ function writeRouterType(writer, includeQuery) {
4677
+ writer.write(`{ ${POM_ROUTER_GLOBAL_NAME}?: { push: (to: `);
4678
+ writeRouterTargetType(writer, includeQuery);
4679
+ writer.write(") => Promise<unknown>; resolve: (to: ");
4680
+ writeRouterTargetType(writer, includeQuery);
4681
+ writer.write(") => { href: string } } }");
4682
+ }
4683
+ function writeRouterBinding(writer, includeQuery) {
4684
+ writer.write("{ name, params");
4685
+ if (includeQuery) {
4686
+ writer.write(", query");
4687
+ }
4688
+ writer.write(" }");
4689
+ }
4690
+ function writeRouterTarget(writer, writeName, includeQuery, paramsExpression, queryExpression) {
4691
+ writer.write("{ name: ");
4692
+ writeName(writer);
4693
+ writer.write(`, params: ${paramsExpression}`);
4694
+ if (includeQuery) {
4695
+ writer.write(`, query: ${queryExpression}`);
4696
+ }
4697
+ writer.write(" }");
4698
+ }
4699
+ function requireNavigationInput(input, context) {
4700
+ if (!input) {
4701
+ throw new Error(`${context} requires a navigation input.`);
4702
+ }
4703
+ return input;
4704
+ }
4705
+ function writeParametrizedRouteSelector(writer, input, pathParamNames) {
4706
+ writer.write(`const useParametrizedRoute = ${input.identifier} !== undefined && [`);
4707
+ pathParamNames.forEach((name, index) => {
4708
+ if (index > 0) {
4709
+ writer.write(", ");
4710
+ }
4711
+ writer.write(JSON.stringify(name));
4712
+ });
4713
+ writer.write(`].some(key => Object.prototype.hasOwnProperty.call(${input.identifier}, key));`).newLine();
4714
+ }
4715
+ function writeSelectionPrelude(writer, selection, input, pathParamNames) {
4716
+ if (selection.kind === "dual" && selection.selectBy === "path-param-presence") {
4717
+ writeParametrizedRouteSelector(
4718
+ writer,
4719
+ requireNavigationInput(input, "Path-param route selection"),
4720
+ pathParamNames
4721
+ );
4722
+ }
4723
+ }
4724
+ function writeSelectedTarget(writer, selection, input) {
4725
+ if (selection.kind === "single") {
4726
+ writer.write(JSON.stringify(selection.target));
4727
+ return;
4728
+ }
4729
+ if (selection.selectBy === "path-param-presence") {
4730
+ writer.write("useParametrizedRoute");
4731
+ } else {
4732
+ writer.write(requireNavigationInput(input, "Input-presence route selection").identifier);
4733
+ }
4734
+ writer.write(` ? ${JSON.stringify(selection.parametrizedTarget)} : ${JSON.stringify(selection.paramlessTarget)}`);
4735
+ }
4736
+ function createRouterNavigationWriter(options) {
4737
+ return (writer) => {
4738
+ writeSelectionPrelude(writer, options.routeName, options.input, options.pathParamNames);
4739
+ const writeRouteName = (nameWriter) => writeSelectedTarget(nameWriter, options.routeName, options.input);
4740
+ const includeQuery = options.queryNames.length > 0;
4741
+ if (includeQuery) {
4742
+ writeFilteredNavigationRecord(writer, "routeParams", options.input, options.pathParamNames);
4743
+ writeFilteredNavigationRecord(writer, "routeQuery", options.input, options.queryNames);
4744
+ } else {
4745
+ writeUnpartitionedRouteParams(writer, options.input);
4746
+ }
4747
+ writer.writeLine(
4748
+ `const isCold = await this.page.evaluate(() => typeof (globalThis as { ${POM_ROUTER_GLOBAL_NAME}?: unknown }).${POM_ROUTER_GLOBAL_NAME} === "undefined");`
4749
+ );
4750
+ writer.writeLine("if (isCold) {");
4751
+ writer.indent(() => {
4752
+ writer.writeLine('await this.page.goto("/", { waitUntil: "commit" });');
4753
+ writer.writeLine(
4754
+ `await this.page.waitForFunction(() => typeof (globalThis as { ${POM_ROUTER_GLOBAL_NAME}?: unknown }).${POM_ROUTER_GLOBAL_NAME} !== "undefined", { timeout: 15000 });`
4755
+ );
4756
+ writer.write("const href = await this.page.evaluate((");
4757
+ writeRouterBinding(writer, includeQuery);
4758
+ writer.write(") => (globalThis as ");
4759
+ writeRouterType(writer, includeQuery);
4760
+ writer.write(`).${POM_ROUTER_GLOBAL_NAME}?.resolve(`);
4761
+ writeRouterBinding(writer, includeQuery);
4762
+ writer.write(")?.href, ");
4763
+ writeRouterTarget(writer, writeRouteName, includeQuery, "routeParams", "routeQuery");
4764
+ writer.write(");").newLine();
4765
+ writer.writeLine("if (href) {");
4766
+ writer.indent(() => {
4767
+ writer.writeLine('await this.page.goto(href, { waitUntil: "domcontentloaded" });');
4768
+ });
4769
+ writer.writeLine("}");
4770
+ });
4771
+ writer.writeLine("} else {");
4772
+ writer.indent(() => {
4773
+ writer.write("await this.page.evaluate(async (");
4774
+ writeRouterBinding(writer, includeQuery);
4775
+ writer.write(") => {").newLine();
4776
+ writer.indent(() => {
4777
+ writer.write("await (globalThis as ");
4778
+ writeRouterType(writer, includeQuery);
4779
+ writer.write(`).${POM_ROUTER_GLOBAL_NAME}?.push(`);
4780
+ writeRouterBinding(writer, includeQuery);
4781
+ writer.write(");").newLine();
4782
+ });
4783
+ writer.write("}, ");
4784
+ writeRouterTarget(writer, writeRouteName, includeQuery, "routeParams", "routeQuery");
4785
+ writer.write(");").newLine();
4786
+ });
4787
+ writer.writeLine("}");
4788
+ };
4789
+ }
4790
+ function writePathParamAssignments(writer, input, pathParams) {
4791
+ for (const param of pathParams) {
4792
+ const token = getParamToken(param.name);
4793
+ if (param.optional) {
4794
+ writer.write("targetUrl = ");
4795
+ writeNavigationValue(writer, input, param.name);
4796
+ writer.write(` === undefined ? targetUrl.replaceAll(${JSON.stringify(`/${token}`)}, "") : targetUrl.replaceAll(${JSON.stringify(token)}, String(`);
4797
+ writeNavigationValue(writer, input, param.name);
4798
+ writer.write("));").newLine();
4799
+ } else {
4800
+ writer.write(`targetUrl = targetUrl.replaceAll(${JSON.stringify(token)}, String(`);
4801
+ writeNavigationValue(writer, input, param.name);
4802
+ writer.write("));").newLine();
4803
+ }
4804
+ }
4805
+ }
4806
+ function writeQueryString(writer, input, queryNames) {
4807
+ if (queryNames.length === 0) {
4808
+ return;
4809
+ }
4810
+ writer.writeLine("const routeQuery = new URLSearchParams();");
4811
+ for (const queryName of queryNames) {
4812
+ writer.write("if (");
4813
+ writeNavigationValue(writer, input, queryName);
4814
+ writer.write(" !== undefined) {").newLine();
4815
+ writer.indent(() => {
4816
+ writer.write(`routeQuery.set(${JSON.stringify(queryName)}, String(`);
4817
+ writeNavigationValue(writer, input, queryName);
4818
+ writer.write("));").newLine();
4819
+ });
4820
+ writer.writeLine("}");
4821
+ }
4822
+ writer.writeLine("const routeQueryString = routeQuery.toString();");
4823
+ writer.writeLine("if (routeQueryString) {");
4824
+ writer.indent(() => {
4825
+ writer.writeLine("targetUrl += `?${routeQueryString}`;");
4826
+ });
4827
+ writer.writeLine("}");
4828
+ }
4829
+ function writeRuntimeUrlNavigation(writer) {
4830
+ writer.writeLine(
4831
+ "const runtimeEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;"
4832
+ );
4833
+ writer.writeLine(
4834
+ "const runtimeBaseUrl = runtimeEnv?.PLAYWRIGHT_RUNTIME_BASE_URL ?? runtimeEnv?.PLAYWRIGHT_TEST_BASE_URL ?? runtimeEnv?.VITE_PLAYWRIGHT_BASE_URL;"
4835
+ );
4836
+ writer.writeLine("const resolvedUrl = runtimeBaseUrl ? new URL(targetUrl, runtimeBaseUrl).toString() : targetUrl;");
4837
+ writer.writeLine("await this.page.goto(resolvedUrl);");
4838
+ }
4839
+ function createUrlNavigationWriter(options) {
4840
+ return (writer) => {
4841
+ writeSelectionPrelude(writer, options.routeTemplate, options.input, options.pathParams.map((param) => param.name));
4842
+ if (options.routeTemplate.kind === "single") {
4843
+ writer.write(`let targetUrl = ${JSON.stringify(options.routeTemplate.target)};`).newLine();
4844
+ } else {
4845
+ writer.write("const template = ");
4846
+ writeSelectedTarget(writer, options.routeTemplate, options.input);
4847
+ writer.write(";").newLine();
4848
+ writer.writeLine("let targetUrl = template;");
4849
+ }
4850
+ if (options.pathParams.length > 0) {
4851
+ const input = requireNavigationInput(options.input, "URL navigation with path params");
4852
+ if (options.routeTemplate.kind === "dual") {
4853
+ writer.write("if (");
4854
+ writer.write(input.identifier);
4855
+ if (options.routeTemplate.selectBy === "path-param-presence") {
4856
+ writer.write(" && useParametrizedRoute");
4857
+ }
4858
+ writer.write(") {").newLine();
4859
+ writer.indent(() => {
4860
+ writePathParamAssignments(writer, input, options.pathParams);
4861
+ });
4862
+ writer.writeLine("}");
4863
+ } else {
4864
+ writePathParamAssignments(writer, input, options.pathParams);
4865
+ }
4866
+ }
4867
+ if (options.queryNames.length > 0) {
4868
+ writeQueryString(
4869
+ writer,
4870
+ requireNavigationInput(options.input, "URL navigation with query params"),
4871
+ options.queryNames
4872
+ );
4873
+ }
4874
+ writeRuntimeUrlNavigation(writer);
4875
+ };
4876
+ }
4631
4877
  const GENERATED_GITATTRIBUTES_BLOCK_START = "# BEGIN vue-pom-generator generated files";
4632
4878
  const GENERATED_GITATTRIBUTES_BLOCK_END = "# END vue-pom-generator generated files";
4633
4879
  const VUE_POM_GENERATOR_ERROR_PREFIX = "[vue-pom-generator]";
@@ -4758,7 +5004,7 @@ async function getRouteMetaByComponent(projectRoot, routerEntry, routerType, opt
4758
5004
  const map = /* @__PURE__ */ new Map();
4759
5005
  for (const entry of routeMetaEntries) {
4760
5006
  const list = map.get(entry.componentName) ?? [];
4761
- list.push({ name: entry.name, template: entry.pathTemplate, params: entry.params });
5007
+ list.push({ name: entry.name, template: entry.pathTemplate, params: entry.params, query: entry.query });
4762
5008
  map.set(entry.componentName, list);
4763
5009
  }
4764
5010
  const dedupeRoutes = (entries) => {
@@ -4797,8 +5043,37 @@ function generateRouteProperty(routeMeta) {
4797
5043
  })
4798
5044
  ];
4799
5045
  }
4800
- function buildParamTypeString(params) {
4801
- return `{ ${params.map((p) => `${p.name}${p.optional ? "?" : ""}: string | number`).join("; ")} }`;
5046
+ function formatNavigationFieldName(name) {
5047
+ return /^[$a-z_][$\w]*$/i.test(name) ? name : JSON.stringify(name);
5048
+ }
5049
+ function buildNavigationTypeString(route, requiredOptionalParamName) {
5050
+ const pathFields = route.params.map((param) => {
5051
+ const forcePresent = param.optional && param.name === requiredOptionalParamName;
5052
+ return `${formatNavigationFieldName(param.name)}${param.optional && !forcePresent ? "?" : ""}: string | number${forcePresent ? " | undefined" : ""}`;
5053
+ });
5054
+ const pathNames = new Set(route.params.map((param) => param.name));
5055
+ const queryFields = route.query.filter((query) => !pathNames.has(query)).map((query) => `${formatNavigationFieldName(query)}?: string | number`);
5056
+ return `{ ${[...pathFields, ...queryFields].join("; ")} }`;
5057
+ }
5058
+ function buildParametrizedRouteSelectionTypeString(route) {
5059
+ if (route.params.some((param) => !param.optional)) {
5060
+ return buildNavigationTypeString(route);
5061
+ }
5062
+ return route.params.map((param) => buildNavigationTypeString(route, param.name)).join(" | ");
5063
+ }
5064
+ function buildImplementationNavigationTypeString(routes) {
5065
+ const fields = /* @__PURE__ */ new Map();
5066
+ for (const route of routes) {
5067
+ for (const param of route.params) {
5068
+ fields.set(param.name, true);
5069
+ }
5070
+ for (const query of route.query) {
5071
+ if (!fields.has(query)) {
5072
+ fields.set(query, true);
5073
+ }
5074
+ }
5075
+ }
5076
+ return `{ ${Array.from(fields.keys()).map((name) => `${formatNavigationFieldName(name)}?: string | number`).join("; ")} }`;
4802
5077
  }
4803
5078
  function chooseParamlessRoute(routes) {
4804
5079
  const paramless = routes.filter((r) => r.params.length === 0);
@@ -4812,31 +5087,12 @@ function chooseParametrizedRoute(routes) {
4812
5087
  return null;
4813
5088
  return parametrized.slice().sort((a, b) => a.params.length - b.params.length || a.template.length - b.template.length || a.template.localeCompare(b.template))[0];
4814
5089
  }
4815
- const GOTO_RUNTIME_LINES = [
4816
- "const runtimeEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;",
4817
- "const runtimeBaseUrl = runtimeEnv?.PLAYWRIGHT_RUNTIME_BASE_URL ?? runtimeEnv?.PLAYWRIGHT_TEST_BASE_URL ?? runtimeEnv?.VITE_PLAYWRIGHT_BASE_URL;",
4818
- "const resolvedUrl = runtimeBaseUrl ? new URL(targetUrl, runtimeBaseUrl).toString() : targetUrl;",
4819
- "await this.page.goto(resolvedUrl);"
4820
- ];
4821
- const ROUTER_GLOBAL_NAME = "__appRouter";
4822
- const pushBlock = (routeNameExpr, paramsExpr, nullable) => {
4823
- const routerType = `{ ${ROUTER_GLOBAL_NAME}?: { push: (to: { name: string; params: Record<string, unknown> }) => Promise<unknown>; resolve: (to: { name: string; params: Record<string, unknown> }) => { href: string } } }`;
4824
- const routeParamsLine = paramsExpr === "undefined" ? "const routeParams = {};" : nullable ? `const routeParams = Object.fromEntries(Object.entries(${paramsExpr} ?? {}).filter(([, v]) => v !== undefined));` : `const routeParams = Object.fromEntries(Object.entries(${paramsExpr}).filter(([, v]) => v !== undefined));`;
4825
- return [
4826
- routeParamsLine,
4827
- `const isCold = await this.page.evaluate(() => typeof (globalThis as { ${ROUTER_GLOBAL_NAME}?: unknown }).${ROUTER_GLOBAL_NAME} === "undefined");`,
4828
- `if (isCold) {`,
4829
- ` await this.page.goto("/", { waitUntil: "commit" });`,
4830
- ` await this.page.waitForFunction(() => typeof (globalThis as { ${ROUTER_GLOBAL_NAME}?: unknown }).${ROUTER_GLOBAL_NAME} !== "undefined", { timeout: 15000 });`,
4831
- ` const href = await this.page.evaluate(({ name, params }) => (globalThis as ${routerType}).${ROUTER_GLOBAL_NAME}?.resolve({ name, params })?.href, { name: ${routeNameExpr}, params: routeParams });`,
4832
- ` if (href) { await this.page.goto(href, { waitUntil: "domcontentloaded" }); }`,
4833
- `} else {`,
4834
- ` await this.page.evaluate(async ({ name, params }) => {`,
4835
- ` await (globalThis as ${routerType}).${ROUTER_GLOBAL_NAME}?.push({ name, params });`,
4836
- ` }, { name: ${routeNameExpr}, params: routeParams });`,
4837
- `}`
4838
- ];
4839
- };
5090
+ function requireRouteName(route) {
5091
+ if (route.name === null) {
5092
+ throw new VuePomGeneratorError(`Named navigation requires a route name for template "${route.template}".`);
5093
+ }
5094
+ return route.name;
5095
+ }
4840
5096
  function generateGoToMethod(componentName, routeMeta) {
4841
5097
  if (!routeMeta) {
4842
5098
  return [
@@ -4864,29 +5120,30 @@ function generateGoToMethod(componentName, routeMeta) {
4864
5120
  })
4865
5121
  ];
4866
5122
  }
4867
- const paramStatements = (entry) => {
4868
- const lines = [];
4869
- for (const param of entry.params) {
4870
- const token = getParamToken(param.name);
4871
- if (param.optional) {
4872
- lines.push(`targetUrl = params.${param.name} === undefined ? targetUrl.replaceAll(${JSON.stringify(`/${token}`)}, "") : targetUrl.replaceAll(${JSON.stringify(token)}, String(params.${param.name}));`);
4873
- } else {
4874
- lines.push(`targetUrl = targetUrl.replaceAll(${JSON.stringify(token)}, String(params.${param.name}));`);
4875
- }
4876
- }
4877
- return lines;
4878
- };
4879
5123
  if (hasParamless && !hasParametrized) {
4880
5124
  const route = paramless;
5125
+ const hasQuery2 = route.query.length > 0;
5126
+ const paramType2 = buildNavigationTypeString(route);
4881
5127
  return [
4882
5128
  createClassMethod({
4883
5129
  name: "goTo",
4884
5130
  isAsync: true,
4885
- statements: route.name !== null ? pushBlock(JSON.stringify(route.name), "undefined", false) : [`const targetUrl = ${JSON.stringify(route.template)};`, ...GOTO_RUNTIME_LINES]
5131
+ parameters: hasQuery2 ? [{ name: "params", type: paramType2, hasQuestionToken: true }] : [],
5132
+ statements: route.name !== null ? createRouterNavigationWriter({
5133
+ routeName: { kind: "single", target: route.name },
5134
+ input: hasQuery2 ? { identifier: "params", optional: true } : void 0,
5135
+ pathParamNames: [],
5136
+ queryNames: route.query
5137
+ }) : createUrlNavigationWriter({
5138
+ routeTemplate: { kind: "single", target: route.template },
5139
+ input: hasQuery2 ? { identifier: "params", optional: true } : void 0,
5140
+ pathParams: [],
5141
+ queryNames: route.query
5142
+ })
4886
5143
  })
4887
5144
  ];
4888
5145
  }
4889
- const paramType = buildParamTypeString(parametrized.params);
5146
+ const paramType = buildNavigationTypeString(parametrized);
4890
5147
  if (hasParametrized && !hasParamless) {
4891
5148
  const route = parametrized;
4892
5149
  const allOptional = route.params.every((p) => p.optional);
@@ -4895,34 +5152,61 @@ function generateGoToMethod(componentName, routeMeta) {
4895
5152
  name: "goTo",
4896
5153
  isAsync: true,
4897
5154
  parameters: [{ name: "params", type: paramType, hasQuestionToken: allOptional }],
4898
- statements: route.name !== null ? pushBlock(JSON.stringify(route.name), "params", allOptional) : [`let targetUrl = ${JSON.stringify(route.template)};`, ...paramStatements(route), ...GOTO_RUNTIME_LINES]
5155
+ statements: route.name !== null ? createRouterNavigationWriter({
5156
+ routeName: { kind: "single", target: route.name },
5157
+ input: { identifier: "params", optional: allOptional },
5158
+ pathParamNames: route.params.map((param) => param.name),
5159
+ queryNames: route.query
5160
+ }) : createUrlNavigationWriter({
5161
+ routeTemplate: { kind: "single", target: route.template },
5162
+ input: { identifier: "params", optional: allOptional },
5163
+ pathParams: route.params,
5164
+ queryNames: route.query
5165
+ })
4899
5166
  })
4900
5167
  ];
4901
5168
  }
4902
5169
  const paramlessRoute = paramless;
4903
5170
  const parametrizedRoute = parametrized;
4904
5171
  const usePush = paramlessRoute.name !== null && parametrizedRoute.name !== null;
5172
+ const paramlessType = buildNavigationTypeString(paramlessRoute);
5173
+ const parametrizedOverloadType = buildParametrizedRouteSelectionTypeString(parametrizedRoute);
5174
+ const queryNames = Array.from(/* @__PURE__ */ new Set([...paramlessRoute.query, ...parametrizedRoute.query]));
5175
+ const hasQuery = queryNames.length > 0;
5176
+ const implementationType = hasQuery ? buildImplementationNavigationTypeString([paramlessRoute, parametrizedRoute]) : paramType;
4905
5177
  return [
4906
5178
  createClassMethod({
4907
5179
  name: "goTo",
4908
5180
  isAsync: true,
4909
5181
  overloads: [
4910
- { parameters: [], returnType: "Promise<void>" },
4911
- { parameters: [{ name: "params", type: paramType }], returnType: "Promise<void>" }
5182
+ {
5183
+ parameters: paramlessRoute.query.length ? [{ name: "params", type: paramlessType, hasQuestionToken: true }] : [],
5184
+ returnType: "Promise<void>"
5185
+ },
5186
+ { parameters: [{ name: "params", type: parametrizedOverloadType }], returnType: "Promise<void>" }
4912
5187
  ],
4913
- parameters: [{ name: "params", type: paramType, hasQuestionToken: true }],
4914
- statements: usePush ? pushBlock(
4915
- `params ? ${JSON.stringify(parametrizedRoute.name)} : ${JSON.stringify(paramlessRoute.name)}`,
4916
- "params",
4917
- true
4918
- ) : [
4919
- `const template = params ? ${JSON.stringify(parametrizedRoute.template)} : ${JSON.stringify(paramlessRoute.template)};`,
4920
- "let targetUrl = template;",
4921
- `if (params) {`,
4922
- ...paramStatements(parametrizedRoute).map((line) => ` ${line}`),
4923
- "}",
4924
- ...GOTO_RUNTIME_LINES
4925
- ]
5188
+ parameters: [{ name: "params", type: implementationType, hasQuestionToken: true }],
5189
+ statements: usePush ? createRouterNavigationWriter({
5190
+ routeName: {
5191
+ kind: "dual",
5192
+ parametrizedTarget: requireRouteName(parametrizedRoute),
5193
+ paramlessTarget: requireRouteName(paramlessRoute),
5194
+ selectBy: hasQuery ? "path-param-presence" : "input-presence"
5195
+ },
5196
+ input: { identifier: "params", optional: true },
5197
+ pathParamNames: parametrizedRoute.params.map((param) => param.name),
5198
+ queryNames: hasQuery ? queryNames : []
5199
+ }) : createUrlNavigationWriter({
5200
+ routeTemplate: {
5201
+ kind: "dual",
5202
+ parametrizedTarget: parametrizedRoute.template,
5203
+ paramlessTarget: paramlessRoute.template,
5204
+ selectBy: hasQuery ? "path-param-presence" : "input-presence"
5205
+ },
5206
+ input: { identifier: "params", optional: true },
5207
+ pathParams: parametrizedRoute.params,
5208
+ queryNames: hasQuery ? queryNames : []
5209
+ })
4926
5210
  })
4927
5211
  ];
4928
5212
  }
@@ -7989,1568 +8273,1571 @@ Fix: remove the explicit ${attrLabel}, or change existingIdBehavior to "overwrit
7989
8273
  }
7990
8274
  };
7991
8275
  }
7992
- function summarizeHierarchyMap(componentHierarchyMap) {
7993
- let interactiveComponentCount = 0;
7994
- let dataTestIdCount = 0;
7995
- for (const dependencies of componentHierarchyMap.values()) {
7996
- const selectorCount = dependencies.dataTestIdSet?.size ?? 0;
7997
- if (selectorCount > 0) {
7998
- interactiveComponentCount += 1;
7999
- dataTestIdCount += selectorCount;
8000
- }
8276
+ function supportsInlineTextAccessibleName(role) {
8277
+ return role === "button" || role === "radio";
8278
+ }
8279
+ function buildAccessibilityAudit(metadata, inferredRole) {
8280
+ if (!metadata || !inferredRole) {
8281
+ return void 0;
8282
+ }
8283
+ const role = normalizePomRoleLabel(inferredRole).toLowerCase();
8284
+ const dynamicProps = new Set(metadata.dynamicProps ?? []);
8285
+ const hasDynamicAccessibleNameSignal = dynamicProps.has("aria-label") || dynamicProps.has("title") || !!metadata.hasDynamicText;
8286
+ let accessibleNameSource;
8287
+ const reasons = [];
8288
+ if (metadata.staticAriaLabel) {
8289
+ accessibleNameSource = "aria-label";
8290
+ } else if (supportsInlineTextAccessibleName(role) && metadata.staticTextContent) {
8291
+ accessibleNameSource = "text";
8292
+ } else if (metadata.staticTitle) {
8293
+ accessibleNameSource = "title";
8294
+ } else if (hasDynamicAccessibleNameSignal) {
8295
+ accessibleNameSource = "dynamic";
8296
+ } else if (role === "input" || role === "select") {
8297
+ accessibleNameSource = "unknown";
8298
+ reasons.push("No inline accessible-name signal was found; the element may rely on external markup such as a separate <label>.");
8299
+ } else {
8300
+ accessibleNameSource = "missing";
8301
+ reasons.push("No compile-time accessible-name signal was found.");
8001
8302
  }
8002
8303
  return {
8003
- entryCount: componentHierarchyMap.size,
8004
- interactiveComponentCount,
8005
- dataTestIdCount
8304
+ needsReview: accessibleNameSource === "unknown" || accessibleNameSource === "missing",
8305
+ accessibleNameSource,
8306
+ reasons,
8307
+ ...metadata.staticAriaLabel ? { staticAriaLabel: metadata.staticAriaLabel } : {},
8308
+ ...metadata.staticRole ? { staticRole: metadata.staticRole } : {},
8309
+ ...metadata.staticTitle ? { staticTitle: metadata.staticTitle } : {},
8310
+ ...metadata.staticTextContent ? { staticTextContent: metadata.staticTextContent } : {}
8006
8311
  };
8007
8312
  }
8008
- function isLessRich(candidate, previous) {
8009
- if (candidate.dataTestIdCount !== previous.dataTestIdCount) {
8010
- return candidate.dataTestIdCount < previous.dataTestIdCount;
8313
+ function collectAccessibilityReviewWarnings(manifest) {
8314
+ const warnings = [];
8315
+ for (const [componentName, component] of Object.entries(manifest)) {
8316
+ for (const entry of component.entries) {
8317
+ if (!entry.accessibility?.needsReview) {
8318
+ continue;
8319
+ }
8320
+ const entryLabel = entry.generatedPropertyName ?? entry.testId;
8321
+ const reasonText = entry.accessibility.reasons.join(" ");
8322
+ warnings.push(
8323
+ `[vue-pom-generator] Accessibility review suggested for ${componentName}.${entryLabel} (role=${entry.inferredRole ?? "unknown"}, testId=${JSON.stringify(entry.testId)}): ${reasonText}`
8324
+ );
8325
+ }
8011
8326
  }
8012
- if (candidate.interactiveComponentCount !== previous.interactiveComponentCount) {
8013
- return candidate.interactiveComponentCount < previous.interactiveComponentCount;
8327
+ return warnings;
8328
+ }
8329
+ function findDataTestIdProp(element, attributeName = "data-testid") {
8330
+ return element.props.find(
8331
+ (prop) => prop.type === NodeTypes.ATTRIBUTE && prop.name === attributeName || prop.type === NodeTypes.DIRECTIVE && prop.name === "bind" && prop.arg?.type === NodeTypes.SIMPLE_EXPRESSION && prop.arg.content === attributeName
8332
+ );
8333
+ }
8334
+ function getTestIdFromProp(prop) {
8335
+ if (!prop) {
8336
+ return null;
8014
8337
  }
8015
- return candidate.entryCount < previous.entryCount;
8338
+ if (prop.type === NodeTypes.ATTRIBUTE) {
8339
+ return prop.value ? prop.value.content : null;
8340
+ }
8341
+ if (prop.type === NodeTypes.DIRECTIVE) {
8342
+ return prop.exp?.type === NodeTypes.SIMPLE_EXPRESSION ? prop.exp.content : null;
8343
+ }
8344
+ return null;
8016
8345
  }
8017
- function createBuildProcessorPlugin(options) {
8018
- const {
8019
- componentHierarchyMap,
8020
- crossFileKeyRegistry,
8021
- vueFilesPathMap,
8022
- getPageDirs,
8023
- getComponentDirs,
8024
- getLayoutDirs,
8025
- getViewsDir,
8026
- getSourceDirs,
8027
- basePageClassPath,
8028
- normalizedBasePagePath,
8029
- generation,
8030
- projectRootRef,
8031
- nativeWrappers,
8032
- optionKeyAttribute,
8033
- excludedComponents,
8034
- getWrapperSearchRoots,
8035
- getResolvedRouterEntry,
8036
- loggerRef
8037
- } = options;
8038
- const {
8039
- outDir,
8040
- emitLanguages,
8041
- typescriptOutputStructure,
8042
- csharp,
8043
- generateFixtures,
8044
- customPomAttachments,
8045
- customPomDir,
8046
- requireCustomPomDir,
8047
- customPomImportAliases,
8048
- customPomImportNameCollisionBehavior,
8049
- testIdAttribute,
8050
- nameCollisionBehavior,
8051
- missingSemanticNameBehavior,
8052
- existingIdBehavior,
8053
- routerAwarePoms,
8054
- routerType,
8055
- routerModuleShims
8056
- } = generation;
8057
- let lastGeneratedMetrics = {
8058
- entryCount: 0,
8059
- interactiveComponentCount: 0,
8060
- dataTestIdCount: 0
8061
- };
8062
- const getViewsDirAbs = () => path.isAbsolute(getViewsDir()) ? getViewsDir() : path.resolve(projectRootRef.current, getViewsDir());
8063
- const getPageDirsAbs = () => getPageDirs().map((dir) => path.isAbsolute(dir) ? dir : path.resolve(projectRootRef.current, dir));
8064
- const getScriptInfo = (source, filename) => {
8065
- try {
8066
- const { descriptor } = parse$1(source, { filename });
8067
- if (!descriptor.script && !descriptor.scriptSetup)
8068
- return { bindings: void 0, isScriptSetup: false };
8069
- const scriptBlock = compileScript(descriptor, { id: filename });
8070
- return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
8071
- } catch {
8072
- return { bindings: void 0, isScriptSetup: false };
8346
+ function parseDynamicProps(dynamicProps) {
8347
+ if (!dynamicProps) {
8348
+ return void 0;
8349
+ }
8350
+ if (typeof dynamicProps === "string") {
8351
+ const parts = [];
8352
+ let current = "";
8353
+ for (let i = 0; i < dynamicProps.length; i++) {
8354
+ const ch = dynamicProps[i];
8355
+ if (ch === ",") {
8356
+ const token = current.trim();
8357
+ if (token.length)
8358
+ parts.push(token);
8359
+ current = "";
8360
+ continue;
8361
+ }
8362
+ current += ch;
8073
8363
  }
8074
- };
8075
- const supplementHierarchyFromFilesystem = () => {
8076
- const walkFilesRecursive = (rootDir) => {
8077
- const out = [];
8078
- const stack = [rootDir];
8079
- while (stack.length) {
8080
- const dir = stack.pop();
8081
- if (!dir) continue;
8082
- let entries = [];
8083
- try {
8084
- entries = fs.readdirSync(dir, { withFileTypes: true });
8085
- } catch {
8086
- continue;
8087
- }
8088
- for (const ent of entries) {
8089
- if (ent.isDirectory()) {
8090
- if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
8091
- continue;
8092
- stack.push(path.join(dir, ent.name));
8093
- continue;
8094
- }
8095
- if (ent.isFile() && ent.name.endsWith(".vue")) {
8096
- out.push(path.join(dir, ent.name));
8097
- }
8098
- }
8099
- }
8100
- return out;
8101
- };
8102
- let supplemented = 0;
8103
- for (const dir of getSourceDirs()) {
8104
- const absDir = path.resolve(projectRootRef.current, dir);
8105
- if (!fs.existsSync(absDir))
8106
- continue;
8107
- for (const filePath of walkFilesRecursive(absDir)) {
8108
- const absolutePath = path.resolve(filePath);
8109
- const componentName = resolveComponentNameFromPath({
8110
- filename: absolutePath,
8111
- projectRoot: projectRootRef.current,
8112
- viewsDirAbs: getViewsDirAbs(),
8113
- sourceDirs: getSourceDirs(),
8114
- extraRoots: [process.cwd()]
8115
- });
8116
- if (componentHierarchyMap.has(componentName))
8117
- continue;
8118
- let sfc = "";
8119
- try {
8120
- sfc = fs.readFileSync(absolutePath, "utf8");
8121
- } catch {
8122
- continue;
8123
- }
8124
- const { descriptor } = parse$1(sfc, { filename: absolutePath });
8125
- const template = descriptor.template?.content ?? "";
8126
- if (!template.trim()) {
8127
- vueFilesPathMap.set(componentName, absolutePath);
8128
- componentHierarchyMap.set(componentName, {
8129
- filePath: absolutePath,
8130
- childrenComponentSet: /* @__PURE__ */ new Set(),
8131
- usedComponentSet: /* @__PURE__ */ new Set(),
8132
- dataTestIdSet: /* @__PURE__ */ new Set(),
8133
- isView: false,
8134
- methodsContent: ""
8135
- });
8136
- supplemented++;
8137
- continue;
8138
- }
8139
- const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
8140
- vueFilesPathMap.set(componentName, absolutePath);
8141
- try {
8142
- compilerDom.compile(template, {
8143
- filename: absolutePath,
8144
- prefixIdentifiers: true,
8145
- inline: isScriptSetup,
8146
- bindingMetadata,
8147
- // See dev-plugin.ts — same rationale: enable TS in template
8148
- // expressions so `(row: RowType) => ...` handlers parse.
8149
- expressionPlugins: ["typescript"],
8150
- nodeTransforms: [
8151
- createTestIdTransform(
8152
- componentName,
8153
- componentHierarchyMap,
8154
- nativeWrappers,
8155
- excludedComponents,
8156
- getViewsDirAbs(),
8157
- {
8158
- existingIdBehavior: existingIdBehavior ?? "error",
8159
- testIdAttribute,
8160
- nameCollisionBehavior,
8161
- missingSemanticNameBehavior,
8162
- warn: (message) => loggerRef.current.warn(message),
8163
- vueFilesPathMap,
8164
- wrapperSearchRoots: getWrapperSearchRoots(),
8165
- crossFileKeyRegistry,
8166
- optionKeyAttribute
8167
- }
8168
- )
8169
- ]
8170
- });
8171
- } catch {
8172
- }
8173
- supplemented++;
8364
+ const last = current.trim();
8365
+ if (last.length)
8366
+ parts.push(last);
8367
+ return parts;
8368
+ }
8369
+ if (isSimpleExpressionNode(dynamicProps)) {
8370
+ const content = dynamicProps.content;
8371
+ if (content.startsWith("[") && content.endsWith("]")) {
8372
+ try {
8373
+ return JSON.parse(content);
8374
+ } catch {
8375
+ return void 0;
8174
8376
  }
8175
8377
  }
8176
- if (supplemented > 0) {
8177
- loggerRef.current.info(`supplemented ${supplemented} components from filesystem walk (not in build graph)`);
8178
- }
8179
- };
8180
- return {
8181
- name: "vue-pom-generator-build",
8182
- // This plugin exists to generate code on build output; it is not needed during dev-server HMR.
8183
- apply: "build",
8184
- enforce: "pre",
8185
- async buildStart() {
8186
- if (!routerAwarePoms) {
8187
- setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
8188
- setResolveToComponentNameFn(() => null);
8189
- return;
8190
- }
8191
- let result;
8192
- if (routerType === "nuxt") {
8193
- result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
8194
- } else {
8195
- const resolvedRouterEntry = getResolvedRouterEntry();
8196
- if (!resolvedRouterEntry)
8197
- throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
8198
- result = await parseRouterFileFromCwd(resolvedRouterEntry, {
8199
- moduleShims: routerModuleShims,
8200
- componentNaming: {
8201
- projectRoot: projectRootRef.current,
8202
- viewsDirAbs: getViewsDirAbs(),
8203
- sourceDirs: getSourceDirs()
8204
- }
8205
- });
8206
- }
8207
- const { routeNameMap, routePathMap } = result;
8208
- setRouteNameToComponentNameMap(routeNameMap);
8209
- setResolveToComponentNameFn((to) => {
8210
- if (typeof to === "string") {
8211
- return routePathMap.get(to) ?? null;
8212
- }
8213
- const maybe = to;
8214
- if (typeof maybe.name === "string" && maybe.name.length) {
8215
- const key = toPascalCase(maybe.name);
8216
- return routeNameMap.get(key) ?? null;
8217
- }
8218
- if (typeof maybe.path === "string" && maybe.path.length) {
8219
- return routePathMap.get(maybe.path) ?? null;
8378
+ return [content];
8379
+ }
8380
+ return void 0;
8381
+ }
8382
+ function findStaticAttributeValue(element, attributeName) {
8383
+ const attribute = element.props.find(
8384
+ (prop) => prop.type === NodeTypes.ATTRIBUTE && prop.name === attributeName
8385
+ );
8386
+ const value = attribute?.value?.content?.trim();
8387
+ return value || void 0;
8388
+ }
8389
+ function collectStaticTextContent(children) {
8390
+ const parts = [];
8391
+ const visit = (nodes) => {
8392
+ for (const node of nodes) {
8393
+ if (node.type === NodeTypes.TEXT) {
8394
+ const text2 = collapseWhitespace(node.content);
8395
+ if (text2) {
8396
+ parts.push(text2);
8220
8397
  }
8221
- return null;
8222
- });
8223
- if (!fs.existsSync(basePageClassPath)) {
8224
- this.error(`Base page runtime file not found at ${basePageClassPath}. Ensure it is included in the build.`);
8225
- }
8226
- this.addWatchFile(basePageClassPath);
8227
- const pointerPath = path.resolve(path.dirname(basePageClassPath), "pointer.ts");
8228
- if (!fs.existsSync(pointerPath)) {
8229
- this.error(`pointer.ts not found at ${pointerPath}. Ensure it is included in the build.`);
8230
- }
8231
- this.addWatchFile(pointerPath);
8232
- const calloutPath = path.resolve(path.dirname(basePageClassPath), "callout.ts");
8233
- if (!fs.existsSync(calloutPath)) {
8234
- this.error(`callout.ts not found at ${calloutPath}. Ensure it is included in the build.`);
8235
- }
8236
- this.addWatchFile(calloutPath);
8237
- const floatingUiCalloutPath = path.resolve(path.dirname(basePageClassPath), "floating-ui-callout.ts");
8238
- if (fs.existsSync(floatingUiCalloutPath)) {
8239
- this.addWatchFile(floatingUiCalloutPath);
8240
- }
8241
- },
8242
- async buildEnd(error) {
8243
- if (error) {
8244
- return;
8245
- }
8246
- supplementHierarchyFromFilesystem();
8247
- const metrics = summarizeHierarchyMap(componentHierarchyMap);
8248
- if (metrics.dataTestIdCount <= 0) {
8249
- return;
8398
+ continue;
8250
8399
  }
8251
- if (isLessRich(metrics, lastGeneratedMetrics)) {
8252
- return;
8400
+ if (node.type === NodeTypes.ELEMENT) {
8401
+ visit(node.children);
8253
8402
  }
8254
- await generateFiles(componentHierarchyMap, vueFilesPathMap, normalizedBasePagePath, {
8255
- outDir,
8256
- emitLanguages,
8257
- typescriptOutputStructure,
8258
- csharp,
8259
- generateFixtures,
8260
- customPomAttachments,
8261
- projectRoot: projectRootRef.current,
8262
- customPomDir,
8263
- requireCustomPomDir,
8264
- customPomImportAliases,
8265
- customPomImportNameCollisionBehavior,
8266
- testIdAttribute,
8267
- vueRouterFluentChaining: routerAwarePoms,
8268
- routerEntry: getResolvedRouterEntry(),
8269
- routerType,
8270
- pageDirs: getPageDirs(),
8271
- componentDirs: getComponentDirs(),
8272
- layoutDirs: getLayoutDirs()
8273
- });
8274
- lastGeneratedMetrics = metrics;
8275
- loggerRef.current.info(`generated POMs (${metrics.entryCount} entries, ${metrics.interactiveComponentCount} interactive components, ${metrics.dataTestIdCount} selectors)`);
8276
- },
8277
- closeBundle() {
8278
- loggerRef.current.info("build complete");
8279
8403
  }
8280
8404
  };
8405
+ visit(children);
8406
+ const text = collapseWhitespace(parts.join(" "));
8407
+ return text || void 0;
8281
8408
  }
8282
- function createDevProcessorPlugin(options) {
8283
- const {
8284
- nativeWrappers,
8285
- optionKeyAttribute,
8286
- excludedComponents,
8287
- getPageDirs,
8288
- getComponentDirs,
8289
- getLayoutDirs,
8290
- getViewsDir,
8291
- getSourceDirs,
8292
- getWrapperSearchRoots,
8293
- projectRootRef,
8294
- normalizedBasePagePath,
8295
- basePageClassPath,
8296
- generation,
8297
- getResolvedRouterEntry,
8298
- loggerRef
8299
- } = options;
8300
- const {
8301
- outDir,
8302
- emitLanguages,
8303
- typescriptOutputStructure,
8304
- csharp,
8305
- generateFixtures,
8306
- customPomAttachments,
8307
- customPomDir,
8308
- requireCustomPomDir,
8309
- customPomImportAliases,
8310
- customPomImportNameCollisionBehavior,
8311
- nameCollisionBehavior,
8312
- missingSemanticNameBehavior,
8313
- existingIdBehavior,
8314
- testIdAttribute,
8315
- routerAwarePoms,
8316
- routerType,
8317
- routerModuleShims
8318
- } = generation;
8319
- let scheduleVueFileRegen = null;
8320
- const getProjectRootCandidates = () => Array.from(/* @__PURE__ */ new Set([
8321
- path.resolve(projectRootRef.current),
8322
- path.resolve(process.cwd())
8409
+ function tryCreateElementMetadata(args) {
8410
+ const { element, semanticNameMap } = args;
8411
+ const testIdAttribute = (args.testIdAttribute ?? "data-testid").trim() || "data-testid";
8412
+ const testIdProp = findDataTestIdProp(element, testIdAttribute);
8413
+ if (!testIdProp) {
8414
+ return null;
8415
+ }
8416
+ const testId = getTestIdFromProp(testIdProp);
8417
+ if (!testId) {
8418
+ return null;
8419
+ }
8420
+ if (!element.codegenNode || element.codegenNode.type !== NodeTypes.VNODE_CALL) {
8421
+ return null;
8422
+ }
8423
+ const codegenNode = element.codegenNode;
8424
+ const patchFlag = codegenNode.patchFlag;
8425
+ let dynamicPropsList = parseDynamicProps(codegenNode.dynamicProps);
8426
+ if (!dynamicPropsList && codegenNode.dynamicProps && typeof codegenNode.dynamicProps !== "string" && isSimpleExpressionNode(codegenNode.dynamicProps)) {
8427
+ const content = codegenNode.dynamicProps.content;
8428
+ if (content.startsWith("[") && content.endsWith("]")) {
8429
+ dynamicPropsList = [content];
8430
+ }
8431
+ }
8432
+ const metadata = {
8433
+ testId,
8434
+ semanticName: semanticNameMap.get(testId),
8435
+ tag: element.tag,
8436
+ tagType: element.tagType,
8437
+ patchFlag,
8438
+ dynamicProps: dynamicPropsList,
8439
+ // Decode patch flags (bitwise) - preserved as-is from existing code.
8440
+ hasClickHandler: patchFlag ? Boolean(patchFlag & 32) : void 0,
8441
+ hasDynamicClass: patchFlag ? Boolean(patchFlag & 2) : void 0,
8442
+ hasDynamicStyle: patchFlag ? Boolean(patchFlag & 4) : void 0,
8443
+ hasDynamicText: patchFlag ? Boolean(patchFlag & 1) : void 0,
8444
+ staticAriaLabel: findStaticAttributeValue(element, "aria-label"),
8445
+ staticRole: findStaticAttributeValue(element, "role"),
8446
+ staticTitle: findStaticAttributeValue(element, "title"),
8447
+ staticTextContent: collectStaticTextContent(element.children),
8448
+ sourceLine: element.loc?.start.line,
8449
+ sourceColumn: element.loc?.start.column
8450
+ };
8451
+ return metadata;
8452
+ }
8453
+ function matchesPrimarySelector(extraMethod, pom) {
8454
+ if (extraMethod.selector.kind !== "testId") {
8455
+ return false;
8456
+ }
8457
+ return extraMethod.selector.testId.formatted === pom.selector.formatted && extraMethod.selector.testId.patternKind === pom.selector.patternKind;
8458
+ }
8459
+ function getManifestEntry(componentName, entry, componentMetadata, extraMethods) {
8460
+ const testId = entry.selectorValue.formatted;
8461
+ const metadata = componentMetadata?.get(testId);
8462
+ const pom = entry.pom;
8463
+ const generatedActionName = pom ? buildPomGeneratedActionName(pom) : null;
8464
+ const extraActionNames = pom ? extraMethods.filter((extraMethod) => matchesPrimarySelector(extraMethod, pom)).map((extraMethod) => extraMethod.name).sort((a, b) => a.localeCompare(b)) : [];
8465
+ const generatedActionNames = Array.from(/* @__PURE__ */ new Set([
8466
+ ...generatedActionName ? [generatedActionName] : [],
8467
+ ...extraActionNames.filter((name) => name !== generatedActionName)
8323
8468
  ]));
8324
- const resolveProjectPath = (maybePath) => {
8325
- if (path.isAbsolute(maybePath))
8326
- return maybePath;
8327
- const candidates = getProjectRootCandidates().map((root) => path.resolve(root, maybePath));
8328
- return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0];
8469
+ const accessibility = buildAccessibilityAudit(metadata, pom?.nativeRole ?? null);
8470
+ return {
8471
+ testId,
8472
+ selectorPatternKind: entry.selectorValue.patternKind,
8473
+ semanticName: metadata?.semanticName ?? (pom ? humanizePomMethodName(pom.methodName) : testId),
8474
+ locatorDescription: pom ? buildPomLocatorDescription({
8475
+ componentName,
8476
+ methodName: pom.methodName,
8477
+ nativeRole: pom.nativeRole
8478
+ }) : componentName,
8479
+ inferredRole: pom?.nativeRole ?? null,
8480
+ ...accessibility ? { accessibility } : {},
8481
+ generatedPropertyName: pom ? buildPomGeneratedPropertyName(pom) : null,
8482
+ generatedActionName,
8483
+ generatedActionNames,
8484
+ emitPrimary: pom?.emitPrimary !== false,
8485
+ ...entry.targetPageObjectModelClass ? { targetPageObjectModelClass: entry.targetPageObjectModelClass } : {},
8486
+ ...metadata?.tag ? { sourceTag: metadata.tag } : {},
8487
+ ...metadata ? { sourceTagType: metadata.tagType } : {},
8488
+ ...metadata?.sourceLine !== void 0 ? { sourceLine: metadata.sourceLine } : {},
8489
+ ...metadata?.sourceColumn !== void 0 ? { sourceColumn: metadata.sourceColumn } : {},
8490
+ ...metadata?.patchFlag !== void 0 ? { patchFlag: metadata.patchFlag } : {},
8491
+ ...metadata?.dynamicProps?.length ? { dynamicProps: metadata.dynamicProps } : {},
8492
+ ...metadata?.hasClickHandler !== void 0 ? { hasClickHandler: metadata.hasClickHandler } : {},
8493
+ ...metadata?.hasDynamicClass !== void 0 ? { hasDynamicClass: metadata.hasDynamicClass } : {},
8494
+ ...metadata?.hasDynamicStyle !== void 0 ? { hasDynamicStyle: metadata.hasDynamicStyle } : {},
8495
+ ...metadata?.hasDynamicText !== void 0 ? { hasDynamicText: metadata.hasDynamicText } : {}
8329
8496
  };
8330
- const getSourceDirRoots = () => Array.from(new Set(
8331
- getProjectRootCandidates().flatMap((root) => getSourceDirs().map((dir) => path.resolve(root, dir)))
8332
- ));
8333
- const isContainedInScanDirs = (filePath) => {
8334
- const absolutePath = path.resolve(filePath);
8335
- return getSourceDirRoots().some((scanDirAbs) => isPathWithinDir(absolutePath, scanDirAbs));
8497
+ }
8498
+ function buildPomManifest(componentHierarchyMap, elementMetadata) {
8499
+ const manifestEntries = Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8500
+ const entries = Array.from(dependencies.dataTestIdSet).sort((a, b) => a.selectorValue.formatted.localeCompare(b.selectorValue.formatted)).map((entry) => getManifestEntry(componentName, entry, elementMetadata.get(componentName), dependencies.pomExtraMethods ?? []));
8501
+ if (!entries.length) {
8502
+ return null;
8503
+ }
8504
+ return [componentName, {
8505
+ componentName,
8506
+ className: componentName,
8507
+ sourceFile: dependencies.filePath,
8508
+ kind: dependencies.isView ? "view" : "component",
8509
+ testIds: Array.from(new Set(entries.map((entry) => entry.testId))),
8510
+ entries
8511
+ }];
8512
+ }).filter((entry) => entry !== null);
8513
+ return Object.fromEntries(manifestEntries);
8514
+ }
8515
+ function buildTestIdManifest(componentHierarchyMap) {
8516
+ return Object.fromEntries(
8517
+ Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8518
+ const testIds = Array.from(dependencies.dataTestIdSet).map((entry) => entry.selectorValue.formatted).filter(Boolean);
8519
+ if (!testIds.length) {
8520
+ return null;
8521
+ }
8522
+ return [componentName, Array.from(new Set(testIds)).sort((a, b) => a.localeCompare(b))];
8523
+ }).filter((entry) => entry !== null)
8524
+ );
8525
+ }
8526
+ function writeConstJson(value) {
8527
+ return (writer) => {
8528
+ writer.write(`${JSON.stringify(value, null, 2)} as const`);
8336
8529
  };
8337
- return {
8338
- name: "vue-pom-generator-dev",
8339
- apply: "serve",
8340
- // Prefer hot-update events over filesystem change events for speed and reliability.
8341
- // This fires when Vite has actually processed the module update.
8342
- handleHotUpdate(ctx) {
8343
- if (!scheduleVueFileRegen)
8344
- return;
8345
- if (!ctx.file.endsWith(".vue"))
8346
- return;
8347
- if (!isContainedInScanDirs(ctx.file))
8348
- return;
8349
- scheduleVueFileRegen(ctx.file, "hmr");
8350
- },
8351
- async configureServer(server) {
8352
- const getViewsDirAbs = () => resolveProjectPath(getViewsDir());
8353
- const getPageDirsAbs = () => getPageDirs().map((dir) => resolveProjectPath(dir));
8354
- const routerInitPromise = (async () => {
8355
- if (!routerAwarePoms) {
8356
- setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
8357
- setResolveToComponentNameFn(() => null);
8358
- return;
8530
+ }
8531
+ function generateTestIdsModule(componentHierarchyMap, elementMetadata) {
8532
+ const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8533
+ const testIdManifest = buildTestIdManifest(componentHierarchyMap);
8534
+ return renderSourceFile("virtual-testids.ts", (sourceFile) => {
8535
+ sourceFile.addStatements("// Virtual module: test id manifest");
8536
+ sourceFile.addVariableStatement({
8537
+ declarationKind: VariableDeclarationKind.Const,
8538
+ isExported: true,
8539
+ declarations: [{
8540
+ name: "testIdManifest",
8541
+ initializer: writeConstJson(testIdManifest)
8542
+ }]
8543
+ });
8544
+ sourceFile.addVariableStatement({
8545
+ declarationKind: VariableDeclarationKind.Const,
8546
+ isExported: true,
8547
+ declarations: [{
8548
+ name: "pomManifest",
8549
+ initializer: writeConstJson(pomManifest)
8550
+ }]
8551
+ });
8552
+ sourceFile.addTypeAlias({
8553
+ isExported: true,
8554
+ name: "TestIdManifest",
8555
+ type: "typeof testIdManifest"
8556
+ });
8557
+ sourceFile.addTypeAlias({
8558
+ isExported: true,
8559
+ name: "ComponentName",
8560
+ type: "keyof TestIdManifest"
8561
+ });
8562
+ sourceFile.addTypeAlias({
8563
+ isExported: true,
8564
+ name: "PomManifest",
8565
+ type: "typeof pomManifest"
8566
+ });
8567
+ sourceFile.addTypeAlias({
8568
+ isExported: true,
8569
+ name: "PomManifestComponentName",
8570
+ type: "keyof PomManifest"
8571
+ });
8572
+ });
8573
+ }
8574
+ function generatePomManifestModule(componentHierarchyMap, elementMetadata) {
8575
+ const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8576
+ return renderSourceFile("virtual-pom-manifest.ts", (sourceFile) => {
8577
+ sourceFile.addStatements("// Virtual module: richer POM discoverability manifest");
8578
+ sourceFile.addVariableStatement({
8579
+ declarationKind: VariableDeclarationKind.Const,
8580
+ isExported: true,
8581
+ declarations: [{
8582
+ name: "pomManifest",
8583
+ initializer: writeConstJson(pomManifest)
8584
+ }]
8585
+ });
8586
+ sourceFile.addTypeAlias({
8587
+ isExported: true,
8588
+ name: "PomManifest",
8589
+ type: "typeof pomManifest"
8590
+ });
8591
+ sourceFile.addTypeAlias({
8592
+ isExported: true,
8593
+ name: "PomManifestComponentName",
8594
+ type: "keyof PomManifest"
8595
+ });
8596
+ });
8597
+ }
8598
+ function resolveExistingIdBehavior(config, componentName) {
8599
+ return typeof config === "string" ? config : config.components[componentName] ?? config.default;
8600
+ }
8601
+ function resolveCompilerSfcParse(compilerSfc) {
8602
+ const parse2 = compilerSfc.parse ?? compilerSfc.default?.parse;
8603
+ if (typeof parse2 !== "function") {
8604
+ throw new TypeError("[vue-pom-generator] Failed to resolve @vue/compiler-sfc.parse.");
8605
+ }
8606
+ return parse2;
8607
+ }
8608
+ function extractMetadataAfterTransform(ast, componentName, elementMetadata, semanticNameMap, testIdAttribute) {
8609
+ const componentMetadata = /* @__PURE__ */ new Map();
8610
+ function traverseNode(node) {
8611
+ if (node.type === NodeTypes.ELEMENT) {
8612
+ const element = node;
8613
+ const testIdAttr = findDataTestIdProp(element, testIdAttribute);
8614
+ if (testIdAttr) {
8615
+ const metadata = tryCreateElementMetadata({
8616
+ element,
8617
+ semanticNameMap,
8618
+ testIdAttribute
8619
+ });
8620
+ if (metadata) {
8621
+ componentMetadata.set(metadata.testId, metadata);
8359
8622
  }
8360
- let result;
8361
- if (routerType === "nuxt") {
8362
- result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
8363
- } else {
8364
- const resolvedRouterEntry = getResolvedRouterEntry();
8365
- if (!resolvedRouterEntry)
8366
- throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
8367
- result = await parseRouterFileFromCwd(resolvedRouterEntry, {
8368
- moduleShims: routerModuleShims,
8369
- componentNaming: {
8370
- projectRoot: projectRootRef.current,
8371
- viewsDirAbs: getViewsDirAbs(),
8372
- sourceDirs: getSourceDirs(),
8373
- extraRoots: [process.cwd()]
8374
- }
8375
- });
8376
- }
8377
- const { routeNameMap, routePathMap } = result;
8378
- setRouteNameToComponentNameMap(routeNameMap);
8379
- setResolveToComponentNameFn((to) => {
8380
- if (typeof to === "string") {
8381
- return routePathMap.get(to) ?? null;
8382
- }
8383
- const maybe = to;
8384
- if (typeof maybe.name === "string" && maybe.name.length) {
8385
- const key = toPascalCase(maybe.name);
8386
- return routeNameMap.get(key) ?? null;
8387
- }
8388
- if (typeof maybe.path === "string" && maybe.path.length) {
8389
- return routePathMap.get(maybe.path) ?? null;
8390
- }
8391
- return null;
8392
- });
8393
- })();
8394
- const logInfo = (message) => loggerRef.current.info(message);
8395
- const logDebug = (message) => loggerRef.current.debug(message);
8396
- let scheduleVueFileRegenLocal = null;
8397
- const formatMs = (ms) => `${ms.toFixed(1)}ms`;
8398
- const extractTemplateFromSfc = (source, filename) => {
8399
- const { descriptor } = parse$1(source, {
8400
- filename: filename ?? "anonymous.vue"
8401
- });
8402
- return descriptor.template?.content ?? "";
8403
- };
8404
- const getScriptInfo = (source, filename) => {
8405
- try {
8406
- const { descriptor } = parse$1(source, { filename });
8407
- if (!descriptor.script && !descriptor.scriptSetup)
8408
- return { bindings: void 0, isScriptSetup: false };
8409
- const scriptBlock = compileScript(descriptor, { id: filename });
8410
- return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
8411
- } catch {
8412
- return { bindings: void 0, isScriptSetup: false };
8413
- }
8414
- };
8415
- const walkFilesRecursive = (rootDir) => {
8416
- const out = [];
8417
- const stack = [rootDir];
8418
- while (stack.length) {
8419
- const dir = stack.pop();
8420
- if (!dir) continue;
8421
- let entries = [];
8422
- try {
8423
- entries = fs.readdirSync(dir, { withFileTypes: true });
8424
- } catch {
8425
- continue;
8426
- }
8427
- for (const ent of entries) {
8428
- if (ent.isDirectory()) {
8429
- if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
8430
- continue;
8431
- stack.push(path.join(dir, ent.name));
8432
- continue;
8433
- }
8434
- if (ent.isFile() && ent.name.endsWith(".vue")) {
8435
- out.push(path.join(dir, ent.name));
8436
- }
8437
- }
8438
- }
8439
- return out;
8440
- };
8441
- let snapshotHierarchy = /* @__PURE__ */ new Map();
8442
- let snapshotVuePathMap = /* @__PURE__ */ new Map();
8443
- const filePathToComponentName = /* @__PURE__ */ new Map();
8444
- const createEmptyComponentDependencies = (absolutePath) => {
8445
- const viewsDirAbs = path.resolve(getViewsDirAbs());
8446
- const relToViewsDir = path.relative(viewsDirAbs, absolutePath);
8447
- const isView = !relToViewsDir.startsWith("..") && !path.isAbsolute(relToViewsDir);
8448
- return {
8449
- filePath: absolutePath,
8450
- childrenComponentSet: /* @__PURE__ */ new Set(),
8451
- usedComponentSet: /* @__PURE__ */ new Set(),
8452
- dataTestIdSet: /* @__PURE__ */ new Set(),
8453
- isView,
8454
- methodsContent: ""
8455
- };
8456
- };
8457
- const getComponentNameForFile = (filePath) => {
8458
- const normalized = path.resolve(filePath);
8459
- const existing = filePathToComponentName.get(normalized);
8460
- if (existing)
8461
- return existing;
8462
- const name = resolveComponentNameFromPath({
8463
- filename: normalized,
8464
- projectRoot: projectRootRef.current,
8465
- viewsDirAbs: getViewsDirAbs(),
8466
- sourceDirs: getSourceDirs(),
8467
- extraRoots: [process.cwd()]
8468
- });
8469
- filePathToComponentName.set(normalized, name);
8470
- return name;
8471
- };
8472
- const compileVueFileIntoSnapshot = (filePath, targetHierarchy = snapshotHierarchy, targetVuePathMap = snapshotVuePathMap) => {
8473
- const started = performance.now();
8474
- const absolutePath = path.resolve(filePath);
8475
- const componentName = getComponentNameForFile(absolutePath);
8476
- let sfc = "";
8477
- try {
8478
- sfc = fs.readFileSync(absolutePath, "utf8");
8479
- } catch {
8480
- return { componentName, ms: performance.now() - started, compiled: false };
8623
+ }
8624
+ if (element.children) {
8625
+ for (const child of element.children) {
8626
+ traverseNode(child);
8481
8627
  }
8482
- const template = extractTemplateFromSfc(sfc, absolutePath);
8483
- if (!template.trim()) {
8484
- targetVuePathMap.set(componentName, absolutePath);
8485
- targetHierarchy.set(componentName, createEmptyComponentDependencies(absolutePath));
8486
- return { componentName, ms: performance.now() - started, compiled: true };
8628
+ }
8629
+ } else if (node.type === NodeTypes.IF) {
8630
+ for (const branch of node.branches) {
8631
+ traverseNode(branch);
8632
+ }
8633
+ } else if (node.type === NodeTypes.IF_BRANCH || node.type === NodeTypes.FOR) {
8634
+ if (node.children) {
8635
+ for (const child of node.children) {
8636
+ traverseNode(child);
8487
8637
  }
8488
- const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
8489
- const provisionalHierarchy = /* @__PURE__ */ new Map();
8490
- const provisionalKeyRegistry = /* @__PURE__ */ new Map();
8491
- const provisionalVuePathMap = new Map(targetVuePathMap);
8492
- provisionalVuePathMap.set(componentName, absolutePath);
8493
- compilerDom.compile(template, {
8494
- filename: absolutePath,
8495
- prefixIdentifiers: true,
8496
- inline: isScriptSetup,
8497
- bindingMetadata,
8498
- // Vue templates may contain TypeScript type annotations in expressions
8499
- // (e.g. `@row-click="(row: RowType) => navigateTo(...)"` in Nuxt + TS
8500
- // apps). Without this flag, Vue's internal processExpression step
8501
- // delegates to @babel/parser without the TS plugin and crashes on
8502
- // "Unexpected token, expected ','".
8503
- expressionPlugins: ["typescript"],
8504
- nodeTransforms: [
8638
+ }
8639
+ } else if (node.type === NodeTypes.ROOT) {
8640
+ for (const child of node.children) {
8641
+ traverseNode(child);
8642
+ }
8643
+ }
8644
+ }
8645
+ traverseNode(ast);
8646
+ if (componentMetadata.size > 0) {
8647
+ elementMetadata.set(componentName, componentMetadata);
8648
+ }
8649
+ return componentMetadata;
8650
+ }
8651
+ function createVuePluginWithTestIds(options) {
8652
+ const {
8653
+ vueOptions,
8654
+ existingIdBehavior,
8655
+ nameCollisionBehavior,
8656
+ missingSemanticNameBehavior = "error",
8657
+ nativeWrappers,
8658
+ optionKeyAttribute,
8659
+ elementMetadata,
8660
+ semanticNameMap,
8661
+ componentHierarchyMap,
8662
+ crossFileKeyRegistry,
8663
+ vueFilesPathMap,
8664
+ excludedComponents,
8665
+ getViewsDirAbs,
8666
+ testIdAttribute,
8667
+ accessibilityAudit,
8668
+ loggerRef,
8669
+ getSourceDirs,
8670
+ getWrapperSearchRoots,
8671
+ getProjectRoot,
8672
+ annotatorMetadata
8673
+ } = options;
8674
+ const lastAccessibilityWarningSignatureByComponent = /* @__PURE__ */ new Map();
8675
+ const getComponentNameFromPath = (filename) => {
8676
+ return resolveComponentNameFromPath({
8677
+ filename,
8678
+ projectRoot: getProjectRoot(),
8679
+ viewsDirAbs: getViewsDirAbs(),
8680
+ sourceDirs: getSourceDirs(),
8681
+ extraRoots: [process.cwd()]
8682
+ });
8683
+ };
8684
+ const isFileInScope = (filename) => {
8685
+ if (!filename)
8686
+ return false;
8687
+ const cleanPath = filename.includes("?") ? filename.substring(0, filename.indexOf("?")) : filename;
8688
+ const projectRoot = getProjectRoot();
8689
+ const matched = isFileInConfiguredSourceScope({
8690
+ filename,
8691
+ projectRoot,
8692
+ viewsDirAbs: getViewsDirAbs(),
8693
+ sourceDirs: getSourceDirs(),
8694
+ extraRoots: [process.cwd()]
8695
+ });
8696
+ if (cleanPath.endsWith(".vue") && !matched) {
8697
+ const absFilename = path.normalize(path.isAbsolute(cleanPath) ? cleanPath : path.resolve(projectRoot, cleanPath));
8698
+ loggerRef.current.debug(`[isFileInScope] REJECTED: ${absFilename} (Clean: ${cleanPath})`);
8699
+ }
8700
+ return matched;
8701
+ };
8702
+ const userTemplate = vueOptions?.template ?? {};
8703
+ const userCompilerOptions = userTemplate.compilerOptions ?? {};
8704
+ const userNodeTransforms = userCompilerOptions.nodeTransforms ?? [];
8705
+ const perFileTransform = /* @__PURE__ */ new Map();
8706
+ const getNodeTransforms = (filename, componentNameOverride) => {
8707
+ const cleanPath = filename.includes("?") ? filename.substring(0, filename.indexOf("?")) : filename;
8708
+ const viewsDirAbs = getViewsDirAbs();
8709
+ const componentName = componentNameOverride || getComponentNameFromPath(cleanPath);
8710
+ return [
8711
+ ...userNodeTransforms,
8712
+ (node, context) => {
8713
+ if (node.type === NodeTypes.ROOT) {
8714
+ componentHierarchyMap.delete(componentName);
8715
+ vueFilesPathMap.set(componentName, filename);
8716
+ perFileTransform.set(
8717
+ componentName,
8505
8718
  createTestIdTransform(
8506
8719
  componentName,
8507
- provisionalHierarchy,
8720
+ componentHierarchyMap,
8508
8721
  nativeWrappers,
8509
8722
  excludedComponents,
8510
- getViewsDirAbs(),
8723
+ viewsDirAbs,
8511
8724
  {
8512
- existingIdBehavior: existingIdBehavior ?? "error",
8725
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
8726
+ testIdAttribute,
8513
8727
  nameCollisionBehavior,
8514
8728
  missingSemanticNameBehavior,
8515
- testIdAttribute,
8516
8729
  warn: (message) => loggerRef.current.warn(message),
8517
- vueFilesPathMap: provisionalVuePathMap,
8730
+ vueFilesPathMap,
8518
8731
  wrapperSearchRoots: getWrapperSearchRoots(),
8519
- crossFileKeyRegistry: provisionalKeyRegistry,
8732
+ annotatorMetadata,
8733
+ crossFileKeyRegistry,
8520
8734
  optionKeyAttribute
8521
8735
  }
8522
8736
  )
8523
- ]
8524
- });
8525
- targetVuePathMap.set(componentName, absolutePath);
8526
- targetHierarchy.set(
8527
- componentName,
8528
- provisionalHierarchy.get(componentName) ?? createEmptyComponentDependencies(absolutePath)
8529
- );
8530
- return { componentName, ms: performance.now() - started, compiled: true };
8531
- };
8532
- const fullRebuildSnapshotFromFilesystem = (logLabel) => {
8533
- const t0 = performance.now();
8534
- const nextHierarchy = /* @__PURE__ */ new Map();
8535
- const nextVuePathMap = /* @__PURE__ */ new Map();
8536
- filePathToComponentName.clear();
8537
- let totalVueFiles = 0;
8538
- let compiledCount = 0;
8539
- for (const absDir of getSourceDirRoots()) {
8540
- if (!fs.existsSync(absDir))
8541
- continue;
8542
- const vueFiles = walkFilesRecursive(absDir);
8543
- totalVueFiles += vueFiles.length;
8544
- for (const file of vueFiles) {
8545
- const res = compileVueFileIntoSnapshot(file, nextHierarchy, nextVuePathMap);
8546
- if (res.compiled)
8547
- compiledCount++;
8548
- }
8549
- }
8550
- snapshotHierarchy = nextHierarchy;
8551
- snapshotVuePathMap = nextVuePathMap;
8552
- const t1 = performance.now();
8553
- logInfo(`scan(${logLabel}): found ${totalVueFiles} .vue files in ${getSourceDirs().join(", ")}`);
8554
- logInfo(`compile(${logLabel}): ${compiledCount}/${totalVueFiles} files in ${formatMs(t1 - t0)} (components=${snapshotHierarchy.size})`);
8555
- };
8556
- const generateAggregatedFromSnapshot = async (logLabel) => {
8557
- const t0 = performance.now();
8558
- await generateFiles(snapshotHierarchy, snapshotVuePathMap, normalizedBasePagePath, {
8559
- outDir,
8560
- emitLanguages,
8561
- typescriptOutputStructure,
8562
- csharp,
8563
- generateFixtures,
8564
- customPomAttachments,
8565
- projectRoot: projectRootRef.current,
8566
- customPomDir,
8567
- requireCustomPomDir,
8568
- customPomImportAliases,
8569
- customPomImportNameCollisionBehavior,
8570
- pageDirs: getPageDirs(),
8571
- componentDirs: getComponentDirs(),
8572
- layoutDirs: getLayoutDirs(),
8573
- testIdAttribute,
8574
- vueRouterFluentChaining: routerAwarePoms,
8575
- routerEntry: getResolvedRouterEntry(),
8576
- routerType
8577
- });
8578
- const t1 = performance.now();
8579
- logInfo(`generate(${logLabel}): components=${snapshotHierarchy.size} in ${formatMs(t1 - t0)}`);
8580
- };
8581
- let timer = null;
8582
- let maxWaitTimer = null;
8583
- const pendingChangedVueFiles = /* @__PURE__ */ new Set();
8584
- const pendingDeletedComponents = /* @__PURE__ */ new Set();
8585
- let regenerationSequence = Promise.resolve();
8586
- const initialBuildPromise = (async () => {
8587
- const t0 = performance.now();
8588
- await routerInitPromise;
8589
- fullRebuildSnapshotFromFilesystem("startup");
8590
- await generateAggregatedFromSnapshot("startup");
8591
- const t1 = performance.now();
8592
- logInfo(`startup total: ${formatMs(t1 - t0)}`);
8593
- })();
8594
- const logGenerationError = (reason, message) => {
8595
- server.config.logger.error(`[vue-pom-generator] dev generation failed during ${reason}: ${message}`);
8596
- };
8597
- const regenerateFromPending = async (reason) => {
8598
- const t0 = performance.now();
8599
- await initialBuildPromise;
8600
- const nextHierarchy = new Map(snapshotHierarchy);
8601
- const nextVuePathMap = new Map(snapshotVuePathMap);
8602
- for (const componentName of pendingDeletedComponents) {
8603
- nextHierarchy.delete(componentName);
8604
- nextVuePathMap.delete(componentName);
8605
- }
8606
- const files = Array.from(pendingChangedVueFiles);
8607
- const deletedCount = pendingDeletedComponents.size;
8608
- pendingChangedVueFiles.clear();
8609
- pendingDeletedComponents.clear();
8610
- let compileMs = 0;
8611
- for (const f of files) {
8612
- const res = compileVueFileIntoSnapshot(f, nextHierarchy, nextVuePathMap);
8613
- compileMs += res.ms;
8614
- }
8615
- snapshotHierarchy = nextHierarchy;
8616
- snapshotVuePathMap = nextVuePathMap;
8617
- const t1 = performance.now();
8618
- await generateAggregatedFromSnapshot(reason);
8619
- const t2 = performance.now();
8620
- return {
8621
- files,
8622
- deletedCount,
8623
- compileMs,
8624
- preGenerateMs: t1 - t0,
8625
- generateMs: t2 - t1,
8626
- totalMs: t2 - t0
8627
- };
8628
- };
8629
- const enqueueRegeneration = (reason) => {
8630
- const currentRun = regenerationSequence.catch(() => void 0).then(() => regenerateFromPending(reason));
8631
- regenerationSequence = currentRun.then(() => void 0, () => void 0);
8632
- return currentRun;
8633
- };
8634
- const runtimeDir = path.dirname(basePageClassPath);
8635
- const localPluginDir = path.resolve(projectRootRef.current, "vite-plugins", "vue-pom-generator");
8636
- server.watcher.add([
8637
- ...fs.existsSync(localPluginDir) ? [localPluginDir] : [],
8638
- basePageClassPath,
8639
- path.resolve(runtimeDir, "pointer.ts"),
8640
- path.resolve(runtimeDir, "callout.ts"),
8641
- path.resolve(runtimeDir, "floating-ui-callout.ts")
8642
- ]);
8643
- scheduleVueFileRegenLocal = (filePath, source) => {
8644
- pendingChangedVueFiles.add(filePath);
8645
- logDebug(`queued(${source}): files=${pendingChangedVueFiles.size} deleted=${pendingDeletedComponents.size}`);
8646
- scheduleAggregatedRegen();
8647
- };
8648
- scheduleVueFileRegen = scheduleVueFileRegenLocal;
8649
- function scheduleAggregatedRegen() {
8650
- const wasEmpty = pendingChangedVueFiles.size === 0 && pendingDeletedComponents.size === 0;
8651
- const MAX_WAIT_MS = 750;
8652
- if (!maxWaitTimer) {
8653
- maxWaitTimer = setTimeout(() => {
8654
- if (timer) {
8655
- clearTimeout(timer);
8656
- timer = null;
8737
+ );
8738
+ return () => {
8739
+ const componentMetadata = extractMetadataAfterTransform(
8740
+ node,
8741
+ componentName,
8742
+ elementMetadata,
8743
+ semanticNameMap,
8744
+ testIdAttribute
8745
+ );
8746
+ if (!accessibilityAudit) {
8747
+ return;
8657
8748
  }
8658
- maxWaitTimer = null;
8659
- void enqueueRegeneration("max-wait").then(({ files, deletedCount, compileMs, preGenerateMs, generateMs, totalMs }) => {
8660
- logInfo(
8661
- `max-wait: files=${files.length} deleted=${deletedCount} compile=${formatMs(compileMs)} wall=${formatMs(preGenerateMs)} gen=${formatMs(generateMs)} total=${formatMs(totalMs)}`
8662
- );
8663
- }).catch((error) => {
8664
- const message = error instanceof Error ? error.message : String(error);
8665
- logGenerationError("max-wait", message);
8666
- });
8667
- }, MAX_WAIT_MS);
8668
- }
8669
- if (wasEmpty) {
8670
- const queuedFiles = pendingChangedVueFiles.size;
8671
- const queuedDeletes = pendingDeletedComponents.size;
8672
- logDebug(`queued: files=${queuedFiles} deleted=${queuedDeletes}`);
8673
- }
8674
- if (timer)
8675
- clearTimeout(timer);
8676
- timer = setTimeout(() => {
8677
- timer = null;
8678
- if (maxWaitTimer) {
8679
- clearTimeout(maxWaitTimer);
8680
- maxWaitTimer = null;
8681
- }
8682
- const reason = pendingChangedVueFiles.size || pendingDeletedComponents.size ? "batched" : "noop";
8683
- void enqueueRegeneration(reason).then(({ files, deletedCount, compileMs, preGenerateMs, generateMs, totalMs }) => {
8684
- if (files.length || deletedCount) {
8685
- logInfo(
8686
- `batched: files=${files.length} deleted=${deletedCount} compile=${formatMs(compileMs)} wall=${formatMs(preGenerateMs)} gen=${formatMs(generateMs)} total=${formatMs(totalMs)}`
8687
- );
8749
+ const dependencies = componentHierarchyMap.get(componentName);
8750
+ if (!dependencies || componentMetadata.size === 0) {
8751
+ return;
8688
8752
  }
8689
- }).catch((error) => {
8690
- const message = error instanceof Error ? error.message : String(error);
8691
- logGenerationError(reason, message);
8692
- });
8693
- }, 75);
8694
- }
8695
- server.watcher.on("change", async (changedPath) => {
8696
- const changedAbsPosix = path.posix.normalize(path.resolve(changedPath));
8697
- const outDirAbsPosix = path.posix.normalize(path.resolve(projectRootRef.current, outDir ?? "./pom"));
8698
- if (changedAbsPosix.startsWith(`${outDirAbsPosix}/`) && (changedAbsPosix.endsWith(".g.ts") || changedAbsPosix.endsWith(".g.ts.map"))) {
8699
- return;
8753
+ const manifest = buildPomManifest(
8754
+ /* @__PURE__ */ new Map([[componentName, dependencies]]),
8755
+ /* @__PURE__ */ new Map([[componentName, componentMetadata]])
8756
+ );
8757
+ const warnings = collectAccessibilityReviewWarnings(manifest);
8758
+ const signature = warnings.join("\n");
8759
+ if (!signature) {
8760
+ lastAccessibilityWarningSignatureByComponent.delete(componentName);
8761
+ return;
8762
+ }
8763
+ if (lastAccessibilityWarningSignatureByComponent.get(componentName) === signature) {
8764
+ return;
8765
+ }
8766
+ lastAccessibilityWarningSignatureByComponent.set(componentName, signature);
8767
+ for (const warning of warnings) {
8768
+ loggerRef.current.warn(warning);
8769
+ }
8770
+ };
8700
8771
  }
8701
- if (changedAbsPosix.includes("/vite-plugins/vue-pom-generator/")) {
8702
- void server.restart();
8772
+ let transform = perFileTransform.get(componentName);
8773
+ if (!transform) {
8774
+ componentHierarchyMap.delete(componentName);
8775
+ vueFilesPathMap.set(componentName, filename);
8776
+ transform = createTestIdTransform(
8777
+ componentName,
8778
+ componentHierarchyMap,
8779
+ nativeWrappers,
8780
+ excludedComponents,
8781
+ viewsDirAbs,
8782
+ {
8783
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
8784
+ testIdAttribute,
8785
+ nameCollisionBehavior,
8786
+ missingSemanticNameBehavior,
8787
+ warn: (message) => loggerRef.current.warn(message),
8788
+ vueFilesPathMap,
8789
+ wrapperSearchRoots: getWrapperSearchRoots(),
8790
+ annotatorMetadata,
8791
+ crossFileKeyRegistry,
8792
+ optionKeyAttribute
8793
+ }
8794
+ );
8795
+ perFileTransform.set(componentName, transform);
8703
8796
  }
8704
- });
8705
- server.watcher.on("add", (p) => {
8706
- if (typeof p !== "string")
8707
- return;
8708
- if (!p.endsWith(".vue"))
8709
- return;
8710
- if (!isContainedInScanDirs(p))
8711
- return;
8712
- void (async () => {
8713
- await initialBuildPromise;
8714
- pendingChangedVueFiles.add(p);
8715
- scheduleAggregatedRegen();
8716
- })();
8717
- });
8718
- server.watcher.on("unlink", (p) => {
8719
- if (typeof p !== "string")
8720
- return;
8721
- if (!p.endsWith(".vue"))
8722
- return;
8723
- if (!isContainedInScanDirs(p))
8724
- return;
8725
- void (async () => {
8726
- await initialBuildPromise;
8727
- const absolutePath = path.resolve(p);
8728
- const componentName = getComponentNameForFile(absolutePath);
8729
- filePathToComponentName.delete(absolutePath);
8730
- pendingDeletedComponents.add(componentName);
8731
- scheduleAggregatedRegen();
8732
- })();
8733
- });
8734
- setTimeout(() => {
8735
- }, 250);
8736
- await initialBuildPromise;
8737
- }
8797
+ return transform(node, context);
8798
+ }
8799
+ ];
8738
8800
  };
8739
- }
8740
- function supportsInlineTextAccessibleName(role) {
8741
- return role === "button" || role === "radio";
8742
- }
8743
- function buildAccessibilityAudit(metadata, inferredRole) {
8744
- if (!metadata || !inferredRole) {
8745
- return void 0;
8746
- }
8747
- const role = normalizePomRoleLabel(inferredRole).toLowerCase();
8748
- const dynamicProps = new Set(metadata.dynamicProps ?? []);
8749
- const hasDynamicAccessibleNameSignal = dynamicProps.has("aria-label") || dynamicProps.has("title") || !!metadata.hasDynamicText;
8750
- let accessibleNameSource;
8751
- const reasons = [];
8752
- if (metadata.staticAriaLabel) {
8753
- accessibleNameSource = "aria-label";
8754
- } else if (supportsInlineTextAccessibleName(role) && metadata.staticTextContent) {
8755
- accessibleNameSource = "text";
8756
- } else if (metadata.staticTitle) {
8757
- accessibleNameSource = "title";
8758
- } else if (hasDynamicAccessibleNameSignal) {
8759
- accessibleNameSource = "dynamic";
8760
- } else if (role === "input" || role === "select") {
8761
- accessibleNameSource = "unknown";
8762
- reasons.push("No inline accessible-name signal was found; the element may rely on external markup such as a separate <label>.");
8763
- } else {
8764
- accessibleNameSource = "missing";
8765
- reasons.push("No compile-time accessible-name signal was found.");
8766
- }
8767
- return {
8768
- needsReview: accessibleNameSource === "unknown" || accessibleNameSource === "missing",
8769
- accessibleNameSource,
8770
- reasons,
8771
- ...metadata.staticAriaLabel ? { staticAriaLabel: metadata.staticAriaLabel } : {},
8772
- ...metadata.staticRole ? { staticRole: metadata.staticRole } : {},
8773
- ...metadata.staticTitle ? { staticTitle: metadata.staticTitle } : {},
8774
- ...metadata.staticTextContent ? { staticTextContent: metadata.staticTextContent } : {}
8801
+ const runtimeNodeTransform = (node, context) => {
8802
+ const filename = context.filename;
8803
+ if (!filename || !filename.endsWith(".vue") || !isFileInScope(filename)) {
8804
+ return;
8805
+ }
8806
+ const transforms = getNodeTransforms(filename);
8807
+ const ourTransform = transforms[transforms.length - 1];
8808
+ return ourTransform(node, context);
8775
8809
  };
8776
- }
8777
- function collectAccessibilityReviewWarnings(manifest) {
8778
- const warnings = [];
8779
- for (const [componentName, component] of Object.entries(manifest)) {
8780
- for (const entry of component.entries) {
8781
- if (!entry.accessibility?.needsReview) {
8782
- continue;
8810
+ const templateCompilerOptions = {
8811
+ ...userCompilerOptions,
8812
+ prefixIdentifiers: true,
8813
+ nodeTransforms: [
8814
+ ...userNodeTransforms,
8815
+ runtimeNodeTransform
8816
+ ]
8817
+ };
8818
+ const metadataCollectorPlugin = {
8819
+ name: "vue-pom-generator-metadata-collector",
8820
+ enforce: "pre",
8821
+ async transform(code, id) {
8822
+ const cleanPath = id.includes("?") ? id.substring(0, id.indexOf("?")) : id;
8823
+ if (!cleanPath.endsWith(".vue") || !isFileInScope(id)) {
8824
+ return null;
8783
8825
  }
8784
- const entryLabel = entry.generatedPropertyName ?? entry.testId;
8785
- const reasonText = entry.accessibility.reasons.join(" ");
8786
- warnings.push(
8787
- `[vue-pom-generator] Accessibility review suggested for ${componentName}.${entryLabel} (role=${entry.inferredRole ?? "unknown"}, testId=${JSON.stringify(entry.testId)}): ${reasonText}`
8788
- );
8826
+ if (id !== cleanPath) {
8827
+ return null;
8828
+ }
8829
+ const componentName = getComponentNameFromPath(cleanPath);
8830
+ loggerRef.current.debug(`Collecting metadata for ${cleanPath} (component: ${componentName})`);
8831
+ const compilerSfc = await import("@vue/compiler-sfc");
8832
+ const parse2 = resolveCompilerSfcParse(compilerSfc);
8833
+ const compilerDom2 = await import("@vue/compiler-dom");
8834
+ const compile = compilerDom2.compile;
8835
+ const { descriptor } = parse2(code, { filename: cleanPath });
8836
+ if (descriptor.template) {
8837
+ const mergedExpressionPlugins = Array.from(
8838
+ /* @__PURE__ */ new Set([
8839
+ "typescript",
8840
+ ...userCompilerOptions.expressionPlugins ?? []
8841
+ ])
8842
+ );
8843
+ compile(descriptor.template.content, {
8844
+ ...userCompilerOptions,
8845
+ filename: cleanPath,
8846
+ expressionPlugins: mergedExpressionPlugins,
8847
+ nodeTransforms: getNodeTransforms(cleanPath, componentName)
8848
+ });
8849
+ loggerRef.current.debug(`Metadata collected for ${cleanPath}`);
8850
+ }
8851
+ return null;
8789
8852
  }
8790
- }
8791
- return warnings;
8853
+ };
8854
+ const template = {
8855
+ ...userTemplate,
8856
+ compilerOptions: templateCompilerOptions
8857
+ };
8858
+ const internalVuePlugin = vue({
8859
+ ...vueOptions,
8860
+ template
8861
+ });
8862
+ const nuxtVueBridgePlugin = {
8863
+ name: "vue-pom-generator-nuxt-vue-bridge",
8864
+ apply: "serve",
8865
+ configResolved(config) {
8866
+ const viteVuePlugin = config.plugins.find((plugin) => {
8867
+ return typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === "vite:vue" && "api" in plugin;
8868
+ });
8869
+ const api = viteVuePlugin?.api;
8870
+ if (!api) {
8871
+ throw new Error("[vue-pom-generator] Nuxt bridge could not find vite:vue plugin to patch.");
8872
+ }
8873
+ const currentOptions = api.options ?? {};
8874
+ const currentTemplate = currentOptions.template ?? {};
8875
+ const currentCompilerOptions = currentTemplate.compilerOptions ?? {};
8876
+ const currentNodeTransforms = currentCompilerOptions.nodeTransforms ?? [];
8877
+ if (currentNodeTransforms.includes(runtimeNodeTransform)) {
8878
+ return;
8879
+ }
8880
+ api.options = {
8881
+ ...currentOptions,
8882
+ template: {
8883
+ ...currentTemplate,
8884
+ compilerOptions: {
8885
+ ...currentCompilerOptions,
8886
+ prefixIdentifiers: true,
8887
+ nodeTransforms: [
8888
+ ...currentNodeTransforms,
8889
+ runtimeNodeTransform
8890
+ ]
8891
+ }
8892
+ }
8893
+ };
8894
+ }
8895
+ };
8896
+ return { metadataCollectorPlugin, internalVuePlugin, nuxtVueBridgePlugin, templateCompilerOptions };
8792
8897
  }
8793
- function matchesPrimarySelector(extraMethod, pom) {
8794
- if (extraMethod.selector.kind !== "testId") {
8795
- return false;
8898
+ function summarizeHierarchyMap(componentHierarchyMap) {
8899
+ let interactiveComponentCount = 0;
8900
+ let dataTestIdCount = 0;
8901
+ for (const dependencies of componentHierarchyMap.values()) {
8902
+ const selectorCount = dependencies.dataTestIdSet?.size ?? 0;
8903
+ if (selectorCount > 0) {
8904
+ interactiveComponentCount += 1;
8905
+ dataTestIdCount += selectorCount;
8906
+ }
8796
8907
  }
8797
- return extraMethod.selector.testId.formatted === pom.selector.formatted && extraMethod.selector.testId.patternKind === pom.selector.patternKind;
8798
- }
8799
- function getManifestEntry(componentName, entry, componentMetadata, extraMethods) {
8800
- const testId = entry.selectorValue.formatted;
8801
- const metadata = componentMetadata?.get(testId);
8802
- const pom = entry.pom;
8803
- const generatedActionName = pom ? buildPomGeneratedActionName(pom) : null;
8804
- const extraActionNames = pom ? extraMethods.filter((extraMethod) => matchesPrimarySelector(extraMethod, pom)).map((extraMethod) => extraMethod.name).sort((a, b) => a.localeCompare(b)) : [];
8805
- const generatedActionNames = Array.from(/* @__PURE__ */ new Set([
8806
- ...generatedActionName ? [generatedActionName] : [],
8807
- ...extraActionNames.filter((name) => name !== generatedActionName)
8808
- ]));
8809
- const accessibility = buildAccessibilityAudit(metadata, pom?.nativeRole ?? null);
8810
8908
  return {
8811
- testId,
8812
- selectorPatternKind: entry.selectorValue.patternKind,
8813
- semanticName: metadata?.semanticName ?? (pom ? humanizePomMethodName(pom.methodName) : testId),
8814
- locatorDescription: pom ? buildPomLocatorDescription({
8815
- componentName,
8816
- methodName: pom.methodName,
8817
- nativeRole: pom.nativeRole
8818
- }) : componentName,
8819
- inferredRole: pom?.nativeRole ?? null,
8820
- ...accessibility ? { accessibility } : {},
8821
- generatedPropertyName: pom ? buildPomGeneratedPropertyName(pom) : null,
8822
- generatedActionName,
8823
- generatedActionNames,
8824
- emitPrimary: pom?.emitPrimary !== false,
8825
- ...entry.targetPageObjectModelClass ? { targetPageObjectModelClass: entry.targetPageObjectModelClass } : {},
8826
- ...metadata?.tag ? { sourceTag: metadata.tag } : {},
8827
- ...metadata ? { sourceTagType: metadata.tagType } : {},
8828
- ...metadata?.sourceLine !== void 0 ? { sourceLine: metadata.sourceLine } : {},
8829
- ...metadata?.sourceColumn !== void 0 ? { sourceColumn: metadata.sourceColumn } : {},
8830
- ...metadata?.patchFlag !== void 0 ? { patchFlag: metadata.patchFlag } : {},
8831
- ...metadata?.dynamicProps?.length ? { dynamicProps: metadata.dynamicProps } : {},
8832
- ...metadata?.hasClickHandler !== void 0 ? { hasClickHandler: metadata.hasClickHandler } : {},
8833
- ...metadata?.hasDynamicClass !== void 0 ? { hasDynamicClass: metadata.hasDynamicClass } : {},
8834
- ...metadata?.hasDynamicStyle !== void 0 ? { hasDynamicStyle: metadata.hasDynamicStyle } : {},
8835
- ...metadata?.hasDynamicText !== void 0 ? { hasDynamicText: metadata.hasDynamicText } : {}
8909
+ entryCount: componentHierarchyMap.size,
8910
+ interactiveComponentCount,
8911
+ dataTestIdCount
8836
8912
  };
8837
8913
  }
8838
- function buildPomManifest(componentHierarchyMap, elementMetadata) {
8839
- const manifestEntries = Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8840
- const entries = Array.from(dependencies.dataTestIdSet).sort((a, b) => a.selectorValue.formatted.localeCompare(b.selectorValue.formatted)).map((entry) => getManifestEntry(componentName, entry, elementMetadata.get(componentName), dependencies.pomExtraMethods ?? []));
8841
- if (!entries.length) {
8842
- return null;
8843
- }
8844
- return [componentName, {
8845
- componentName,
8846
- className: componentName,
8847
- sourceFile: dependencies.filePath,
8848
- kind: dependencies.isView ? "view" : "component",
8849
- testIds: Array.from(new Set(entries.map((entry) => entry.testId))),
8850
- entries
8851
- }];
8852
- }).filter((entry) => entry !== null);
8853
- return Object.fromEntries(manifestEntries);
8854
- }
8855
- function buildTestIdManifest(componentHierarchyMap) {
8856
- return Object.fromEntries(
8857
- Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8858
- const testIds = Array.from(dependencies.dataTestIdSet).map((entry) => entry.selectorValue.formatted).filter(Boolean);
8859
- if (!testIds.length) {
8860
- return null;
8861
- }
8862
- return [componentName, Array.from(new Set(testIds)).sort((a, b) => a.localeCompare(b))];
8863
- }).filter((entry) => entry !== null)
8864
- );
8865
- }
8866
- function writeConstJson(value) {
8867
- return (writer) => {
8868
- writer.write(`${JSON.stringify(value, null, 2)} as const`);
8869
- };
8914
+ function isLessRich(candidate, previous) {
8915
+ if (candidate.dataTestIdCount !== previous.dataTestIdCount) {
8916
+ return candidate.dataTestIdCount < previous.dataTestIdCount;
8917
+ }
8918
+ if (candidate.interactiveComponentCount !== previous.interactiveComponentCount) {
8919
+ return candidate.interactiveComponentCount < previous.interactiveComponentCount;
8920
+ }
8921
+ return candidate.entryCount < previous.entryCount;
8870
8922
  }
8871
- function generateTestIdsModule(componentHierarchyMap, elementMetadata) {
8872
- const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8873
- const testIdManifest = buildTestIdManifest(componentHierarchyMap);
8874
- return renderSourceFile("virtual-testids.ts", (sourceFile) => {
8875
- sourceFile.addStatements("// Virtual module: test id manifest");
8876
- sourceFile.addVariableStatement({
8877
- declarationKind: VariableDeclarationKind.Const,
8878
- isExported: true,
8879
- declarations: [{
8880
- name: "testIdManifest",
8881
- initializer: writeConstJson(testIdManifest)
8882
- }]
8883
- });
8884
- sourceFile.addVariableStatement({
8885
- declarationKind: VariableDeclarationKind.Const,
8886
- isExported: true,
8887
- declarations: [{
8888
- name: "pomManifest",
8889
- initializer: writeConstJson(pomManifest)
8890
- }]
8891
- });
8892
- sourceFile.addTypeAlias({
8893
- isExported: true,
8894
- name: "TestIdManifest",
8895
- type: "typeof testIdManifest"
8896
- });
8897
- sourceFile.addTypeAlias({
8898
- isExported: true,
8899
- name: "ComponentName",
8900
- type: "keyof TestIdManifest"
8901
- });
8902
- sourceFile.addTypeAlias({
8903
- isExported: true,
8904
- name: "PomManifest",
8905
- type: "typeof pomManifest"
8906
- });
8907
- sourceFile.addTypeAlias({
8908
- isExported: true,
8909
- name: "PomManifestComponentName",
8910
- type: "keyof PomManifest"
8911
- });
8912
- });
8913
- }
8914
- function generatePomManifestModule(componentHierarchyMap, elementMetadata) {
8915
- const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8916
- return renderSourceFile("virtual-pom-manifest.ts", (sourceFile) => {
8917
- sourceFile.addStatements("// Virtual module: richer POM discoverability manifest");
8918
- sourceFile.addVariableStatement({
8919
- declarationKind: VariableDeclarationKind.Const,
8920
- isExported: true,
8921
- declarations: [{
8922
- name: "pomManifest",
8923
- initializer: writeConstJson(pomManifest)
8924
- }]
8925
- });
8926
- sourceFile.addTypeAlias({
8927
- isExported: true,
8928
- name: "PomManifest",
8929
- type: "typeof pomManifest"
8930
- });
8931
- sourceFile.addTypeAlias({
8932
- isExported: true,
8933
- name: "PomManifestComponentName",
8934
- type: "keyof PomManifest"
8935
- });
8936
- });
8937
- }
8938
- const TEST_IDS_VIRTUAL_ID = "virtual:testids";
8939
- const TEST_IDS_RESOLVED_ID = `\0${TEST_IDS_VIRTUAL_ID}`;
8940
- const POM_MANIFEST_VIRTUAL_ID = "virtual:pom-manifest";
8941
- const POM_MANIFEST_RESOLVED_ID = `\0${POM_MANIFEST_VIRTUAL_ID}`;
8942
- function createTestIdsVirtualModulesPlugin(componentHierarchyMap, elementMetadata) {
8943
- return {
8944
- name: "vue-pom-generator:virtual-testids",
8945
- resolveId(id) {
8946
- if (id === TEST_IDS_VIRTUAL_ID)
8947
- return TEST_IDS_RESOLVED_ID;
8948
- if (id === POM_MANIFEST_VIRTUAL_ID)
8949
- return POM_MANIFEST_RESOLVED_ID;
8950
- },
8951
- load(id) {
8952
- if (id === TEST_IDS_RESOLVED_ID)
8953
- return generateTestIdsModule(componentHierarchyMap, elementMetadata);
8954
- if (id === POM_MANIFEST_RESOLVED_ID)
8955
- return generatePomManifestModule(componentHierarchyMap, elementMetadata);
8956
- }
8957
- };
8958
- }
8959
- const ANNOTATOR_CLIENT_VIRTUAL_ID = "virtual:vue-pom-generator/annotator-client";
8960
- const ANNOTATOR_CLIENT_RESOLVED_ID = `\0${ANNOTATOR_CLIENT_VIRTUAL_ID}`;
8961
- const DEFAULT_ENTRY_SUFFIXES = [
8962
- "/src/main.ts",
8963
- "/src/main.js",
8964
- "/src/main.mts",
8965
- "/src/main.tsx",
8966
- "/src/main.jsx"
8967
- ];
8968
- function normalizePathSeparators(filePath) {
8969
- return filePath.replace(/\\/g, "/");
8970
- }
8971
- function toFsImportPath(filePath) {
8972
- return `/@fs/${normalizePathSeparators(filePath)}`;
8973
- }
8974
- function resolveAnnotatorClientPath() {
8975
- const candidates = [
8976
- fileURLToPath(new URL("./client.ts", import.meta.url)),
8977
- fileURLToPath(new URL("../plugin/runtime/annotator/client.ts", import.meta.url))
8978
- ];
8979
- const resolved = candidates.find((candidate) => fs.existsSync(candidate));
8980
- if (!resolved) {
8981
- throw new Error("[vue-pom-generator] Unable to locate annotator client source.");
8982
- }
8983
- return path.resolve(resolved);
8984
- }
8985
- function createAnnotatorUiPlugin(options) {
8986
- const clientPath = resolveAnnotatorClientPath();
8987
- const clientImportPath = toFsImportPath(clientPath);
8988
- const clientOptions = JSON.stringify({
8989
- sourceAttribute: options.sourceAttribute,
8990
- metadataAttributePrefix: options.metadataAttributePrefix,
8991
- outputDetail: options.outputDetail,
8992
- copyToClipboard: options.copyToClipboard,
8993
- showComponentTree: options.showComponentTree
8994
- });
8995
- return {
8996
- name: "vue-pom-generator:annotator-ui",
8997
- apply: "serve",
8998
- resolveId(id) {
8999
- if (id === ANNOTATOR_CLIENT_VIRTUAL_ID) {
9000
- return ANNOTATOR_CLIENT_RESOLVED_ID;
9001
- }
9002
- },
9003
- load(id) {
9004
- if (id !== ANNOTATOR_CLIENT_RESOLVED_ID) {
9005
- return null;
9006
- }
9007
- return [
9008
- `import { mountAnnotatorClient } from ${JSON.stringify(clientImportPath)};`,
9009
- `mountAnnotatorClient(${clientOptions});`,
9010
- ""
9011
- ].join("\n");
9012
- },
9013
- transform(code, id) {
9014
- if (!options.enabled) {
9015
- return null;
9016
- }
9017
- const normalizedId = normalizePathSeparators(id);
9018
- if (!DEFAULT_ENTRY_SUFFIXES.some((suffix) => normalizedId.endsWith(suffix))) {
9019
- return null;
9020
- }
9021
- if (code.includes(ANNOTATOR_CLIENT_VIRTUAL_ID)) {
9022
- return null;
9023
- }
9024
- return {
9025
- code: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};
9026
- ${code}`,
9027
- map: null
9028
- };
9029
- },
9030
- transformIndexHtml() {
9031
- if (!options.enabled) {
9032
- return void 0;
9033
- }
9034
- const tag = {
9035
- tag: "script",
9036
- attrs: { type: "module" },
9037
- children: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};`,
9038
- injectTo: "body"
9039
- };
9040
- return [tag];
9041
- }
9042
- };
9043
- }
9044
- function createInternalPlugins(options) {
8923
+ function createBuildProcessorPlugin(options) {
9045
8924
  const {
9046
8925
  componentHierarchyMap,
9047
8926
  crossFileKeyRegistry,
9048
- elementMetadata,
9049
8927
  vueFilesPathMap,
9050
- nativeWrappers,
9051
- optionKeyAttribute,
9052
- excludedComponents,
9053
8928
  getPageDirs,
9054
8929
  getComponentDirs,
9055
8930
  getLayoutDirs,
9056
8931
  getViewsDir,
9057
8932
  getSourceDirs,
9058
- getWrapperSearchRoots,
8933
+ basePageClassPath,
8934
+ normalizedBasePagePath,
9059
8935
  generation,
9060
8936
  projectRootRef,
9061
- basePageClassPath: basePageClassPathOverride,
9062
- loggerRef,
9063
- annotatorRuntime
8937
+ nativeWrappers,
8938
+ optionKeyAttribute,
8939
+ excludedComponents,
8940
+ getWrapperSearchRoots,
8941
+ getResolvedRouterEntry,
8942
+ loggerRef
9064
8943
  } = options;
9065
8944
  const {
8945
+ outDir,
8946
+ emitLanguages,
8947
+ typescriptOutputStructure,
8948
+ csharp,
8949
+ generateFixtures,
8950
+ customPomAttachments,
8951
+ customPomDir,
8952
+ requireCustomPomDir,
8953
+ customPomImportAliases,
8954
+ customPomImportNameCollisionBehavior,
8955
+ testIdAttribute,
8956
+ nameCollisionBehavior,
8957
+ missingSemanticNameBehavior,
8958
+ existingIdBehavior,
9066
8959
  routerAwarePoms,
9067
- routerEntry,
9068
- routerType
8960
+ routerType,
8961
+ routerModuleShims
9069
8962
  } = generation;
9070
- const resolveRouterEntry2 = () => {
9071
- if (!routerAwarePoms)
9072
- return void 0;
9073
- if (routerType === "nuxt")
9074
- return void 0;
9075
- if (!routerEntry)
9076
- throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
9077
- return path.isAbsolute(routerEntry) ? routerEntry : path.resolve(projectRootRef.current, routerEntry);
8963
+ let lastGeneratedMetrics = {
8964
+ entryCount: 0,
8965
+ interactiveComponentCount: 0,
8966
+ dataTestIdCount: 0
9078
8967
  };
9079
- const getDefaultBasePageClassPath = () => {
8968
+ const getViewsDirAbs = () => path.isAbsolute(getViewsDir()) ? getViewsDir() : path.resolve(projectRootRef.current, getViewsDir());
8969
+ const getPageDirsAbs = () => getPageDirs().map((dir) => path.isAbsolute(dir) ? dir : path.resolve(projectRootRef.current, dir));
8970
+ const getScriptInfo = (source, filename) => {
9080
8971
  try {
9081
- return fileURLToPath(new URL("../class-generation/base-page.ts", import.meta.url));
8972
+ const { descriptor } = parse$1(source, { filename });
8973
+ if (!descriptor.script && !descriptor.scriptSetup)
8974
+ return { bindings: void 0, isScriptSetup: false };
8975
+ const scriptBlock = compileScript(descriptor, { id: filename });
8976
+ return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
9082
8977
  } catch {
9083
- return path.resolve(__dirname, "..", "class-generation", "base-page.ts");
8978
+ return { bindings: void 0, isScriptSetup: false };
9084
8979
  }
9085
8980
  };
9086
- const basePageClassPath = basePageClassPathOverride ?? getDefaultBasePageClassPath();
9087
- const normalizedBasePagePath = path.posix.normalize(basePageClassPath);
9088
- const tsProcessor = createBuildProcessorPlugin({
9089
- componentHierarchyMap,
9090
- crossFileKeyRegistry,
9091
- vueFilesPathMap,
9092
- getPageDirs,
9093
- getComponentDirs,
9094
- getLayoutDirs,
9095
- getViewsDir,
9096
- getSourceDirs,
9097
- basePageClassPath,
9098
- normalizedBasePagePath,
9099
- generation,
9100
- projectRootRef,
9101
- nativeWrappers,
9102
- optionKeyAttribute,
9103
- excludedComponents,
9104
- getWrapperSearchRoots,
9105
- getResolvedRouterEntry: resolveRouterEntry2,
9106
- loggerRef
9107
- });
9108
- const devProcessor = createDevProcessorPlugin({
9109
- nativeWrappers,
9110
- optionKeyAttribute,
9111
- excludedComponents,
9112
- getPageDirs,
9113
- getComponentDirs,
9114
- getLayoutDirs,
9115
- getViewsDir,
9116
- getSourceDirs,
9117
- getWrapperSearchRoots,
9118
- projectRootRef,
9119
- normalizedBasePagePath,
9120
- basePageClassPath,
9121
- generation,
9122
- getResolvedRouterEntry: resolveRouterEntry2,
9123
- loggerRef
9124
- });
9125
- const virtualModules = createTestIdsVirtualModulesPlugin(componentHierarchyMap, elementMetadata);
9126
- const annotatorUiPlugin = createAnnotatorUiPlugin({
9127
- ...annotatorRuntime.ui,
9128
- enabled: annotatorRuntime.enabled && annotatorRuntime.ui.enabled,
9129
- sourceAttribute: annotatorRuntime.sourceAttribute,
9130
- metadataAttributePrefix: annotatorRuntime.metadataAttributePrefix
9131
- });
9132
- return [tsProcessor, devProcessor, virtualModules, annotatorUiPlugin];
9133
- }
9134
- function findDataTestIdProp(element, attributeName = "data-testid") {
9135
- return element.props.find(
9136
- (prop) => prop.type === NodeTypes.ATTRIBUTE && prop.name === attributeName || prop.type === NodeTypes.DIRECTIVE && prop.name === "bind" && prop.arg?.type === NodeTypes.SIMPLE_EXPRESSION && prop.arg.content === attributeName
9137
- );
9138
- }
9139
- function getTestIdFromProp(prop) {
9140
- if (!prop) {
9141
- return null;
9142
- }
9143
- if (prop.type === NodeTypes.ATTRIBUTE) {
9144
- return prop.value ? prop.value.content : null;
9145
- }
9146
- if (prop.type === NodeTypes.DIRECTIVE) {
9147
- return prop.exp?.type === NodeTypes.SIMPLE_EXPRESSION ? prop.exp.content : null;
9148
- }
9149
- return null;
9150
- }
9151
- function parseDynamicProps(dynamicProps) {
9152
- if (!dynamicProps) {
9153
- return void 0;
9154
- }
9155
- if (typeof dynamicProps === "string") {
9156
- const parts = [];
9157
- let current = "";
9158
- for (let i = 0; i < dynamicProps.length; i++) {
9159
- const ch = dynamicProps[i];
9160
- if (ch === ",") {
9161
- const token = current.trim();
9162
- if (token.length)
9163
- parts.push(token);
9164
- current = "";
9165
- continue;
9166
- }
9167
- current += ch;
9168
- }
9169
- const last = current.trim();
9170
- if (last.length)
9171
- parts.push(last);
9172
- return parts;
9173
- }
9174
- if (isSimpleExpressionNode(dynamicProps)) {
9175
- const content = dynamicProps.content;
9176
- if (content.startsWith("[") && content.endsWith("]")) {
9177
- try {
9178
- return JSON.parse(content);
9179
- } catch {
9180
- return void 0;
9181
- }
9182
- }
9183
- return [content];
9184
- }
9185
- return void 0;
9186
- }
9187
- function findStaticAttributeValue(element, attributeName) {
9188
- const attribute = element.props.find(
9189
- (prop) => prop.type === NodeTypes.ATTRIBUTE && prop.name === attributeName
9190
- );
9191
- const value = attribute?.value?.content?.trim();
9192
- return value || void 0;
9193
- }
9194
- function collectStaticTextContent(children) {
9195
- const parts = [];
9196
- const visit = (nodes) => {
9197
- for (const node of nodes) {
9198
- if (node.type === NodeTypes.TEXT) {
9199
- const text2 = collapseWhitespace(node.content);
9200
- if (text2) {
9201
- parts.push(text2);
8981
+ const supplementHierarchyFromFilesystem = () => {
8982
+ const walkFilesRecursive = (rootDir) => {
8983
+ const out = [];
8984
+ const stack = [rootDir];
8985
+ while (stack.length) {
8986
+ const dir = stack.pop();
8987
+ if (!dir) continue;
8988
+ let entries = [];
8989
+ try {
8990
+ entries = fs.readdirSync(dir, { withFileTypes: true });
8991
+ } catch {
8992
+ continue;
8993
+ }
8994
+ for (const ent of entries) {
8995
+ if (ent.isDirectory()) {
8996
+ if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
8997
+ continue;
8998
+ stack.push(path.join(dir, ent.name));
8999
+ continue;
9000
+ }
9001
+ if (ent.isFile() && ent.name.endsWith(".vue")) {
9002
+ out.push(path.join(dir, ent.name));
9003
+ }
9202
9004
  }
9203
- continue;
9204
9005
  }
9205
- if (node.type === NodeTypes.ELEMENT) {
9206
- visit(node.children);
9006
+ return out;
9007
+ };
9008
+ let supplemented = 0;
9009
+ for (const dir of getSourceDirs()) {
9010
+ const absDir = path.resolve(projectRootRef.current, dir);
9011
+ if (!fs.existsSync(absDir))
9012
+ continue;
9013
+ for (const filePath of walkFilesRecursive(absDir)) {
9014
+ const absolutePath = path.resolve(filePath);
9015
+ const componentName = resolveComponentNameFromPath({
9016
+ filename: absolutePath,
9017
+ projectRoot: projectRootRef.current,
9018
+ viewsDirAbs: getViewsDirAbs(),
9019
+ sourceDirs: getSourceDirs(),
9020
+ extraRoots: [process.cwd()]
9021
+ });
9022
+ if (componentHierarchyMap.has(componentName))
9023
+ continue;
9024
+ let sfc = "";
9025
+ try {
9026
+ sfc = fs.readFileSync(absolutePath, "utf8");
9027
+ } catch {
9028
+ continue;
9029
+ }
9030
+ const { descriptor } = parse$1(sfc, { filename: absolutePath });
9031
+ const template = descriptor.template?.content ?? "";
9032
+ if (!template.trim()) {
9033
+ vueFilesPathMap.set(componentName, absolutePath);
9034
+ componentHierarchyMap.set(componentName, {
9035
+ filePath: absolutePath,
9036
+ childrenComponentSet: /* @__PURE__ */ new Set(),
9037
+ usedComponentSet: /* @__PURE__ */ new Set(),
9038
+ dataTestIdSet: /* @__PURE__ */ new Set(),
9039
+ isView: false,
9040
+ methodsContent: ""
9041
+ });
9042
+ supplemented++;
9043
+ continue;
9044
+ }
9045
+ const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
9046
+ vueFilesPathMap.set(componentName, absolutePath);
9047
+ try {
9048
+ compilerDom.compile(template, {
9049
+ filename: absolutePath,
9050
+ prefixIdentifiers: true,
9051
+ inline: isScriptSetup,
9052
+ bindingMetadata,
9053
+ // See dev-plugin.ts — same rationale: enable TS in template
9054
+ // expressions so `(row: RowType) => ...` handlers parse.
9055
+ expressionPlugins: ["typescript"],
9056
+ nodeTransforms: [
9057
+ createTestIdTransform(
9058
+ componentName,
9059
+ componentHierarchyMap,
9060
+ nativeWrappers,
9061
+ excludedComponents,
9062
+ getViewsDirAbs(),
9063
+ {
9064
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
9065
+ testIdAttribute,
9066
+ nameCollisionBehavior,
9067
+ missingSemanticNameBehavior,
9068
+ warn: (message) => loggerRef.current.warn(message),
9069
+ vueFilesPathMap,
9070
+ wrapperSearchRoots: getWrapperSearchRoots(),
9071
+ crossFileKeyRegistry,
9072
+ optionKeyAttribute
9073
+ }
9074
+ )
9075
+ ]
9076
+ });
9077
+ } catch {
9078
+ }
9079
+ supplemented++;
9207
9080
  }
9208
9081
  }
9209
- };
9210
- visit(children);
9211
- const text = collapseWhitespace(parts.join(" "));
9212
- return text || void 0;
9213
- }
9214
- function tryCreateElementMetadata(args) {
9215
- const { element, semanticNameMap } = args;
9216
- const testIdAttribute = (args.testIdAttribute ?? "data-testid").trim() || "data-testid";
9217
- const testIdProp = findDataTestIdProp(element, testIdAttribute);
9218
- if (!testIdProp) {
9219
- return null;
9220
- }
9221
- const testId = getTestIdFromProp(testIdProp);
9222
- if (!testId) {
9223
- return null;
9224
- }
9225
- if (!element.codegenNode || element.codegenNode.type !== NodeTypes.VNODE_CALL) {
9226
- return null;
9227
- }
9228
- const codegenNode = element.codegenNode;
9229
- const patchFlag = codegenNode.patchFlag;
9230
- let dynamicPropsList = parseDynamicProps(codegenNode.dynamicProps);
9231
- if (!dynamicPropsList && codegenNode.dynamicProps && typeof codegenNode.dynamicProps !== "string" && isSimpleExpressionNode(codegenNode.dynamicProps)) {
9232
- const content = codegenNode.dynamicProps.content;
9233
- if (content.startsWith("[") && content.endsWith("]")) {
9234
- dynamicPropsList = [content];
9082
+ if (supplemented > 0) {
9083
+ loggerRef.current.info(`supplemented ${supplemented} components from filesystem walk (not in build graph)`);
9235
9084
  }
9236
- }
9237
- const metadata = {
9238
- testId,
9239
- semanticName: semanticNameMap.get(testId),
9240
- tag: element.tag,
9241
- tagType: element.tagType,
9242
- patchFlag,
9243
- dynamicProps: dynamicPropsList,
9244
- // Decode patch flags (bitwise) - preserved as-is from existing code.
9245
- hasClickHandler: patchFlag ? Boolean(patchFlag & 32) : void 0,
9246
- hasDynamicClass: patchFlag ? Boolean(patchFlag & 2) : void 0,
9247
- hasDynamicStyle: patchFlag ? Boolean(patchFlag & 4) : void 0,
9248
- hasDynamicText: patchFlag ? Boolean(patchFlag & 1) : void 0,
9249
- staticAriaLabel: findStaticAttributeValue(element, "aria-label"),
9250
- staticRole: findStaticAttributeValue(element, "role"),
9251
- staticTitle: findStaticAttributeValue(element, "title"),
9252
- staticTextContent: collectStaticTextContent(element.children),
9253
- sourceLine: element.loc?.start.line,
9254
- sourceColumn: element.loc?.start.column
9255
9085
  };
9256
- return metadata;
9257
- }
9258
- function resolveCompilerSfcParse(compilerSfc) {
9259
- const parse2 = compilerSfc.parse ?? compilerSfc.default?.parse;
9260
- if (typeof parse2 !== "function") {
9261
- throw new TypeError("[vue-pom-generator] Failed to resolve @vue/compiler-sfc.parse.");
9262
- }
9263
- return parse2;
9264
- }
9265
- function extractMetadataAfterTransform(ast, componentName, elementMetadata, semanticNameMap, testIdAttribute) {
9266
- const componentMetadata = /* @__PURE__ */ new Map();
9267
- function traverseNode(node) {
9268
- if (node.type === NodeTypes.ELEMENT) {
9269
- const element = node;
9270
- const testIdAttr = findDataTestIdProp(element, testIdAttribute);
9271
- if (testIdAttr) {
9272
- const metadata = tryCreateElementMetadata({
9273
- element,
9274
- semanticNameMap,
9275
- testIdAttribute
9276
- });
9277
- if (metadata) {
9278
- componentMetadata.set(metadata.testId, metadata);
9279
- }
9086
+ return {
9087
+ name: "vue-pom-generator-build",
9088
+ // This plugin exists to generate code on build output; it is not needed during dev-server HMR.
9089
+ apply: "build",
9090
+ enforce: "pre",
9091
+ async buildStart() {
9092
+ if (!routerAwarePoms) {
9093
+ setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
9094
+ setResolveToComponentNameFn(() => null);
9095
+ return;
9280
9096
  }
9281
- if (element.children) {
9282
- for (const child of element.children) {
9283
- traverseNode(child);
9097
+ let result;
9098
+ if (routerType === "nuxt") {
9099
+ result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
9100
+ } else {
9101
+ const resolvedRouterEntry = getResolvedRouterEntry();
9102
+ if (!resolvedRouterEntry)
9103
+ throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
9104
+ result = await parseRouterFileFromCwd(resolvedRouterEntry, {
9105
+ moduleShims: routerModuleShims,
9106
+ componentNaming: {
9107
+ projectRoot: projectRootRef.current,
9108
+ viewsDirAbs: getViewsDirAbs(),
9109
+ sourceDirs: getSourceDirs()
9110
+ }
9111
+ });
9112
+ }
9113
+ const { routeNameMap, routePathMap } = result;
9114
+ setRouteNameToComponentNameMap(routeNameMap);
9115
+ setResolveToComponentNameFn((to) => {
9116
+ if (typeof to === "string") {
9117
+ return routePathMap.get(to) ?? null;
9118
+ }
9119
+ const maybe = to;
9120
+ if (typeof maybe.name === "string" && maybe.name.length) {
9121
+ const key = toPascalCase(maybe.name);
9122
+ return routeNameMap.get(key) ?? null;
9123
+ }
9124
+ if (typeof maybe.path === "string" && maybe.path.length) {
9125
+ return routePathMap.get(maybe.path) ?? null;
9126
+ }
9127
+ return null;
9128
+ });
9129
+ if (!fs.existsSync(basePageClassPath)) {
9130
+ this.error(`Base page runtime file not found at ${basePageClassPath}. Ensure it is included in the build.`);
9131
+ }
9132
+ this.addWatchFile(basePageClassPath);
9133
+ const pointerPath = path.resolve(path.dirname(basePageClassPath), "pointer.ts");
9134
+ if (!fs.existsSync(pointerPath)) {
9135
+ this.error(`pointer.ts not found at ${pointerPath}. Ensure it is included in the build.`);
9136
+ }
9137
+ this.addWatchFile(pointerPath);
9138
+ const calloutPath = path.resolve(path.dirname(basePageClassPath), "callout.ts");
9139
+ if (!fs.existsSync(calloutPath)) {
9140
+ this.error(`callout.ts not found at ${calloutPath}. Ensure it is included in the build.`);
9141
+ }
9142
+ this.addWatchFile(calloutPath);
9143
+ const floatingUiCalloutPath = path.resolve(path.dirname(basePageClassPath), "floating-ui-callout.ts");
9144
+ if (fs.existsSync(floatingUiCalloutPath)) {
9145
+ this.addWatchFile(floatingUiCalloutPath);
9146
+ }
9147
+ },
9148
+ async buildEnd(error) {
9149
+ if (error) {
9150
+ return;
9151
+ }
9152
+ supplementHierarchyFromFilesystem();
9153
+ const metrics = summarizeHierarchyMap(componentHierarchyMap);
9154
+ if (metrics.dataTestIdCount <= 0) {
9155
+ return;
9156
+ }
9157
+ if (isLessRich(metrics, lastGeneratedMetrics)) {
9158
+ return;
9159
+ }
9160
+ await generateFiles(componentHierarchyMap, vueFilesPathMap, normalizedBasePagePath, {
9161
+ outDir,
9162
+ emitLanguages,
9163
+ typescriptOutputStructure,
9164
+ csharp,
9165
+ generateFixtures,
9166
+ customPomAttachments,
9167
+ projectRoot: projectRootRef.current,
9168
+ customPomDir,
9169
+ requireCustomPomDir,
9170
+ customPomImportAliases,
9171
+ customPomImportNameCollisionBehavior,
9172
+ testIdAttribute,
9173
+ vueRouterFluentChaining: routerAwarePoms,
9174
+ routerEntry: getResolvedRouterEntry(),
9175
+ routerType,
9176
+ pageDirs: getPageDirs(),
9177
+ componentDirs: getComponentDirs(),
9178
+ layoutDirs: getLayoutDirs()
9179
+ });
9180
+ lastGeneratedMetrics = metrics;
9181
+ loggerRef.current.info(`generated POMs (${metrics.entryCount} entries, ${metrics.interactiveComponentCount} interactive components, ${metrics.dataTestIdCount} selectors)`);
9182
+ },
9183
+ closeBundle() {
9184
+ loggerRef.current.info("build complete");
9185
+ }
9186
+ };
9187
+ }
9188
+ function createDevProcessorPlugin(options) {
9189
+ const {
9190
+ nativeWrappers,
9191
+ optionKeyAttribute,
9192
+ excludedComponents,
9193
+ getPageDirs,
9194
+ getComponentDirs,
9195
+ getLayoutDirs,
9196
+ getViewsDir,
9197
+ getSourceDirs,
9198
+ getWrapperSearchRoots,
9199
+ projectRootRef,
9200
+ normalizedBasePagePath,
9201
+ basePageClassPath,
9202
+ generation,
9203
+ getResolvedRouterEntry,
9204
+ loggerRef
9205
+ } = options;
9206
+ const {
9207
+ outDir,
9208
+ emitLanguages,
9209
+ typescriptOutputStructure,
9210
+ csharp,
9211
+ generateFixtures,
9212
+ customPomAttachments,
9213
+ customPomDir,
9214
+ requireCustomPomDir,
9215
+ customPomImportAliases,
9216
+ customPomImportNameCollisionBehavior,
9217
+ nameCollisionBehavior,
9218
+ missingSemanticNameBehavior,
9219
+ existingIdBehavior,
9220
+ testIdAttribute,
9221
+ routerAwarePoms,
9222
+ routerType,
9223
+ routerModuleShims
9224
+ } = generation;
9225
+ let scheduleVueFileRegen = null;
9226
+ const getProjectRootCandidates = () => Array.from(/* @__PURE__ */ new Set([
9227
+ path.resolve(projectRootRef.current),
9228
+ path.resolve(process.cwd())
9229
+ ]));
9230
+ const resolveProjectPath = (maybePath) => {
9231
+ if (path.isAbsolute(maybePath))
9232
+ return maybePath;
9233
+ const candidates = getProjectRootCandidates().map((root) => path.resolve(root, maybePath));
9234
+ return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0];
9235
+ };
9236
+ const getSourceDirRoots = () => Array.from(new Set(
9237
+ getProjectRootCandidates().flatMap((root) => getSourceDirs().map((dir) => path.resolve(root, dir)))
9238
+ ));
9239
+ const isContainedInScanDirs = (filePath) => {
9240
+ const absolutePath = path.resolve(filePath);
9241
+ return getSourceDirRoots().some((scanDirAbs) => isPathWithinDir(absolutePath, scanDirAbs));
9242
+ };
9243
+ return {
9244
+ name: "vue-pom-generator-dev",
9245
+ apply: "serve",
9246
+ // Prefer hot-update events over filesystem change events for speed and reliability.
9247
+ // This fires when Vite has actually processed the module update.
9248
+ handleHotUpdate(ctx) {
9249
+ if (!scheduleVueFileRegen)
9250
+ return;
9251
+ if (!ctx.file.endsWith(".vue"))
9252
+ return;
9253
+ if (!isContainedInScanDirs(ctx.file))
9254
+ return;
9255
+ scheduleVueFileRegen(ctx.file, "hmr");
9256
+ },
9257
+ async configureServer(server) {
9258
+ const getViewsDirAbs = () => resolveProjectPath(getViewsDir());
9259
+ const getPageDirsAbs = () => getPageDirs().map((dir) => resolveProjectPath(dir));
9260
+ const routerInitPromise = (async () => {
9261
+ if (!routerAwarePoms) {
9262
+ setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
9263
+ setResolveToComponentNameFn(() => null);
9264
+ return;
9265
+ }
9266
+ let result;
9267
+ if (routerType === "nuxt") {
9268
+ result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
9269
+ } else {
9270
+ const resolvedRouterEntry = getResolvedRouterEntry();
9271
+ if (!resolvedRouterEntry)
9272
+ throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
9273
+ result = await parseRouterFileFromCwd(resolvedRouterEntry, {
9274
+ moduleShims: routerModuleShims,
9275
+ componentNaming: {
9276
+ projectRoot: projectRootRef.current,
9277
+ viewsDirAbs: getViewsDirAbs(),
9278
+ sourceDirs: getSourceDirs(),
9279
+ extraRoots: [process.cwd()]
9280
+ }
9281
+ });
9282
+ }
9283
+ const { routeNameMap, routePathMap } = result;
9284
+ setRouteNameToComponentNameMap(routeNameMap);
9285
+ setResolveToComponentNameFn((to) => {
9286
+ if (typeof to === "string") {
9287
+ return routePathMap.get(to) ?? null;
9288
+ }
9289
+ const maybe = to;
9290
+ if (typeof maybe.name === "string" && maybe.name.length) {
9291
+ const key = toPascalCase(maybe.name);
9292
+ return routeNameMap.get(key) ?? null;
9293
+ }
9294
+ if (typeof maybe.path === "string" && maybe.path.length) {
9295
+ return routePathMap.get(maybe.path) ?? null;
9296
+ }
9297
+ return null;
9298
+ });
9299
+ })();
9300
+ const logInfo = (message) => loggerRef.current.info(message);
9301
+ const logDebug = (message) => loggerRef.current.debug(message);
9302
+ let scheduleVueFileRegenLocal = null;
9303
+ const formatMs = (ms) => `${ms.toFixed(1)}ms`;
9304
+ const extractTemplateFromSfc = (source, filename) => {
9305
+ const { descriptor } = parse$1(source, {
9306
+ filename: filename ?? "anonymous.vue"
9307
+ });
9308
+ return descriptor.template?.content ?? "";
9309
+ };
9310
+ const getScriptInfo = (source, filename) => {
9311
+ try {
9312
+ const { descriptor } = parse$1(source, { filename });
9313
+ if (!descriptor.script && !descriptor.scriptSetup)
9314
+ return { bindings: void 0, isScriptSetup: false };
9315
+ const scriptBlock = compileScript(descriptor, { id: filename });
9316
+ return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
9317
+ } catch {
9318
+ return { bindings: void 0, isScriptSetup: false };
9319
+ }
9320
+ };
9321
+ const walkFilesRecursive = (rootDir) => {
9322
+ const out = [];
9323
+ const stack = [rootDir];
9324
+ while (stack.length) {
9325
+ const dir = stack.pop();
9326
+ if (!dir) continue;
9327
+ let entries = [];
9328
+ try {
9329
+ entries = fs.readdirSync(dir, { withFileTypes: true });
9330
+ } catch {
9331
+ continue;
9332
+ }
9333
+ for (const ent of entries) {
9334
+ if (ent.isDirectory()) {
9335
+ if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
9336
+ continue;
9337
+ stack.push(path.join(dir, ent.name));
9338
+ continue;
9339
+ }
9340
+ if (ent.isFile() && ent.name.endsWith(".vue")) {
9341
+ out.push(path.join(dir, ent.name));
9342
+ }
9343
+ }
9344
+ }
9345
+ return out;
9346
+ };
9347
+ let snapshotHierarchy = /* @__PURE__ */ new Map();
9348
+ let snapshotVuePathMap = /* @__PURE__ */ new Map();
9349
+ const filePathToComponentName = /* @__PURE__ */ new Map();
9350
+ const createEmptyComponentDependencies = (absolutePath) => {
9351
+ const viewsDirAbs = path.resolve(getViewsDirAbs());
9352
+ const relToViewsDir = path.relative(viewsDirAbs, absolutePath);
9353
+ const isView = !relToViewsDir.startsWith("..") && !path.isAbsolute(relToViewsDir);
9354
+ return {
9355
+ filePath: absolutePath,
9356
+ childrenComponentSet: /* @__PURE__ */ new Set(),
9357
+ usedComponentSet: /* @__PURE__ */ new Set(),
9358
+ dataTestIdSet: /* @__PURE__ */ new Set(),
9359
+ isView,
9360
+ methodsContent: ""
9361
+ };
9362
+ };
9363
+ const getComponentNameForFile = (filePath) => {
9364
+ const normalized = path.resolve(filePath);
9365
+ const existing = filePathToComponentName.get(normalized);
9366
+ if (existing)
9367
+ return existing;
9368
+ const name = resolveComponentNameFromPath({
9369
+ filename: normalized,
9370
+ projectRoot: projectRootRef.current,
9371
+ viewsDirAbs: getViewsDirAbs(),
9372
+ sourceDirs: getSourceDirs(),
9373
+ extraRoots: [process.cwd()]
9374
+ });
9375
+ filePathToComponentName.set(normalized, name);
9376
+ return name;
9377
+ };
9378
+ const compileVueFileIntoSnapshot = (filePath, targetHierarchy = snapshotHierarchy, targetVuePathMap = snapshotVuePathMap) => {
9379
+ const started = performance.now();
9380
+ const absolutePath = path.resolve(filePath);
9381
+ const componentName = getComponentNameForFile(absolutePath);
9382
+ let sfc = "";
9383
+ try {
9384
+ sfc = fs.readFileSync(absolutePath, "utf8");
9385
+ } catch {
9386
+ return { componentName, ms: performance.now() - started, compiled: false };
9387
+ }
9388
+ const template = extractTemplateFromSfc(sfc, absolutePath);
9389
+ if (!template.trim()) {
9390
+ targetVuePathMap.set(componentName, absolutePath);
9391
+ targetHierarchy.set(componentName, createEmptyComponentDependencies(absolutePath));
9392
+ return { componentName, ms: performance.now() - started, compiled: true };
9393
+ }
9394
+ const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
9395
+ const provisionalHierarchy = /* @__PURE__ */ new Map();
9396
+ const provisionalKeyRegistry = /* @__PURE__ */ new Map();
9397
+ const provisionalVuePathMap = new Map(targetVuePathMap);
9398
+ provisionalVuePathMap.set(componentName, absolutePath);
9399
+ compilerDom.compile(template, {
9400
+ filename: absolutePath,
9401
+ prefixIdentifiers: true,
9402
+ inline: isScriptSetup,
9403
+ bindingMetadata,
9404
+ // Vue templates may contain TypeScript type annotations in expressions
9405
+ // (e.g. `@row-click="(row: RowType) => navigateTo(...)"` in Nuxt + TS
9406
+ // apps). Without this flag, Vue's internal processExpression step
9407
+ // delegates to @babel/parser without the TS plugin and crashes on
9408
+ // "Unexpected token, expected ','".
9409
+ expressionPlugins: ["typescript"],
9410
+ nodeTransforms: [
9411
+ createTestIdTransform(
9412
+ componentName,
9413
+ provisionalHierarchy,
9414
+ nativeWrappers,
9415
+ excludedComponents,
9416
+ getViewsDirAbs(),
9417
+ {
9418
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
9419
+ nameCollisionBehavior,
9420
+ missingSemanticNameBehavior,
9421
+ testIdAttribute,
9422
+ warn: (message) => loggerRef.current.warn(message),
9423
+ vueFilesPathMap: provisionalVuePathMap,
9424
+ wrapperSearchRoots: getWrapperSearchRoots(),
9425
+ crossFileKeyRegistry: provisionalKeyRegistry,
9426
+ optionKeyAttribute
9427
+ }
9428
+ )
9429
+ ]
9430
+ });
9431
+ targetVuePathMap.set(componentName, absolutePath);
9432
+ targetHierarchy.set(
9433
+ componentName,
9434
+ provisionalHierarchy.get(componentName) ?? createEmptyComponentDependencies(absolutePath)
9435
+ );
9436
+ return { componentName, ms: performance.now() - started, compiled: true };
9437
+ };
9438
+ const fullRebuildSnapshotFromFilesystem = (logLabel) => {
9439
+ const t0 = performance.now();
9440
+ const nextHierarchy = /* @__PURE__ */ new Map();
9441
+ const nextVuePathMap = /* @__PURE__ */ new Map();
9442
+ filePathToComponentName.clear();
9443
+ let totalVueFiles = 0;
9444
+ let compiledCount = 0;
9445
+ for (const absDir of getSourceDirRoots()) {
9446
+ if (!fs.existsSync(absDir))
9447
+ continue;
9448
+ const vueFiles = walkFilesRecursive(absDir);
9449
+ totalVueFiles += vueFiles.length;
9450
+ for (const file of vueFiles) {
9451
+ const res = compileVueFileIntoSnapshot(file, nextHierarchy, nextVuePathMap);
9452
+ if (res.compiled)
9453
+ compiledCount++;
9454
+ }
9455
+ }
9456
+ snapshotHierarchy = nextHierarchy;
9457
+ snapshotVuePathMap = nextVuePathMap;
9458
+ const t1 = performance.now();
9459
+ logInfo(`scan(${logLabel}): found ${totalVueFiles} .vue files in ${getSourceDirs().join(", ")}`);
9460
+ logInfo(`compile(${logLabel}): ${compiledCount}/${totalVueFiles} files in ${formatMs(t1 - t0)} (components=${snapshotHierarchy.size})`);
9461
+ };
9462
+ const generateAggregatedFromSnapshot = async (logLabel) => {
9463
+ const t0 = performance.now();
9464
+ await generateFiles(snapshotHierarchy, snapshotVuePathMap, normalizedBasePagePath, {
9465
+ outDir,
9466
+ emitLanguages,
9467
+ typescriptOutputStructure,
9468
+ csharp,
9469
+ generateFixtures,
9470
+ customPomAttachments,
9471
+ projectRoot: projectRootRef.current,
9472
+ customPomDir,
9473
+ requireCustomPomDir,
9474
+ customPomImportAliases,
9475
+ customPomImportNameCollisionBehavior,
9476
+ pageDirs: getPageDirs(),
9477
+ componentDirs: getComponentDirs(),
9478
+ layoutDirs: getLayoutDirs(),
9479
+ testIdAttribute,
9480
+ vueRouterFluentChaining: routerAwarePoms,
9481
+ routerEntry: getResolvedRouterEntry(),
9482
+ routerType
9483
+ });
9484
+ const t1 = performance.now();
9485
+ logInfo(`generate(${logLabel}): components=${snapshotHierarchy.size} in ${formatMs(t1 - t0)}`);
9486
+ };
9487
+ let timer = null;
9488
+ let maxWaitTimer = null;
9489
+ const pendingChangedVueFiles = /* @__PURE__ */ new Set();
9490
+ const pendingDeletedComponents = /* @__PURE__ */ new Set();
9491
+ let regenerationSequence = Promise.resolve();
9492
+ const initialBuildPromise = (async () => {
9493
+ const t0 = performance.now();
9494
+ await routerInitPromise;
9495
+ fullRebuildSnapshotFromFilesystem("startup");
9496
+ await generateAggregatedFromSnapshot("startup");
9497
+ const t1 = performance.now();
9498
+ logInfo(`startup total: ${formatMs(t1 - t0)}`);
9499
+ })();
9500
+ const logGenerationError = (reason, message) => {
9501
+ server.config.logger.error(`[vue-pom-generator] dev generation failed during ${reason}: ${message}`);
9502
+ };
9503
+ const regenerateFromPending = async (reason) => {
9504
+ const t0 = performance.now();
9505
+ await initialBuildPromise;
9506
+ const nextHierarchy = new Map(snapshotHierarchy);
9507
+ const nextVuePathMap = new Map(snapshotVuePathMap);
9508
+ for (const componentName of pendingDeletedComponents) {
9509
+ nextHierarchy.delete(componentName);
9510
+ nextVuePathMap.delete(componentName);
9511
+ }
9512
+ const files = Array.from(pendingChangedVueFiles);
9513
+ const deletedCount = pendingDeletedComponents.size;
9514
+ pendingChangedVueFiles.clear();
9515
+ pendingDeletedComponents.clear();
9516
+ let compileMs = 0;
9517
+ for (const f of files) {
9518
+ const res = compileVueFileIntoSnapshot(f, nextHierarchy, nextVuePathMap);
9519
+ compileMs += res.ms;
9520
+ }
9521
+ snapshotHierarchy = nextHierarchy;
9522
+ snapshotVuePathMap = nextVuePathMap;
9523
+ const t1 = performance.now();
9524
+ await generateAggregatedFromSnapshot(reason);
9525
+ const t2 = performance.now();
9526
+ return {
9527
+ files,
9528
+ deletedCount,
9529
+ compileMs,
9530
+ preGenerateMs: t1 - t0,
9531
+ generateMs: t2 - t1,
9532
+ totalMs: t2 - t0
9533
+ };
9534
+ };
9535
+ const enqueueRegeneration = (reason) => {
9536
+ const currentRun = regenerationSequence.catch(() => void 0).then(() => regenerateFromPending(reason));
9537
+ regenerationSequence = currentRun.then(() => void 0, () => void 0);
9538
+ return currentRun;
9539
+ };
9540
+ const runtimeDir = path.dirname(basePageClassPath);
9541
+ const localPluginDir = path.resolve(projectRootRef.current, "vite-plugins", "vue-pom-generator");
9542
+ server.watcher.add([
9543
+ ...fs.existsSync(localPluginDir) ? [localPluginDir] : [],
9544
+ basePageClassPath,
9545
+ path.resolve(runtimeDir, "pointer.ts"),
9546
+ path.resolve(runtimeDir, "callout.ts"),
9547
+ path.resolve(runtimeDir, "floating-ui-callout.ts")
9548
+ ]);
9549
+ scheduleVueFileRegenLocal = (filePath, source) => {
9550
+ pendingChangedVueFiles.add(filePath);
9551
+ logDebug(`queued(${source}): files=${pendingChangedVueFiles.size} deleted=${pendingDeletedComponents.size}`);
9552
+ scheduleAggregatedRegen();
9553
+ };
9554
+ scheduleVueFileRegen = scheduleVueFileRegenLocal;
9555
+ function scheduleAggregatedRegen() {
9556
+ const wasEmpty = pendingChangedVueFiles.size === 0 && pendingDeletedComponents.size === 0;
9557
+ const MAX_WAIT_MS = 750;
9558
+ if (!maxWaitTimer) {
9559
+ maxWaitTimer = setTimeout(() => {
9560
+ if (timer) {
9561
+ clearTimeout(timer);
9562
+ timer = null;
9563
+ }
9564
+ maxWaitTimer = null;
9565
+ void enqueueRegeneration("max-wait").then(({ files, deletedCount, compileMs, preGenerateMs, generateMs, totalMs }) => {
9566
+ logInfo(
9567
+ `max-wait: files=${files.length} deleted=${deletedCount} compile=${formatMs(compileMs)} wall=${formatMs(preGenerateMs)} gen=${formatMs(generateMs)} total=${formatMs(totalMs)}`
9568
+ );
9569
+ }).catch((error) => {
9570
+ const message = error instanceof Error ? error.message : String(error);
9571
+ logGenerationError("max-wait", message);
9572
+ });
9573
+ }, MAX_WAIT_MS);
9284
9574
  }
9285
- }
9286
- } else if (node.type === NodeTypes.IF) {
9287
- for (const branch of node.branches) {
9288
- traverseNode(branch);
9289
- }
9290
- } else if (node.type === NodeTypes.IF_BRANCH || node.type === NodeTypes.FOR) {
9291
- if (node.children) {
9292
- for (const child of node.children) {
9293
- traverseNode(child);
9575
+ if (wasEmpty) {
9576
+ const queuedFiles = pendingChangedVueFiles.size;
9577
+ const queuedDeletes = pendingDeletedComponents.size;
9578
+ logDebug(`queued: files=${queuedFiles} deleted=${queuedDeletes}`);
9294
9579
  }
9295
- }
9296
- } else if (node.type === NodeTypes.ROOT) {
9297
- for (const child of node.children) {
9298
- traverseNode(child);
9299
- }
9300
- }
9301
- }
9302
- traverseNode(ast);
9303
- if (componentMetadata.size > 0) {
9304
- elementMetadata.set(componentName, componentMetadata);
9305
- }
9306
- return componentMetadata;
9307
- }
9308
- function createVuePluginWithTestIds(options) {
9309
- const {
9310
- vueOptions,
9311
- existingIdBehavior,
9312
- nameCollisionBehavior,
9313
- missingSemanticNameBehavior = "error",
9314
- nativeWrappers,
9315
- optionKeyAttribute,
9316
- elementMetadata,
9317
- semanticNameMap,
9318
- componentHierarchyMap,
9319
- crossFileKeyRegistry,
9320
- vueFilesPathMap,
9321
- excludedComponents,
9322
- getViewsDirAbs,
9323
- testIdAttribute,
9324
- accessibilityAudit,
9325
- loggerRef,
9326
- getSourceDirs,
9327
- getWrapperSearchRoots,
9328
- getProjectRoot,
9329
- annotatorMetadata
9330
- } = options;
9331
- const lastAccessibilityWarningSignatureByComponent = /* @__PURE__ */ new Map();
9332
- const getComponentNameFromPath = (filename) => {
9333
- return resolveComponentNameFromPath({
9334
- filename,
9335
- projectRoot: getProjectRoot(),
9336
- viewsDirAbs: getViewsDirAbs(),
9337
- sourceDirs: getSourceDirs(),
9338
- extraRoots: [process.cwd()]
9339
- });
9340
- };
9341
- const isFileInScope = (filename) => {
9342
- if (!filename)
9343
- return false;
9344
- const cleanPath = filename.includes("?") ? filename.substring(0, filename.indexOf("?")) : filename;
9345
- const projectRoot = getProjectRoot();
9346
- const matched = isFileInConfiguredSourceScope({
9347
- filename,
9348
- projectRoot,
9349
- viewsDirAbs: getViewsDirAbs(),
9350
- sourceDirs: getSourceDirs(),
9351
- extraRoots: [process.cwd()]
9352
- });
9353
- if (cleanPath.endsWith(".vue") && !matched) {
9354
- const absFilename = path.normalize(path.isAbsolute(cleanPath) ? cleanPath : path.resolve(projectRoot, cleanPath));
9355
- loggerRef.current.debug(`[isFileInScope] REJECTED: ${absFilename} (Clean: ${cleanPath})`);
9356
- }
9357
- return matched;
9358
- };
9359
- const userTemplate = vueOptions?.template ?? {};
9360
- const userCompilerOptions = userTemplate.compilerOptions ?? {};
9361
- const userNodeTransforms = userCompilerOptions.nodeTransforms ?? [];
9362
- const perFileTransform = /* @__PURE__ */ new Map();
9363
- const getNodeTransforms = (filename, componentNameOverride) => {
9364
- const cleanPath = filename.includes("?") ? filename.substring(0, filename.indexOf("?")) : filename;
9365
- const viewsDirAbs = getViewsDirAbs();
9366
- const componentName = componentNameOverride || getComponentNameFromPath(cleanPath);
9367
- return [
9368
- ...userNodeTransforms,
9369
- (node, context) => {
9370
- if (node.type === NodeTypes.ROOT) {
9371
- componentHierarchyMap.delete(componentName);
9372
- vueFilesPathMap.set(componentName, filename);
9373
- perFileTransform.set(
9374
- componentName,
9375
- createTestIdTransform(
9376
- componentName,
9377
- componentHierarchyMap,
9378
- nativeWrappers,
9379
- excludedComponents,
9380
- viewsDirAbs,
9381
- {
9382
- existingIdBehavior,
9383
- testIdAttribute,
9384
- nameCollisionBehavior,
9385
- missingSemanticNameBehavior,
9386
- warn: (message) => loggerRef.current.warn(message),
9387
- vueFilesPathMap,
9388
- wrapperSearchRoots: getWrapperSearchRoots(),
9389
- annotatorMetadata,
9390
- crossFileKeyRegistry,
9391
- optionKeyAttribute
9392
- }
9393
- )
9394
- );
9395
- return () => {
9396
- const componentMetadata = extractMetadataAfterTransform(
9397
- node,
9398
- componentName,
9399
- elementMetadata,
9400
- semanticNameMap,
9401
- testIdAttribute
9402
- );
9403
- if (!accessibilityAudit) {
9404
- return;
9405
- }
9406
- const dependencies = componentHierarchyMap.get(componentName);
9407
- if (!dependencies || componentMetadata.size === 0) {
9408
- return;
9409
- }
9410
- const manifest = buildPomManifest(
9411
- /* @__PURE__ */ new Map([[componentName, dependencies]]),
9412
- /* @__PURE__ */ new Map([[componentName, componentMetadata]])
9413
- );
9414
- const warnings = collectAccessibilityReviewWarnings(manifest);
9415
- const signature = warnings.join("\n");
9416
- if (!signature) {
9417
- lastAccessibilityWarningSignatureByComponent.delete(componentName);
9418
- return;
9419
- }
9420
- if (lastAccessibilityWarningSignatureByComponent.get(componentName) === signature) {
9421
- return;
9422
- }
9423
- lastAccessibilityWarningSignatureByComponent.set(componentName, signature);
9424
- for (const warning of warnings) {
9425
- loggerRef.current.warn(warning);
9580
+ if (timer)
9581
+ clearTimeout(timer);
9582
+ timer = setTimeout(() => {
9583
+ timer = null;
9584
+ if (maxWaitTimer) {
9585
+ clearTimeout(maxWaitTimer);
9586
+ maxWaitTimer = null;
9587
+ }
9588
+ const reason = pendingChangedVueFiles.size || pendingDeletedComponents.size ? "batched" : "noop";
9589
+ void enqueueRegeneration(reason).then(({ files, deletedCount, compileMs, preGenerateMs, generateMs, totalMs }) => {
9590
+ if (files.length || deletedCount) {
9591
+ logInfo(
9592
+ `batched: files=${files.length} deleted=${deletedCount} compile=${formatMs(compileMs)} wall=${formatMs(preGenerateMs)} gen=${formatMs(generateMs)} total=${formatMs(totalMs)}`
9593
+ );
9426
9594
  }
9427
- };
9595
+ }).catch((error) => {
9596
+ const message = error instanceof Error ? error.message : String(error);
9597
+ logGenerationError(reason, message);
9598
+ });
9599
+ }, 75);
9600
+ }
9601
+ server.watcher.on("change", async (changedPath) => {
9602
+ const changedAbsPosix = path.posix.normalize(path.resolve(changedPath));
9603
+ const outDirAbsPosix = path.posix.normalize(path.resolve(projectRootRef.current, outDir ?? "./pom"));
9604
+ if (changedAbsPosix.startsWith(`${outDirAbsPosix}/`) && (changedAbsPosix.endsWith(".g.ts") || changedAbsPosix.endsWith(".g.ts.map"))) {
9605
+ return;
9428
9606
  }
9429
- let transform = perFileTransform.get(componentName);
9430
- if (!transform) {
9431
- componentHierarchyMap.delete(componentName);
9432
- vueFilesPathMap.set(componentName, filename);
9433
- transform = createTestIdTransform(
9434
- componentName,
9435
- componentHierarchyMap,
9436
- nativeWrappers,
9437
- excludedComponents,
9438
- viewsDirAbs,
9439
- {
9440
- existingIdBehavior,
9441
- testIdAttribute,
9442
- nameCollisionBehavior,
9443
- missingSemanticNameBehavior,
9444
- warn: (message) => loggerRef.current.warn(message),
9445
- vueFilesPathMap,
9446
- wrapperSearchRoots: getWrapperSearchRoots(),
9447
- annotatorMetadata,
9448
- crossFileKeyRegistry,
9449
- optionKeyAttribute
9450
- }
9451
- );
9452
- perFileTransform.set(componentName, transform);
9607
+ if (changedAbsPosix.includes("/vite-plugins/vue-pom-generator/")) {
9608
+ void server.restart();
9453
9609
  }
9454
- return transform(node, context);
9455
- }
9456
- ];
9610
+ });
9611
+ server.watcher.on("add", (p) => {
9612
+ if (typeof p !== "string")
9613
+ return;
9614
+ if (!p.endsWith(".vue"))
9615
+ return;
9616
+ if (!isContainedInScanDirs(p))
9617
+ return;
9618
+ void (async () => {
9619
+ await initialBuildPromise;
9620
+ pendingChangedVueFiles.add(p);
9621
+ scheduleAggregatedRegen();
9622
+ })();
9623
+ });
9624
+ server.watcher.on("unlink", (p) => {
9625
+ if (typeof p !== "string")
9626
+ return;
9627
+ if (!p.endsWith(".vue"))
9628
+ return;
9629
+ if (!isContainedInScanDirs(p))
9630
+ return;
9631
+ void (async () => {
9632
+ await initialBuildPromise;
9633
+ const absolutePath = path.resolve(p);
9634
+ const componentName = getComponentNameForFile(absolutePath);
9635
+ filePathToComponentName.delete(absolutePath);
9636
+ pendingDeletedComponents.add(componentName);
9637
+ scheduleAggregatedRegen();
9638
+ })();
9639
+ });
9640
+ setTimeout(() => {
9641
+ }, 250);
9642
+ await initialBuildPromise;
9643
+ }
9457
9644
  };
9458
- const runtimeNodeTransform = (node, context) => {
9459
- const filename = context.filename;
9460
- if (!filename || !filename.endsWith(".vue") || !isFileInScope(filename)) {
9461
- return;
9645
+ }
9646
+ const TEST_IDS_VIRTUAL_ID = "virtual:testids";
9647
+ const TEST_IDS_RESOLVED_ID = `\0${TEST_IDS_VIRTUAL_ID}`;
9648
+ const POM_MANIFEST_VIRTUAL_ID = "virtual:pom-manifest";
9649
+ const POM_MANIFEST_RESOLVED_ID = `\0${POM_MANIFEST_VIRTUAL_ID}`;
9650
+ function createTestIdsVirtualModulesPlugin(componentHierarchyMap, elementMetadata) {
9651
+ return {
9652
+ name: "vue-pom-generator:virtual-testids",
9653
+ resolveId(id) {
9654
+ if (id === TEST_IDS_VIRTUAL_ID)
9655
+ return TEST_IDS_RESOLVED_ID;
9656
+ if (id === POM_MANIFEST_VIRTUAL_ID)
9657
+ return POM_MANIFEST_RESOLVED_ID;
9658
+ },
9659
+ load(id) {
9660
+ if (id === TEST_IDS_RESOLVED_ID)
9661
+ return generateTestIdsModule(componentHierarchyMap, elementMetadata);
9662
+ if (id === POM_MANIFEST_RESOLVED_ID)
9663
+ return generatePomManifestModule(componentHierarchyMap, elementMetadata);
9462
9664
  }
9463
- const transforms = getNodeTransforms(filename);
9464
- const ourTransform = transforms[transforms.length - 1];
9465
- return ourTransform(node, context);
9466
- };
9467
- const templateCompilerOptions = {
9468
- ...userCompilerOptions,
9469
- prefixIdentifiers: true,
9470
- nodeTransforms: [
9471
- ...userNodeTransforms,
9472
- runtimeNodeTransform
9473
- ]
9474
9665
  };
9475
- const metadataCollectorPlugin = {
9476
- name: "vue-pom-generator-metadata-collector",
9477
- enforce: "pre",
9478
- async transform(code, id) {
9479
- const cleanPath = id.includes("?") ? id.substring(0, id.indexOf("?")) : id;
9480
- if (!cleanPath.endsWith(".vue") || !isFileInScope(id)) {
9666
+ }
9667
+ const ANNOTATOR_CLIENT_VIRTUAL_ID = "virtual:vue-pom-generator/annotator-client";
9668
+ const ANNOTATOR_CLIENT_RESOLVED_ID = `\0${ANNOTATOR_CLIENT_VIRTUAL_ID}`;
9669
+ const DEFAULT_ENTRY_SUFFIXES = [
9670
+ "/src/main.ts",
9671
+ "/src/main.js",
9672
+ "/src/main.mts",
9673
+ "/src/main.tsx",
9674
+ "/src/main.jsx"
9675
+ ];
9676
+ function normalizePathSeparators(filePath) {
9677
+ return filePath.replace(/\\/g, "/");
9678
+ }
9679
+ function toFsImportPath(filePath) {
9680
+ return `/@fs/${normalizePathSeparators(filePath)}`;
9681
+ }
9682
+ function resolveAnnotatorClientPath() {
9683
+ const candidates = [
9684
+ fileURLToPath(new URL("./client.ts", import.meta.url)),
9685
+ fileURLToPath(new URL("../plugin/runtime/annotator/client.ts", import.meta.url))
9686
+ ];
9687
+ const resolved = candidates.find((candidate) => fs.existsSync(candidate));
9688
+ if (!resolved) {
9689
+ throw new Error("[vue-pom-generator] Unable to locate annotator client source.");
9690
+ }
9691
+ return path.resolve(resolved);
9692
+ }
9693
+ function createAnnotatorUiPlugin(options) {
9694
+ const clientPath = resolveAnnotatorClientPath();
9695
+ const clientImportPath = toFsImportPath(clientPath);
9696
+ const clientOptions = JSON.stringify({
9697
+ sourceAttribute: options.sourceAttribute,
9698
+ metadataAttributePrefix: options.metadataAttributePrefix,
9699
+ outputDetail: options.outputDetail,
9700
+ copyToClipboard: options.copyToClipboard,
9701
+ showComponentTree: options.showComponentTree
9702
+ });
9703
+ return {
9704
+ name: "vue-pom-generator:annotator-ui",
9705
+ apply: "serve",
9706
+ resolveId(id) {
9707
+ if (id === ANNOTATOR_CLIENT_VIRTUAL_ID) {
9708
+ return ANNOTATOR_CLIENT_RESOLVED_ID;
9709
+ }
9710
+ },
9711
+ load(id) {
9712
+ if (id !== ANNOTATOR_CLIENT_RESOLVED_ID) {
9481
9713
  return null;
9482
9714
  }
9483
- if (id !== cleanPath) {
9715
+ return [
9716
+ `import { mountAnnotatorClient } from ${JSON.stringify(clientImportPath)};`,
9717
+ `mountAnnotatorClient(${clientOptions});`,
9718
+ ""
9719
+ ].join("\n");
9720
+ },
9721
+ transform(code, id) {
9722
+ if (!options.enabled) {
9484
9723
  return null;
9485
9724
  }
9486
- const componentName = getComponentNameFromPath(cleanPath);
9487
- loggerRef.current.debug(`Collecting metadata for ${cleanPath} (component: ${componentName})`);
9488
- const compilerSfc = await import("@vue/compiler-sfc");
9489
- const parse2 = resolveCompilerSfcParse(compilerSfc);
9490
- const compilerDom2 = await import("@vue/compiler-dom");
9491
- const compile = compilerDom2.compile;
9492
- const { descriptor } = parse2(code, { filename: cleanPath });
9493
- if (descriptor.template) {
9494
- const mergedExpressionPlugins = Array.from(
9495
- /* @__PURE__ */ new Set([
9496
- "typescript",
9497
- ...userCompilerOptions.expressionPlugins ?? []
9498
- ])
9499
- );
9500
- compile(descriptor.template.content, {
9501
- ...userCompilerOptions,
9502
- filename: cleanPath,
9503
- expressionPlugins: mergedExpressionPlugins,
9504
- nodeTransforms: getNodeTransforms(cleanPath, componentName)
9505
- });
9506
- loggerRef.current.debug(`Metadata collected for ${cleanPath}`);
9725
+ const normalizedId = normalizePathSeparators(id);
9726
+ if (!DEFAULT_ENTRY_SUFFIXES.some((suffix) => normalizedId.endsWith(suffix))) {
9727
+ return null;
9507
9728
  }
9508
- return null;
9509
- }
9510
- };
9511
- const template = {
9512
- ...userTemplate,
9513
- compilerOptions: templateCompilerOptions
9514
- };
9515
- const internalVuePlugin = vue({
9516
- ...vueOptions,
9517
- template
9518
- });
9519
- const nuxtVueBridgePlugin = {
9520
- name: "vue-pom-generator-nuxt-vue-bridge",
9521
- apply: "serve",
9522
- configResolved(config) {
9523
- const viteVuePlugin = config.plugins.find((plugin) => {
9524
- return typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === "vite:vue" && "api" in plugin;
9525
- });
9526
- const api = viteVuePlugin?.api;
9527
- if (!api) {
9528
- throw new Error("[vue-pom-generator] Nuxt bridge could not find vite:vue plugin to patch.");
9729
+ if (code.includes(ANNOTATOR_CLIENT_VIRTUAL_ID)) {
9730
+ return null;
9529
9731
  }
9530
- const currentOptions = api.options ?? {};
9531
- const currentTemplate = currentOptions.template ?? {};
9532
- const currentCompilerOptions = currentTemplate.compilerOptions ?? {};
9533
- const currentNodeTransforms = currentCompilerOptions.nodeTransforms ?? [];
9534
- if (currentNodeTransforms.includes(runtimeNodeTransform)) {
9535
- return;
9732
+ return {
9733
+ code: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};
9734
+ ${code}`,
9735
+ map: null
9736
+ };
9737
+ },
9738
+ transformIndexHtml() {
9739
+ if (!options.enabled) {
9740
+ return void 0;
9536
9741
  }
9537
- api.options = {
9538
- ...currentOptions,
9539
- template: {
9540
- ...currentTemplate,
9541
- compilerOptions: {
9542
- ...currentCompilerOptions,
9543
- prefixIdentifiers: true,
9544
- nodeTransforms: [
9545
- ...currentNodeTransforms,
9546
- runtimeNodeTransform
9547
- ]
9548
- }
9549
- }
9742
+ const tag = {
9743
+ tag: "script",
9744
+ attrs: { type: "module" },
9745
+ children: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};`,
9746
+ injectTo: "body"
9550
9747
  };
9748
+ return [tag];
9551
9749
  }
9552
9750
  };
9553
- return { metadataCollectorPlugin, internalVuePlugin, nuxtVueBridgePlugin, templateCompilerOptions };
9751
+ }
9752
+ function createInternalPlugins(options) {
9753
+ const {
9754
+ componentHierarchyMap,
9755
+ crossFileKeyRegistry,
9756
+ elementMetadata,
9757
+ vueFilesPathMap,
9758
+ nativeWrappers,
9759
+ optionKeyAttribute,
9760
+ excludedComponents,
9761
+ getPageDirs,
9762
+ getComponentDirs,
9763
+ getLayoutDirs,
9764
+ getViewsDir,
9765
+ getSourceDirs,
9766
+ getWrapperSearchRoots,
9767
+ generation,
9768
+ projectRootRef,
9769
+ basePageClassPath: basePageClassPathOverride,
9770
+ loggerRef,
9771
+ annotatorRuntime
9772
+ } = options;
9773
+ const {
9774
+ routerAwarePoms,
9775
+ routerEntry,
9776
+ routerType
9777
+ } = generation;
9778
+ const resolveRouterEntry2 = () => {
9779
+ if (!routerAwarePoms)
9780
+ return void 0;
9781
+ if (routerType === "nuxt")
9782
+ return void 0;
9783
+ if (!routerEntry)
9784
+ throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
9785
+ return path.isAbsolute(routerEntry) ? routerEntry : path.resolve(projectRootRef.current, routerEntry);
9786
+ };
9787
+ const getDefaultBasePageClassPath = () => {
9788
+ try {
9789
+ return fileURLToPath(new URL("../class-generation/base-page.ts", import.meta.url));
9790
+ } catch {
9791
+ return path.resolve(__dirname, "..", "class-generation", "base-page.ts");
9792
+ }
9793
+ };
9794
+ const basePageClassPath = basePageClassPathOverride ?? getDefaultBasePageClassPath();
9795
+ const normalizedBasePagePath = path.posix.normalize(basePageClassPath);
9796
+ const tsProcessor = createBuildProcessorPlugin({
9797
+ componentHierarchyMap,
9798
+ crossFileKeyRegistry,
9799
+ vueFilesPathMap,
9800
+ getPageDirs,
9801
+ getComponentDirs,
9802
+ getLayoutDirs,
9803
+ getViewsDir,
9804
+ getSourceDirs,
9805
+ basePageClassPath,
9806
+ normalizedBasePagePath,
9807
+ generation,
9808
+ projectRootRef,
9809
+ nativeWrappers,
9810
+ optionKeyAttribute,
9811
+ excludedComponents,
9812
+ getWrapperSearchRoots,
9813
+ getResolvedRouterEntry: resolveRouterEntry2,
9814
+ loggerRef
9815
+ });
9816
+ const devProcessor = createDevProcessorPlugin({
9817
+ nativeWrappers,
9818
+ optionKeyAttribute,
9819
+ excludedComponents,
9820
+ getPageDirs,
9821
+ getComponentDirs,
9822
+ getLayoutDirs,
9823
+ getViewsDir,
9824
+ getSourceDirs,
9825
+ getWrapperSearchRoots,
9826
+ projectRootRef,
9827
+ normalizedBasePagePath,
9828
+ basePageClassPath,
9829
+ generation,
9830
+ getResolvedRouterEntry: resolveRouterEntry2,
9831
+ loggerRef
9832
+ });
9833
+ const virtualModules = createTestIdsVirtualModulesPlugin(componentHierarchyMap, elementMetadata);
9834
+ const annotatorUiPlugin = createAnnotatorUiPlugin({
9835
+ ...annotatorRuntime.ui,
9836
+ enabled: annotatorRuntime.enabled && annotatorRuntime.ui.enabled,
9837
+ sourceAttribute: annotatorRuntime.sourceAttribute,
9838
+ metadataAttributePrefix: annotatorRuntime.metadataAttributePrefix
9839
+ });
9840
+ return [tsProcessor, devProcessor, virtualModules, annotatorUiPlugin];
9554
9841
  }
9555
9842
  const nuxtConfigMarker$1 = /* @__PURE__ */ Symbol.for("@immense/vue-pom-generator.nuxt");
9556
9843
  const nuxtConfigFileNames = [