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

utils.ts

1,312 lines36.3 KB

1/* eslint-disable @typescript-eslint/prefer-for-of */
2import * as fsp from 'node:fs/promises'
3import path from 'node:path'
4import * as prettier from 'prettier'
5import { rootPathId } from './filesystem/physical/rootPathId'
6import type { Config, TokenMatcher } from './config'
7import type {
8 ImportDeclaration,
9 RouteNode,
10 RoutePathSegmentMetadata,
11} from './types'
12​
13/**
14 * Prefix map for O(1) parent route lookups.
15 * Maps each route path prefix to the route node that owns that prefix.
16 * Enables finding longest matching parent without linear search.
17 */
18export class RoutePrefixMap {
19 private prefixToRoute: Map<string, RouteNode> = new Map()
20​
21 constructor(routes: Array<RouteNode>) {
22 for (const route of routes) {
23 if (!route.routePath || route.routePath === `/${rootPathId}`) continue
24​
25 // Skip route pieces (lazy, loader, component, etc.) - they are merged with main routes
26 // and should not be valid parent candidates
27 if (
28 route._fsRouteType === 'lazy' ||
29 route._fsRouteType === 'loader' ||
30 route._fsRouteType === 'component' ||
31 route._fsRouteType === 'pendingComponent' ||
32 route._fsRouteType === 'errorComponent' ||
33 route._fsRouteType === 'notFoundComponent'
34 ) {
35 continue
36 }
37​
38 // Index by exact path for direct lookups
39 this.prefixToRoute.set(route.routePath, route)
40 }
41 }
42​
43 /**
44 * Find the longest matching parent route for a given path.
45 * O(k) where k is the number of path segments, not O(n) routes.
46 */
47 findParent(routePath: string): RouteNode | null {
48 if (!routePath || routePath === '/') return null
49​
50 // Walk up the path segments
51 let searchPath = routePath
52 while (searchPath.length > 0) {
53 const lastSlash = searchPath.lastIndexOf('/')
54 if (lastSlash <= 0) break
55​
56 searchPath = searchPath.substring(0, lastSlash)
57 const parent = this.prefixToRoute.get(searchPath)
58 if (parent && parent.routePath !== routePath) {
59 return parent
60 }
61 }
62 return null
63 }
64​
65 /**
66 * Check if a route exists at the given path.
67 */
68 has(routePath: string): boolean {
69 return this.prefixToRoute.has(routePath)
70 }
71​
72 /**
73 * Get a route by exact path.
74 */
75 get(routePath: string): RouteNode | undefined {
76 return this.prefixToRoute.get(routePath)
77 }
79​
80export function multiSortBy<T>(
81 arr: Array<T>,
82 accessors: Array<(item: T) => any> = [(d) => d],
83): Array<T> {
84 const len = arr.length
85 // Pre-compute all accessor values to avoid repeated function calls during sort
86 const indexed: Array<{ item: T; index: number; keys: Array<any> }> =
87 new Array(len)
88 for (let i = 0; i < len; i++) {
89 const item = arr[i]!
90 const keys = new Array(accessors.length)
91 for (let j = 0; j < accessors.length; j++) {
92 keys[j] = accessors[j]!(item)
93 }
94 indexed[i] = { item, index: i, keys }
95 }
96​
97 indexed.sort((a, b) => {
98 for (let j = 0; j < accessors.length; j++) {
99 const ao = a.keys[j]
100 const bo = b.keys[j]
101​
102 if (typeof ao === 'undefined') {
103 if (typeof bo === 'undefined') {
104 continue
105 }
106 return 1
107 }
108​
109 if (ao === bo) {
110 continue
111 }
112​
113 return ao > bo ? 1 : -1
114 }
115​
116 return a.index - b.index
117 })
118​
119 const result: Array<T> = new Array(len)
120 for (let i = 0; i < len; i++) {
121 result[i] = indexed[i]!.item
122 }
123 return result
125​
126/**
127 * Sorts route nodes by root, path depth, index status, and finally `routePath`.
128 * The `routePath` comparison keeps the output consistent when the earlier
129 * values are the same.
130 */
131export function sortRouteNodes(
132 routeNodes: Array<RouteNode>,
133 indexTokenSegmentRegex: RegExp,
134): Array<RouteNode> {
135 return multiSortBy(routeNodes, [
136 (d) => (d.routePath?.includes(`/${rootPathId}`) ? -1 : 1),
137 (d) =>
138 d.routePath === undefined
139 ? undefined
140 : countSlashSeparatedParts(d.routePath),
141 (d) => {
142 const segments = d.routePath?.split('/').filter(Boolean) ?? []
143 const last = segments[segments.length - 1] ?? ''
144 return indexTokenSegmentRegex.test(last) ? -1 : 1
145 },
146 (d) => d.routePath,
147 ])
149​
150export function cleanPath(path: string) {
151 // remove double slashes
152 return path.replace(/\/{2,}/g, '/')
154​
155export function trimPathLeft(path: string) {
156 return path === '/' ? path : path.replace(/^\/{1,}/, '')
158​
159export function removeLeadingSlash(path: string): string {
160 return path.replace(/^\//, '')
162​
163export function removeTrailingSlash(s: string) {
164 return s.replace(/\/$/, '')
166​
167const BRACKET_CONTENT_RE = /\[(.*?)\]/g
168const SPLIT_REGEX = /(?<!\[)\.(?!\])/g
169​
170/**
171 * Characters that cannot be escaped in square brackets.
172 * These are characters that would cause issues in URLs or file systems.
173 */
174const DISALLOWED_ESCAPE_CHARS = new Set([
175 '/',
176 '\\',
177 '?',
178 '#',
179 ':',
180 '*',
181 '<',
182 '>',
183 '|',
184 '!',
185 '$',
186 '%',
187])
188​
189function determineInitialRoutePathFromParts(
190 routePath: string,
191 parts: Array<string>,
192) {
193 const originalRoutePath =
194 cleanPath(`/${cleanPath(parts.join('/')) || ''}`) || ''
195​
196 // Escape any characters that in square brackets
197 // we keep the original path untouched
198 const escapedParts = parts.map((part) => {
199 // Check if any disallowed characters are used in brackets
200​
201 let match
202 while ((match = BRACKET_CONTENT_RE.exec(part)) !== null) {
203 const character = match[1]
204 if (character === undefined) continue
205 if (DISALLOWED_ESCAPE_CHARS.has(character)) {
206 console.error(
207 `Error: Disallowed character "${character}" found in square brackets in route path "${routePath}".\nYou cannot use any of the following characters in square brackets: ${Array.from(
208 DISALLOWED_ESCAPE_CHARS,
209 ).join(', ')}\nPlease remove and/or replace them.`,
210 )
211 process.exit(1)
212 }
213 }
214​
215 // Since this split segment is safe at this point, we can
216 // remove the brackets and replace them with the content inside
217 return part.replace(BRACKET_CONTENT_RE, '$1')
218 })
219​
220 // If the syntax for prefix/suffix is different, from the path
221 // matching internals of router-core, we'd perform those changes here
222 // on the `escapedParts` array before it is joined back together in
223 // `final`
224​
225 const final = cleanPath(`/${escapedParts.join('/')}`) || ''
226​
227 return {
228 routePath: final,
229 originalRoutePath,
230 }
232​
233export function determineInitialRoutePath(routePath: string) {
234 return determineInitialRoutePathFromParts(
235 routePath,
236 routePath.split(SPLIT_REGEX),
237 )
239​
240/**
241 * Resolves bracket escapes in an explicit route path or ID without applying
242 * the dot-delimited flat-file route convention.
243 */
244export function determineInitialRoutePathFromExplicitPath(routePath: string) {
245 return determineInitialRoutePathFromParts(routePath, [routePath])
247​
248/**
249 * Checks if a segment is fully escaped (entirely wrapped in brackets with no nested brackets).
250 * E.g., "[index]" -> true, "[_layout]" -> true, "foo[.]bar" -> false, "index" -> false
251 */
252function isFullyEscapedSegment(originalSegment: string): boolean {
253 return (
254 originalSegment.startsWith('[') &&
255 originalSegment.endsWith(']') &&
256 !originalSegment.slice(1, -1).includes('[') &&
257 !originalSegment.slice(1, -1).includes(']')
258 )
260​
261/**
262 * Checks if the leading underscore in a segment is escaped.
263 * Returns true if:
264 * - Segment starts with [_] pattern: "[_]layout" -> "_layout"
265 * - Segment is fully escaped and content starts with _: "[_1nd3x]" -> "_1nd3x"
266 */
267export function hasEscapedLeadingUnderscore(originalSegment: string): boolean {
268 // Pattern: [_]something or [_something]
269 return (
270 originalSegment.startsWith('[_]') ||
271 (originalSegment.startsWith('[_') && isFullyEscapedSegment(originalSegment))
272 )
274​
275/**
276 * Checks if the trailing underscore in a segment is escaped.
277 * Returns true if:
278 * - Segment ends with [_] pattern: "blog[_]" -> "blog_"
279 * - Segment is fully escaped and content ends with _: "[_r0ut3_]" -> "_r0ut3_"
280 */
281export function hasEscapedTrailingUnderscore(originalSegment: string): boolean {
282 // Pattern: something[_] or [something_]
283 return (
284 originalSegment.endsWith('[_]') ||
285 (originalSegment.endsWith('_]') && isFullyEscapedSegment(originalSegment))
286 )
288​
289export function countRoutePathSegments(routePath?: string): number {
290 const path = routePath ?? ''
291 let count = 0
292 let inSegment = false
293​
294 for (let i = 0; i < path.length; i++) {
295 if (path[i] === '/') {
296 inSegment = false
297 continue
298 }
299​
300 if (!inSegment) {
301 count++
302 inSegment = true
303 }
304 }
305​
306 return count
308​
309export function countSlashSeparatedParts(path: string): number {
310 let count = 1
311​
312 for (let i = 0; i < path.length; i++) {
313 if (path[i] === '/') count++
314 }
315​
316 return count
318​
319export function hasRoutePathSegmentMetadata(
320 metadata: RoutePathSegmentMetadata | undefined,
321): metadata is RoutePathSegmentMetadata {
322 return !!(
323 metadata?.literalLeadingUnderscore || metadata?.literalTrailingUnderscore
324 )
326​
327function mergeRoutePathSegmentMetadata(
328 current: RoutePathSegmentMetadata | undefined,
329 incoming: RoutePathSegmentMetadata | undefined,
330): RoutePathSegmentMetadata | undefined {
331 const hasCurrent = hasRoutePathSegmentMetadata(current)
332 const hasIncoming = hasRoutePathSegmentMetadata(incoming)
333​
334 if (!hasCurrent) return hasIncoming ? incoming : undefined
335 if (!hasIncoming) return current
336​
337 return {
338 literalLeadingUnderscore:
339 current.literalLeadingUnderscore || incoming.literalLeadingUnderscore,
340 literalTrailingUnderscore:
341 current.literalTrailingUnderscore || incoming.literalTrailingUnderscore,
342 }
344​
345export function createRoutePathSegmentMetadata(
346 routePath: string = '/',
347 originalPath?: string,
348): Array<RoutePathSegmentMetadata | undefined> | undefined {
349 if (!originalPath) return undefined
350​
351 const routeSegments = routePath.split('/')
352 const originalSegments = originalPath.split('/')
353 const metadata = new Array<RoutePathSegmentMetadata | undefined>(
354 routeSegments.length,
355 )
356 let hasMetadata = false
357​
358 for (let i = 0; i < routeSegments.length; i++) {
359 const segment = routeSegments[i]!
360 const originalSegment = originalSegments[i] || ''
361 const literalLeadingUnderscore =
362 segment.startsWith('_') && hasEscapedLeadingUnderscore(originalSegment)
363 const literalTrailingUnderscore =
364 segment.endsWith('_') && hasEscapedTrailingUnderscore(originalSegment)
365​
366 if (!literalLeadingUnderscore && !literalTrailingUnderscore) continue
367​
368 hasMetadata = true
369 metadata[i] = {
370 literalLeadingUnderscore: literalLeadingUnderscore || undefined,
371 literalTrailingUnderscore: literalTrailingUnderscore || undefined,
372 }
373 }
374​
375 return hasMetadata ? metadata : undefined
377​
378export function createLiteralRoutePathSegmentMetadata(
379 routePath: string,
380 parent?: RouteNode,
381 literalNewSegments = false,
382): Array<RoutePathSegmentMetadata | undefined> | undefined {
383 const routeSegments = routePath.split('/')
384 const metadata = new Array<RoutePathSegmentMetadata | undefined>(
385 routeSegments.length,
386 )
387 const parentDepth = countRoutePathSegments(parent?.routePath)
388 let hasMetadata = false
389 let depth = 0
390​
391 for (let i = 0; i < routeSegments.length; i++) {
392 const segment = routeSegments[i]
393 metadata[i] = parent?._routePathSegmentMetadata?.[i]
394 hasMetadata ||= hasRoutePathSegmentMetadata(metadata[i])
395​
396 if (!segment) continue
397​
398 if (literalNewSegments && depth >= parentDepth) {
399 const literalLeadingUnderscore = segment.startsWith('_')
400 const literalTrailingUnderscore = segment.endsWith('_')
401​
402 if (literalLeadingUnderscore || literalTrailingUnderscore) {
403 metadata[i] = mergeRoutePathSegmentMetadata(metadata[i], {
404 literalLeadingUnderscore: literalLeadingUnderscore || undefined,
405 literalTrailingUnderscore: literalTrailingUnderscore || undefined,
406 })
407 hasMetadata = true
408 }
409 }
410​
411 depth++
412 }
413​
414 return hasMetadata ? metadata : undefined
416​
417export function joinRoutePathSegmentMetadata(
418 routePath: string,
419 prefixPath: string,
420 prefixMetadata: Array<RoutePathSegmentMetadata | undefined> | undefined,
421 childMetadata: Array<RoutePathSegmentMetadata | undefined> | undefined,
422): Array<RoutePathSegmentMetadata | undefined> | undefined {
423 const metadata = new Array<RoutePathSegmentMetadata | undefined>(
424 countSlashSeparatedParts(routePath),
425 )
426 let hasMetadata = false
427​
428 if (prefixMetadata) {
429 for (let i = 0; i < prefixMetadata.length && i < metadata.length; i++) {
430 metadata[i] = prefixMetadata[i]
431 hasMetadata ||= hasRoutePathSegmentMetadata(metadata[i])
432 }
433 }
434​
435 const offset = countRoutePathSegments(prefixPath)
436 if (childMetadata) {
437 for (let i = 1; i < childMetadata.length; i++) {
438 const targetIndex = offset + i
439 if (targetIndex >= metadata.length) break
440​
441 metadata[targetIndex] = mergeRoutePathSegmentMetadata(
442 metadata[targetIndex],
443 childMetadata[i],
444 )
445 hasMetadata ||= hasRoutePathSegmentMetadata(metadata[targetIndex])
446 }
447 }
448​
449 return hasMetadata ? metadata : undefined
451​
452const backslashRegex = /\\/g
453​
454export function replaceBackslash(s: string) {
455 return s.replace(backslashRegex, '/')
457​
458const alphanumericRegex = /[a-zA-Z0-9_]/
459const splatSlashRegex = /\/\$\//g
460const trailingSplatRegex = /\$$/g
461const bracketSplatRegex = /\$\{\$\}/g
462const dollarSignRegex = /\$/g
463const splitPathRegex = /[/-]/g
464const leadingDigitRegex = /^(\d)/g
465​
466const toVariableSafeChar = (char: string): string => {
467 if (alphanumericRegex.test(char)) {
468 return char // Keep alphanumeric characters and underscores as is
469 }
470​
471 // Replace special characters with meaningful text equivalents
472 switch (char) {
473 case '.':
474 return 'Dot'
475 case '-':
476 return 'Dash'
477 case '@':
478 return 'At'
479 case '(':
480 return '' // Removed since route groups use parentheses
481 case ')':
482 return '' // Removed since route groups use parentheses
483 case ' ':
484 return '' // Remove spaces
485 default:
486 return `Char${char.charCodeAt(0)}` // For any other characters
487 }
489​
490export function routePathToVariable(routePath: string): string {
491 const cleaned = removeUnderscores(routePath)
492 if (!cleaned) return ''
493​
494 const parts = cleaned
495 .replace(splatSlashRegex, '/splat/')
496 .replace(trailingSplatRegex, 'splat')
497 .replace(bracketSplatRegex, 'splat')
498 .replace(dollarSignRegex, '')
499 .split(splitPathRegex)
500​
501 let result = ''
502 for (let i = 0; i < parts.length; i++) {
503 const part = parts[i]!
504 const segment = i > 0 ? capitalize(part) : part
505 for (let j = 0; j < segment.length; j++) {
506 result += toVariableSafeChar(segment[j]!)
507 }
508 }
509​
510 return result.replace(leadingDigitRegex, 'R$1')
512​
513const underscoreStartEndRegex = /(^_|_$)/gi
514const underscoreSlashRegex = /(\/_|_\/)/gi
515​
516export function removeUnderscores(s?: string) {
517 return s
518 ?.replace(underscoreStartEndRegex, '')
519 .replace(underscoreSlashRegex, '/')
521​
522function removeUnderscoresFromSegment(
523 segment: string,
524 metadata?: RoutePathSegmentMetadata,
525): string {
526 let result = segment
527​
528 if (result.startsWith('_') && !metadata?.literalLeadingUnderscore) {
529 result = result.slice(1)
530 }
531​
532 if (result.endsWith('_') && !metadata?.literalTrailingUnderscore) {
533 result = result.slice(0, -1)
534 }
535​
536 return result
538​
539/**
540 * Removes underscores from a path, but preserves underscores that were escaped
541 * in the original path (indicated by [_] syntax).
542 *
543 * @param routePath - The path with brackets removed
544 * @param originalPath - The original path that may contain [_] escape sequences
545 * @returns The path with non-escaped underscores removed
546 */
547export function removeUnderscoresWithEscape(
548 routePath?: string,
549 originalPath?: string,
550): string {
551 if (!routePath) return ''
552 if (!originalPath) return removeUnderscores(routePath) ?? ''
553​
554 const routeSegments = routePath.split('/')
555 const metadata = createRoutePathSegmentMetadata(routePath, originalPath)
556 const newSegments = new Array<string>(routeSegments.length)
557​
558 for (let i = 0; i < routeSegments.length; i++) {
559 newSegments[i] = removeUnderscoresFromSegment(
560 routeSegments[i]!,
561 metadata?.[i],
562 )
563 }
564​
565 return newSegments.join('/')
567​
568export function removeLayoutSegmentsAndUnderscoresWithEscape(
569 routePath: string = '/',
570 originalPath?: string,
571 routePathSegmentMetadata?: Array<RoutePathSegmentMetadata | undefined>,
572): string {
573 if (!originalPath) {
574 return removeUnderscores(removeLayoutSegments(routePath)) ?? ''
575 }
576​
577 const metadata =
578 routePathSegmentMetadata ??
579 createRoutePathSegmentMetadata(routePath, originalPath)
580​
581 const routeSegments = routePath.split('/')
582 const originalSegments = originalPath.split('/')
583 const newSegments: Array<string> = []
584​
585 for (let i = 0; i < routeSegments.length; i++) {
586 const segment = routeSegments[i]!
587 const originalSegment = originalSegments[i] || ''
588 const segmentMetadata = metadata?.[i]
589​
590 if (
591 !segmentMetadata?.literalLeadingUnderscore &&
592 isSegmentPathless(segment, originalSegment)
593 ) {
594 continue
595 }
596​
597 newSegments.push(removeUnderscoresFromSegment(segment, segmentMetadata))
598 }
599​
600 return newSegments.join('/')
602​
603/**
604 * Removes layout segments (segments starting with underscore) from a path,
605 * but preserves segments where the underscore was escaped.
606 *
607 * @param routePath - The path with brackets removed
608 * @param originalPath - The original path that may contain [_] escape sequences
609 * @returns The path with non-escaped layout segments removed
610 */
611export function removeLayoutSegmentsWithEscape(
612 routePath: string = '/',
613 originalPath?: string,
614): string {
615 if (!originalPath) return removeLayoutSegments(routePath)
616​
617 const routeSegments = routePath.split('/')
618 const originalSegments = originalPath.split('/')
619​
620 // Keep segments that are NOT pathless (i.e., don't start with unescaped underscore)
621 const newSegments = routeSegments.filter((segment, i) => {
622 const originalSegment = originalSegments[i] || ''
623 return !isSegmentPathless(segment, originalSegment)
624 })
625​
626 return newSegments.join('/')
628​
629/**
630 * Checks if a segment should be treated as a pathless/layout segment.
631 * A segment is pathless if it starts with underscore and the underscore is not escaped.
632 *
633 * @param segment - The segment from routePath (brackets removed)
634 * @param originalSegment - The segment from originalRoutePath (may contain brackets)
635 * @returns true if the segment is pathless (has non-escaped leading underscore)
636 */
637export function isSegmentPathless(
638 segment: string,
639 originalSegment: string,
640): boolean {
641 if (!segment.startsWith('_')) return false
642 return !hasEscapedLeadingUnderscore(originalSegment)
644​
645export function escapeRegExp(s: string): string {
646 return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
648​
649function sanitizeTokenFlags(flags?: string): string | undefined {
650 if (!flags) return flags
651​
652 // Prevent stateful behavior with RegExp.prototype.test/exec
653 // g = global, y = sticky
654 return flags.replace(/[gy]/g, '')
656​
657export function createTokenRegex(
658 token: TokenMatcher,
659 opts: {
660 type: 'segment' | 'filename'
661 },
662): RegExp {
663 // Defensive check: if token is undefined/null, throw a clear error
664 // (runtime safety for config loading edge cases)
665 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
666 if (token === undefined || token === null) {
667 throw new Error(
668 `createTokenRegex: token is ${token}. This usually means the config was not properly parsed with defaults.`,
669 )
670 }
671​
672 try {
673 if (typeof token === 'string') {
674 return opts.type === 'segment'
675 ? new RegExp(`^${escapeRegExp(token)}$`)
676 : new RegExp(`[./]${escapeRegExp(token)}[.]`)
677 }
678​
679 if (token instanceof RegExp) {
680 const flags = sanitizeTokenFlags(token.flags)
681 return opts.type === 'segment'
682 ? new RegExp(`^(?:${token.source})$`, flags)
683 : new RegExp(`[./](?:${token.source})[.]`, flags)
684 }
685​
686 // Handle JSON regex object form: { regex: string, flags?: string }
687 if (typeof token === 'object' && 'regex' in token) {
688 const flags = sanitizeTokenFlags(token.flags)
689 return opts.type === 'segment'
690 ? new RegExp(`^(?:${token.regex})$`, flags)
691 : new RegExp(`[./](?:${token.regex})[.]`, flags)
692 }
693​
694 throw new Error(
695 `createTokenRegex: invalid token type. Expected string, RegExp, or { regex, flags } object, got: ${typeof token}`,
696 )
697 } catch (e) {
698 if (e instanceof SyntaxError) {
699 const pattern =
700 typeof token === 'string'
701 ? token
702 : token instanceof RegExp
703 ? token.source
704 : token.regex
705 throw new Error(
706 `Invalid regex pattern in token config: "${pattern}". ${e.message}`,
707 )
708 }
709 throw e
710 }
712​
713function isBracketWrappedSegment(segment: string): boolean {
714 return segment.startsWith('[') && segment.endsWith(']')
716​
717export function unwrapBracketWrappedSegment(segment: string): string {
718 return isBracketWrappedSegment(segment) ? segment.slice(1, -1) : segment
720​
721export function removeLeadingUnderscores(s: string, routeToken: string) {
722 if (!s) return s
723​
724 const hasLeadingUnderscore = routeToken[0] === '_'
725​
726 const routeTokenToExclude = hasLeadingUnderscore
727 ? routeToken.slice(1)
728 : routeToken
729​
730 const escapedRouteToken = escapeRegExp(routeTokenToExclude)
731​
732 const leadingUnderscoreRegex = hasLeadingUnderscore
733 ? new RegExp(`(?<=^|\\/)_(?!${escapedRouteToken})`, 'g')
734 : new RegExp(`(?<=^|\\/)_`, 'g')
735​
736 return s.replaceAll(leadingUnderscoreRegex, '')
738​
739export function removeTrailingUnderscores(s: string, routeToken: string) {
740 if (!s) return s
741​
742 const hasTrailingUnderscore = routeToken.slice(-1) === '_'
743​
744 const routeTokenToExclude = hasTrailingUnderscore
745 ? routeToken.slice(0, -1)
746 : routeToken
747​
748 const escapedRouteToken = escapeRegExp(routeTokenToExclude)
749​
750 const trailingUnderscoreRegex = hasTrailingUnderscore
751 ? new RegExp(`(?<!${escapedRouteToken})_(?=\\/|$)`, 'g')
752 : new RegExp(`_(?=\\/)|_$`, 'g')
753​
754 return s.replaceAll(trailingUnderscoreRegex, '')
756​
757export function capitalize(s: string) {
758 if (typeof s !== 'string') return ''
759 return s.charAt(0).toUpperCase() + s.slice(1)
761​
762export function removeExt(d: string, addExtensions: boolean | string = false) {
763 if (typeof addExtensions === 'string') {
764 const dotIndex = d.lastIndexOf('.')
765 if (dotIndex === -1) return d
766 return d.substring(0, dotIndex) + addExtensions
767 }
768 return addExtensions ? d : d.substring(0, d.lastIndexOf('.')) || d
770​
771/**
772 * This function writes to a file if the content is different.
773 *
774 * @param filepath The path to the file
775 * @param content Original content
776 * @param incomingContent New content
777 * @param callbacks Callbacks to run before and after writing
778 * @returns Whether the file was written
779 */
780export async function writeIfDifferent(
781 filepath: string,
782 content: string,
783 incomingContent: string,
784 callbacks?: { beforeWrite?: () => void; afterWrite?: () => void },
785): Promise<boolean> {
786 if (content !== incomingContent) {
787 callbacks?.beforeWrite?.()
788 await fsp.writeFile(filepath, incomingContent)
789 callbacks?.afterWrite?.()
790 return true
791 }
792 return false
794​
795/**
796 * This function formats the source code using the default formatter (Prettier).
797 *
798 * @param source The content to format
799 * @param config The configuration object
800 * @returns The formatted content
801 */
802export async function format(
803 source: string,
804 config: {
805 quoteStyle: 'single' | 'double'
806 semicolons: boolean
807 },
808): Promise<string> {
809 const prettierOptions: prettier.Config = {
810 semi: config.semicolons,
811 singleQuote: config.quoteStyle === 'single',
812 parser: 'typescript',
813 }
814 return prettier.format(source, prettierOptions)
816​
817/**
818 * This function resets the regex index to 0 so that it can be reused
819 * without having to create a new regex object or worry about the last
820 * state when using the global flag.
821 *
822 * @param regex The regex object to reset
823 * @returns
824 */
825export function resetRegex(regex: RegExp) {
826 regex.lastIndex = 0
827 return
829​
830/**
831 * This function checks if a file exists.
832 *
833 * @param file The path to the file
834 * @returns Whether the file exists
835 */
836export async function checkFileExists(file: string) {
837 try {
838 await fsp.access(file, fsp.constants.F_OK)
839 return true
840 } catch {
841 return false
842 }
844​
845const possiblyNestedRouteGroupPatternRegex = /\([^/]+\)\/?/g
846export function removeGroups(s: string) {
847 return s.replace(possiblyNestedRouteGroupPatternRegex, '')
849​
850/**
851 * Removes all segments from a given path that start with an underscore ('_').
852 *
853 * @param {string} routePath - The path from which to remove segments. Defaults to '/'.
854 * @returns {string} The path with all underscore-prefixed segments removed.
855 * @example
856 * removeLayoutSegments('/workspace/_auth/foo') // '/workspace/foo'
857 */
858export function removeLayoutSegments(routePath: string = '/'): string {
859 const segments = routePath.split('/')
860 const newSegments = segments.filter((segment) => !segment.startsWith('_'))
861 return newSegments.join('/')
863​
864/**
865 * The `node.path` is used as the `id` in the route definition.
866 * This function checks if the given node has a parent and if so, it determines the correct path for the given node.
867 * @param node - The node to determine the path for.
868 * @returns The correct path for the given node.
869 */
870export function determineNodePath(node: RouteNode) {
871 return (node.path = node.parent
872 ? node.routePath?.replace(node.parent.routePath ?? '', '') || '/'
873 : node.routePath)
875​
876/**
877 * Removes the last segment from a given path. Segments are considered to be separated by a '/'.
878 *
879 * @param {string} routePath - The path from which to remove the last segment. Defaults to '/'.
880 * @returns {string} The path with the last segment removed.
881 * @example
882 * removeLastSegmentFromPath('/workspace/_auth/foo') // '/workspace/_auth'
883 */
884export function removeLastSegmentFromPath(routePath: string = '/'): string {
885 const segments = routePath.split('/')
886 segments.pop() // Remove the last segment
887 return segments.join('/')
889​
890/**
891 * Find parent route using RoutePrefixMap for O(k) lookups instead of O(n).
892 */
893export function hasParentRoute(
894 prefixMap: RoutePrefixMap,
895 node: RouteNode,
896 routePathToCheck: string | undefined,
897): RouteNode | null {
898 if (!routePathToCheck || routePathToCheck === '/') {
899 return null
900 }
901​
902 return prefixMap.findParent(routePathToCheck)
904​
905/**
906 * Gets the final variable name for a route
907 */
908export const getResolvedRouteNodeVariableName = (
909 routeNode: RouteNode,
910): string => {
911 return routeNode.children?.length
912 ? `${routeNode.variableName}RouteWithChildren`
913 : `${routeNode.variableName}Route`
915​
916/**
917 * Infers the path for use by TS
918 */
919const inferPath = (routeNode: RouteNode): string => {
920 if (routeNode.cleanedPath === '/') {
921 return routeNode.cleanedPath ?? ''
922 }
923 return routeNode.cleanedPath?.replace(/\/$/, '') ?? ''
925​
926/**
927 * Infers the full path for use by TS
928 */
929export const inferFullPath = (routeNode: RouteNode): string => {
930 const fullPath = removeGroups(
931 removeLayoutSegmentsAndUnderscoresWithEscape(
932 routeNode.routePath,
933 routeNode.originalRoutePath,
934 routeNode._routePathSegmentMetadata,
935 ),
936 )
937​
938 if (fullPath === '') {
939 return '/'
940 }
941​
942 // Preserve trailing slash for index routes (routePath ends with '/')
943 // This ensures types match runtime behavior
944 const isIndexRoute = routeNode.routePath?.endsWith('/')
945 if (isIndexRoute) {
946 return fullPath
947 }
948​
949 return fullPath.replace(/\/$/, '')
951​
952const shouldPreferIndexRoute = (
953 current: RouteNode,
954 existing: RouteNode,
955): boolean => {
956 return existing.cleanedPath === '/' && current.cleanedPath !== '/'
958​
959const isIndexRouteNode = (routeNode: RouteNode): boolean => {
960 return routeNode.routePath?.endsWith('/') ?? false
962​
963const isPathlessRouteNode = (routeNode: RouteNode): boolean => {
964 return routeNode._fsRouteType === 'pathless_layout'
966​
967const shouldReplaceRouteNodeForTo = (
968 current: RouteNode,
969 existing: RouteNode,
970): boolean => {
971 const currentIsIndex = isIndexRouteNode(current)
972 const existingIsIndex = isIndexRouteNode(existing)
973 if (currentIsIndex !== existingIsIndex) {
974 return currentIsIndex
975 }
976​
977 const currentIsPathless = isPathlessRouteNode(current)
978 const existingIsPathless = isPathlessRouteNode(existing)
979 if (currentIsPathless !== existingIsPathless) {
980 return !currentIsPathless
981 }
982​
983 return true
985​
986const shouldReplaceRouteNodeForFullPath = (
987 current: RouteNode,
988 existing: RouteNode,
989): boolean => {
990 const currentIsPathless = isPathlessRouteNode(current)
991 const existingIsPathless = isPathlessRouteNode(existing)
992 if (currentIsPathless !== existingIsPathless) {
993 return !currentIsPathless
994 }
995​
996 return true
998​
999/**
1000 * Creates a map from fullPath to routeNode
1001 */
1002export const createRouteNodesByFullPath = (
1003 routeNodes: Array<RouteNode>,
1004): Map<string, RouteNode> => {
1005 const map = new Map<string, RouteNode>()
1006​
1007 for (const routeNode of routeNodes) {
1008 const fullPath = inferFullPath(routeNode)
1009​
1010 if (fullPath === '/' && map.has('/')) {
1011 const existing = map.get('/')!
1012 if (shouldPreferIndexRoute(routeNode, existing)) {
1013 continue
1016​
1017 const existing = map.get(fullPath)
1018 if (existing && !shouldReplaceRouteNodeForFullPath(routeNode, existing)) {
1019 continue
1021​
1022 map.set(fullPath, routeNode)
1024​
1025 return map
1027​
1028/**
1029 * Create a map from 'to' to a routeNode
1030 */
1031export const createRouteNodesByTo = (
1032 routeNodes: Array<RouteNode>,
1033): Map<string, RouteNode> => {
1034 const map = new Map<string, RouteNode>()
1035​
1036 for (const routeNode of dedupeBranchesAndIndexRoutes(routeNodes)) {
1037 const to = inferTo(routeNode)
1038​
1039 const existing = map.get(to)
1040 if (existing && !shouldReplaceRouteNodeForTo(routeNode, existing)) {
1041 continue
1043​
1044 map.set(to, routeNode)
1046​
1047 return map
1049​
1050/**
1051 * Create a map from 'id' to a routeNode
1052 */
1053export const createRouteNodesById = (
1054 routeNodes: Array<RouteNode>,
1055): Map<string, RouteNode> => {
1056 return new Map(
1057 routeNodes.map((routeNode) => {
1058 const id = routeNode.routePath ?? ''
1059 return [id, routeNode]
1060 }),
1063​
1064/**
1065 * Infers to path
1066 */
1067const inferTo = (routeNode: RouteNode): string => {
1068 const fullPath = inferFullPath(routeNode)
1069​
1070 if (fullPath === '/') return fullPath
1071​
1072 return fullPath.replace(/\/$/, '')
1074​
1075/**
1076 * Dedupes branches and index routes
1077 */
1078const dedupeBranchesAndIndexRoutes = (
1079 routes: Array<RouteNode>,
1080): Array<RouteNode> => {
1081 return routes.filter((route) => {
1082 if (route.children?.find((child) => child.cleanedPath === '/')) return false
1083 return true
1084 })
1086​
1087function checkUnique<TElement>(routes: Array<TElement>, key: keyof TElement) {
1088 // Check no two routes have the same `key`
1089 // if they do, throw an error with the conflicting filePaths
1090 const keys = routes.map((d) => d[key])
1091 const uniqueKeys = new Set(keys)
1092 if (keys.length !== uniqueKeys.size) {
1093 const duplicateKeys = keys.filter((d, i) => keys.indexOf(d) !== i)
1094 const conflictingFiles = routes.filter((d) =>
1095 duplicateKeys.includes(d[key]),
1097 return conflictingFiles
1099 return undefined
1101​
1102export function checkRouteFullPathUniqueness(
1103 _routes: Array<RouteNode>,
1104 config: Config,
1105) {
1106 const emptyPathRoutes = _routes.filter((d) => d.routePath === '')
1107 if (emptyPathRoutes.length) {
1108 const errorMessage = `Invalid route path "" was found. Root routes must be defined via __root.tsx (createRootRoute), not createFileRoute('') or a route file that resolves to an empty path.
1109Conflicting files: \n ${emptyPathRoutes
1110 .map((d) => path.resolve(config.routesDirectory, d.filePath))
1111 .join('\n ')}\n`
1112 throw new Error(errorMessage)
1114​
1115 const routes = _routes.map((d) => {
1116 const inferredFullPath = inferFullPath(d)
1117 return { ...d, inferredFullPath }
1118 })
1119​
1120 const conflictingFiles = checkUnique(routes, 'inferredFullPath')
1121​
1122 if (conflictingFiles !== undefined) {
1123 const errorMessage = `Conflicting configuration paths were found for the following route${conflictingFiles.length > 1 ? 's' : ''}: ${conflictingFiles
1124 .map((p) => `"${p.inferredFullPath}"`)
1125 .join(', ')}.
1126Please ensure each Route has a unique full path.
1127Conflicting files: \n ${conflictingFiles.map((d) => path.resolve(config.routesDirectory, d.filePath)).join('\n ')}\n`
1128 throw new Error(errorMessage)
1131​
1132export function buildRouteTreeConfig(
1133 nodes: Array<RouteNode>,
1134 disableTypes: boolean,
1135 depth = 1,
1136): Array<string> {
1137 const children = nodes.map((node) => {
1138 if (node._fsRouteType === '__root') {
1139 return
1141​
1142 if (node._fsRouteType === 'pathless_layout' && !node.children?.length) {
1143 return
1145​
1146 const route = `${node.variableName}`
1147​
1148 if (node.children?.length) {
1149 const childConfigs = buildRouteTreeConfig(
1150 node.children,
1151 disableTypes,
1152 depth + 1,
1154​
1155 const childrenDeclaration = disableTypes
1156 ? ''
1157 : `interface ${route}RouteChildren {
1158 ${node.children
1159 .map(
1160 (child) =>
1161 `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`,
1163 .join(',')}
1165​
1166 const children = `const ${route}RouteChildren${disableTypes ? '' : `: ${route}RouteChildren`} = {
1167 ${node.children
1168 .map(
1169 (child) =>
1170 `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`,
1172 .join(',')}
1174​
1175 const routeWithChildren = `const ${route}RouteWithChildren = ${route}Route._addFileChildren(${route}RouteChildren)`
1176​
1177 return [
1178 childConfigs.join('\n'),
1179 childrenDeclaration,
1180 children,
1181 routeWithChildren,
1182 ].join('\n\n')
1184​
1185 return undefined
1186 })
1187​
1188 return children.filter((x) => x !== undefined)
1190​
1191export function buildImportString(
1192 importDeclaration: ImportDeclaration,
1193): string {
1194 const { source, specifiers, importKind } = importDeclaration
1195 return specifiers.length
1196 ? `import ${importKind === 'type' ? 'type ' : ''}{ ${specifiers.map((s) => (s.local ? `${s.imported} as ${s.local}` : s.imported)).join(', ')} } from '${source}'`
1197 : ''
1199​
1200export function mergeImportDeclarations(
1201 imports: Array<ImportDeclaration>,
1202): Array<ImportDeclaration> {
1203 const merged = new Map<string, ImportDeclaration>()
1204​
1205 for (const imp of imports) {
1206 const key = `${imp.source}-${imp.importKind ?? ''}`
1207 let existing = merged.get(key)
1208 if (!existing) {
1209 existing = { ...imp, specifiers: [] }
1210 merged.set(key, existing)
1212​
1213 const existingSpecs = existing.specifiers
1214 for (const specifier of imp.specifiers) {
1215 let found = false
1216 for (let i = 0; i < existingSpecs.length; i++) {
1217 const e = existingSpecs[i]!
1218 if (e.imported === specifier.imported && e.local === specifier.local) {
1219 found = true
1220 break
1223 if (!found) {
1224 existingSpecs.push(specifier)
1228​
1229 return [...merged.values()]
1231​
1232export const findParent = (node: RouteNode | undefined): string => {
1233 if (!node) {
1234 return `rootRouteImport`
1236 if (node.parent) {
1237 return `${node.parent.variableName}Route`
1239 return findParent(node.parent)
1241​
1242export function buildFileRoutesByPathInterface(opts: {
1243 routeNodes: Array<RouteNode>
1244 module: string
1245 interfaceName: string
1246 config?: Pick<Config, 'routeToken'>
1247}): string {
1248 return `declare module '${opts.module}' {
1249 interface ${opts.interfaceName} {
1250 ${opts.routeNodes
1251 .map((routeNode) => {
1252 const filePathId = routeNode.routePath
1253 const preloaderRoute = `typeof ${routeNode.variableName}RouteImport`
1254​
1255 const parent = findParent(routeNode)
1256​
1257 return `'${filePathId}': {
1258 id: '${filePathId}'
1259 path: '${inferPath(routeNode)}'
1260 fullPath: '${inferFullPath(routeNode)}'
1261 preLoaderRoute: ${preloaderRoute}
1262 parentRoute: typeof ${parent}
1263 }`
1264 })
1265 .join('\n')}
1269​
1270function getImportPath(
1271 node: RouteNode,
1272 config: Config,
1273 generatedRouteTreePath: string,
1274): string {
1275 return replaceBackslash(
1276 removeExt(
1277 path.relative(
1278 path.dirname(generatedRouteTreePath),
1279 path.resolve(config.routesDirectory, node.filePath),
1280 ),
1281 config.addExtensions,
1282 ),
1285​
1286export function getImportForRouteNode(
1287 node: RouteNode,
1288 config: Config,
1289 generatedRouteTreePath: string,
1290 root: string,
1291): ImportDeclaration {
1292 let source = ''
1293 if (config.importRoutesUsingAbsolutePaths) {
1294 source = replaceBackslash(
1295 removeExt(
1296 path.resolve(root, config.routesDirectory, node.filePath),
1297 config.addExtensions,
1298 ),
1300 } else {
1301 source = `./${getImportPath(node, config, generatedRouteTreePath)}`
1303 return {
1304 source,
1305 specifiers: [
1307 imported: 'Route',
1308 local: `${node.variableName}RouteImport`,
1309 },
1310 ],
1311 } satisfies ImportDeclaration