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

config.ts

181 lines5.6 KB

1import path from 'node:path'
2import { existsSync, readFileSync } from 'node:fs'
3import { z } from 'zod'
4import { virtualRootRouteSchema } from './filesystem/virtual/config'
5import type { GeneratorPlugin } from './plugin/types'
6​
7export const baseConfigSchema = z.object({
8 target: z.enum(['react', 'solid']).optional().default('react'),
9 virtualRouteConfig: virtualRootRouteSchema.or(z.string()).optional(),
10 routeFilePrefix: z.string().optional(),
11 routeFileIgnorePrefix: z.string().optional().default('-'),
12 routeFileIgnorePattern: z.string().optional(),
13 routesDirectory: z.string().optional().default('./src/routes'),
14 quoteStyle: z.enum(['single', 'double']).optional().default('single'),
15 semicolons: z.boolean().optional().default(false),
16 disableLogging: z.boolean().optional().default(false),
17 routeTreeFileHeader: z
18 .array(z.string())
19 .optional()
20 .default([
21 '/* eslint-disable */',
22 '// @ts-nocheck',
23 '// noinspection JSUnusedGlobalSymbols',
24 ]),
25 indexToken: z.string().optional().default('index'),
26 routeToken: z.string().optional().default('route'),
27 pathParamsAllowedCharacters: z
28 .array(z.enum([';', ':', '@', '&', '=', '+', '$', ',']))
29 .optional(),
30})
31​
32export type BaseConfig = z.infer<typeof baseConfigSchema>
33​
34export const configSchema = baseConfigSchema.extend({
35 generatedRouteTree: z.string().optional().default('./src/routeTree.gen.ts'),
36 disableTypes: z.boolean().optional().default(false),
37 verboseFileRoutes: z.boolean().optional(),
38 addExtensions: z.boolean().optional().default(false),
39 enableRouteTreeFormatting: z.boolean().optional().default(true),
40 routeTreeFileFooter: z
41 .union([
42 z.array(z.string()).optional().default([]),
43 z.function().returns(z.array(z.string())),
44 ])
45 .optional(),
46 autoCodeSplitting: z.boolean().optional(),
47 customScaffolding: z
48 .object({
49 routeTemplate: z.string().optional(),
50 lazyRouteTemplate: z.string().optional(),
51 })
52 .optional(),
53 experimental: z
54 .object({
55 // TODO: This has been made stable and is now "autoCodeSplitting". Remove in next major version.
56 enableCodeSplitting: z.boolean().optional(),
57 // TODO: This resolves issues with non-nested paths in file-based routing. To be made default in next major version.
58 nonNestedRoutes: z.boolean().optional(),
59 })
60 .optional(),
61 plugins: z.array(z.custom<GeneratorPlugin>()).optional(),
62 tmpDir: z.string().optional().default(''),
63 importRoutesUsingAbsolutePaths: z.boolean().optional().default(false),
64})
65​
66export type Config = z.infer<typeof configSchema>
67​
68type ResolveParams = {
69 configDirectory: string
71​
72export function resolveConfigPath({ configDirectory }: ResolveParams) {
73 return path.resolve(configDirectory, 'tsr.config.json')
75​
76export function getConfig(
77 inlineConfig: Partial<Config> = {},
78 configDirectory?: string,
79): Config {
80 if (configDirectory === undefined) {
81 configDirectory = process.cwd()
82 }
83 const configFilePathJson = resolveConfigPath({ configDirectory })
84 const exists = existsSync(configFilePathJson)
85​
86 let config: Config
87​
88 if (exists) {
89 config = configSchema.parse({
90 ...JSON.parse(readFileSync(configFilePathJson, 'utf-8')),
91 ...inlineConfig,
92 })
93 } else {
94 config = configSchema.parse(inlineConfig)
95 }
96​
97 // If typescript is disabled, make sure the generated route tree is a .js file
98 if (config.disableTypes) {
99 config.generatedRouteTree = config.generatedRouteTree.replace(
100 /\.(ts|tsx)$/,
101 '.js',
102 )
103 }
104​
105 // if a configDirectory is used, paths should be relative to that directory
106 if (configDirectory) {
107 // if absolute configDirectory is provided, use it as the root
108 if (path.isAbsolute(configDirectory)) {
109 config.routesDirectory = path.resolve(
110 configDirectory,
111 config.routesDirectory,
112 )
113 config.generatedRouteTree = path.resolve(
114 configDirectory,
115 config.generatedRouteTree,
116 )
117 } else {
118 config.routesDirectory = path.resolve(
119 process.cwd(),
120 configDirectory,
121 config.routesDirectory,
122 )
123 config.generatedRouteTree = path.resolve(
124 process.cwd(),
125 configDirectory,
126 config.generatedRouteTree,
127 )
128 }
129 }
130​
131 const resolveTmpDir = (dir: string | Array<string>) => {
132 if (Array.isArray(dir)) {
133 dir = path.join(...dir)
134 }
135 if (!path.isAbsolute(dir)) {
136 dir = path.resolve(process.cwd(), dir)
137 }
138 return dir
139 }
140​
141 if (config.tmpDir) {
142 config.tmpDir = resolveTmpDir(config.tmpDir)
143 } else if (process.env.TSR_TMP_DIR) {
144 config.tmpDir = resolveTmpDir(process.env.TSR_TMP_DIR)
145 } else {
146 config.tmpDir = resolveTmpDir(['.tanstack', 'tmp'])
147 }
148​
149 validateConfig(config)
150 return config
152​
153function validateConfig(config: Config) {
154 if (typeof config.experimental?.enableCodeSplitting !== 'undefined') {
155 const message = `
156------
157⚠️ ⚠️ ⚠️
158ERROR: The "experimental.enableCodeSplitting" flag has been made stable and is now "autoCodeSplitting". Please update your configuration file to use "autoCodeSplitting" instead of "experimental.enableCodeSplitting".
159------
161 console.error(message)
162 throw new Error(message)
163 }
164​
165 if (config.indexToken === config.routeToken) {
166 throw new Error(
167 `The "indexToken" and "routeToken" options must be different.`,
168 )
169 }
170​
171 if (
172 config.routeFileIgnorePrefix &&
173 config.routeFileIgnorePrefix.trim() === '_'
174 ) {
175 throw new Error(
176 `The "routeFileIgnorePrefix" cannot be an underscore ("_"). This is a reserved character used to denote a pathless route. Please use a different prefix.`,
177 )
178 }
179​
180 return config