[routing-utils] Allow passing internal params to convertRewrites (#6742)

This adds an argument to allow passing internal param names that should be ignored when considering whether params should be auto-added to a rewrite's destination query. After adding this we should be able to resolve https://github.com/vercel/next.js/issues/27563 in the runtime where `convertRewrites` is called. 

This matches Next.js' handling for internal params which can be seen [here](e90825ad88/packages/next/shared/lib/router/utils/prepare-destination.ts (L203))

### Related Issues

x-ref: https://github.com/vercel/next.js/issues/27563

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This commit is contained in:
JJ Kasper
2021-09-20 19:15:29 -05:00
committed by GitHub
parent de0b13a46e
commit 2fd3fc73e5
2 changed files with 143 additions and 113 deletions

View File

@@ -77,12 +77,21 @@ export function convertRedirects(
});
}
export function convertRewrites(rewrites: Rewrite[]): Route[] {
export function convertRewrites(
rewrites: Rewrite[],
internalParamNames?: string[]
): Route[] {
return rewrites.map(r => {
const { src, segments } = sourceToRegex(r.source);
const hasSegments = collectHasSegments(r.has);
try {
const dest = replaceSegments(segments, hasSegments, r.destination);
const dest = replaceSegments(
segments,
hasSegments,
r.destination,
false,
internalParamNames
);
const route: Route = { src, dest, check: true };
if (r.has) {
@@ -220,7 +229,8 @@ function replaceSegments(
segments: string[],
hasItemSegments: string[],
destination: string,
isRedirect?: boolean
isRedirect?: boolean,
internalParamNames?: string[]
): string {
const namedSegments = segments.filter(name => name !== UN_NAMED_SEGMENT);
const canNeedReplacing =
@@ -296,7 +306,13 @@ function replaceSegments(
// or more params aren't already used in the destination's path
const paramKeys = Object.keys(indexes);
const needsQueryUpdating =
!isRedirect && !paramKeys.some(param => destParams.has(param));
// we do not consider an internal param since it is added automatically
!isRedirect &&
!paramKeys.some(
param =>
!(internalParamNames && internalParamNames.includes(param)) &&
destParams.has(param)
);
if (needsQueryUpdating) {
for (const param of paramKeys) {