diff --git a/src/router.ts b/src/router.ts index 34e85bcdbd7..c3c982b1135 100644 --- a/src/router.ts +++ b/src/router.ts @@ -145,6 +145,7 @@ export function pathToPattern(path: string): string { let route = ""; + let nonOptionalSegments = 0; for (let i = 0; i < parts.length; i++) { const part = parts[i]; @@ -217,7 +218,12 @@ export function pathToPattern(path: string): string { } } - route += (optional ? "" : "/") + pattern; + if (optional) { + route += pattern; + } else { + nonOptionalSegments++; + route += "/" + pattern; + } } // Case: /(group)/index.tsx @@ -225,5 +231,15 @@ export function pathToPattern(path: string): string { route = "/"; } + // Handles all cases where a route starts with + // an optional parameter and does not contain + // any non-group and non-optional segments after + // Case: /[[id]].tsx + // Case: /(group)/[[id]].tsx + // Case: /(group)/[[name]]/(group2)/index.tsx + if (route.startsWith(`{/`) && nonOptionalSegments === 0) { + route = route.replace("{/", "/{"); + } + return route; } diff --git a/src/router_test.ts b/src/router_test.ts index 97addf3c0f7..80fcd72e05b 100644 --- a/src/router_test.ts +++ b/src/router_test.ts @@ -163,6 +163,11 @@ Deno.test("pathToPattern", async (t) => { ).toEqual( "/foo{/:name}?/bar{/:bob}?", ); + expect( + pathToPattern("(group)/[[name]]/(group2)/index"), + ).toEqual( + "/{:name}?", + ); }); await t.step("throws on invalid patterns", () => {