Open History to see the last commit
1import { cleanPath, trimPath } from './path'
2import type { LocationRewrite } from './router'
3β
4/** Compose multiple rewrite pairs into a single in/out rewrite. */
5export function composeRewrites(rewrites: Array<LocationRewrite>) {
6 return {
7 input: ({ url }) => {
8 for (const rewrite of rewrites) {
9 url = executeRewriteInput(rewrite, url)
10 }
11 return url
12 },
13 output: ({ url }) => {
14 for (let i = rewrites.length - 1; i >= 0; i--) {
15 url = executeRewriteOutput(rewrites[i], url)
16 }
17 return url
18 },
19 } satisfies LocationRewrite
20}
21β
22/** Create a rewrite pair that strips/adds a basepath on input/output. */
23export function rewriteBasepath(
24 basepath: string,
25 caseSensitive?: boolean,
26 rewrite?: LocationRewrite,
27) {
28 const trimmedBasepath = trimPath(basepath)
29 const normalizedBasepath = `/${trimmedBasepath}`
30 const checkBasepath = caseSensitive
31 ? normalizedBasepath
32 : normalizedBasepath.toLowerCase()
33 const checkBasepathWithSlash = `${checkBasepath}/`
34β
35 const basepathRewrite = {
36 input: ({ url }) => {
37 const pathname = caseSensitive ? url.pathname : url.pathname.toLowerCase()
38β
39 // Handle exact basepath match (e.g., /my-app -> /)
40 if (pathname === checkBasepath) {
41 url.pathname = '/'
42 } else if (pathname.startsWith(checkBasepathWithSlash)) {
43 // Handle basepath with trailing content (e.g., /my-app/users -> /users)
44 url.pathname = url.pathname.slice(normalizedBasepath.length)
45 }
46 return url
47 },
48 output: ({ url }) => {
49 // `url.pathname` always starts with "/", so only slashes already inside
50 // it can repeat; cleanPath keeps the joinPaths normalization.
51 url.pathname = cleanPath(`/${trimmedBasepath}${url.pathname}`)
52 return url
53 },
54 } satisfies LocationRewrite
55β
56 // Strip the basepath before custom input and restore it after custom output.
57 return rewrite
58 ? ({
59 input: ({ url }) =>
60 executeRewriteInput(rewrite, basepathRewrite.input({ url })),
61 output: ({ url }) =>
62 basepathRewrite.output({ url: executeRewriteOutput(rewrite, url) }),
63 } satisfies LocationRewrite)
64 : basepathRewrite
65}
66β
67/** Execute a location input rewrite if provided. */
68export function executeRewriteInput(
69 rewrite: LocationRewrite | undefined,
70 url: URL,
71): URL {
72 const res = rewrite?.input?.({ url })
73 if (res) {
74 if (typeof res === 'string') {
75 return new URL(res)
76 } else if (res instanceof URL) {
77 return res
78 }
79 }
80 return url
81}
82β
83/** Execute a location output rewrite if provided. */
84export function executeRewriteOutput(
85 rewrite: LocationRewrite | undefined,
86 url: URL,
87): URL {
88 const res = rewrite?.output?.({ url })
89 if (res) {
90 if (typeof res === 'string') {
91 return new URL(res)
92 } else if (res instanceof URL) {
93 return res
94 }
95 }
96 return url
97}