* Convert a path under src/pages/ to an Astro route path. * * blog/[slug].astro -> /blog/:slug * blog/[...path].astro -> /blog/*path * api/posts.ts -> /api/posts * index.astro -> /
(afterPages: string)
| 203 | * index.astro -> / |
| 204 | */ |
| 205 | function filePathToAstroRoute(afterPages: string): string { |
| 206 | // Remove the extension |
| 207 | const withoutExt = afterPages.replace(/\.(astro|ts|js|mjs)$/, ''); |
| 208 | |
| 209 | // index files map to their parent path (index -> /, blog/index -> /blog) |
| 210 | const withoutIndex = withoutExt.replace(/(^|\/)index$/, '$1').replace(/\/$/, ''); |
| 211 | |
| 212 | // Convert Astro param syntax |
| 213 | const route = '/' + withoutIndex |
| 214 | .replace(/\[\.\.\.([^\]]+)\]/g, '*$1') // [...rest] -> *rest (catch-all) |
| 215 | .replace(/\[([^\]]+)\]/g, ':$1'); // [param] -> :param |
| 216 | |
| 217 | if (route === '/') return '/'; |
| 218 | // Remove trailing slash |
| 219 | return route.replace(/\/$/, ''); |
| 220 | } |