@immense/vue-pom-generator 1.0.89 → 1.0.90

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 (40) hide show
  1. package/README.md +12 -0
  2. package/RELEASE_NOTES.md +64 -39
  3. package/class-generation/index.ts +5 -5
  4. package/dist/class-generation/index.d.ts.map +1 -1
  5. package/dist/eslint/index.cjs +42 -0
  6. package/dist/eslint/index.cjs.map +1 -1
  7. package/dist/eslint/index.d.ts +3 -0
  8. package/dist/eslint/index.d.ts.map +1 -1
  9. package/dist/eslint/index.mjs +42 -0
  10. package/dist/eslint/index.mjs.map +1 -1
  11. package/dist/eslint/no-data-testid-in-specs.d.ts +3 -0
  12. package/dist/eslint/no-data-testid-in-specs.d.ts.map +1 -0
  13. package/dist/index.cjs +1364 -1360
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.mjs +1355 -1351
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/plugin/internal/build-plugin.d.ts.map +1 -1
  20. package/dist/plugin/internal/dev-plugin.d.ts.map +1 -1
  21. package/dist/plugin/resolved-generation-options.d.ts +2 -2
  22. package/dist/plugin/resolved-generation-options.d.ts.map +1 -1
  23. package/dist/plugin/resolved-injection-options.d.ts +3 -3
  24. package/dist/plugin/resolved-injection-options.d.ts.map +1 -1
  25. package/dist/plugin/types.d.ts +11 -3
  26. package/dist/plugin/types.d.ts.map +1 -1
  27. package/dist/plugin/vue-plugin.d.ts +3 -2
  28. package/dist/plugin/vue-plugin.d.ts.map +1 -1
  29. package/dist/router-bridge.d.ts +18 -0
  30. package/dist/router-bridge.d.ts.map +1 -0
  31. package/dist/router.cjs +9 -0
  32. package/dist/router.cjs.map +1 -0
  33. package/dist/router.mjs +9 -0
  34. package/dist/router.mjs.map +1 -0
  35. package/dist/tests/existing-id-behavior.test.d.ts +2 -0
  36. package/dist/tests/existing-id-behavior.test.d.ts.map +1 -0
  37. package/dist/tests/router-bridge.test.d.ts +2 -0
  38. package/dist/tests/router-bridge.test.d.ts.map +1 -0
  39. package/dist/vite.config.d.ts.map +1 -1
  40. 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) {
@@ -4818,7 +4819,7 @@ const GOTO_RUNTIME_LINES = [
4818
4819
  "const resolvedUrl = runtimeBaseUrl ? new URL(targetUrl, runtimeBaseUrl).toString() : targetUrl;",
4819
4820
  "await this.page.goto(resolvedUrl);"
4820
4821
  ];
4821
- const ROUTER_GLOBAL_NAME = "__appRouter";
4822
+ const ROUTER_GLOBAL_NAME = POM_ROUTER_GLOBAL_NAME;
4822
4823
  const pushBlock = (routeNameExpr, paramsExpr, nullable) => {
4823
4824
  const routerType = `{ ${ROUTER_GLOBAL_NAME}?: { push: (to: { name: string; params: Record<string, unknown> }) => Promise<unknown>; resolve: (to: { name: string; params: Record<string, unknown> }) => { href: string } } }`;
4824
4825
  const routeParamsLine = paramsExpr === "undefined" ? "const routeParams = {};" : nullable ? `const routeParams = Object.fromEntries(Object.entries(${paramsExpr} ?? {}).filter(([, v]) => v !== undefined));` : `const routeParams = Object.fromEntries(Object.entries(${paramsExpr}).filter(([, v]) => v !== undefined));`;
@@ -7989,824 +7990,200 @@ Fix: remove the explicit ${attrLabel}, or change existingIdBehavior to "overwrit
7989
7990
  }
7990
7991
  };
7991
7992
  }
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
- }
7993
+ function supportsInlineTextAccessibleName(role) {
7994
+ return role === "button" || role === "radio";
7995
+ }
7996
+ function buildAccessibilityAudit(metadata, inferredRole) {
7997
+ if (!metadata || !inferredRole) {
7998
+ return void 0;
7999
+ }
8000
+ const role = normalizePomRoleLabel(inferredRole).toLowerCase();
8001
+ const dynamicProps = new Set(metadata.dynamicProps ?? []);
8002
+ const hasDynamicAccessibleNameSignal = dynamicProps.has("aria-label") || dynamicProps.has("title") || !!metadata.hasDynamicText;
8003
+ let accessibleNameSource;
8004
+ const reasons = [];
8005
+ if (metadata.staticAriaLabel) {
8006
+ accessibleNameSource = "aria-label";
8007
+ } else if (supportsInlineTextAccessibleName(role) && metadata.staticTextContent) {
8008
+ accessibleNameSource = "text";
8009
+ } else if (metadata.staticTitle) {
8010
+ accessibleNameSource = "title";
8011
+ } else if (hasDynamicAccessibleNameSignal) {
8012
+ accessibleNameSource = "dynamic";
8013
+ } else if (role === "input" || role === "select") {
8014
+ accessibleNameSource = "unknown";
8015
+ reasons.push("No inline accessible-name signal was found; the element may rely on external markup such as a separate <label>.");
8016
+ } else {
8017
+ accessibleNameSource = "missing";
8018
+ reasons.push("No compile-time accessible-name signal was found.");
8001
8019
  }
8002
8020
  return {
8003
- entryCount: componentHierarchyMap.size,
8004
- interactiveComponentCount,
8005
- dataTestIdCount
8021
+ needsReview: accessibleNameSource === "unknown" || accessibleNameSource === "missing",
8022
+ accessibleNameSource,
8023
+ reasons,
8024
+ ...metadata.staticAriaLabel ? { staticAriaLabel: metadata.staticAriaLabel } : {},
8025
+ ...metadata.staticRole ? { staticRole: metadata.staticRole } : {},
8026
+ ...metadata.staticTitle ? { staticTitle: metadata.staticTitle } : {},
8027
+ ...metadata.staticTextContent ? { staticTextContent: metadata.staticTextContent } : {}
8006
8028
  };
8007
8029
  }
8008
- function isLessRich(candidate, previous) {
8009
- if (candidate.dataTestIdCount !== previous.dataTestIdCount) {
8010
- return candidate.dataTestIdCount < previous.dataTestIdCount;
8030
+ function collectAccessibilityReviewWarnings(manifest) {
8031
+ const warnings = [];
8032
+ for (const [componentName, component] of Object.entries(manifest)) {
8033
+ for (const entry of component.entries) {
8034
+ if (!entry.accessibility?.needsReview) {
8035
+ continue;
8036
+ }
8037
+ const entryLabel = entry.generatedPropertyName ?? entry.testId;
8038
+ const reasonText = entry.accessibility.reasons.join(" ");
8039
+ warnings.push(
8040
+ `[vue-pom-generator] Accessibility review suggested for ${componentName}.${entryLabel} (role=${entry.inferredRole ?? "unknown"}, testId=${JSON.stringify(entry.testId)}): ${reasonText}`
8041
+ );
8042
+ }
8011
8043
  }
8012
- if (candidate.interactiveComponentCount !== previous.interactiveComponentCount) {
8013
- return candidate.interactiveComponentCount < previous.interactiveComponentCount;
8044
+ return warnings;
8045
+ }
8046
+ function findDataTestIdProp(element, attributeName = "data-testid") {
8047
+ return element.props.find(
8048
+ (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
8049
+ );
8050
+ }
8051
+ function getTestIdFromProp(prop) {
8052
+ if (!prop) {
8053
+ return null;
8014
8054
  }
8015
- return candidate.entryCount < previous.entryCount;
8055
+ if (prop.type === NodeTypes.ATTRIBUTE) {
8056
+ return prop.value ? prop.value.content : null;
8057
+ }
8058
+ if (prop.type === NodeTypes.DIRECTIVE) {
8059
+ return prop.exp?.type === NodeTypes.SIMPLE_EXPRESSION ? prop.exp.content : null;
8060
+ }
8061
+ return null;
8016
8062
  }
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 };
8073
- }
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))
8063
+ function parseDynamicProps(dynamicProps) {
8064
+ if (!dynamicProps) {
8065
+ return void 0;
8066
+ }
8067
+ if (typeof dynamicProps === "string") {
8068
+ const parts = [];
8069
+ let current = "";
8070
+ for (let i = 0; i < dynamicProps.length; i++) {
8071
+ const ch = dynamicProps[i];
8072
+ if (ch === ",") {
8073
+ const token = current.trim();
8074
+ if (token.length)
8075
+ parts.push(token);
8076
+ current = "";
8106
8077
  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++;
8174
8078
  }
8079
+ current += ch;
8175
8080
  }
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
- });
8081
+ const last = current.trim();
8082
+ if (last.length)
8083
+ parts.push(last);
8084
+ return parts;
8085
+ }
8086
+ if (isSimpleExpressionNode(dynamicProps)) {
8087
+ const content = dynamicProps.content;
8088
+ if (content.startsWith("[") && content.endsWith("]")) {
8089
+ try {
8090
+ return JSON.parse(content);
8091
+ } catch {
8092
+ return void 0;
8206
8093
  }
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;
8094
+ }
8095
+ return [content];
8096
+ }
8097
+ return void 0;
8098
+ }
8099
+ function findStaticAttributeValue(element, attributeName) {
8100
+ const attribute = element.props.find(
8101
+ (prop) => prop.type === NodeTypes.ATTRIBUTE && prop.name === attributeName
8102
+ );
8103
+ const value = attribute?.value?.content?.trim();
8104
+ return value || void 0;
8105
+ }
8106
+ function collectStaticTextContent(children) {
8107
+ const parts = [];
8108
+ const visit = (nodes) => {
8109
+ for (const node of nodes) {
8110
+ if (node.type === NodeTypes.TEXT) {
8111
+ const text2 = collapseWhitespace(node.content);
8112
+ if (text2) {
8113
+ parts.push(text2);
8220
8114
  }
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;
8115
+ continue;
8250
8116
  }
8251
- if (isLessRich(metrics, lastGeneratedMetrics)) {
8252
- return;
8117
+ if (node.type === NodeTypes.ELEMENT) {
8118
+ visit(node.children);
8253
8119
  }
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
8120
  }
8280
8121
  };
8122
+ visit(children);
8123
+ const text = collapseWhitespace(parts.join(" "));
8124
+ return text || void 0;
8281
8125
  }
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())
8323
- ]));
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];
8329
- };
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));
8126
+ function tryCreateElementMetadata(args) {
8127
+ const { element, semanticNameMap } = args;
8128
+ const testIdAttribute = (args.testIdAttribute ?? "data-testid").trim() || "data-testid";
8129
+ const testIdProp = findDataTestIdProp(element, testIdAttribute);
8130
+ if (!testIdProp) {
8131
+ return null;
8132
+ }
8133
+ const testId = getTestIdFromProp(testIdProp);
8134
+ if (!testId) {
8135
+ return null;
8136
+ }
8137
+ if (!element.codegenNode || element.codegenNode.type !== NodeTypes.VNODE_CALL) {
8138
+ return null;
8139
+ }
8140
+ const codegenNode = element.codegenNode;
8141
+ const patchFlag = codegenNode.patchFlag;
8142
+ let dynamicPropsList = parseDynamicProps(codegenNode.dynamicProps);
8143
+ if (!dynamicPropsList && codegenNode.dynamicProps && typeof codegenNode.dynamicProps !== "string" && isSimpleExpressionNode(codegenNode.dynamicProps)) {
8144
+ const content = codegenNode.dynamicProps.content;
8145
+ if (content.startsWith("[") && content.endsWith("]")) {
8146
+ dynamicPropsList = [content];
8147
+ }
8148
+ }
8149
+ const metadata = {
8150
+ testId,
8151
+ semanticName: semanticNameMap.get(testId),
8152
+ tag: element.tag,
8153
+ tagType: element.tagType,
8154
+ patchFlag,
8155
+ dynamicProps: dynamicPropsList,
8156
+ // Decode patch flags (bitwise) - preserved as-is from existing code.
8157
+ hasClickHandler: patchFlag ? Boolean(patchFlag & 32) : void 0,
8158
+ hasDynamicClass: patchFlag ? Boolean(patchFlag & 2) : void 0,
8159
+ hasDynamicStyle: patchFlag ? Boolean(patchFlag & 4) : void 0,
8160
+ hasDynamicText: patchFlag ? Boolean(patchFlag & 1) : void 0,
8161
+ staticAriaLabel: findStaticAttributeValue(element, "aria-label"),
8162
+ staticRole: findStaticAttributeValue(element, "role"),
8163
+ staticTitle: findStaticAttributeValue(element, "title"),
8164
+ staticTextContent: collectStaticTextContent(element.children),
8165
+ sourceLine: element.loc?.start.line,
8166
+ sourceColumn: element.loc?.start.column
8336
8167
  };
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;
8359
- }
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 };
8481
- }
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 };
8487
- }
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: [
8505
- createTestIdTransform(
8506
- componentName,
8507
- provisionalHierarchy,
8508
- nativeWrappers,
8509
- excludedComponents,
8510
- getViewsDirAbs(),
8511
- {
8512
- existingIdBehavior: existingIdBehavior ?? "error",
8513
- nameCollisionBehavior,
8514
- missingSemanticNameBehavior,
8515
- testIdAttribute,
8516
- warn: (message) => loggerRef.current.warn(message),
8517
- vueFilesPathMap: provisionalVuePathMap,
8518
- wrapperSearchRoots: getWrapperSearchRoots(),
8519
- crossFileKeyRegistry: provisionalKeyRegistry,
8520
- optionKeyAttribute
8521
- }
8522
- )
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;
8657
- }
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
- );
8688
- }
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;
8700
- }
8701
- if (changedAbsPosix.includes("/vite-plugins/vue-pom-generator/")) {
8702
- void server.restart();
8703
- }
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
- }
8738
- };
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 } : {}
8775
- };
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;
8783
- }
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
- );
8789
- }
8790
- }
8791
- return warnings;
8792
- }
8793
- function matchesPrimarySelector(extraMethod, pom) {
8794
- if (extraMethod.selector.kind !== "testId") {
8795
- return false;
8796
- }
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);
8168
+ return metadata;
8169
+ }
8170
+ function matchesPrimarySelector(extraMethod, pom) {
8171
+ if (extraMethod.selector.kind !== "testId") {
8172
+ return false;
8173
+ }
8174
+ return extraMethod.selector.testId.formatted === pom.selector.formatted && extraMethod.selector.testId.patternKind === pom.selector.patternKind;
8175
+ }
8176
+ function getManifestEntry(componentName, entry, componentMetadata, extraMethods) {
8177
+ const testId = entry.selectorValue.formatted;
8178
+ const metadata = componentMetadata?.get(testId);
8179
+ const pom = entry.pom;
8180
+ const generatedActionName = pom ? buildPomGeneratedActionName(pom) : null;
8181
+ const extraActionNames = pom ? extraMethods.filter((extraMethod) => matchesPrimarySelector(extraMethod, pom)).map((extraMethod) => extraMethod.name).sort((a, b) => a.localeCompare(b)) : [];
8182
+ const generatedActionNames = Array.from(/* @__PURE__ */ new Set([
8183
+ ...generatedActionName ? [generatedActionName] : [],
8184
+ ...extraActionNames.filter((name) => name !== generatedActionName)
8185
+ ]));
8186
+ const accessibility = buildAccessibilityAudit(metadata, pom?.nativeRole ?? null);
8810
8187
  return {
8811
8188
  testId,
8812
8189
  selectorPatternKind: entry.selectorValue.patternKind,
@@ -8935,157 +8312,333 @@ function generatePomManifestModule(componentHierarchyMap, elementMetadata) {
8935
8312
  });
8936
8313
  });
8937
8314
  }
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);
8315
+ function resolveExistingIdBehavior(config, componentName) {
8316
+ return typeof config === "string" ? config : config.components[componentName] ?? config.default;
8317
+ }
8318
+ function resolveCompilerSfcParse(compilerSfc) {
8319
+ const parse2 = compilerSfc.parse ?? compilerSfc.default?.parse;
8320
+ if (typeof parse2 !== "function") {
8321
+ throw new TypeError("[vue-pom-generator] Failed to resolve @vue/compiler-sfc.parse.");
8322
+ }
8323
+ return parse2;
8324
+ }
8325
+ function extractMetadataAfterTransform(ast, componentName, elementMetadata, semanticNameMap, testIdAttribute) {
8326
+ const componentMetadata = /* @__PURE__ */ new Map();
8327
+ function traverseNode(node) {
8328
+ if (node.type === NodeTypes.ELEMENT) {
8329
+ const element = node;
8330
+ const testIdAttr = findDataTestIdProp(element, testIdAttribute);
8331
+ if (testIdAttr) {
8332
+ const metadata = tryCreateElementMetadata({
8333
+ element,
8334
+ semanticNameMap,
8335
+ testIdAttribute
8336
+ });
8337
+ if (metadata) {
8338
+ componentMetadata.set(metadata.testId, metadata);
8339
+ }
8340
+ }
8341
+ if (element.children) {
8342
+ for (const child of element.children) {
8343
+ traverseNode(child);
8344
+ }
8345
+ }
8346
+ } else if (node.type === NodeTypes.IF) {
8347
+ for (const branch of node.branches) {
8348
+ traverseNode(branch);
8349
+ }
8350
+ } else if (node.type === NodeTypes.IF_BRANCH || node.type === NodeTypes.FOR) {
8351
+ if (node.children) {
8352
+ for (const child of node.children) {
8353
+ traverseNode(child);
8354
+ }
8355
+ }
8356
+ } else if (node.type === NodeTypes.ROOT) {
8357
+ for (const child of node.children) {
8358
+ traverseNode(child);
8359
+ }
8360
+ }
8361
+ }
8362
+ traverseNode(ast);
8363
+ if (componentMetadata.size > 0) {
8364
+ elementMetadata.set(componentName, componentMetadata);
8365
+ }
8366
+ return componentMetadata;
8367
+ }
8368
+ function createVuePluginWithTestIds(options) {
8369
+ const {
8370
+ vueOptions,
8371
+ existingIdBehavior,
8372
+ nameCollisionBehavior,
8373
+ missingSemanticNameBehavior = "error",
8374
+ nativeWrappers,
8375
+ optionKeyAttribute,
8376
+ elementMetadata,
8377
+ semanticNameMap,
8378
+ componentHierarchyMap,
8379
+ crossFileKeyRegistry,
8380
+ vueFilesPathMap,
8381
+ excludedComponents,
8382
+ getViewsDirAbs,
8383
+ testIdAttribute,
8384
+ accessibilityAudit,
8385
+ loggerRef,
8386
+ getSourceDirs,
8387
+ getWrapperSearchRoots,
8388
+ getProjectRoot,
8389
+ annotatorMetadata
8390
+ } = options;
8391
+ const lastAccessibilityWarningSignatureByComponent = /* @__PURE__ */ new Map();
8392
+ const getComponentNameFromPath = (filename) => {
8393
+ return resolveComponentNameFromPath({
8394
+ filename,
8395
+ projectRoot: getProjectRoot(),
8396
+ viewsDirAbs: getViewsDirAbs(),
8397
+ sourceDirs: getSourceDirs(),
8398
+ extraRoots: [process.cwd()]
8399
+ });
8400
+ };
8401
+ const isFileInScope = (filename) => {
8402
+ if (!filename)
8403
+ return false;
8404
+ const cleanPath = filename.includes("?") ? filename.substring(0, filename.indexOf("?")) : filename;
8405
+ const projectRoot = getProjectRoot();
8406
+ const matched = isFileInConfiguredSourceScope({
8407
+ filename,
8408
+ projectRoot,
8409
+ viewsDirAbs: getViewsDirAbs(),
8410
+ sourceDirs: getSourceDirs(),
8411
+ extraRoots: [process.cwd()]
8412
+ });
8413
+ if (cleanPath.endsWith(".vue") && !matched) {
8414
+ const absFilename = path.normalize(path.isAbsolute(cleanPath) ? cleanPath : path.resolve(projectRoot, cleanPath));
8415
+ loggerRef.current.debug(`[isFileInScope] REJECTED: ${absFilename} (Clean: ${cleanPath})`);
8416
+ }
8417
+ return matched;
8418
+ };
8419
+ const userTemplate = vueOptions?.template ?? {};
8420
+ const userCompilerOptions = userTemplate.compilerOptions ?? {};
8421
+ const userNodeTransforms = userCompilerOptions.nodeTransforms ?? [];
8422
+ const perFileTransform = /* @__PURE__ */ new Map();
8423
+ const getNodeTransforms = (filename, componentNameOverride) => {
8424
+ const cleanPath = filename.includes("?") ? filename.substring(0, filename.indexOf("?")) : filename;
8425
+ const viewsDirAbs = getViewsDirAbs();
8426
+ const componentName = componentNameOverride || getComponentNameFromPath(cleanPath);
8427
+ return [
8428
+ ...userNodeTransforms,
8429
+ (node, context) => {
8430
+ if (node.type === NodeTypes.ROOT) {
8431
+ componentHierarchyMap.delete(componentName);
8432
+ vueFilesPathMap.set(componentName, filename);
8433
+ perFileTransform.set(
8434
+ componentName,
8435
+ createTestIdTransform(
8436
+ componentName,
8437
+ componentHierarchyMap,
8438
+ nativeWrappers,
8439
+ excludedComponents,
8440
+ viewsDirAbs,
8441
+ {
8442
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
8443
+ testIdAttribute,
8444
+ nameCollisionBehavior,
8445
+ missingSemanticNameBehavior,
8446
+ warn: (message) => loggerRef.current.warn(message),
8447
+ vueFilesPathMap,
8448
+ wrapperSearchRoots: getWrapperSearchRoots(),
8449
+ annotatorMetadata,
8450
+ crossFileKeyRegistry,
8451
+ optionKeyAttribute
8452
+ }
8453
+ )
8454
+ );
8455
+ return () => {
8456
+ const componentMetadata = extractMetadataAfterTransform(
8457
+ node,
8458
+ componentName,
8459
+ elementMetadata,
8460
+ semanticNameMap,
8461
+ testIdAttribute
8462
+ );
8463
+ if (!accessibilityAudit) {
8464
+ return;
8465
+ }
8466
+ const dependencies = componentHierarchyMap.get(componentName);
8467
+ if (!dependencies || componentMetadata.size === 0) {
8468
+ return;
8469
+ }
8470
+ const manifest = buildPomManifest(
8471
+ /* @__PURE__ */ new Map([[componentName, dependencies]]),
8472
+ /* @__PURE__ */ new Map([[componentName, componentMetadata]])
8473
+ );
8474
+ const warnings = collectAccessibilityReviewWarnings(manifest);
8475
+ const signature = warnings.join("\n");
8476
+ if (!signature) {
8477
+ lastAccessibilityWarningSignatureByComponent.delete(componentName);
8478
+ return;
8479
+ }
8480
+ if (lastAccessibilityWarningSignatureByComponent.get(componentName) === signature) {
8481
+ return;
8482
+ }
8483
+ lastAccessibilityWarningSignatureByComponent.set(componentName, signature);
8484
+ for (const warning of warnings) {
8485
+ loggerRef.current.warn(warning);
8486
+ }
8487
+ };
8488
+ }
8489
+ let transform = perFileTransform.get(componentName);
8490
+ if (!transform) {
8491
+ componentHierarchyMap.delete(componentName);
8492
+ vueFilesPathMap.set(componentName, filename);
8493
+ transform = createTestIdTransform(
8494
+ componentName,
8495
+ componentHierarchyMap,
8496
+ nativeWrappers,
8497
+ excludedComponents,
8498
+ viewsDirAbs,
8499
+ {
8500
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
8501
+ testIdAttribute,
8502
+ nameCollisionBehavior,
8503
+ missingSemanticNameBehavior,
8504
+ warn: (message) => loggerRef.current.warn(message),
8505
+ vueFilesPathMap,
8506
+ wrapperSearchRoots: getWrapperSearchRoots(),
8507
+ annotatorMetadata,
8508
+ crossFileKeyRegistry,
8509
+ optionKeyAttribute
8510
+ }
8511
+ );
8512
+ perFileTransform.set(componentName, transform);
8513
+ }
8514
+ return transform(node, context);
8515
+ }
8516
+ ];
8517
+ };
8518
+ const runtimeNodeTransform = (node, context) => {
8519
+ const filename = context.filename;
8520
+ if (!filename || !filename.endsWith(".vue") || !isFileInScope(filename)) {
8521
+ return;
8956
8522
  }
8523
+ const transforms = getNodeTransforms(filename);
8524
+ const ourTransform = transforms[transforms.length - 1];
8525
+ return ourTransform(node, context);
8957
8526
  };
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) {
8527
+ const templateCompilerOptions = {
8528
+ ...userCompilerOptions,
8529
+ prefixIdentifiers: true,
8530
+ nodeTransforms: [
8531
+ ...userNodeTransforms,
8532
+ runtimeNodeTransform
8533
+ ]
8534
+ };
8535
+ const metadataCollectorPlugin = {
8536
+ name: "vue-pom-generator-metadata-collector",
8537
+ enforce: "pre",
8538
+ async transform(code, id) {
8539
+ const cleanPath = id.includes("?") ? id.substring(0, id.indexOf("?")) : id;
8540
+ if (!cleanPath.endsWith(".vue") || !isFileInScope(id)) {
9005
8541
  return null;
9006
8542
  }
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) {
8543
+ if (id !== cleanPath) {
9015
8544
  return null;
9016
8545
  }
9017
- const normalizedId = normalizePathSeparators(id);
9018
- if (!DEFAULT_ENTRY_SUFFIXES.some((suffix) => normalizedId.endsWith(suffix))) {
9019
- return null;
8546
+ const componentName = getComponentNameFromPath(cleanPath);
8547
+ loggerRef.current.debug(`Collecting metadata for ${cleanPath} (component: ${componentName})`);
8548
+ const compilerSfc = await import("@vue/compiler-sfc");
8549
+ const parse2 = resolveCompilerSfcParse(compilerSfc);
8550
+ const compilerDom2 = await import("@vue/compiler-dom");
8551
+ const compile = compilerDom2.compile;
8552
+ const { descriptor } = parse2(code, { filename: cleanPath });
8553
+ if (descriptor.template) {
8554
+ const mergedExpressionPlugins = Array.from(
8555
+ /* @__PURE__ */ new Set([
8556
+ "typescript",
8557
+ ...userCompilerOptions.expressionPlugins ?? []
8558
+ ])
8559
+ );
8560
+ compile(descriptor.template.content, {
8561
+ ...userCompilerOptions,
8562
+ filename: cleanPath,
8563
+ expressionPlugins: mergedExpressionPlugins,
8564
+ nodeTransforms: getNodeTransforms(cleanPath, componentName)
8565
+ });
8566
+ loggerRef.current.debug(`Metadata collected for ${cleanPath}`);
9020
8567
  }
9021
- if (code.includes(ANNOTATOR_CLIENT_VIRTUAL_ID)) {
9022
- return null;
8568
+ return null;
8569
+ }
8570
+ };
8571
+ const template = {
8572
+ ...userTemplate,
8573
+ compilerOptions: templateCompilerOptions
8574
+ };
8575
+ const internalVuePlugin = vue({
8576
+ ...vueOptions,
8577
+ template
8578
+ });
8579
+ const nuxtVueBridgePlugin = {
8580
+ name: "vue-pom-generator-nuxt-vue-bridge",
8581
+ apply: "serve",
8582
+ configResolved(config) {
8583
+ const viteVuePlugin = config.plugins.find((plugin) => {
8584
+ return typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === "vite:vue" && "api" in plugin;
8585
+ });
8586
+ const api = viteVuePlugin?.api;
8587
+ if (!api) {
8588
+ throw new Error("[vue-pom-generator] Nuxt bridge could not find vite:vue plugin to patch.");
9023
8589
  }
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;
8590
+ const currentOptions = api.options ?? {};
8591
+ const currentTemplate = currentOptions.template ?? {};
8592
+ const currentCompilerOptions = currentTemplate.compilerOptions ?? {};
8593
+ const currentNodeTransforms = currentCompilerOptions.nodeTransforms ?? [];
8594
+ if (currentNodeTransforms.includes(runtimeNodeTransform)) {
8595
+ return;
9033
8596
  }
9034
- const tag = {
9035
- tag: "script",
9036
- attrs: { type: "module" },
9037
- children: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};`,
9038
- injectTo: "body"
8597
+ api.options = {
8598
+ ...currentOptions,
8599
+ template: {
8600
+ ...currentTemplate,
8601
+ compilerOptions: {
8602
+ ...currentCompilerOptions,
8603
+ prefixIdentifiers: true,
8604
+ nodeTransforms: [
8605
+ ...currentNodeTransforms,
8606
+ runtimeNodeTransform
8607
+ ]
8608
+ }
8609
+ }
9039
8610
  };
9040
- return [tag];
9041
8611
  }
9042
8612
  };
8613
+ return { metadataCollectorPlugin, internalVuePlugin, nuxtVueBridgePlugin, templateCompilerOptions };
9043
8614
  }
9044
- function createInternalPlugins(options) {
9045
- const {
9046
- componentHierarchyMap,
9047
- crossFileKeyRegistry,
9048
- elementMetadata,
9049
- vueFilesPathMap,
9050
- nativeWrappers,
9051
- optionKeyAttribute,
9052
- excludedComponents,
9053
- getPageDirs,
9054
- getComponentDirs,
9055
- getLayoutDirs,
9056
- getViewsDir,
9057
- getSourceDirs,
9058
- getWrapperSearchRoots,
9059
- generation,
9060
- projectRootRef,
9061
- basePageClassPath: basePageClassPathOverride,
9062
- loggerRef,
9063
- annotatorRuntime
9064
- } = options;
9065
- const {
9066
- routerAwarePoms,
9067
- routerEntry,
9068
- routerType
9069
- } = 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);
9078
- };
9079
- const getDefaultBasePageClassPath = () => {
9080
- try {
9081
- return fileURLToPath(new URL("../class-generation/base-page.ts", import.meta.url));
9082
- } catch {
9083
- return path.resolve(__dirname, "..", "class-generation", "base-page.ts");
8615
+ function summarizeHierarchyMap(componentHierarchyMap) {
8616
+ let interactiveComponentCount = 0;
8617
+ let dataTestIdCount = 0;
8618
+ for (const dependencies of componentHierarchyMap.values()) {
8619
+ const selectorCount = dependencies.dataTestIdSet?.size ?? 0;
8620
+ if (selectorCount > 0) {
8621
+ interactiveComponentCount += 1;
8622
+ dataTestIdCount += selectorCount;
9084
8623
  }
8624
+ }
8625
+ return {
8626
+ entryCount: componentHierarchyMap.size,
8627
+ interactiveComponentCount,
8628
+ dataTestIdCount
9085
8629
  };
9086
- const basePageClassPath = basePageClassPathOverride ?? getDefaultBasePageClassPath();
9087
- const normalizedBasePagePath = path.posix.normalize(basePageClassPath);
9088
- const tsProcessor = createBuildProcessorPlugin({
8630
+ }
8631
+ function isLessRich(candidate, previous) {
8632
+ if (candidate.dataTestIdCount !== previous.dataTestIdCount) {
8633
+ return candidate.dataTestIdCount < previous.dataTestIdCount;
8634
+ }
8635
+ if (candidate.interactiveComponentCount !== previous.interactiveComponentCount) {
8636
+ return candidate.interactiveComponentCount < previous.interactiveComponentCount;
8637
+ }
8638
+ return candidate.entryCount < previous.entryCount;
8639
+ }
8640
+ function createBuildProcessorPlugin(options) {
8641
+ const {
9089
8642
  componentHierarchyMap,
9090
8643
  crossFileKeyRegistry,
9091
8644
  vueFilesPathMap,
@@ -9102,10 +8655,255 @@ function createInternalPlugins(options) {
9102
8655
  optionKeyAttribute,
9103
8656
  excludedComponents,
9104
8657
  getWrapperSearchRoots,
9105
- getResolvedRouterEntry: resolveRouterEntry2,
8658
+ getResolvedRouterEntry,
9106
8659
  loggerRef
9107
- });
9108
- const devProcessor = createDevProcessorPlugin({
8660
+ } = options;
8661
+ const {
8662
+ outDir,
8663
+ emitLanguages,
8664
+ typescriptOutputStructure,
8665
+ csharp,
8666
+ generateFixtures,
8667
+ customPomAttachments,
8668
+ customPomDir,
8669
+ requireCustomPomDir,
8670
+ customPomImportAliases,
8671
+ customPomImportNameCollisionBehavior,
8672
+ testIdAttribute,
8673
+ nameCollisionBehavior,
8674
+ missingSemanticNameBehavior,
8675
+ existingIdBehavior,
8676
+ routerAwarePoms,
8677
+ routerType,
8678
+ routerModuleShims
8679
+ } = generation;
8680
+ let lastGeneratedMetrics = {
8681
+ entryCount: 0,
8682
+ interactiveComponentCount: 0,
8683
+ dataTestIdCount: 0
8684
+ };
8685
+ const getViewsDirAbs = () => path.isAbsolute(getViewsDir()) ? getViewsDir() : path.resolve(projectRootRef.current, getViewsDir());
8686
+ const getPageDirsAbs = () => getPageDirs().map((dir) => path.isAbsolute(dir) ? dir : path.resolve(projectRootRef.current, dir));
8687
+ const getScriptInfo = (source, filename) => {
8688
+ try {
8689
+ const { descriptor } = parse$1(source, { filename });
8690
+ if (!descriptor.script && !descriptor.scriptSetup)
8691
+ return { bindings: void 0, isScriptSetup: false };
8692
+ const scriptBlock = compileScript(descriptor, { id: filename });
8693
+ return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
8694
+ } catch {
8695
+ return { bindings: void 0, isScriptSetup: false };
8696
+ }
8697
+ };
8698
+ const supplementHierarchyFromFilesystem = () => {
8699
+ const walkFilesRecursive = (rootDir) => {
8700
+ const out = [];
8701
+ const stack = [rootDir];
8702
+ while (stack.length) {
8703
+ const dir = stack.pop();
8704
+ if (!dir) continue;
8705
+ let entries = [];
8706
+ try {
8707
+ entries = fs.readdirSync(dir, { withFileTypes: true });
8708
+ } catch {
8709
+ continue;
8710
+ }
8711
+ for (const ent of entries) {
8712
+ if (ent.isDirectory()) {
8713
+ if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
8714
+ continue;
8715
+ stack.push(path.join(dir, ent.name));
8716
+ continue;
8717
+ }
8718
+ if (ent.isFile() && ent.name.endsWith(".vue")) {
8719
+ out.push(path.join(dir, ent.name));
8720
+ }
8721
+ }
8722
+ }
8723
+ return out;
8724
+ };
8725
+ let supplemented = 0;
8726
+ for (const dir of getSourceDirs()) {
8727
+ const absDir = path.resolve(projectRootRef.current, dir);
8728
+ if (!fs.existsSync(absDir))
8729
+ continue;
8730
+ for (const filePath of walkFilesRecursive(absDir)) {
8731
+ const absolutePath = path.resolve(filePath);
8732
+ const componentName = resolveComponentNameFromPath({
8733
+ filename: absolutePath,
8734
+ projectRoot: projectRootRef.current,
8735
+ viewsDirAbs: getViewsDirAbs(),
8736
+ sourceDirs: getSourceDirs(),
8737
+ extraRoots: [process.cwd()]
8738
+ });
8739
+ if (componentHierarchyMap.has(componentName))
8740
+ continue;
8741
+ let sfc = "";
8742
+ try {
8743
+ sfc = fs.readFileSync(absolutePath, "utf8");
8744
+ } catch {
8745
+ continue;
8746
+ }
8747
+ const { descriptor } = parse$1(sfc, { filename: absolutePath });
8748
+ const template = descriptor.template?.content ?? "";
8749
+ if (!template.trim()) {
8750
+ vueFilesPathMap.set(componentName, absolutePath);
8751
+ componentHierarchyMap.set(componentName, {
8752
+ filePath: absolutePath,
8753
+ childrenComponentSet: /* @__PURE__ */ new Set(),
8754
+ usedComponentSet: /* @__PURE__ */ new Set(),
8755
+ dataTestIdSet: /* @__PURE__ */ new Set(),
8756
+ isView: false,
8757
+ methodsContent: ""
8758
+ });
8759
+ supplemented++;
8760
+ continue;
8761
+ }
8762
+ const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
8763
+ vueFilesPathMap.set(componentName, absolutePath);
8764
+ try {
8765
+ compilerDom.compile(template, {
8766
+ filename: absolutePath,
8767
+ prefixIdentifiers: true,
8768
+ inline: isScriptSetup,
8769
+ bindingMetadata,
8770
+ // See dev-plugin.ts — same rationale: enable TS in template
8771
+ // expressions so `(row: RowType) => ...` handlers parse.
8772
+ expressionPlugins: ["typescript"],
8773
+ nodeTransforms: [
8774
+ createTestIdTransform(
8775
+ componentName,
8776
+ componentHierarchyMap,
8777
+ nativeWrappers,
8778
+ excludedComponents,
8779
+ getViewsDirAbs(),
8780
+ {
8781
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
8782
+ testIdAttribute,
8783
+ nameCollisionBehavior,
8784
+ missingSemanticNameBehavior,
8785
+ warn: (message) => loggerRef.current.warn(message),
8786
+ vueFilesPathMap,
8787
+ wrapperSearchRoots: getWrapperSearchRoots(),
8788
+ crossFileKeyRegistry,
8789
+ optionKeyAttribute
8790
+ }
8791
+ )
8792
+ ]
8793
+ });
8794
+ } catch {
8795
+ }
8796
+ supplemented++;
8797
+ }
8798
+ }
8799
+ if (supplemented > 0) {
8800
+ loggerRef.current.info(`supplemented ${supplemented} components from filesystem walk (not in build graph)`);
8801
+ }
8802
+ };
8803
+ return {
8804
+ name: "vue-pom-generator-build",
8805
+ // This plugin exists to generate code on build output; it is not needed during dev-server HMR.
8806
+ apply: "build",
8807
+ enforce: "pre",
8808
+ async buildStart() {
8809
+ if (!routerAwarePoms) {
8810
+ setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
8811
+ setResolveToComponentNameFn(() => null);
8812
+ return;
8813
+ }
8814
+ let result;
8815
+ if (routerType === "nuxt") {
8816
+ result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
8817
+ } else {
8818
+ const resolvedRouterEntry = getResolvedRouterEntry();
8819
+ if (!resolvedRouterEntry)
8820
+ throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
8821
+ result = await parseRouterFileFromCwd(resolvedRouterEntry, {
8822
+ moduleShims: routerModuleShims,
8823
+ componentNaming: {
8824
+ projectRoot: projectRootRef.current,
8825
+ viewsDirAbs: getViewsDirAbs(),
8826
+ sourceDirs: getSourceDirs()
8827
+ }
8828
+ });
8829
+ }
8830
+ const { routeNameMap, routePathMap } = result;
8831
+ setRouteNameToComponentNameMap(routeNameMap);
8832
+ setResolveToComponentNameFn((to) => {
8833
+ if (typeof to === "string") {
8834
+ return routePathMap.get(to) ?? null;
8835
+ }
8836
+ const maybe = to;
8837
+ if (typeof maybe.name === "string" && maybe.name.length) {
8838
+ const key = toPascalCase(maybe.name);
8839
+ return routeNameMap.get(key) ?? null;
8840
+ }
8841
+ if (typeof maybe.path === "string" && maybe.path.length) {
8842
+ return routePathMap.get(maybe.path) ?? null;
8843
+ }
8844
+ return null;
8845
+ });
8846
+ if (!fs.existsSync(basePageClassPath)) {
8847
+ this.error(`Base page runtime file not found at ${basePageClassPath}. Ensure it is included in the build.`);
8848
+ }
8849
+ this.addWatchFile(basePageClassPath);
8850
+ const pointerPath = path.resolve(path.dirname(basePageClassPath), "pointer.ts");
8851
+ if (!fs.existsSync(pointerPath)) {
8852
+ this.error(`pointer.ts not found at ${pointerPath}. Ensure it is included in the build.`);
8853
+ }
8854
+ this.addWatchFile(pointerPath);
8855
+ const calloutPath = path.resolve(path.dirname(basePageClassPath), "callout.ts");
8856
+ if (!fs.existsSync(calloutPath)) {
8857
+ this.error(`callout.ts not found at ${calloutPath}. Ensure it is included in the build.`);
8858
+ }
8859
+ this.addWatchFile(calloutPath);
8860
+ const floatingUiCalloutPath = path.resolve(path.dirname(basePageClassPath), "floating-ui-callout.ts");
8861
+ if (fs.existsSync(floatingUiCalloutPath)) {
8862
+ this.addWatchFile(floatingUiCalloutPath);
8863
+ }
8864
+ },
8865
+ async buildEnd(error) {
8866
+ if (error) {
8867
+ return;
8868
+ }
8869
+ supplementHierarchyFromFilesystem();
8870
+ const metrics = summarizeHierarchyMap(componentHierarchyMap);
8871
+ if (metrics.dataTestIdCount <= 0) {
8872
+ return;
8873
+ }
8874
+ if (isLessRich(metrics, lastGeneratedMetrics)) {
8875
+ return;
8876
+ }
8877
+ await generateFiles(componentHierarchyMap, vueFilesPathMap, normalizedBasePagePath, {
8878
+ outDir,
8879
+ emitLanguages,
8880
+ typescriptOutputStructure,
8881
+ csharp,
8882
+ generateFixtures,
8883
+ customPomAttachments,
8884
+ projectRoot: projectRootRef.current,
8885
+ customPomDir,
8886
+ requireCustomPomDir,
8887
+ customPomImportAliases,
8888
+ customPomImportNameCollisionBehavior,
8889
+ testIdAttribute,
8890
+ vueRouterFluentChaining: routerAwarePoms,
8891
+ routerEntry: getResolvedRouterEntry(),
8892
+ routerType,
8893
+ pageDirs: getPageDirs(),
8894
+ componentDirs: getComponentDirs(),
8895
+ layoutDirs: getLayoutDirs()
8896
+ });
8897
+ lastGeneratedMetrics = metrics;
8898
+ loggerRef.current.info(`generated POMs (${metrics.entryCount} entries, ${metrics.interactiveComponentCount} interactive components, ${metrics.dataTestIdCount} selectors)`);
8899
+ },
8900
+ closeBundle() {
8901
+ loggerRef.current.info("build complete");
8902
+ }
8903
+ };
8904
+ }
8905
+ function createDevProcessorPlugin(options) {
8906
+ const {
9109
8907
  nativeWrappers,
9110
8908
  optionKeyAttribute,
9111
8909
  excludedComponents,
@@ -9119,438 +8917,644 @@ function createInternalPlugins(options) {
9119
8917
  normalizedBasePagePath,
9120
8918
  basePageClassPath,
9121
8919
  generation,
9122
- getResolvedRouterEntry: resolveRouterEntry2,
8920
+ getResolvedRouterEntry,
9123
8921
  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);
8922
+ } = options;
8923
+ const {
8924
+ outDir,
8925
+ emitLanguages,
8926
+ typescriptOutputStructure,
8927
+ csharp,
8928
+ generateFixtures,
8929
+ customPomAttachments,
8930
+ customPomDir,
8931
+ requireCustomPomDir,
8932
+ customPomImportAliases,
8933
+ customPomImportNameCollisionBehavior,
8934
+ nameCollisionBehavior,
8935
+ missingSemanticNameBehavior,
8936
+ existingIdBehavior,
8937
+ testIdAttribute,
8938
+ routerAwarePoms,
8939
+ routerType,
8940
+ routerModuleShims
8941
+ } = generation;
8942
+ let scheduleVueFileRegen = null;
8943
+ const getProjectRootCandidates = () => Array.from(/* @__PURE__ */ new Set([
8944
+ path.resolve(projectRootRef.current),
8945
+ path.resolve(process.cwd())
8946
+ ]));
8947
+ const resolveProjectPath = (maybePath) => {
8948
+ if (path.isAbsolute(maybePath))
8949
+ return maybePath;
8950
+ const candidates = getProjectRootCandidates().map((root) => path.resolve(root, maybePath));
8951
+ return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0];
8952
+ };
8953
+ const getSourceDirRoots = () => Array.from(new Set(
8954
+ getProjectRootCandidates().flatMap((root) => getSourceDirs().map((dir) => path.resolve(root, dir)))
8955
+ ));
8956
+ const isContainedInScanDirs = (filePath) => {
8957
+ const absolutePath = path.resolve(filePath);
8958
+ return getSourceDirRoots().some((scanDirAbs) => isPathWithinDir(absolutePath, scanDirAbs));
8959
+ };
8960
+ return {
8961
+ name: "vue-pom-generator-dev",
8962
+ apply: "serve",
8963
+ // Prefer hot-update events over filesystem change events for speed and reliability.
8964
+ // This fires when Vite has actually processed the module update.
8965
+ handleHotUpdate(ctx) {
8966
+ if (!scheduleVueFileRegen)
8967
+ return;
8968
+ if (!ctx.file.endsWith(".vue"))
8969
+ return;
8970
+ if (!isContainedInScanDirs(ctx.file))
8971
+ return;
8972
+ scheduleVueFileRegen(ctx.file, "hmr");
8973
+ },
8974
+ async configureServer(server) {
8975
+ const getViewsDirAbs = () => resolveProjectPath(getViewsDir());
8976
+ const getPageDirsAbs = () => getPageDirs().map((dir) => resolveProjectPath(dir));
8977
+ const routerInitPromise = (async () => {
8978
+ if (!routerAwarePoms) {
8979
+ setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
8980
+ setResolveToComponentNameFn(() => null);
8981
+ return;
8982
+ }
8983
+ let result;
8984
+ if (routerType === "nuxt") {
8985
+ result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
8986
+ } else {
8987
+ const resolvedRouterEntry = getResolvedRouterEntry();
8988
+ if (!resolvedRouterEntry)
8989
+ throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
8990
+ result = await parseRouterFileFromCwd(resolvedRouterEntry, {
8991
+ moduleShims: routerModuleShims,
8992
+ componentNaming: {
8993
+ projectRoot: projectRootRef.current,
8994
+ viewsDirAbs: getViewsDirAbs(),
8995
+ sourceDirs: getSourceDirs(),
8996
+ extraRoots: [process.cwd()]
8997
+ }
8998
+ });
8999
+ }
9000
+ const { routeNameMap, routePathMap } = result;
9001
+ setRouteNameToComponentNameMap(routeNameMap);
9002
+ setResolveToComponentNameFn((to) => {
9003
+ if (typeof to === "string") {
9004
+ return routePathMap.get(to) ?? null;
9005
+ }
9006
+ const maybe = to;
9007
+ if (typeof maybe.name === "string" && maybe.name.length) {
9008
+ const key = toPascalCase(maybe.name);
9009
+ return routeNameMap.get(key) ?? null;
9010
+ }
9011
+ if (typeof maybe.path === "string" && maybe.path.length) {
9012
+ return routePathMap.get(maybe.path) ?? null;
9013
+ }
9014
+ return null;
9015
+ });
9016
+ })();
9017
+ const logInfo = (message) => loggerRef.current.info(message);
9018
+ const logDebug = (message) => loggerRef.current.debug(message);
9019
+ let scheduleVueFileRegenLocal = null;
9020
+ const formatMs = (ms) => `${ms.toFixed(1)}ms`;
9021
+ const extractTemplateFromSfc = (source, filename) => {
9022
+ const { descriptor } = parse$1(source, {
9023
+ filename: filename ?? "anonymous.vue"
9024
+ });
9025
+ return descriptor.template?.content ?? "";
9026
+ };
9027
+ const getScriptInfo = (source, filename) => {
9028
+ try {
9029
+ const { descriptor } = parse$1(source, { filename });
9030
+ if (!descriptor.script && !descriptor.scriptSetup)
9031
+ return { bindings: void 0, isScriptSetup: false };
9032
+ const scriptBlock = compileScript(descriptor, { id: filename });
9033
+ return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
9034
+ } catch {
9035
+ return { bindings: void 0, isScriptSetup: false };
9036
+ }
9037
+ };
9038
+ const walkFilesRecursive = (rootDir) => {
9039
+ const out = [];
9040
+ const stack = [rootDir];
9041
+ while (stack.length) {
9042
+ const dir = stack.pop();
9043
+ if (!dir) continue;
9044
+ let entries = [];
9045
+ try {
9046
+ entries = fs.readdirSync(dir, { withFileTypes: true });
9047
+ } catch {
9048
+ continue;
9049
+ }
9050
+ for (const ent of entries) {
9051
+ if (ent.isDirectory()) {
9052
+ if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
9053
+ continue;
9054
+ stack.push(path.join(dir, ent.name));
9055
+ continue;
9056
+ }
9057
+ if (ent.isFile() && ent.name.endsWith(".vue")) {
9058
+ out.push(path.join(dir, ent.name));
9059
+ }
9060
+ }
9061
+ }
9062
+ return out;
9063
+ };
9064
+ let snapshotHierarchy = /* @__PURE__ */ new Map();
9065
+ let snapshotVuePathMap = /* @__PURE__ */ new Map();
9066
+ const filePathToComponentName = /* @__PURE__ */ new Map();
9067
+ const createEmptyComponentDependencies = (absolutePath) => {
9068
+ const viewsDirAbs = path.resolve(getViewsDirAbs());
9069
+ const relToViewsDir = path.relative(viewsDirAbs, absolutePath);
9070
+ const isView = !relToViewsDir.startsWith("..") && !path.isAbsolute(relToViewsDir);
9071
+ return {
9072
+ filePath: absolutePath,
9073
+ childrenComponentSet: /* @__PURE__ */ new Set(),
9074
+ usedComponentSet: /* @__PURE__ */ new Set(),
9075
+ dataTestIdSet: /* @__PURE__ */ new Set(),
9076
+ isView,
9077
+ methodsContent: ""
9078
+ };
9079
+ };
9080
+ const getComponentNameForFile = (filePath) => {
9081
+ const normalized = path.resolve(filePath);
9082
+ const existing = filePathToComponentName.get(normalized);
9083
+ if (existing)
9084
+ return existing;
9085
+ const name = resolveComponentNameFromPath({
9086
+ filename: normalized,
9087
+ projectRoot: projectRootRef.current,
9088
+ viewsDirAbs: getViewsDirAbs(),
9089
+ sourceDirs: getSourceDirs(),
9090
+ extraRoots: [process.cwd()]
9091
+ });
9092
+ filePathToComponentName.set(normalized, name);
9093
+ return name;
9094
+ };
9095
+ const compileVueFileIntoSnapshot = (filePath, targetHierarchy = snapshotHierarchy, targetVuePathMap = snapshotVuePathMap) => {
9096
+ const started = performance.now();
9097
+ const absolutePath = path.resolve(filePath);
9098
+ const componentName = getComponentNameForFile(absolutePath);
9099
+ let sfc = "";
9100
+ try {
9101
+ sfc = fs.readFileSync(absolutePath, "utf8");
9102
+ } catch {
9103
+ return { componentName, ms: performance.now() - started, compiled: false };
9202
9104
  }
9203
- continue;
9204
- }
9205
- if (node.type === NodeTypes.ELEMENT) {
9206
- visit(node.children);
9207
- }
9208
- }
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];
9235
- }
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
- };
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
9105
+ const template = extractTemplateFromSfc(sfc, absolutePath);
9106
+ if (!template.trim()) {
9107
+ targetVuePathMap.set(componentName, absolutePath);
9108
+ targetHierarchy.set(componentName, createEmptyComponentDependencies(absolutePath));
9109
+ return { componentName, ms: performance.now() - started, compiled: true };
9110
+ }
9111
+ const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
9112
+ const provisionalHierarchy = /* @__PURE__ */ new Map();
9113
+ const provisionalKeyRegistry = /* @__PURE__ */ new Map();
9114
+ const provisionalVuePathMap = new Map(targetVuePathMap);
9115
+ provisionalVuePathMap.set(componentName, absolutePath);
9116
+ compilerDom.compile(template, {
9117
+ filename: absolutePath,
9118
+ prefixIdentifiers: true,
9119
+ inline: isScriptSetup,
9120
+ bindingMetadata,
9121
+ // Vue templates may contain TypeScript type annotations in expressions
9122
+ // (e.g. `@row-click="(row: RowType) => navigateTo(...)"` in Nuxt + TS
9123
+ // apps). Without this flag, Vue's internal processExpression step
9124
+ // delegates to @babel/parser without the TS plugin and crashes on
9125
+ // "Unexpected token, expected ','".
9126
+ expressionPlugins: ["typescript"],
9127
+ nodeTransforms: [
9128
+ createTestIdTransform(
9129
+ componentName,
9130
+ provisionalHierarchy,
9131
+ nativeWrappers,
9132
+ excludedComponents,
9133
+ getViewsDirAbs(),
9134
+ {
9135
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
9136
+ nameCollisionBehavior,
9137
+ missingSemanticNameBehavior,
9138
+ testIdAttribute,
9139
+ warn: (message) => loggerRef.current.warn(message),
9140
+ vueFilesPathMap: provisionalVuePathMap,
9141
+ wrapperSearchRoots: getWrapperSearchRoots(),
9142
+ crossFileKeyRegistry: provisionalKeyRegistry,
9143
+ optionKeyAttribute
9144
+ }
9145
+ )
9146
+ ]
9276
9147
  });
9277
- if (metadata) {
9278
- componentMetadata.set(metadata.testId, metadata);
9148
+ targetVuePathMap.set(componentName, absolutePath);
9149
+ targetHierarchy.set(
9150
+ componentName,
9151
+ provisionalHierarchy.get(componentName) ?? createEmptyComponentDependencies(absolutePath)
9152
+ );
9153
+ return { componentName, ms: performance.now() - started, compiled: true };
9154
+ };
9155
+ const fullRebuildSnapshotFromFilesystem = (logLabel) => {
9156
+ const t0 = performance.now();
9157
+ const nextHierarchy = /* @__PURE__ */ new Map();
9158
+ const nextVuePathMap = /* @__PURE__ */ new Map();
9159
+ filePathToComponentName.clear();
9160
+ let totalVueFiles = 0;
9161
+ let compiledCount = 0;
9162
+ for (const absDir of getSourceDirRoots()) {
9163
+ if (!fs.existsSync(absDir))
9164
+ continue;
9165
+ const vueFiles = walkFilesRecursive(absDir);
9166
+ totalVueFiles += vueFiles.length;
9167
+ for (const file of vueFiles) {
9168
+ const res = compileVueFileIntoSnapshot(file, nextHierarchy, nextVuePathMap);
9169
+ if (res.compiled)
9170
+ compiledCount++;
9171
+ }
9279
9172
  }
9280
- }
9281
- if (element.children) {
9282
- for (const child of element.children) {
9283
- traverseNode(child);
9173
+ snapshotHierarchy = nextHierarchy;
9174
+ snapshotVuePathMap = nextVuePathMap;
9175
+ const t1 = performance.now();
9176
+ logInfo(`scan(${logLabel}): found ${totalVueFiles} .vue files in ${getSourceDirs().join(", ")}`);
9177
+ logInfo(`compile(${logLabel}): ${compiledCount}/${totalVueFiles} files in ${formatMs(t1 - t0)} (components=${snapshotHierarchy.size})`);
9178
+ };
9179
+ const generateAggregatedFromSnapshot = async (logLabel) => {
9180
+ const t0 = performance.now();
9181
+ await generateFiles(snapshotHierarchy, snapshotVuePathMap, normalizedBasePagePath, {
9182
+ outDir,
9183
+ emitLanguages,
9184
+ typescriptOutputStructure,
9185
+ csharp,
9186
+ generateFixtures,
9187
+ customPomAttachments,
9188
+ projectRoot: projectRootRef.current,
9189
+ customPomDir,
9190
+ requireCustomPomDir,
9191
+ customPomImportAliases,
9192
+ customPomImportNameCollisionBehavior,
9193
+ pageDirs: getPageDirs(),
9194
+ componentDirs: getComponentDirs(),
9195
+ layoutDirs: getLayoutDirs(),
9196
+ testIdAttribute,
9197
+ vueRouterFluentChaining: routerAwarePoms,
9198
+ routerEntry: getResolvedRouterEntry(),
9199
+ routerType
9200
+ });
9201
+ const t1 = performance.now();
9202
+ logInfo(`generate(${logLabel}): components=${snapshotHierarchy.size} in ${formatMs(t1 - t0)}`);
9203
+ };
9204
+ let timer = null;
9205
+ let maxWaitTimer = null;
9206
+ const pendingChangedVueFiles = /* @__PURE__ */ new Set();
9207
+ const pendingDeletedComponents = /* @__PURE__ */ new Set();
9208
+ let regenerationSequence = Promise.resolve();
9209
+ const initialBuildPromise = (async () => {
9210
+ const t0 = performance.now();
9211
+ await routerInitPromise;
9212
+ fullRebuildSnapshotFromFilesystem("startup");
9213
+ await generateAggregatedFromSnapshot("startup");
9214
+ const t1 = performance.now();
9215
+ logInfo(`startup total: ${formatMs(t1 - t0)}`);
9216
+ })();
9217
+ const logGenerationError = (reason, message) => {
9218
+ server.config.logger.error(`[vue-pom-generator] dev generation failed during ${reason}: ${message}`);
9219
+ };
9220
+ const regenerateFromPending = async (reason) => {
9221
+ const t0 = performance.now();
9222
+ await initialBuildPromise;
9223
+ const nextHierarchy = new Map(snapshotHierarchy);
9224
+ const nextVuePathMap = new Map(snapshotVuePathMap);
9225
+ for (const componentName of pendingDeletedComponents) {
9226
+ nextHierarchy.delete(componentName);
9227
+ nextVuePathMap.delete(componentName);
9228
+ }
9229
+ const files = Array.from(pendingChangedVueFiles);
9230
+ const deletedCount = pendingDeletedComponents.size;
9231
+ pendingChangedVueFiles.clear();
9232
+ pendingDeletedComponents.clear();
9233
+ let compileMs = 0;
9234
+ for (const f of files) {
9235
+ const res = compileVueFileIntoSnapshot(f, nextHierarchy, nextVuePathMap);
9236
+ compileMs += res.ms;
9237
+ }
9238
+ snapshotHierarchy = nextHierarchy;
9239
+ snapshotVuePathMap = nextVuePathMap;
9240
+ const t1 = performance.now();
9241
+ await generateAggregatedFromSnapshot(reason);
9242
+ const t2 = performance.now();
9243
+ return {
9244
+ files,
9245
+ deletedCount,
9246
+ compileMs,
9247
+ preGenerateMs: t1 - t0,
9248
+ generateMs: t2 - t1,
9249
+ totalMs: t2 - t0
9250
+ };
9251
+ };
9252
+ const enqueueRegeneration = (reason) => {
9253
+ const currentRun = regenerationSequence.catch(() => void 0).then(() => regenerateFromPending(reason));
9254
+ regenerationSequence = currentRun.then(() => void 0, () => void 0);
9255
+ return currentRun;
9256
+ };
9257
+ const runtimeDir = path.dirname(basePageClassPath);
9258
+ const localPluginDir = path.resolve(projectRootRef.current, "vite-plugins", "vue-pom-generator");
9259
+ server.watcher.add([
9260
+ ...fs.existsSync(localPluginDir) ? [localPluginDir] : [],
9261
+ basePageClassPath,
9262
+ path.resolve(runtimeDir, "pointer.ts"),
9263
+ path.resolve(runtimeDir, "callout.ts"),
9264
+ path.resolve(runtimeDir, "floating-ui-callout.ts")
9265
+ ]);
9266
+ scheduleVueFileRegenLocal = (filePath, source) => {
9267
+ pendingChangedVueFiles.add(filePath);
9268
+ logDebug(`queued(${source}): files=${pendingChangedVueFiles.size} deleted=${pendingDeletedComponents.size}`);
9269
+ scheduleAggregatedRegen();
9270
+ };
9271
+ scheduleVueFileRegen = scheduleVueFileRegenLocal;
9272
+ function scheduleAggregatedRegen() {
9273
+ const wasEmpty = pendingChangedVueFiles.size === 0 && pendingDeletedComponents.size === 0;
9274
+ const MAX_WAIT_MS = 750;
9275
+ if (!maxWaitTimer) {
9276
+ maxWaitTimer = setTimeout(() => {
9277
+ if (timer) {
9278
+ clearTimeout(timer);
9279
+ timer = null;
9280
+ }
9281
+ maxWaitTimer = null;
9282
+ void enqueueRegeneration("max-wait").then(({ files, deletedCount, compileMs, preGenerateMs, generateMs, totalMs }) => {
9283
+ logInfo(
9284
+ `max-wait: files=${files.length} deleted=${deletedCount} compile=${formatMs(compileMs)} wall=${formatMs(preGenerateMs)} gen=${formatMs(generateMs)} total=${formatMs(totalMs)}`
9285
+ );
9286
+ }).catch((error) => {
9287
+ const message = error instanceof Error ? error.message : String(error);
9288
+ logGenerationError("max-wait", message);
9289
+ });
9290
+ }, MAX_WAIT_MS);
9284
9291
  }
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);
9292
+ if (wasEmpty) {
9293
+ const queuedFiles = pendingChangedVueFiles.size;
9294
+ const queuedDeletes = pendingDeletedComponents.size;
9295
+ logDebug(`queued: files=${queuedFiles} deleted=${queuedDeletes}`);
9294
9296
  }
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);
9297
+ if (timer)
9298
+ clearTimeout(timer);
9299
+ timer = setTimeout(() => {
9300
+ timer = null;
9301
+ if (maxWaitTimer) {
9302
+ clearTimeout(maxWaitTimer);
9303
+ maxWaitTimer = null;
9304
+ }
9305
+ const reason = pendingChangedVueFiles.size || pendingDeletedComponents.size ? "batched" : "noop";
9306
+ void enqueueRegeneration(reason).then(({ files, deletedCount, compileMs, preGenerateMs, generateMs, totalMs }) => {
9307
+ if (files.length || deletedCount) {
9308
+ logInfo(
9309
+ `batched: files=${files.length} deleted=${deletedCount} compile=${formatMs(compileMs)} wall=${formatMs(preGenerateMs)} gen=${formatMs(generateMs)} total=${formatMs(totalMs)}`
9310
+ );
9426
9311
  }
9427
- };
9312
+ }).catch((error) => {
9313
+ const message = error instanceof Error ? error.message : String(error);
9314
+ logGenerationError(reason, message);
9315
+ });
9316
+ }, 75);
9317
+ }
9318
+ server.watcher.on("change", async (changedPath) => {
9319
+ const changedAbsPosix = path.posix.normalize(path.resolve(changedPath));
9320
+ const outDirAbsPosix = path.posix.normalize(path.resolve(projectRootRef.current, outDir ?? "./pom"));
9321
+ if (changedAbsPosix.startsWith(`${outDirAbsPosix}/`) && (changedAbsPosix.endsWith(".g.ts") || changedAbsPosix.endsWith(".g.ts.map"))) {
9322
+ return;
9428
9323
  }
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);
9324
+ if (changedAbsPosix.includes("/vite-plugins/vue-pom-generator/")) {
9325
+ void server.restart();
9453
9326
  }
9454
- return transform(node, context);
9455
- }
9456
- ];
9327
+ });
9328
+ server.watcher.on("add", (p) => {
9329
+ if (typeof p !== "string")
9330
+ return;
9331
+ if (!p.endsWith(".vue"))
9332
+ return;
9333
+ if (!isContainedInScanDirs(p))
9334
+ return;
9335
+ void (async () => {
9336
+ await initialBuildPromise;
9337
+ pendingChangedVueFiles.add(p);
9338
+ scheduleAggregatedRegen();
9339
+ })();
9340
+ });
9341
+ server.watcher.on("unlink", (p) => {
9342
+ if (typeof p !== "string")
9343
+ return;
9344
+ if (!p.endsWith(".vue"))
9345
+ return;
9346
+ if (!isContainedInScanDirs(p))
9347
+ return;
9348
+ void (async () => {
9349
+ await initialBuildPromise;
9350
+ const absolutePath = path.resolve(p);
9351
+ const componentName = getComponentNameForFile(absolutePath);
9352
+ filePathToComponentName.delete(absolutePath);
9353
+ pendingDeletedComponents.add(componentName);
9354
+ scheduleAggregatedRegen();
9355
+ })();
9356
+ });
9357
+ setTimeout(() => {
9358
+ }, 250);
9359
+ await initialBuildPromise;
9360
+ }
9457
9361
  };
9458
- const runtimeNodeTransform = (node, context) => {
9459
- const filename = context.filename;
9460
- if (!filename || !filename.endsWith(".vue") || !isFileInScope(filename)) {
9461
- return;
9362
+ }
9363
+ const TEST_IDS_VIRTUAL_ID = "virtual:testids";
9364
+ const TEST_IDS_RESOLVED_ID = `\0${TEST_IDS_VIRTUAL_ID}`;
9365
+ const POM_MANIFEST_VIRTUAL_ID = "virtual:pom-manifest";
9366
+ const POM_MANIFEST_RESOLVED_ID = `\0${POM_MANIFEST_VIRTUAL_ID}`;
9367
+ function createTestIdsVirtualModulesPlugin(componentHierarchyMap, elementMetadata) {
9368
+ return {
9369
+ name: "vue-pom-generator:virtual-testids",
9370
+ resolveId(id) {
9371
+ if (id === TEST_IDS_VIRTUAL_ID)
9372
+ return TEST_IDS_RESOLVED_ID;
9373
+ if (id === POM_MANIFEST_VIRTUAL_ID)
9374
+ return POM_MANIFEST_RESOLVED_ID;
9375
+ },
9376
+ load(id) {
9377
+ if (id === TEST_IDS_RESOLVED_ID)
9378
+ return generateTestIdsModule(componentHierarchyMap, elementMetadata);
9379
+ if (id === POM_MANIFEST_RESOLVED_ID)
9380
+ return generatePomManifestModule(componentHierarchyMap, elementMetadata);
9462
9381
  }
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
9382
  };
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)) {
9383
+ }
9384
+ const ANNOTATOR_CLIENT_VIRTUAL_ID = "virtual:vue-pom-generator/annotator-client";
9385
+ const ANNOTATOR_CLIENT_RESOLVED_ID = `\0${ANNOTATOR_CLIENT_VIRTUAL_ID}`;
9386
+ const DEFAULT_ENTRY_SUFFIXES = [
9387
+ "/src/main.ts",
9388
+ "/src/main.js",
9389
+ "/src/main.mts",
9390
+ "/src/main.tsx",
9391
+ "/src/main.jsx"
9392
+ ];
9393
+ function normalizePathSeparators(filePath) {
9394
+ return filePath.replace(/\\/g, "/");
9395
+ }
9396
+ function toFsImportPath(filePath) {
9397
+ return `/@fs/${normalizePathSeparators(filePath)}`;
9398
+ }
9399
+ function resolveAnnotatorClientPath() {
9400
+ const candidates = [
9401
+ fileURLToPath(new URL("./client.ts", import.meta.url)),
9402
+ fileURLToPath(new URL("../plugin/runtime/annotator/client.ts", import.meta.url))
9403
+ ];
9404
+ const resolved = candidates.find((candidate) => fs.existsSync(candidate));
9405
+ if (!resolved) {
9406
+ throw new Error("[vue-pom-generator] Unable to locate annotator client source.");
9407
+ }
9408
+ return path.resolve(resolved);
9409
+ }
9410
+ function createAnnotatorUiPlugin(options) {
9411
+ const clientPath = resolveAnnotatorClientPath();
9412
+ const clientImportPath = toFsImportPath(clientPath);
9413
+ const clientOptions = JSON.stringify({
9414
+ sourceAttribute: options.sourceAttribute,
9415
+ metadataAttributePrefix: options.metadataAttributePrefix,
9416
+ outputDetail: options.outputDetail,
9417
+ copyToClipboard: options.copyToClipboard,
9418
+ showComponentTree: options.showComponentTree
9419
+ });
9420
+ return {
9421
+ name: "vue-pom-generator:annotator-ui",
9422
+ apply: "serve",
9423
+ resolveId(id) {
9424
+ if (id === ANNOTATOR_CLIENT_VIRTUAL_ID) {
9425
+ return ANNOTATOR_CLIENT_RESOLVED_ID;
9426
+ }
9427
+ },
9428
+ load(id) {
9429
+ if (id !== ANNOTATOR_CLIENT_RESOLVED_ID) {
9481
9430
  return null;
9482
9431
  }
9483
- if (id !== cleanPath) {
9432
+ return [
9433
+ `import { mountAnnotatorClient } from ${JSON.stringify(clientImportPath)};`,
9434
+ `mountAnnotatorClient(${clientOptions});`,
9435
+ ""
9436
+ ].join("\n");
9437
+ },
9438
+ transform(code, id) {
9439
+ if (!options.enabled) {
9484
9440
  return null;
9485
9441
  }
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}`);
9442
+ const normalizedId = normalizePathSeparators(id);
9443
+ if (!DEFAULT_ENTRY_SUFFIXES.some((suffix) => normalizedId.endsWith(suffix))) {
9444
+ return null;
9507
9445
  }
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.");
9446
+ if (code.includes(ANNOTATOR_CLIENT_VIRTUAL_ID)) {
9447
+ return null;
9529
9448
  }
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;
9449
+ return {
9450
+ code: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};
9451
+ ${code}`,
9452
+ map: null
9453
+ };
9454
+ },
9455
+ transformIndexHtml() {
9456
+ if (!options.enabled) {
9457
+ return void 0;
9536
9458
  }
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
- }
9459
+ const tag = {
9460
+ tag: "script",
9461
+ attrs: { type: "module" },
9462
+ children: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};`,
9463
+ injectTo: "body"
9550
9464
  };
9465
+ return [tag];
9551
9466
  }
9552
9467
  };
9553
- return { metadataCollectorPlugin, internalVuePlugin, nuxtVueBridgePlugin, templateCompilerOptions };
9468
+ }
9469
+ function createInternalPlugins(options) {
9470
+ const {
9471
+ componentHierarchyMap,
9472
+ crossFileKeyRegistry,
9473
+ elementMetadata,
9474
+ vueFilesPathMap,
9475
+ nativeWrappers,
9476
+ optionKeyAttribute,
9477
+ excludedComponents,
9478
+ getPageDirs,
9479
+ getComponentDirs,
9480
+ getLayoutDirs,
9481
+ getViewsDir,
9482
+ getSourceDirs,
9483
+ getWrapperSearchRoots,
9484
+ generation,
9485
+ projectRootRef,
9486
+ basePageClassPath: basePageClassPathOverride,
9487
+ loggerRef,
9488
+ annotatorRuntime
9489
+ } = options;
9490
+ const {
9491
+ routerAwarePoms,
9492
+ routerEntry,
9493
+ routerType
9494
+ } = generation;
9495
+ const resolveRouterEntry2 = () => {
9496
+ if (!routerAwarePoms)
9497
+ return void 0;
9498
+ if (routerType === "nuxt")
9499
+ return void 0;
9500
+ if (!routerEntry)
9501
+ throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
9502
+ return path.isAbsolute(routerEntry) ? routerEntry : path.resolve(projectRootRef.current, routerEntry);
9503
+ };
9504
+ const getDefaultBasePageClassPath = () => {
9505
+ try {
9506
+ return fileURLToPath(new URL("../class-generation/base-page.ts", import.meta.url));
9507
+ } catch {
9508
+ return path.resolve(__dirname, "..", "class-generation", "base-page.ts");
9509
+ }
9510
+ };
9511
+ const basePageClassPath = basePageClassPathOverride ?? getDefaultBasePageClassPath();
9512
+ const normalizedBasePagePath = path.posix.normalize(basePageClassPath);
9513
+ const tsProcessor = createBuildProcessorPlugin({
9514
+ componentHierarchyMap,
9515
+ crossFileKeyRegistry,
9516
+ vueFilesPathMap,
9517
+ getPageDirs,
9518
+ getComponentDirs,
9519
+ getLayoutDirs,
9520
+ getViewsDir,
9521
+ getSourceDirs,
9522
+ basePageClassPath,
9523
+ normalizedBasePagePath,
9524
+ generation,
9525
+ projectRootRef,
9526
+ nativeWrappers,
9527
+ optionKeyAttribute,
9528
+ excludedComponents,
9529
+ getWrapperSearchRoots,
9530
+ getResolvedRouterEntry: resolveRouterEntry2,
9531
+ loggerRef
9532
+ });
9533
+ const devProcessor = createDevProcessorPlugin({
9534
+ nativeWrappers,
9535
+ optionKeyAttribute,
9536
+ excludedComponents,
9537
+ getPageDirs,
9538
+ getComponentDirs,
9539
+ getLayoutDirs,
9540
+ getViewsDir,
9541
+ getSourceDirs,
9542
+ getWrapperSearchRoots,
9543
+ projectRootRef,
9544
+ normalizedBasePagePath,
9545
+ basePageClassPath,
9546
+ generation,
9547
+ getResolvedRouterEntry: resolveRouterEntry2,
9548
+ loggerRef
9549
+ });
9550
+ const virtualModules = createTestIdsVirtualModulesPlugin(componentHierarchyMap, elementMetadata);
9551
+ const annotatorUiPlugin = createAnnotatorUiPlugin({
9552
+ ...annotatorRuntime.ui,
9553
+ enabled: annotatorRuntime.enabled && annotatorRuntime.ui.enabled,
9554
+ sourceAttribute: annotatorRuntime.sourceAttribute,
9555
+ metadataAttributePrefix: annotatorRuntime.metadataAttributePrefix
9556
+ });
9557
+ return [tsProcessor, devProcessor, virtualModules, annotatorUiPlugin];
9554
9558
  }
9555
9559
  const nuxtConfigMarker$1 = /* @__PURE__ */ Symbol.for("@immense/vue-pom-generator.nuxt");
9556
9560
  const nuxtConfigFileNames = [