Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

utils.ts

70 lines1.9 KB

1import { b, walk } from 'yuku-ast'
2import type { Identifier, Program, Property } from '@yuku-toolchain/types'
3​
4export const debug =
5 process.env.TSR_VITE_DEBUG &&
6 ['true', 'router-plugin'].includes(process.env.TSR_VITE_DEBUG)
7​
8/**
9 * Normalizes a file path by converting Windows backslashes to forward slashes.
10 * This ensures consistent path handling across different bundlers and operating systems.
11 *
12 * The route generator stores paths with forward slashes, but rspack/webpack on Windows
13 * pass native paths with backslashes to transform handlers.
14 */
15export function normalizePath(path: string): string {
16 return path.replace(/\\/g, '/')
18​
19export const routeFactoryCallCodeFilter = [
20 // A call may pass type arguments: createFileRoute<'/a'>('/a')
21 /\bcreateFileRoute\s*(?:<|\()/,
22 /\bcreateRootRoute\s*(?:<|\()/,
23 /\bcreateRootRouteWithContext\s*(?:<|\()/,
24 // An aliased import, which the plugins report
25 /\b(?:createFileRoute|createRootRoute|createRootRouteWithContext)\s+as\s/,
27​
28export function getObjectPropertyKeyName(prop: Property): string | undefined {
29 if (prop.computed) {
30 return undefined
31 }
32​
33 if (prop.key.type === 'Identifier') {
34 return prop.key.name
35 }
36​
37 if (prop.key.type === 'Literal' && typeof prop.key.value === 'string') {
38 return prop.key.value
39 }
40​
41 return undefined
43​
44const reservedProgramNames = new WeakMap<Program, Set<string>>()
45​
46export function getUniqueProgramIdentifier(
47 program: Program,
48 baseName: string,
49): Identifier {
50 let names = reservedProgramNames.get(program)
51 if (!names) {
52 names = new Set<string>()
53 reservedProgramNames.set(program, names)
54 }
55 walk(program, {
56 Identifier(node) {
57 names.add(node.name)
58 },
59 JSXIdentifier(node) {
60 names.add(node.name)
61 },
62 })
63 let name = baseName
64 let suffix = 2
65 while (names.has(name)) {
66 name = `${baseName}${suffix++}`
67 }
68 names.add(name)
69 return b.Identifier({ name })