@immense/vue-pom-generator 1.0.90 → 1.0.91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,7 +23,7 @@ If you already use Playwright with `getByTestId`, the point is simple: this pack
23
23
 
24
24
  - **It is not a runtime DOM crawler.** It only knows what it can learn from Vue SFC templates and router introspection.
25
25
  - **It does not fully understand arbitrary wrapper components automatically.** There is some wrapper inference for simple local SFCs and some naming conventions, but serious design-system components still need `injection.nativeWrappers`.
26
- - **It does not fully fill route params for you.** Generated `goTo()` / `goToSelf()` methods use the discovered route template literally. A route like `/users/:id` still needs a real `/users/123` when you actually navigate.
26
+ - **It cannot infer query-value types from arbitrary route-props code.** Generated `goTo()` accepts discovered query keys as optional `string | number` values; callers still choose and supply the values appropriate for their application.
27
27
  - **It does not auto-attach every file in `pom/custom`.** Custom helpers are imported, but they only affect generated classes when you explicitly configure attachments, or when they match the built-in `Toggle` / `Checkbox` widget conventions.
28
28
  - **It does not make override classes globally replace generated classes.** `pom/overrides` only changes generated fixture instantiation. Direct imports from the generated barrel still give you the generated class unless you import your override yourself.
29
29
  - **The C# emitter is not feature-parity with the TypeScript emitter.** It emits locator/action classes, but not Playwright fixtures, not helper attachments, and not the same route helper surface.
@@ -407,26 +407,46 @@ What is not fully supported:
407
407
 
408
408
  - arbitrary computed `:to` expressions
409
409
  - parameter-aware `goToSelf()` URL filling
410
- - exposing rich route-param metadata on the generated POM surface
410
+ - inferring query-value types from arbitrary route-props transformations
411
411
 
412
412
  ### 2) View-level `route`, `goTo()`, and `goToSelf()`
413
413
 
414
414
  When `generation.router` is enabled, each view POM gets:
415
415
 
416
416
  - `static readonly route: { template: string } | null`
417
- - `async goTo()`
417
+ - a typed `async goTo(...)` whose flat input includes discovered path params and optional query keys
418
418
  - `async goToSelf()`
419
419
 
420
+ For a route such as:
421
+
422
+ ```ts
423
+ {
424
+ path: "/users/:userId",
425
+ name: "user-details",
426
+ component: UserDetailsPage,
427
+ props: route => ({
428
+ userId: route.params.userId,
429
+ tab: route.query.tab,
430
+ }),
431
+ }
432
+ ```
433
+
434
+ the generated method is shaped like this:
435
+
436
+ ```ts
437
+ goTo(params: { userId: string | number; tab?: string | number }): Promise<void>
438
+ ```
439
+
440
+ `goTo({ userId: 42, tab: "activity" })` partitions the flat input into Vue Router's
441
+ `params` and `query` records. On a cold page it resolves and fully loads the named route;
442
+ on a warm page it uses `router.push`.
443
+
420
444
  Important caveats:
421
445
 
422
446
  - `goToSelf()` calls `page.goto(...)`, resolving the route template against `PLAYWRIGHT_RUNTIME_BASE_URL`, `PLAYWRIGHT_TEST_BASE_URL`, or `VITE_PLAYWRIGHT_BASE_URL` when those runtime env vars are present
423
- - a dynamic route template like `/users/:id` stays `/users/:id`
447
+ - unlike `goTo()`, a dynamic `goToSelf()` template like `/users/:id` stays `/users/:id`
424
448
  - if a component is matched by multiple routes, the generator currently picks one route template (the shortest one)
425
-
426
- So the safe rule is:
427
-
428
- - use generated `goTo()` for simple/static routes
429
- - for dynamic routes, navigate with a real URL yourself or wrap that behavior in your override/custom code
449
+ - when a component has both a paramless route and a route whose path params are all optional, pass at least one path-param key (it may be `undefined`) to select the parametrized route; a query-only object selects the paramless route
430
450
 
431
451
  ### Why `moduleShims` exists
432
452
 
@@ -1266,7 +1286,7 @@ If you are evaluating this package critically, the most accurate short version i
1266
1286
  - it is strongest when your team already wants `getByTestId`-style Playwright tests
1267
1287
  - it is strongest in TypeScript-first Playwright projects
1268
1288
  - it is strongest when your Vue component library is either native-heavy or can be described with `nativeWrappers`
1269
- - it is useful with router-aware pages, but you should treat dynamic-route `goTo()` support as partial and explicit
1289
+ - it is useful with router-aware pages, including typed path params and discovered query keys
1270
1290
  - it becomes much more maintainable when you pair it with the ESLint cleanup rule and a small `pom/custom` folder for the genuinely hard widgets
1271
1291
 
1272
1292
  If that matches your codebase, the package removes a surprising amount of repetitive test maintenance. If it does not, the caveats above are the important ones to believe.
package/RELEASE_NOTES.md CHANGED
@@ -1,86 +1,36 @@
1
- I'll investigate the repository to determine which PRs fall within the release window and gather
2
- details for accurate release notes.
1
+ Looking at the provided data, the v1.0.90..HEAD range contains only one commit/PR (#53), confirmed
2
+ by the diffstat showing 6 files. I'll generate release notes focused on that change.
3
3
 
4
- Let me examine the actual content of the key changes to understand what was introduced.
5
-
6
- Now I have a complete picture. Let me verify the key breaking change — the router global key rename.
7
-
8
- I now have a complete understanding of all changes. Here are the release notes for v1.0.90:
4
+ v1.0.91
9
5
 
10
6
  Highlights
11
7
 
12
- - New browser-safe router bridge — exposeRouterForPomNavigation() lets consumers expose the live
13
- Vue Router to generated POM goTo() methods via a dedicated @immense/vue-pom-generator/router entry
14
- point.
15
- - Per-component existingIdBehavior overrides — the option now accepts { default, components } to
16
- apply different test-ID collision policies on a per-SFC basis.
17
- - New no-data-testid-in-specs ESLint rule — bans raw data-testid selectors and getByTestId() calls
18
- in spec files, steering authors toward generated POM accessors.
19
- - Router global key namespaced — the internal globalThis key used by generated goTo() is renamed
20
- from __appRouter to __vuePomGeneratorRouter, backed by a shared constant in the new bridge module.
8
+ - New route-navigation-codegen module generates type-safe Vue Router navigation helpers with
9
+ query-parameter awareness
10
+ - class-generation refactored to integrate route navigation generation into POM class output
11
+ - Router bridge wired to pass route metadata into the navigation codegen
12
+ - README updated with documentation for query-aware navigation generation
13
+ - New generated-tsc test suite verifies generated navigation code passes TypeScript compilation
21
14
 
22
15
  Changes
23
16
 
24
- Router Bridge
25
-
26
- - Added router-bridge.ts with exposeRouterForPomNavigation(), POM_ROUTER_GLOBAL_NAME, and
27
- PomNavigationRouter / PomNavigationTarget interfaces.
28
- - Registered @immense/vue-pom-generator/router as a new package export in package.json and
29
- vite.config.ts.
30
- - Updated class-generation/index.ts to import and use the shared POM_ROUTER_GLOBAL_NAME constant
31
- instead of a local magic string.
32
- - Broadened the bridge's push/resolve callable constraints to accept Vue Router's overloads.
33
- - Documented the router bridge usage in README.md.
34
-
35
- Existing ID Behavior
36
-
37
- - Added ExistingIdBehaviorByComponent interface and ExistingIdBehaviorConfig type
38
- (ExistingIdBehavior | ExistingIdBehaviorByComponent).
39
- - Exported ExistingIdBehaviorByComponent and ExistingIdBehaviorConfig from the main entry point.
40
- - Added resolveExistingIdBehavior(config, componentName) to plugin/vue-plugin.ts and wired it into
41
- both build and dev plugin processors.
42
- - Widened existingIdBehavior option type to ExistingIdBehaviorConfig across
43
- resolved-generation-options.ts, resolved-injection-options.ts, and vue-plugin.ts.
44
- - Corrected the JSDoc default annotation from "preserve" to "error" (the code default was already
45
- "error").
46
-
47
- ESLint
48
-
49
- - Added no-data-testid-in-specs rule that flags data-testid in string literals, template literals,
50
- and getByTestId() calls (including computed member access).
51
- - Exported the rule from @immense/vue-pom-generator/eslint.
52
-
53
- Tests
54
-
55
- - Added tests/router-bridge.test.ts covering exposeRouterForPomNavigation().
56
- - Added tests/existing-id-behavior.test.ts covering resolveExistingIdBehavior with scalar and
57
- per-component configs.
58
- - Extended tests/existing-id-error.test.ts with a per-component override scenario.
59
- - Extended tests/eslint.test.ts with no-data-testid-in-specs valid/invalid cases.
60
- - Updated tests/class-generation-coverage.test.ts to reference the renamed __vuePomGeneratorRouter
61
- key.
62
-
63
- Breaking Changes
64
-
65
- - Router global key renamed: generated goTo() methods now read the live router from
66
- globalThis.__vuePomGeneratorRouter instead of globalThis.__appRouter. Consumers who manually set
67
- globalThis.__appRouter = router should switch to exposeRouterForPomNavigation(router) from
68
- @immense/vue-pom-generator/router.
69
- - existingIdBehavior type widened: the option type is now ExistingIdBehaviorConfig
70
- (ExistingIdBehavior | ExistingIdBehaviorByComponent). Existing string values remain valid; code that
71
- narrowed the option to ExistingIdBehavior may need a type update.
17
+ - Route navigation codegen: Added route-navigation-codegen.ts — generates goTo(params)-style
18
+ navigation accessors that account for declared route query parameters
19
+ - Class generation: Refactored class-generation/index.ts to produce navigation methods alongside
20
+ existing POM class members
21
+ - Router bridge: Updated router-bridge.ts to expose route metadata needed by the navigation codegen
22
+ - Documentation: Updated README.md with details on the new query-aware navigation generation
23
+ feature
24
+ - Tests: Added tests/generated-tsc.test.ts to assert generated navigation output type-checks;
25
+ updated tests/class-generation-coverage.test.ts for new navigation behavior
72
26
 
73
27
  Pull Requests Included
74
28
 
75
- No pull requests were merged in this release window. All changes were committed directly:
76
-
77
- - a2f3c67 feat: add POM consumer integration APIs
78
- - be7b0be fix: isolate browser router bridge
79
- - c3ca37a fix: accept Vue Router in bridge
29
+ - #53 Support query-aware generated navigation
30
+ (]8;id=md-1gwtg7u;https://github.com/immense/vue-pom-generator/pull/53https://github.com/immense/vue-pom-generator/pull/53]8;;]8;;)]8;;
80
31
 
81
32
  Testing
82
33
 
83
- New unit tests cover the router bridge, resolveExistingIdBehavior (scalar and per-component), and
84
- the no-data-testid-in-specs ESLint rule. Existing class-generation coverage tests were updated for
85
- the router key rename.
34
+ - Added generated-tsc.test.ts for TypeScript compilation validation of generated navigation code;
35
+ updated class-generation-coverage.test.ts to cover new navigation generation behavior.
86
36
 
@@ -28,8 +28,7 @@ import {
28
28
  type PomStringPattern,
29
29
  } from "../pom-patterns";
30
30
  import { buildPomLocatorDescription, stripPomActionPrefix } from "../pom-discoverability";
31
- import { getParamToken, introspectNuxtPages, parseRouterFileFromCwd } from "../router-introspection";
32
- import { POM_ROUTER_GLOBAL_NAME } from "../router-bridge";
31
+ import { introspectNuxtPages, parseRouterFileFromCwd } from "../router-introspection";
33
32
  import {
34
33
  addExportAll,
35
34
  addNamedImport,
@@ -62,6 +61,10 @@ import {
62
61
  // Intentionally imported so tooling understands this exported helper is part of the
63
62
  // generated POM public surface (it is consumed by generated Playwright fixtures).
64
63
  import { setPlaywrightAnimationOptions } from "./pointer";
64
+ import {
65
+ createRouterNavigationWriter,
66
+ createUrlNavigationWriter,
67
+ } from "../route-navigation-codegen";
65
68
 
66
69
  void setPlaywrightAnimationOptions;
67
70
 
@@ -118,6 +121,7 @@ interface RouteEntry {
118
121
  name: string | null;
119
122
  template: string;
120
123
  params: RouteParamMeta[];
124
+ query: string[];
121
125
  }
122
126
 
123
127
  interface RouteMeta {
@@ -295,7 +299,7 @@ async function getRouteMetaByComponent(
295
299
  const map = new Map<string, RouteEntry[]>();
296
300
  for (const entry of routeMetaEntries) {
297
301
  const list = map.get(entry.componentName) ?? [];
298
- list.push({ name: entry.name, template: entry.pathTemplate, params: entry.params });
302
+ list.push({ name: entry.name, template: entry.pathTemplate, params: entry.params, query: entry.query });
299
303
  map.set(entry.componentName, list);
300
304
  }
301
305
 
@@ -345,8 +349,50 @@ function generateRouteProperty(routeMeta: RouteMeta | null): TypeScriptClassMemb
345
349
  ];
346
350
  }
347
351
 
348
- function buildParamTypeString(params: RouteParamMeta[]): string {
349
- return `{ ${params.map(p => `${p.name}${p.optional ? "?" : ""}: string | number`).join("; ")} }`;
352
+ function formatNavigationFieldName(name: string): string {
353
+ return /^[$a-z_][$\w]*$/i.test(name) ? name : JSON.stringify(name);
354
+ }
355
+
356
+ function buildNavigationTypeString(route: RouteEntry, requiredOptionalParamName?: string): string {
357
+ const pathFields = route.params.map((param) => {
358
+ const forcePresent = param.optional && param.name === requiredOptionalParamName;
359
+ return `${formatNavigationFieldName(param.name)}${param.optional && !forcePresent ? "?" : ""}: string | number${forcePresent ? " | undefined" : ""}`;
360
+ });
361
+ const pathNames = new Set(route.params.map(param => param.name));
362
+ const queryFields = route.query
363
+ .filter(query => !pathNames.has(query))
364
+ .map(query => `${formatNavigationFieldName(query)}?: string | number`);
365
+ return `{ ${[...pathFields, ...queryFields].join("; ")} }`;
366
+ }
367
+
368
+ function buildParametrizedRouteSelectionTypeString(route: RouteEntry): string {
369
+ if (route.params.some(param => !param.optional)) {
370
+ return buildNavigationTypeString(route);
371
+ }
372
+
373
+ // In a dual-route overload, the runtime selects the parametrized route by path-key
374
+ // presence. Require at least one optional path key to be present so the public type
375
+ // cannot accept an object that runtime would send to the paramless route. Its value may
376
+ // still be undefined, which intentionally selects the optional-param route with that
377
+ // segment omitted.
378
+ return route.params
379
+ .map(param => buildNavigationTypeString(route, param.name))
380
+ .join(" | ");
381
+ }
382
+
383
+ function buildImplementationNavigationTypeString(routes: RouteEntry[]): string {
384
+ const fields = new Map<string, boolean>();
385
+ for (const route of routes) {
386
+ for (const param of route.params) {
387
+ fields.set(param.name, true);
388
+ }
389
+ for (const query of route.query) {
390
+ if (!fields.has(query)) {
391
+ fields.set(query, true);
392
+ }
393
+ }
394
+ }
395
+ return `{ ${Array.from(fields.keys()).map(name => `${formatNavigationFieldName(name)}?: string | number`).join("; ")} }`;
350
396
  }
351
397
 
352
398
  function chooseParamlessRoute(routes: RouteEntry[]): RouteEntry | null {
@@ -367,66 +413,12 @@ function chooseParametrizedRoute(routes: RouteEntry[]): RouteEntry | null {
367
413
  .sort((a, b) => a.params.length - b.params.length || a.template.length - b.template.length || a.template.localeCompare(b.template))[0];
368
414
  }
369
415
 
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 generator-owned `window`/`globalThis` key used by `exposeRouterForPomNavigation`,
379
- * so generated `goTo()` can drive `router.push({ name, params })` instead of reconstructing
380
- * URLs from opaque path-template tokens.
381
- */
382
- const ROUTER_GLOBAL_NAME = POM_ROUTER_GLOBAL_NAME;
383
-
384
- /**
385
- * Emits the router-driven `goTo()` body for a named route. Two regimes:
386
- *
387
- * - **Cold page** (fresh Playwright page on `about:blank` — the SPA hasn't booted, so the
388
- * router global is `undefined`): boot the app with a cheap `page.goto("/")`, wait for the
389
- * router to install, then **full-load the resolved target URL** (`router.resolve({ name,
390
- * params }).href` + `page.goto`). A full load is unavoidable here — you cannot `push`
391
- * before the router exists — and resolving the target (rather than stopping at "/") means
392
- * the route's component mounts via a stable page load, exactly as the original
393
- * `page.goto`-based tests did. This matters because the POM runtime clicks with
394
- * `force: true` (skipping Playwright's actionability check): a SPA `push` into a freshly
395
- * mounted view can resolve before radios/inputs are interactive, so a force-click fired
396
- * the instant the push resolves can miss (the control's handler isn't attached yet). A
397
- * full load gives a fully-rendered, interactive page.
398
- * - **Warm page** (the app is already mounted — any later `goTo()` in the same test): the
399
- * guard is a single cheap `evaluate` that finds the router present, so the navigation is a
400
- * pure SPA `router.push({ name, params })` — no reload — the intended fast path.
401
- *
402
- * `routeNameExpr` is a TS expression yielding the route name (a string literal for single
403
- * routes, or `params ? "edit" : "new"` for the dual-route overload). `paramsExpr` is the
404
- * params source (`"undefined"` for a paramless route, `"params"` otherwise); `nullable` is
405
- * true only when that source may itself be `undefined` (the all-optional-params overload),
406
- * gating the `?? {}` guard that TS2871 would otherwise flag on a required param.
407
- */
408
- const pushBlock = (routeNameExpr: string, paramsExpr: string, nullable: boolean): string[] => {
409
- 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 } } }`;
410
- const routeParamsLine = paramsExpr === "undefined"
411
- ? "const routeParams = {};"
412
- : nullable
413
- ? `const routeParams = Object.fromEntries(Object.entries(${paramsExpr} ?? {}).filter(([, v]) => v !== undefined));`
414
- : `const routeParams = Object.fromEntries(Object.entries(${paramsExpr}).filter(([, v]) => v !== undefined));`;
415
- return [
416
- routeParamsLine,
417
- `const isCold = await this.page.evaluate(() => typeof (globalThis as { ${ROUTER_GLOBAL_NAME}?: unknown }).${ROUTER_GLOBAL_NAME} === "undefined");`,
418
- `if (isCold) {`,
419
- ` await this.page.goto("/", { waitUntil: "commit" });`,
420
- ` await this.page.waitForFunction(() => typeof (globalThis as { ${ROUTER_GLOBAL_NAME}?: unknown }).${ROUTER_GLOBAL_NAME} !== "undefined", { timeout: 15000 });`,
421
- ` const href = await this.page.evaluate(({ name, params }) => (globalThis as ${routerType}).${ROUTER_GLOBAL_NAME}?.resolve({ name, params })?.href, { name: ${routeNameExpr}, params: routeParams });`,
422
- ` if (href) { await this.page.goto(href, { waitUntil: "domcontentloaded" }); }`,
423
- `} else {`,
424
- ` await this.page.evaluate(async ({ name, params }) => {`,
425
- ` await (globalThis as ${routerType}).${ROUTER_GLOBAL_NAME}?.push({ name, params });`,
426
- ` }, { name: ${routeNameExpr}, params: routeParams });`,
427
- `}`,
428
- ];
429
- };
416
+ function requireRouteName(route: RouteEntry): string {
417
+ if (route.name === null) {
418
+ throw new VuePomGeneratorError(`Named navigation requires a route name for template "${route.template}".`);
419
+ }
420
+ return route.name;
421
+ }
430
422
 
431
423
  function generateGoToMethod(componentName: string, routeMeta: RouteMeta | null): TypeScriptClassMember[] {
432
424
  // No route metadata: emit a goTo() that fails loudly when invoked.
@@ -460,44 +452,39 @@ function generateGoToMethod(componentName: string, routeMeta: RouteMeta | null):
460
452
  ];
461
453
  }
462
454
 
463
- // Fallback (unnamed routes, e.g. Nuxt file-based routes whose names the static walk
464
- // cannot recover): reconstruct the URL from the tokenized template and `page.goto` it.
465
- const paramStatements = (entry: RouteEntry): string[] => {
466
- const lines: string[] = [];
467
- for (const param of entry.params) {
468
- const token = getParamToken(param.name);
469
- if (param.optional) {
470
- // An omitted optional param drops its entire path segment (including the leading "/"),
471
- // so `/persons/:personId/:tabName?` with tabName omitted resolves to `/persons/123`.
472
- lines.push(`targetUrl = params.${param.name} === undefined ? targetUrl.replaceAll(${JSON.stringify(`/${token}`)}, "") : targetUrl.replaceAll(${JSON.stringify(token)}, String(params.${param.name}));`);
473
- }
474
- else {
475
- lines.push(`targetUrl = targetUrl.replaceAll(${JSON.stringify(token)}, String(params.${param.name}));`);
476
- }
477
- }
478
- return lines;
479
- };
480
-
481
455
  // Preferred path: the route is named, so hand the param object straight to the runtime
482
456
  // router. `undefined` values are stripped first — omitted optional params are simply not
483
457
  // passed, and the router builds the URL (handling optional segments, redirects, and param
484
- // coercion) itself. No opaque tokens, no string substitution. See `pushBlock` for the
458
+ // coercion) itself. No opaque tokens, no string substitution. The centralized router writer owns the
485
459
  // cold-start (full-load resolved target) vs warm (SPA `router.push`) regimes.
486
- // Paramless-only: simple no-arg goTo().
460
+ // Paramless-only: query keys, when present, are optional navigation arguments.
487
461
  if (hasParamless && !hasParametrized) {
488
462
  const route = paramless!;
463
+ const hasQuery = route.query.length > 0;
464
+ const paramType = buildNavigationTypeString(route);
489
465
  return [
490
466
  createClassMethod({
491
467
  name: "goTo",
492
468
  isAsync: true,
469
+ parameters: hasQuery ? [{ name: "params", type: paramType, hasQuestionToken: true }] : [],
493
470
  statements: route.name !== null
494
- ? pushBlock(JSON.stringify(route.name), "undefined", false)
495
- : [`const targetUrl = ${JSON.stringify(route.template)};`, ...GOTO_RUNTIME_LINES],
471
+ ? createRouterNavigationWriter({
472
+ routeName: { kind: "single", target: route.name },
473
+ input: hasQuery ? { identifier: "params", optional: true } : undefined,
474
+ pathParamNames: [],
475
+ queryNames: route.query,
476
+ })
477
+ : createUrlNavigationWriter({
478
+ routeTemplate: { kind: "single", target: route.template },
479
+ input: hasQuery ? { identifier: "params", optional: true } : undefined,
480
+ pathParams: [],
481
+ queryNames: route.query,
482
+ }),
496
483
  }),
497
484
  ];
498
485
  }
499
486
 
500
- const paramType = buildParamTypeString(parametrized!.params);
487
+ const paramType = buildNavigationTypeString(parametrized!);
501
488
 
502
489
  // Parametrized-only: goTo(params). When every declared param is optional, the params
503
490
  // object itself is optional too — `goTo()` is a valid call that navigates to the route
@@ -511,8 +498,18 @@ function generateGoToMethod(componentName: string, routeMeta: RouteMeta | null):
511
498
  isAsync: true,
512
499
  parameters: [{ name: "params", type: paramType, hasQuestionToken: allOptional }],
513
500
  statements: route.name !== null
514
- ? pushBlock(JSON.stringify(route.name), "params", allOptional)
515
- : [`let targetUrl = ${JSON.stringify(route.template)};`, ...paramStatements(route), ...GOTO_RUNTIME_LINES],
501
+ ? createRouterNavigationWriter({
502
+ routeName: { kind: "single", target: route.name },
503
+ input: { identifier: "params", optional: allOptional },
504
+ pathParamNames: route.params.map(param => param.name),
505
+ queryNames: route.query,
506
+ })
507
+ : createUrlNavigationWriter({
508
+ routeTemplate: { kind: "single", target: route.template },
509
+ input: { identifier: "params", optional: allOptional },
510
+ pathParams: route.params,
511
+ queryNames: route.query,
512
+ }),
516
513
  }),
517
514
  ];
518
515
  }
@@ -522,30 +519,50 @@ function generateGoToMethod(componentName: string, routeMeta: RouteMeta | null):
522
519
  const paramlessRoute = paramless!;
523
520
  const parametrizedRoute = parametrized!;
524
521
  const usePush = paramlessRoute.name !== null && parametrizedRoute.name !== null;
525
-
522
+ const paramlessType = buildNavigationTypeString(paramlessRoute);
523
+ const parametrizedOverloadType = buildParametrizedRouteSelectionTypeString(parametrizedRoute);
524
+ const queryNames = Array.from(new Set([...paramlessRoute.query, ...parametrizedRoute.query]));
525
+ const hasQuery = queryNames.length > 0;
526
+ const implementationType = hasQuery
527
+ ? buildImplementationNavigationTypeString([paramlessRoute, parametrizedRoute])
528
+ : paramType;
526
529
  return [
527
530
  createClassMethod({
528
531
  name: "goTo",
529
532
  isAsync: true,
530
533
  overloads: [
531
- { parameters: [], returnType: "Promise<void>" },
532
- { parameters: [{ name: "params", type: paramType }], returnType: "Promise<void>" },
534
+ {
535
+ parameters: paramlessRoute.query.length
536
+ ? [{ name: "params", type: paramlessType, hasQuestionToken: true }]
537
+ : [],
538
+ returnType: "Promise<void>",
539
+ },
540
+ { parameters: [{ name: "params", type: parametrizedOverloadType }], returnType: "Promise<void>" },
533
541
  ],
534
- parameters: [{ name: "params", type: paramType, hasQuestionToken: true }],
542
+ parameters: [{ name: "params", type: implementationType, hasQuestionToken: true }],
535
543
  statements: usePush
536
- ? pushBlock(
537
- `params ? ${JSON.stringify(parametrizedRoute.name)} : ${JSON.stringify(paramlessRoute.name)}`,
538
- "params",
539
- true,
540
- )
541
- : [
542
- `const template = params ? ${JSON.stringify(parametrizedRoute.template)} : ${JSON.stringify(paramlessRoute.template)};`,
543
- "let targetUrl = template;",
544
- `if (params) {`,
545
- ...paramStatements(parametrizedRoute).map(line => ` ${line}`),
546
- "}",
547
- ...GOTO_RUNTIME_LINES,
548
- ],
544
+ ? createRouterNavigationWriter({
545
+ routeName: {
546
+ kind: "dual",
547
+ parametrizedTarget: requireRouteName(parametrizedRoute),
548
+ paramlessTarget: requireRouteName(paramlessRoute),
549
+ selectBy: hasQuery ? "path-param-presence" : "input-presence",
550
+ },
551
+ input: { identifier: "params", optional: true },
552
+ pathParamNames: parametrizedRoute.params.map(param => param.name),
553
+ queryNames: hasQuery ? queryNames : [],
554
+ })
555
+ : createUrlNavigationWriter({
556
+ routeTemplate: {
557
+ kind: "dual",
558
+ parametrizedTarget: parametrizedRoute.template,
559
+ paramlessTarget: paramlessRoute.template,
560
+ selectBy: hasQuery ? "path-param-presence" : "input-presence",
561
+ },
562
+ input: { identifier: "params", optional: true },
563
+ pathParams: parametrizedRoute.params,
564
+ queryNames: hasQuery ? queryNames : [],
565
+ }),
549
566
  }),
550
567
  ];
551
568
  }
@@ -10,6 +10,7 @@ interface RouteEntry {
10
10
  name: string | null;
11
11
  template: string;
12
12
  params: RouteParamMeta[];
13
+ query: string[];
13
14
  }
14
15
  interface RouteMeta {
15
16
  /** Shortest route template — used for the static `route` property. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../class-generation/index.ts"],"names":[],"mappings":"AAUA,OAAO,EAAkC,oCAAoC,EAAE,MAAM,sBAAsB,CAAC;AAyC5G,OAAO,EACL,sBAAsB,EAOvB,MAAM,UAAU,CAAC;AAQlB,OAAO,EAAE,oCAAoC,EAAE,CAAC;AA2ChD,UAAU,cAAc;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,OAAO,CAAC;CACnB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