@immense/vue-pom-generator 1.0.83 → 1.0.85

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 (51) hide show
  1. package/RELEASE_NOTES.md +57 -30
  2. package/class-generation/index.ts +234 -26
  3. package/class-generation/playwright-types.ts +120 -2
  4. package/dist/class-generation/index.d.ts +13 -0
  5. package/dist/class-generation/index.d.ts.map +1 -1
  6. package/dist/class-generation/playwright-types.d.ts +256 -2
  7. package/dist/class-generation/playwright-types.d.ts.map +1 -1
  8. package/dist/compiler-metadata-utils.d.ts.map +1 -1
  9. package/dist/eslint/index.cjs +16 -3
  10. package/dist/eslint/index.cjs.map +1 -1
  11. package/dist/eslint/index.mjs +16 -3
  12. package/dist/eslint/index.mjs.map +1 -1
  13. package/dist/eslint/no-raw-playwright-apis.d.ts.map +1 -1
  14. package/dist/eslint.config.d.ts.map +1 -1
  15. package/dist/index.cjs +163 -49
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.mjs +163 -49
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/pom-patterns.d.ts +28 -4
  20. package/dist/pom-patterns.d.ts.map +1 -1
  21. package/dist/router-introspection.d.ts +5 -0
  22. package/dist/router-introspection.d.ts.map +1 -1
  23. package/dist/tests/annotator-runtime-helpers.test.d.ts +2 -0
  24. package/dist/tests/annotator-runtime-helpers.test.d.ts.map +1 -0
  25. package/dist/tests/broad/accessibility-audit-ts.test.d.ts +2 -0
  26. package/dist/tests/broad/accessibility-audit-ts.test.d.ts.map +1 -0
  27. package/dist/tests/broad/class-generation-base-page-ts.test.d.ts +2 -0
  28. package/dist/tests/broad/class-generation-base-page-ts.test.d.ts.map +1 -0
  29. package/dist/tests/broad/compiler-metadata-utils-ts.test.d.ts +2 -0
  30. package/dist/tests/broad/compiler-metadata-utils-ts.test.d.ts.map +1 -0
  31. package/dist/tests/broad/helpers/fake-runtime.d.ts +162 -0
  32. package/dist/tests/broad/helpers/fake-runtime.d.ts.map +1 -0
  33. package/dist/tests/broad/manifest-generator-ts.test.d.ts +2 -0
  34. package/dist/tests/broad/manifest-generator-ts.test.d.ts.map +1 -0
  35. package/dist/tests/broad/metadata-collector-ts.test.d.ts +2 -0
  36. package/dist/tests/broad/metadata-collector-ts.test.d.ts.map +1 -0
  37. package/dist/tests/broad/plugin-logger-ts.test.d.ts +2 -0
  38. package/dist/tests/broad/plugin-logger-ts.test.d.ts.map +1 -0
  39. package/dist/tests/broad/plugin-resolved-generation-options-ts.test.d.ts +2 -0
  40. package/dist/tests/broad/plugin-resolved-generation-options-ts.test.d.ts.map +1 -0
  41. package/dist/tests/broad/plugin-runtime-annotator-format-ts.test.d.ts +2 -0
  42. package/dist/tests/broad/plugin-runtime-annotator-format-ts.test.d.ts.map +1 -0
  43. package/dist/tests/broad/typescript-codegen-ts.test.d.ts +2 -0
  44. package/dist/tests/broad/typescript-codegen-ts.test.d.ts.map +1 -0
  45. package/dist/tests/helpers/typed-mocks.d.ts +58 -0
  46. package/dist/tests/helpers/typed-mocks.d.ts.map +1 -0
  47. package/dist/transform.d.ts +36 -5
  48. package/dist/transform.d.ts.map +1 -1
  49. package/dist/utils.d.ts +261 -2
  50. package/dist/utils.d.ts.map +1 -1
  51. package/package.json +1 -1
package/RELEASE_NOTES.md CHANGED
@@ -1,50 +1,77 @@
1
- Only PR #45 falls in the git range v1.0.82..HEAD (confirmed by git log), with no release-bump commit
2
- to exclude. The long PR list spans prior releases; the 9-minute window and the diffstat both point
3
- to #45 alone. Here are the release notes:
1
+ I'll gather more context on the changes in this release range before writing the notes.
2
+
3
+ Git log confirms only two commits in the v1.0.84..HEAD range (no release bump commit to exclude). I
4
+ now have full PR context. Here are the release notes:
5
+
6
+ v1.0.85
4
7
 
5
8
  Highlights
6
9
 
7
- - Pure refactor, no behavior changes — consolidates annotator display-text helpers and normalizes
8
- the export surface.
9
- - Extracts shared display-text normalization into a new annotator/text-utils.ts, eliminating two
10
- duplicate inline copies.
11
- - Exposes pure annotator string helpers via an __internal export to enable direct unit testing.
12
- - Renames splitDiscoverabilityWords/joinDiscoverabilityWords to the shorter splitWords/joinWords
13
- with @example TSDoc.
14
- - Adds @example TSDoc to annotator helper functions for improved discoverability.
10
+ - Generated view POMs now emit a parametrized goTo(params) that drives the consumer's live Vue
11
+ Router at runtime via router.push({ name, params }), replacing the broken goToSelf() literal
12
+ template (#51)
13
+ - All route shapes are supported: paramless, required-param, all-optional-param, dual-route
14
+ overloads, and multi-param routes, with unnamed-route fallback to token substitution + page.goto
15
+ (#51)
16
+ - Cold-page navigation performs a full-load after router resolve to ensure interactive elements are
17
+ ready; warm-page uses pure SPA router.push with no reload (#51)
18
+ - router-introspection.ts now captures the Vue Router route name, enabling router.push/resolve by
19
+ name (#51)
20
+ - no-raw-playwright-apis ESLint rule now bans getByTestId as a raw locator-filter method (#49)
21
+ - Closes a computed-member bypass that let page["getByTestId"], page["locator"], and page["click"]
22
+ slip past the rule (#49)
15
23
 
16
24
  Changes
17
25
 
18
- Annotator runtime (plugin/runtime/annotator/)
26
+ Class Generation
27
+
28
+ - Replace goToSelf() with parametrized goTo(params) using router.push({ name, params }) at runtime
29
+ via globalThis.__appRouter (dev-gated by import.meta.env.DEV) (#51)
30
+ - Generate correct signatures per route shape: no-arg goTo() for paramless, goTo(params: { id })
31
+ for required, goTo(params?: { id? }) for all-optional, overloaded goTo()/goTo(params) for dual
32
+ routes, and multi-param goTo(params: { orgId; userId }) (#51)
33
+ - Cold-page regime: boot with page.goto("/"), waitForFunction for the router, resolve the href,
34
+ then full-load it to guarantee interactive readiness before force-clicks (#51)
35
+ - Warm-page regime: pure SPA router.push({ name, params }) with no reload (#51)
36
+
37
+ Router Introspection
38
+
39
+ - routeMetaEntries now include name: string | null (the Vue Router route name) for
40
+ router.push/resolve by name; token substitution retained only as the unnamed-route fallback (#51)
41
+
42
+ ESLint
19
43
 
20
- - Added text-utils.ts housing normalizeInlineText, now shared by client.ts and format.ts (replaces
21
- duplicated inline copies).
22
- - Added normalizePathSeparators to the annotator plugin.
23
- - Exposed pure helpers — placementPrimarySide, stripSourcePosition, inferNameFromFile,
24
- isComponentLikeSourceTag, formatSourceLabel, ignoredComponentNamePattern — via a __internal export
25
- for unit tests.
26
- - Added @example TSDoc to stripSourcePosition, inferNameFromFile, isComponentLikeSourceTag,
27
- formatSourceLabel, and ignoredComponentNamePattern in vue-detector.ts.
44
+ - Ban getByTestId as a raw locator-filter method alongside locator, getByRole, getByText, and
45
+ getByLabel — callable on Page, Locator, and Frame (#49)
46
+ - Replace early callee.computed return with resolveMemberPropertyName, which resolves the accessed
47
+ name from both Identifier form (page.getByTestId) and computed string-Literal form
48
+ (page["getByTestId"]) (#49)
49
+ - Dynamic computed keys (non-Literal, e.g. obj[dynamicKey]()) remain unresolvable and are left
50
+ alone (#49)
28
51
 
29
- POM discoverability (pom-discoverability.ts)
52
+ Tests
30
53
 
31
- - Renamed splitDiscoverabilityWords → splitWords and joinDiscoverabilityWords → joinWords; updated
32
- all internal call sites (humanizePomMethodName, humanizePomComponentName,
33
- buildPomLocatorDescription).
34
- - Added @example TSDoc to both renamed functions.
54
+ - Add TDD coverage for all goTo shapes: paramless, required, all-optional, dual-route overload, and
55
+ multi-param — asserting emitted signatures, cold/warm branches, routeParams construction, and
56
+ inlined dual-route name (#51)
57
+ - Add RuleTester cases for getByTestId bans (plain, on locator, with template-literal arg),
58
+ computed access to banned APIs, and negative cases for non-banned/dynamic computed access (#49)
35
59
 
36
60
  Breaking Changes
37
61
 
38
- None. This is a pure refactor with no behavior changes; renamed helpers were internal-only with no
39
- external callers.
62
+ None in this release.
40
63
 
41
64
  Pull Requests Included
42
65
 
43
- - ]8;id=md-gu5yjh;https://github.com/immense/vue-pom-generator/pull/45#45 — refactor: consolidate annotator display-text helpers and normalize export surface]8;;]8;; ]8;;
66
+ - ]8;id=md-1gcu8tw;https://github.com/immense/vue-pom-generator/pull/51#51 feat: emit parametrized goTo(params) for routes with declared params]8;;]8;; (@dkattan)]8;;
67
+ - ]8;id=md-diaq7t;https://github.com/immense/vue-pom-generator/pull/49#49 feat(eslint): ban getByTestId and close computed-member bypass in no-raw-playwright-apis]8;;]8;; ]8;;
44
68
  (@dkattan)
45
69
 
46
70
  Testing
47
71
 
48
- No new tests added. As a pure refactor preserving existing behavior, the unchanged functionality
49
- remains covered by the existing test suite.
72
+ - All 373 tests pass; npm run typecheck and npm run build are green (#51)
73
+ - RuleTester: 10 passed; tsc --noEmit and eslint . clean (#49)
74
+ - Three pre-existing DOM-environment suite failures (base-page, pointer,
75
+ broad/class-generation-base-page-ts) are environmental (jsdom under local vitest) and unrelated to
76
+ these changes (#49)
50
77
 
@@ -28,7 +28,7 @@ import {
28
28
  type PomStringPattern,
29
29
  } from "../pom-patterns";
30
30
  import { buildPomLocatorDescription, stripPomActionPrefix } from "../pom-discoverability";
31
- import { introspectNuxtPages, parseRouterFileFromCwd } from "../router-introspection";
31
+ import { getParamToken, introspectNuxtPages, parseRouterFileFromCwd } from "../router-introspection";
32
32
  import {
33
33
  addExportAll,
34
34
  addNamedImport,
@@ -108,8 +108,23 @@ function resolveRouterEntry(projectRoot?: string, routerEntry?: string) {
108
108
  return path.isAbsolute(routerEntry) ? routerEntry : path.resolve(root, routerEntry);
109
109
  }
110
110
 
111
+ interface RouteParamMeta {
112
+ name: string;
113
+ optional: boolean;
114
+ }
115
+
116
+ interface RouteEntry {
117
+ /** Vue Router route `name`, when declared. Enables runtime `router.push({ name, params })`. */
118
+ name: string | null;
119
+ template: string;
120
+ params: RouteParamMeta[];
121
+ }
122
+
111
123
  interface RouteMeta {
124
+ /** Shortest route template — used for the static `route` property. */
112
125
  template: string;
126
+ /** Every route that renders this component (name + template + declared params). */
127
+ routes: RouteEntry[];
113
128
  }
114
129
 
115
130
  type CustomPomMethodSignatureMap = Map<string, PomMethodSignature>;
@@ -277,27 +292,40 @@ async function getRouteMetaByComponent(
277
292
  },
278
293
  });
279
294
 
280
- const map = new Map<string, RouteMeta[]>();
295
+ const map = new Map<string, RouteEntry[]>();
281
296
  for (const entry of routeMetaEntries) {
282
297
  const list = map.get(entry.componentName) ?? [];
283
- list.push({ template: entry.pathTemplate });
298
+ list.push({ name: entry.name, template: entry.pathTemplate, params: entry.params });
284
299
  map.set(entry.componentName, list);
285
300
  }
286
301
 
287
- const chooseRouteMeta = (entries: RouteMeta[]): RouteMeta | null => {
302
+ const dedupeRoutes = (entries: RouteEntry[]): RouteEntry[] => {
303
+ const seen = new Set<string>();
304
+ const unique: RouteEntry[] = [];
305
+ for (const entry of entries) {
306
+ if (seen.has(entry.template))
307
+ continue;
308
+ seen.add(entry.template);
309
+ unique.push(entry);
310
+ }
311
+ return unique;
312
+ };
313
+
314
+ const choosePrimaryTemplate = (entries: RouteEntry[]): string | null => {
288
315
  if (!entries.length)
289
316
  return null;
290
317
  return entries
291
318
  .slice()
292
- .sort((a, b) => a.template.length - b.template.length || a.template.localeCompare(b.template))[0];
319
+ .sort((a, b) => a.template.length - b.template.length || a.template.localeCompare(b.template))[0].template;
293
320
  };
294
321
 
295
322
  const sorted = Array.from(map.entries()).sort((a, b) => a[0].localeCompare(b[0]));
296
323
  return Object.fromEntries(
297
324
  sorted
298
- .map(([componentName, entries]) => {
299
- const chosen = chooseRouteMeta(entries);
300
- return chosen ? [componentName, chosen] : null;
325
+ .map(([componentName, rawEntries]) => {
326
+ const routes = dedupeRoutes(rawEntries);
327
+ const primaryTemplate = choosePrimaryTemplate(routes);
328
+ return primaryTemplate ? [componentName, { template: primaryTemplate, routes }] : null;
301
329
  })
302
330
  .filter((entry): entry is [string, RouteMeta] => !!entry),
303
331
  );
@@ -317,28 +345,208 @@ function generateRouteProperty(routeMeta: RouteMeta | null): TypeScriptClassMemb
317
345
  ];
318
346
  }
319
347
 
320
- function generateGoToSelfMethod(componentName: string): TypeScriptClassMember[] {
348
+ function buildParamTypeString(params: RouteParamMeta[]): string {
349
+ return `{ ${params.map(p => `${p.name}${p.optional ? "?" : ""}: string | number`).join("; ")} }`;
350
+ }
351
+
352
+ function chooseParamlessRoute(routes: RouteEntry[]): RouteEntry | null {
353
+ const paramless = routes.filter(r => r.params.length === 0);
354
+ if (!paramless.length)
355
+ return null;
356
+ return paramless
357
+ .slice()
358
+ .sort((a, b) => a.template.length - b.template.length || a.template.localeCompare(b.template))[0];
359
+ }
360
+
361
+ function chooseParametrizedRoute(routes: RouteEntry[]): RouteEntry | null {
362
+ const parametrized = routes.filter(r => r.params.length > 0);
363
+ if (!parametrized.length)
364
+ return null;
365
+ return parametrized
366
+ .slice()
367
+ .sort((a, b) => a.params.length - b.params.length || a.template.length - b.template.length || a.template.localeCompare(b.template))[0];
368
+ }
369
+
370
+ const GOTO_RUNTIME_LINES = [
371
+ "const runtimeEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;",
372
+ "const runtimeBaseUrl = runtimeEnv?.PLAYWRIGHT_RUNTIME_BASE_URL ?? runtimeEnv?.PLAYWRIGHT_TEST_BASE_URL ?? runtimeEnv?.VITE_PLAYWRIGHT_BASE_URL;",
373
+ "const resolvedUrl = runtimeBaseUrl ? new URL(targetUrl, runtimeBaseUrl).toString() : targetUrl;",
374
+ "await this.page.goto(resolvedUrl);",
375
+ ];
376
+
377
+ /**
378
+ * The `window`/`globalThis` key the consumer exposes the live Vue Router instance under
379
+ * (dev-gated), so generated `goTo()` can drive `router.push({ name, params })` instead of
380
+ * reconstructing URLs from opaque path-template tokens. The consumer is responsible for
381
+ * installing `globalThis[ROUTER_GLOBAL_NAME] = router` in test/dev builds.
382
+ */
383
+ const ROUTER_GLOBAL_NAME = "__appRouter";
384
+
385
+ /**
386
+ * Emits the router-driven `goTo()` body for a named route. Two regimes:
387
+ *
388
+ * - **Cold page** (fresh Playwright page on `about:blank` — the SPA hasn't booted, so the
389
+ * router global is `undefined`): boot the app with a cheap `page.goto("/")`, wait for the
390
+ * router to install, then **full-load the resolved target URL** (`router.resolve({ name,
391
+ * params }).href` + `page.goto`). A full load is unavoidable here — you cannot `push`
392
+ * before the router exists — and resolving the target (rather than stopping at "/") means
393
+ * the route's component mounts via a stable page load, exactly as the original
394
+ * `page.goto`-based tests did. This matters because the POM runtime clicks with
395
+ * `force: true` (skipping Playwright's actionability check): a SPA `push` into a freshly
396
+ * mounted view can resolve before radios/inputs are interactive, so a force-click fired
397
+ * the instant the push resolves can miss (the control's handler isn't attached yet). A
398
+ * full load gives a fully-rendered, interactive page.
399
+ * - **Warm page** (the app is already mounted — any later `goTo()` in the same test): the
400
+ * guard is a single cheap `evaluate` that finds the router present, so the navigation is a
401
+ * pure SPA `router.push({ name, params })` — no reload — the intended fast path.
402
+ *
403
+ * `routeNameExpr` is a TS expression yielding the route name (a string literal for single
404
+ * routes, or `params ? "edit" : "new"` for the dual-route overload). `paramsExpr` is the
405
+ * params source (`"undefined"` for a paramless route, `"params"` otherwise); `nullable` is
406
+ * true only when that source may itself be `undefined` (the all-optional-params overload),
407
+ * gating the `?? {}` guard that TS2871 would otherwise flag on a required param.
408
+ */
409
+ const pushBlock = (routeNameExpr: string, paramsExpr: string, nullable: boolean): string[] => {
410
+ 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 } } }`;
411
+ const routeParamsLine = paramsExpr === "undefined"
412
+ ? "const routeParams = {};"
413
+ : nullable
414
+ ? `const routeParams = Object.fromEntries(Object.entries(${paramsExpr} ?? {}).filter(([, v]) => v !== undefined));`
415
+ : `const routeParams = Object.fromEntries(Object.entries(${paramsExpr}).filter(([, v]) => v !== undefined));`;
416
+ return [
417
+ routeParamsLine,
418
+ `const isCold = await this.page.evaluate(() => typeof (globalThis as { ${ROUTER_GLOBAL_NAME}?: unknown }).${ROUTER_GLOBAL_NAME} === "undefined");`,
419
+ `if (isCold) {`,
420
+ ` await this.page.goto("/", { waitUntil: "commit" });`,
421
+ ` await this.page.waitForFunction(() => typeof (globalThis as { ${ROUTER_GLOBAL_NAME}?: unknown }).${ROUTER_GLOBAL_NAME} !== "undefined", { timeout: 15000 });`,
422
+ ` const href = await this.page.evaluate(({ name, params }) => (globalThis as ${routerType}).${ROUTER_GLOBAL_NAME}?.resolve({ name, params })?.href, { name: ${routeNameExpr}, params: routeParams });`,
423
+ ` if (href) { await this.page.goto(href, { waitUntil: "domcontentloaded" }); }`,
424
+ `} else {`,
425
+ ` await this.page.evaluate(async ({ name, params }) => {`,
426
+ ` await (globalThis as ${routerType}).${ROUTER_GLOBAL_NAME}?.push({ name, params });`,
427
+ ` }, { name: ${routeNameExpr}, params: routeParams });`,
428
+ `}`,
429
+ ];
430
+ };
431
+
432
+ function generateGoToMethod(componentName: string, routeMeta: RouteMeta | null): TypeScriptClassMember[] {
433
+ // No route metadata: emit a goTo() that fails loudly when invoked.
434
+ if (!routeMeta) {
435
+ return [
436
+ createClassMethod({
437
+ name: "goTo",
438
+ isAsync: true,
439
+ statements: [
440
+ `throw new Error("[pom] No router path found for component/page-object '${componentName}'.");`,
441
+ ],
442
+ }),
443
+ ];
444
+ }
445
+
446
+ const paramless = chooseParamlessRoute(routeMeta.routes);
447
+ const parametrized = chooseParametrizedRoute(routeMeta.routes);
448
+ const hasParamless = paramless !== null;
449
+ const hasParametrized = parametrized !== null;
450
+
451
+ // Neither a paramless nor a parametrized route (shouldn't happen — routeMeta is non-null — but guard anyway).
452
+ if (!hasParamless && !hasParametrized) {
453
+ return [
454
+ createClassMethod({
455
+ name: "goTo",
456
+ isAsync: true,
457
+ statements: [
458
+ `throw new Error("[pom] No router path found for component/page-object '${componentName}'.");`,
459
+ ],
460
+ }),
461
+ ];
462
+ }
463
+
464
+ // Fallback (unnamed routes, e.g. Nuxt file-based routes whose names the static walk
465
+ // cannot recover): reconstruct the URL from the tokenized template and `page.goto` it.
466
+ const paramStatements = (entry: RouteEntry): string[] => {
467
+ const lines: string[] = [];
468
+ for (const param of entry.params) {
469
+ const token = getParamToken(param.name);
470
+ if (param.optional) {
471
+ // An omitted optional param drops its entire path segment (including the leading "/"),
472
+ // so `/persons/:personId/:tabName?` with tabName omitted resolves to `/persons/123`.
473
+ lines.push(`targetUrl = params.${param.name} === undefined ? targetUrl.replaceAll(${JSON.stringify(`/${token}`)}, "") : targetUrl.replaceAll(${JSON.stringify(token)}, String(params.${param.name}));`);
474
+ }
475
+ else {
476
+ lines.push(`targetUrl = targetUrl.replaceAll(${JSON.stringify(token)}, String(params.${param.name}));`);
477
+ }
478
+ }
479
+ return lines;
480
+ };
481
+
482
+ // Preferred path: the route is named, so hand the param object straight to the runtime
483
+ // router. `undefined` values are stripped first — omitted optional params are simply not
484
+ // passed, and the router builds the URL (handling optional segments, redirects, and param
485
+ // coercion) itself. No opaque tokens, no string substitution. See `pushBlock` for the
486
+ // cold-start (full-load resolved target) vs warm (SPA `router.push`) regimes.
487
+ // Paramless-only: simple no-arg goTo().
488
+ if (hasParamless && !hasParametrized) {
489
+ const route = paramless!;
490
+ return [
491
+ createClassMethod({
492
+ name: "goTo",
493
+ isAsync: true,
494
+ statements: route.name !== null
495
+ ? pushBlock(JSON.stringify(route.name), "undefined", false)
496
+ : [`const targetUrl = ${JSON.stringify(route.template)};`, ...GOTO_RUNTIME_LINES],
497
+ }),
498
+ ];
499
+ }
500
+
501
+ const paramType = buildParamTypeString(parametrized!.params);
502
+
503
+ // Parametrized-only: goTo(params). When every declared param is optional, the params
504
+ // object itself is optional too — `goTo()` is a valid call that navigates to the route
505
+ // with all optional params omitted (e.g. `/preferences/:tabName?` -> `/preferences`).
506
+ if (hasParametrized && !hasParamless) {
507
+ const route = parametrized!;
508
+ const allOptional = route.params.every(p => p.optional);
509
+ return [
510
+ createClassMethod({
511
+ name: "goTo",
512
+ isAsync: true,
513
+ parameters: [{ name: "params", type: paramType, hasQuestionToken: allOptional }],
514
+ statements: route.name !== null
515
+ ? pushBlock(JSON.stringify(route.name), "params", allOptional)
516
+ : [`let targetUrl = ${JSON.stringify(route.template)};`, ...paramStatements(route), ...GOTO_RUNTIME_LINES],
517
+ }),
518
+ ];
519
+ }
520
+
521
+ // Both routes present. Use the runtime router only when both chosen routes are named;
522
+ // otherwise fall back to token reconstruction for consistency across the overloads.
523
+ const paramlessRoute = paramless!;
524
+ const parametrizedRoute = parametrized!;
525
+ const usePush = paramlessRoute.name !== null && parametrizedRoute.name !== null;
526
+
321
527
  return [
322
528
  createClassMethod({
323
529
  name: "goTo",
324
530
  isAsync: true,
325
- statements: [
326
- "await this.goToSelf();",
327
- ],
328
- }),
329
- createClassMethod({
330
- name: "goToSelf",
331
- isAsync: true,
332
- statements: [
333
- `const route = ${componentName}.route;`,
334
- "if (!route) {",
335
- ` throw new Error("[pom] No router path found for component/page-object '${componentName}'.");`,
336
- "}",
337
- "const runtimeEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;",
338
- "const runtimeBaseUrl = runtimeEnv?.PLAYWRIGHT_RUNTIME_BASE_URL ?? runtimeEnv?.PLAYWRIGHT_TEST_BASE_URL ?? runtimeEnv?.VITE_PLAYWRIGHT_BASE_URL;",
339
- "const targetUrl = runtimeBaseUrl ? new URL(route.template, runtimeBaseUrl).toString() : route.template;",
340
- "await this.page.goto(targetUrl);",
531
+ overloads: [
532
+ { parameters: [], returnType: "Promise<void>" },
533
+ { parameters: [{ name: "params", type: paramType }], returnType: "Promise<void>" },
341
534
  ],
535
+ parameters: [{ name: "params", type: paramType, hasQuestionToken: true }],
536
+ statements: usePush
537
+ ? pushBlock(
538
+ `params ? ${JSON.stringify(parametrizedRoute.name)} : ${JSON.stringify(paramlessRoute.name)}`,
539
+ "params",
540
+ true,
541
+ )
542
+ : [
543
+ `const template = params ? ${JSON.stringify(parametrizedRoute.template)} : ${JSON.stringify(paramlessRoute.template)};`,
544
+ "let targetUrl = template;",
545
+ `if (params) {`,
546
+ ...paramStatements(parametrizedRoute).map(line => ` ${line}`),
547
+ "}",
548
+ ...GOTO_RUNTIME_LINES,
549
+ ],
342
550
  }),
343
551
  ];
344
552
  }
@@ -1795,7 +2003,7 @@ function prepareViewObjectModelClass(
1795
2003
  if (isView && options.vueRouterFluentChaining) {
1796
2004
  const routeMeta = options.routeMetaByComponent?.[componentName] ?? null;
1797
2005
  members.push(...generateRouteProperty(routeMeta));
1798
- members.push(...generateGoToSelfMethod(className));
2006
+ members.push(...generateGoToMethod(className, routeMeta));
1799
2007
  }
1800
2008
 
1801
2009
  members.push(...generateMethodsContentForDependencies(componentName, dependencies));
@@ -1,5 +1,123 @@
1
- import type { Locator as PwLocator, Page as PwPage } from "playwright";
1
+ import type { Keyboard, Response, Screencast } from "playwright";
2
2
 
3
- export type { PwLocator, PwPage };
3
+ /**
4
+ * Narrow subset of the Playwright {@link Locator} surface that the generated
5
+ * POM runtime (`base-page.ts`, `callout.ts`, `pointer.ts`) and generated page
6
+ * object accessors actually use.
7
+ *
8
+ * Locators flow through many chained calls and the full `Locator` interface has
9
+ * ~70 members — too many to stub in tests. Declaring the dependency as this
10
+ * narrow structural interface lets test doubles satisfy it with a handful of
11
+ * real methods, while a real Playwright `Locator` still satisfies it
12
+ * structurally (it has every member here). Member signatures mirror Playwright's
13
+ * own so call sites and downstream consumers keep working.
14
+ *
15
+ * @see BasePagePage for the narrowed page dependency.
16
+ */
17
+ export interface BasePageLocator {
18
+ first(): BasePageLocator;
19
+ last(): BasePageLocator;
20
+ nth(index: number): BasePageLocator;
21
+ locator(
22
+ selector: string,
23
+ options?: { has?: BasePageLocator; hasNot?: BasePageLocator; hasNotText?: string | RegExp; hasText?: string | RegExp },
24
+ ): BasePageLocator;
25
+ describe(description: string): BasePageLocator;
26
+ filter(options?: { has?: BasePageLocator; hasNot?: BasePageLocator; hasNotText?: string | RegExp; hasText?: string | RegExp; visible?: boolean }): BasePageLocator;
27
+ getByLabel(text: string | RegExp, options?: { exact?: boolean }): BasePageLocator;
28
+ getByText(text: string | RegExp, options?: { exact?: boolean }): BasePageLocator;
29
+ getByPlaceholder(text: string | RegExp, options?: { exact?: boolean }): BasePageLocator;
30
+ getByAltText(text: string | RegExp, options?: { exact?: boolean }): BasePageLocator;
31
+ getByTitle(text: string | RegExp, options?: { exact?: boolean }): BasePageLocator;
32
+ getByTestId(testId: string | RegExp): BasePageLocator;
33
+ getByRole(
34
+ role: string,
35
+ options?: {
36
+ checked?: boolean;
37
+ description?: string | RegExp;
38
+ disabled?: boolean;
39
+ exact?: boolean;
40
+ expanded?: boolean;
41
+ includeHidden?: boolean;
42
+ level?: number;
43
+ name?: string | RegExp;
44
+ pressed?: boolean;
45
+ selected?: boolean;
46
+ },
47
+ ): BasePageLocator;
48
+ count(): Promise<number>;
49
+ click(options?: { button?: "left" | "right" | "middle"; clickCount?: number; delay?: number; force?: boolean; noWaitAfter?: boolean; position?: { x: number; y: number }; timeout?: number; trial?: boolean }): Promise<void>;
50
+ clear(options?: { force?: boolean; noWaitAfter?: boolean; timeout?: number }): Promise<void>;
51
+ fill(value: string, options?: { force?: boolean; noWaitAfter?: boolean; timeout?: number }): Promise<void>;
52
+ hover(options?: { force?: boolean; noWaitAfter?: boolean; position?: { x: number; y: number }; timeout?: number; trial?: boolean }): Promise<void>;
53
+ press(key: string, options?: { delay?: number; noWaitAfter?: boolean; timeout?: number }): Promise<void>;
54
+ check(options?: { force?: boolean; noWaitAfter?: boolean; timeout?: number; trial?: boolean }): Promise<void>;
55
+ uncheck(options?: { force?: boolean; noWaitAfter?: boolean; timeout?: number; trial?: boolean }): Promise<void>;
56
+ scrollIntoViewIfNeeded(options?: { timeout?: number }): Promise<void>;
57
+ waitFor(options?: { state?: "attached" | "detached" | "visible" | "hidden"; timeout?: number }): Promise<void>;
58
+ isVisible(options?: { timeout?: number }): Promise<boolean>;
59
+ isHidden(options?: { timeout?: number }): Promise<boolean>;
60
+ isEnabled(options?: { timeout?: number }): Promise<boolean>;
61
+ isDisabled(options?: { timeout?: number }): Promise<boolean>;
62
+ textContent(options?: { timeout?: number }): Promise<string | null>;
63
+ innerText(options?: { timeout?: number }): Promise<string>;
64
+ innerHTML(options?: { timeout?: number }): Promise<string>;
65
+ getAttribute(name: string, options?: { timeout?: number }): Promise<string | null>;
66
+ boundingBox(options?: { timeout?: number }): Promise<{ x: number; y: number; width: number; height: number } | null>;
67
+ selectOption(
68
+ values: null | string | ReadonlyArray<string> | { value?: string; label?: string; index?: number } | ReadonlyArray<{ value?: string; label?: string; index?: number }>,
69
+ options?: { force?: boolean; noWaitAfter?: boolean; timeout?: number },
70
+ ): Promise<string[]>;
71
+ type(text: string, options?: { delay?: number; noWaitAfter?: boolean; timeout?: number }): Promise<void>;
72
+ evaluate<R>(pageFunction: (element: { tagName: string; isContentEditable?: boolean }) => R | Promise<R>): Promise<R>;
73
+ }
74
+
75
+ /**
76
+ * Narrow subset of the Playwright {@link Page} surface that the generated POM
77
+ * runtime depends on.
78
+ *
79
+ * The full `Page` interface has ~250 members — stubbing them all in tests is
80
+ * large and brittle. This interface declares only the members the runtime and
81
+ * generated page objects use, so test doubles need only a handful of real
82
+ * methods. A real Playwright `Page` still satisfies it structurally.
83
+ *
84
+ * `keyboard` and `screencast` keep their full Playwright types (`Keyboard`,
85
+ * `Screencast`) because those sub-objects are small and exposed verbatim to
86
+ * consumers (e.g. for video recording).
87
+ */
88
+ export interface BasePagePage {
89
+ url(): string;
90
+ goto(url: string, options?: { referer?: string; timeout?: number; waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit" }): Promise<Response | null>;
91
+ locator(selector: string, options?: { has?: BasePageLocator; hasNot?: BasePageLocator; hasNotText?: string | RegExp; hasText?: string | RegExp }): BasePageLocator;
92
+ isVisible(selector: string, options?: { strict?: boolean; timeout?: number }): Promise<boolean>;
93
+ textContent(selector: string, options?: { strict?: boolean; timeout?: number }): Promise<string | null>;
94
+ waitForSelector(selector: string, options?: { state?: "attached" | "detached" | "visible" | "hidden"; timeout?: number; strict?: boolean }): Promise<unknown>;
95
+ hover(selector: string, options?: { force?: boolean; noWaitAfter?: boolean; position?: { x: number; y: number }; strict?: boolean; timeout?: number; trial?: boolean }): Promise<void>;
96
+ selectOption(
97
+ selector: string,
98
+ values: null | string | ReadonlyArray<string> | { value?: string; label?: string; index?: number } | ReadonlyArray<{ value?: string; label?: string; index?: number }>,
99
+ options?: { force?: boolean; noWaitAfter?: boolean; strict?: boolean; timeout?: number },
100
+ ): Promise<string[]>;
101
+ waitForTimeout(timeout: number): Promise<void>;
102
+ evaluate<R, Arg = never>(pageFunction: string | ((arg: Arg) => R | Promise<R>), arg?: Arg): Promise<R>;
103
+ readonly keyboard: Keyboard;
104
+ readonly screencast: Screencast;
105
+ }
106
+
107
+ /**
108
+ * Page dependency type used by the generated POM runtime. Narrowed from
109
+ * Playwright's full `Page` to {@link BasePagePage} so test doubles can satisfy
110
+ * it without stubbing hundreds of members. A real `Page` is still assignable.
111
+ */
112
+ export type PwPage = BasePagePage;
113
+
114
+ /**
115
+ * Locator type used by the generated POM runtime. Narrowed from Playwright's
116
+ * full `Locator` to {@link BasePageLocator}. A real `Locator` is still
117
+ * assignable.
118
+ */
119
+ export type PwLocator = BasePageLocator;
120
+
121
+ export type { Keyboard, Screencast };
4
122
 
5
123
  export type PwSelectOption = string | { value?: string; label?: string; index?: number };
@@ -1,8 +1,21 @@
1
1
  import { generateViewObjectModelMethodContent } from "../method-generation";
2
2
  import { IComponentDependencies } from "../utils";
3
3
  export { generateViewObjectModelMethodContent };
4
+ interface RouteParamMeta {
5
+ name: string;
6
+ optional: boolean;
7
+ }
8
+ interface RouteEntry {
9
+ /** Vue Router route `name`, when declared. Enables runtime `router.push({ name, params })`. */
10
+ name: string | null;
11
+ template: string;
12
+ params: RouteParamMeta[];
13
+ }
4
14
  interface RouteMeta {
15
+ /** Shortest route template — used for the static `route` property. */
5
16
  template: string;
17
+ /** Every route that renders this component (name + template + declared params). */
18
+ routes: RouteEntry[];
6
19
  }
7
20
  interface CustomPomAttachment {
8
21
  className: string;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../class-generation/index.ts"],"names":[],"mappings":"AAUA,OAAO,EAAkC,oCAAoC,EAAE,MAAM,sBAAsB,CAA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