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

utils.ts

1,315 lines36.5 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 // The next route path scans from the start again
207 BRACKET_CONTENT_RE.lastIndex = 0
208 // Throw rather than exit the process: the generator's callers report
209 // it, so a dev server stays up and a build fails.
210 throw new Error(
211 `Disallowed character "${character}" found in square brackets in route path "${routePath}".\nYou cannot use any of the following characters in square brackets: ${Array.from(
212 DISALLOWED_ESCAPE_CHARS,
213 ).join(', ')}\nPlease remove and/or replace them.`,
214 )
215 }
216 }
217​
218 // Since this split segment is safe at this point, we can
219 // remove the brackets and replace them with the content inside
220 return part.replace(BRACKET_CONTENT_RE, '$1')
221 })
222​
223 // If the syntax for prefix/suffix is different, from the path
224 // matching internals of router-core, we'd perform those changes here
225 // on the `escapedParts` array before it is joined back together in
226 // `final`
227​
228 const final = cleanPath(`/${escapedParts.join('/')}`) || ''
229​
230 return {
231 routePath: final,
232 originalRoutePath,
233 }
235​
236export function determineInitialRoutePath(routePath: string) {
237 return determineInitialRoutePathFromParts(
238 routePath,
239 routePath.split(SPLIT_REGEX),
240 )
242​
243/**
244 * Resolves bracket escapes in an explicit route path or ID without applying
245 * the dot-delimited flat-file route convention.
246 */
247export function determineInitialRoutePathFromExplicitPath(routePath: string) {
248 return determineInitialRoutePathFromParts(routePath, [routePath])
250​
251/**
252 * Checks if a segment is fully escaped (entirely wrapped in brackets with no nested brackets).
253 * E.g., "[index]" -> true, "[_layout]" -> true, "foo[.]bar" -> false, "index" -> false
254 */
255function isFullyEscapedSegment(originalSegment: string): boolean {
256 return (
257 originalSegment.startsWith('[') &&
258 originalSegment.endsWith(']') &&
259 !originalSegment.slice(1, -1).includes('[') &&
260 !originalSegment.slice(1, -1).includes(']')
261 )
263​
264/**
265 * Checks if the leading underscore in a segment is escaped.
266 * Returns true if:
267 * - Segment starts with [_] pattern: "[_]layout" -> "_layout"
268 * - Segment is fully escaped and content starts with _: "[_1nd3x]" -> "_1nd3x"
269 */
270export function hasEscapedLeadingUnderscore(originalSegment: string): boolean {
271 // Pattern: [_]something or [_something]
272 return (
273 originalSegment.startsWith('[_]') ||
274 (originalSegment.startsWith('[_') && isFullyEscapedSegment(originalSegment))
275 )
277​
278/**
279 * Checks if the trailing underscore in a segment is escaped.
280 * Returns true if:
281 * - Segment ends with [_] pattern: "blog[_]" -> "blog_"
282 * - Segment is fully escaped and content ends with _: "[_r0ut3_]" -> "_r0ut3_"
283 */
284export function hasEscapedTrailingUnderscore(originalSegment: string): boolean {
285 // Pattern: something[_] or [something_]
286 return (
287 originalSegment.endsWith('[_]') ||
288 (originalSegment.endsWith('_]') && isFullyEscapedSegment(originalSegment))
289 )
291​
292export function countRoutePathSegments(routePath?: string): number {
293 const path = routePath ?? ''
294 let count = 0
295 let inSegment = false
296​
297 for (let i = 0; i < path.length; i++) {
298 if (path[i] === '/') {
299 inSegment = false
300 continue
301 }
302​
303 if (!inSegment) {
304 count++
305 inSegment = true
306 }
307 }
308​
309 return count
311​
312export function countSlashSeparatedParts(path: string): number {
313 let count = 1
314​
315 for (let i = 0; i < path.length; i++) {
316 if (path[i] === '/') count++
317 }
318​
319 return count
321​
322export function hasRoutePathSegmentMetadata(
323 metadata: RoutePathSegmentMetadata | undefined,
324): metadata is RoutePathSegmentMetadata {
325 return !!(
326 metadata?.literalLeadingUnderscore || metadata?.literalTrailingUnderscore
327 )
329​
330function mergeRoutePathSegmentMetadata(
331 current: RoutePathSegmentMetadata | undefined,
332 incoming: RoutePathSegmentMetadata | undefined,
333): RoutePathSegmentMetadata | undefined {
334 const hasCurrent = hasRoutePathSegmentMetadata(current)
335 const hasIncoming = hasRoutePathSegmentMetadata(incoming)
336​
337 if (!hasCurrent) return hasIncoming ? incoming : undefined
338 if (!hasIncoming) return current
339​
340 return {
341 literalLeadingUnderscore:
342 current.literalLeadingUnderscore || incoming.literalLeadingUnderscore,
343 literalTrailingUnderscore:
344 current.literalTrailingUnderscore || incoming.literalTrailingUnderscore,
345 }
347​
348export function createRoutePathSegmentMetadata(
349 routePath: string = '/',
350 originalPath?: string,
351): Array<RoutePathSegmentMetadata | undefined> | undefined {
352 if (!originalPath) return undefined
353​
354 const routeSegments = routePath.split('/')
355 const originalSegments = originalPath.split('/')
356 const metadata = new Array<RoutePathSegmentMetadata | undefined>(
357 routeSegments.length,
358 )
359 let hasMetadata = false
360​
361 for (let i = 0; i < routeSegments.length; i++) {
362 const segment = routeSegments[i]!
363 const originalSegment = originalSegments[i] || ''
364 const literalLeadingUnderscore =
365 segment.startsWith('_') && hasEscapedLeadingUnderscore(originalSegment)
366 const literalTrailingUnderscore =
367 segment.endsWith('_') && hasEscapedTrailingUnderscore(originalSegment)
368​
369 if (!literalLeadingUnderscore && !literalTrailingUnderscore) continue
370​
371 hasMetadata = true
372 metadata[i] = {
373 literalLeadingUnderscore: literalLeadingUnderscore || undefined,
374 literalTrailingUnderscore: literalTrailingUnderscore || undefined,
375 }
376 }
377​
378 return hasMetadata ? metadata : undefined
380​
381export function createLiteralRoutePathSegmentMetadata(
382 routePath: string,
383 parent?: RouteNode,
384 literalNewSegments = false,
385): Array<RoutePathSegmentMetadata | undefined> | undefined {
386 const routeSegments = routePath.split('/')
387 const metadata = new Array<RoutePathSegmentMetadata | undefined>(
388 routeSegments.length,
389 )
390 const parentDepth = countRoutePathSegments(parent?.routePath)
391 let hasMetadata = false
392 let depth = 0
393​
394 for (let i = 0; i < routeSegments.length; i++) {
395 const segment = routeSegments[i]
396 metadata[i] = parent?._routePathSegmentMetadata?.[i]
397 hasMetadata ||= hasRoutePathSegmentMetadata(metadata[i])
398​
399 if (!segment) continue
400​
401 if (literalNewSegments && depth >= parentDepth) {
402 const literalLeadingUnderscore = segment.startsWith('_')
403 const literalTrailingUnderscore = segment.endsWith('_')
404​
405 if (literalLeadingUnderscore || literalTrailingUnderscore) {
406 metadata[i] = mergeRoutePathSegmentMetadata(metadata[i], {
407 literalLeadingUnderscore: literalLeadingUnderscore || undefined,
408 literalTrailingUnderscore: literalTrailingUnderscore || undefined,
409 })
410 hasMetadata = true
411 }
412 }
413​
414 depth++
415 }
416​
417 return hasMetadata ? metadata : undefined
419​
420export function joinRoutePathSegmentMetadata(
421 routePath: string,
422 prefixPath: string,
423 prefixMetadata: Array<RoutePathSegmentMetadata | undefined> | undefined,
424 childMetadata: Array<RoutePathSegmentMetadata | undefined> | undefined,
425): Array<RoutePathSegmentMetadata | undefined> | undefined {
426 const metadata = new Array<RoutePathSegmentMetadata | undefined>(
427 countSlashSeparatedParts(routePath),
428 )
429 let hasMetadata = false
430​
431 if (prefixMetadata) {
432 for (let i = 0; i < prefixMetadata.length && i < metadata.length; i++) {
433 metadata[i] = prefixMetadata[i]
434 hasMetadata ||= hasRoutePathSegmentMetadata(metadata[i])
435 }
436 }
437​
438 const offset = countRoutePathSegments(prefixPath)
439 if (childMetadata) {
440 for (let i = 1; i < childMetadata.length; i++) {
441 const targetIndex = offset + i
442 if (targetIndex >= metadata.length) break
443​
444 metadata[targetIndex] = mergeRoutePathSegmentMetadata(
445 metadata[targetIndex],
446 childMetadata[i],
447 )
448 hasMetadata ||= hasRoutePathSegmentMetadata(metadata[targetIndex])
449 }
450 }
451​
452 return hasMetadata ? metadata : undefined
454​
455const backslashRegex = /\\/g
456​
457export function replaceBackslash(s: string) {
458 return s.replace(backslashRegex, '/')
460​
461const alphanumericRegex = /[a-zA-Z0-9_]/
462const splatSlashRegex = /\/\$\//g
463const trailingSplatRegex = /\$$/g
464const bracketSplatRegex = /\$\{\$\}/g
465const dollarSignRegex = /\$/g
466const splitPathRegex = /[/-]/g
467const leadingDigitRegex = /^(\d)/g
468​
469const toVariableSafeChar = (char: string): string => {
470 if (alphanumericRegex.test(char)) {
471 return char // Keep alphanumeric characters and underscores as is
472 }
473​
474 // Replace special characters with meaningful text equivalents
475 switch (char) {
476 case '.':
477 return 'Dot'
478 case '-':
479 return 'Dash'
480 case '@':
481 return 'At'
482 case '(':
483 return '' // Removed since route groups use parentheses
484 case ')':
485 return '' // Removed since route groups use parentheses
486 case ' ':
487 return '' // Remove spaces
488 default:
489 return `Char${char.charCodeAt(0)}` // For any other characters
490 }
492​
493export function routePathToVariable(routePath: string): string {
494 const cleaned = removeUnderscores(routePath)
495 if (!cleaned) return ''
496​
497 const parts = cleaned
498 .replace(splatSlashRegex, '/splat/')
499 .replace(trailingSplatRegex, 'splat')
500 .replace(bracketSplatRegex, 'splat')
501 .replace(dollarSignRegex, '')
502 .split(splitPathRegex)
503​
504 let result = ''
505 for (let i = 0; i < parts.length; i++) {
506 const part = parts[i]!
507 const segment = i > 0 ? capitalize(part) : part
508 for (let j = 0; j < segment.length; j++) {
509 result += toVariableSafeChar(segment[j]!)
510 }
511 }
512​
513 return result.replace(leadingDigitRegex, 'R$1')
515​
516const underscoreStartEndRegex = /(^_|_$)/gi
517const underscoreSlashRegex = /(\/_|_\/)/gi
518​
519export function removeUnderscores(s?: string) {
520 return s
521 ?.replace(underscoreStartEndRegex, '')
522 .replace(underscoreSlashRegex, '/')
524​
525function removeUnderscoresFromSegment(
526 segment: string,
527 metadata?: RoutePathSegmentMetadata,
528): string {
529 let result = segment
530​
531 if (result.startsWith('_') && !metadata?.literalLeadingUnderscore) {
532 result = result.slice(1)
533 }
534​
535 if (result.endsWith('_') && !metadata?.literalTrailingUnderscore) {
536 result = result.slice(0, -1)
537 }
538​
539 return result
541​
542/**
543 * Removes underscores from a path, but preserves underscores that were escaped
544 * in the original path (indicated by [_] syntax).
545 *
546 * @param routePath - The path with brackets removed
547 * @param originalPath - The original path that may contain [_] escape sequences
548 * @returns The path with non-escaped underscores removed
549 */
550export function removeUnderscoresWithEscape(
551 routePath?: string,
552 originalPath?: string,
553): string {
554 if (!routePath) return ''
555 if (!originalPath) return removeUnderscores(routePath) ?? ''
556​
557 const routeSegments = routePath.split('/')
558 const metadata = createRoutePathSegmentMetadata(routePath, originalPath)
559 const newSegments = new Array<string>(routeSegments.length)
560​
561 for (let i = 0; i < routeSegments.length; i++) {
562 newSegments[i] = removeUnderscoresFromSegment(
563 routeSegments[i]!,
564 metadata?.[i],
565 )
566 }
567​
568 return newSegments.join('/')
570​
571export function removeLayoutSegmentsAndUnderscoresWithEscape(
572 routePath: string = '/',
573 originalPath?: string,
574 routePathSegmentMetadata?: Array<RoutePathSegmentMetadata | undefined>,
575): string {
576 if (!originalPath) {
577 return removeUnderscores(removeLayoutSegments(routePath)) ?? ''
578 }
579​
580 const metadata =
581 routePathSegmentMetadata ??
582 createRoutePathSegmentMetadata(routePath, originalPath)
583​
584 const routeSegments = routePath.split('/')
585 const originalSegments = originalPath.split('/')
586 const newSegments: Array<string> = []
587​
588 for (let i = 0; i < routeSegments.length; i++) {
589 const segment = routeSegments[i]!
590 const originalSegment = originalSegments[i] || ''
591 const segmentMetadata = metadata?.[i]
592​
593 if (
594 !segmentMetadata?.literalLeadingUnderscore &&
595 isSegmentPathless(segment, originalSegment)
596 ) {
597 continue
598 }
599​
600 newSegments.push(removeUnderscoresFromSegment(segment, segmentMetadata))
601 }
602​
603 return newSegments.join('/')
605​
606/**
607 * Removes layout segments (segments starting with underscore) from a path,
608 * but preserves segments where the underscore was escaped.
609 *
610 * @param routePath - The path with brackets removed
611 * @param originalPath - The original path that may contain [_] escape sequences
612 * @returns The path with non-escaped layout segments removed
613 */
614export function removeLayoutSegmentsWithEscape(
615 routePath: string = '/',
616 originalPath?: string,
617): string {
618 if (!originalPath) return removeLayoutSegments(routePath)
619​
620 const routeSegments = routePath.split('/')
621 const originalSegments = originalPath.split('/')
622​
623 // Keep segments that are NOT pathless (i.e., don't start with unescaped underscore)
624 const newSegments = routeSegments.filter((segment, i) => {
625 const originalSegment = originalSegments[i] || ''
626 return !isSegmentPathless(segment, originalSegment)
627 })
628​
629 return newSegments.join('/')
631​
632/**
633 * Checks if a segment should be treated as a pathless/layout segment.
634 * A segment is pathless if it starts with underscore and the underscore is not escaped.
635 *
636 * @param segment - The segment from routePath (brackets removed)
637 * @param originalSegment - The segment from originalRoutePath (may contain brackets)
638 * @returns true if the segment is pathless (has non-escaped leading underscore)
639 */
640export function isSegmentPathless(
641 segment: string,
642 originalSegment: string,
643): boolean {
644 if (!segment.startsWith('_')) return false
645 return !hasEscapedLeadingUnderscore(originalSegment)
647​
648export function escapeRegExp(s: string): string {
649 return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
651​
652function sanitizeTokenFlags(flags?: string): string | undefined {
653 if (!flags) return flags
654​
655 // Prevent stateful behavior with RegExp.prototype.test/exec
656 // g = global, y = sticky
657 return flags.replace(/[gy]/g, '')
659​
660export function createTokenRegex(
661 token: TokenMatcher,
662 opts: {
663 type: 'segment' | 'filename'
664 },
665): RegExp {
666 // Defensive check: if token is undefined/null, throw a clear error
667 // (runtime safety for config loading edge cases)
668 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
669 if (token === undefined || token === null) {
670 throw new Error(
671 `createTokenRegex: token is ${token}. This usually means the config was not properly parsed with defaults.`,
672 )
673 }
674​
675 try {
676 if (typeof token === 'string') {
677 return opts.type === 'segment'
678 ? new RegExp(`^${escapeRegExp(token)}$`)
679 : new RegExp(`[./]${escapeRegExp(token)}[.]`)
680 }
681​
682 if (token instanceof RegExp) {
683 const flags = sanitizeTokenFlags(token.flags)
684 return opts.type === 'segment'
685 ? new RegExp(`^(?:${token.source})$`, flags)
686 : new RegExp(`[./](?:${token.source})[.]`, flags)
687 }
688​
689 // Handle JSON regex object form: { regex: string, flags?: string }
690 if (typeof token === 'object' && 'regex' in token) {
691 const flags = sanitizeTokenFlags(token.flags)
692 return opts.type === 'segment'
693 ? new RegExp(`^(?:${token.regex})$`, flags)
694 : new RegExp(`[./](?:${token.regex})[.]`, flags)
695 }
696​
697 throw new Error(
698 `createTokenRegex: invalid token type. Expected string, RegExp, or { regex, flags } object, got: ${typeof token}`,
699 )
700 } catch (e) {
701 if (e instanceof SyntaxError) {
702 const pattern =
703 typeof token === 'string'
704 ? token
705 : token instanceof RegExp
706 ? token.source
707 : token.regex
708 throw new Error(
709 `Invalid regex pattern in token config: "${pattern}". ${e.message}`,
710 )
711 }
712 throw e
713 }
715​
716function isBracketWrappedSegment(segment: string): boolean {
717 return segment.startsWith('[') && segment.endsWith(']')
719​
720export function unwrapBracketWrappedSegment(segment: string): string {
721 return isBracketWrappedSegment(segment) ? segment.slice(1, -1) : segment
723​
724export function removeLeadingUnderscores(s: string, routeToken: string) {
725 if (!s) return s
726​
727 const hasLeadingUnderscore = routeToken[0] === '_'
728​
729 const routeTokenToExclude = hasLeadingUnderscore
730 ? routeToken.slice(1)
731 : routeToken
732​
733 const escapedRouteToken = escapeRegExp(routeTokenToExclude)
734​
735 const leadingUnderscoreRegex = hasLeadingUnderscore
736 ? new RegExp(`(?<=^|\\/)_(?!${escapedRouteToken})`, 'g')
737 : new RegExp(`(?<=^|\\/)_`, 'g')
738​
739 return s.replaceAll(leadingUnderscoreRegex, '')
741​
742export function removeTrailingUnderscores(s: string, routeToken: string) {
743 if (!s) return s
744​
745 const hasTrailingUnderscore = routeToken.slice(-1) === '_'
746​
747 const routeTokenToExclude = hasTrailingUnderscore
748 ? routeToken.slice(0, -1)
749 : routeToken
750​
751 const escapedRouteToken = escapeRegExp(routeTokenToExclude)
752​
753 const trailingUnderscoreRegex = hasTrailingUnderscore
754 ? new RegExp(`(?<!${escapedRouteToken})_(?=\\/|$)`, 'g')
755 : new RegExp(`_(?=\\/)|_$`, 'g')
756​
757 return s.replaceAll(trailingUnderscoreRegex, '')
759​
760export function capitalize(s: string) {
761 if (typeof s !== 'string') return ''
762 return s.charAt(0).toUpperCase() + s.slice(1)
764​
765export function removeExt(d: string, addExtensions: boolean | string = false) {
766 if (typeof addExtensions === 'string') {
767 const dotIndex = d.lastIndexOf('.')
768 if (dotIndex === -1) return d
769 return d.substring(0, dotIndex) + addExtensions
770 }
771 return addExtensions ? d : d.substring(0, d.lastIndexOf('.')) || d
773​
774/**
775 * This function writes to a file if the content is different.
776 *
777 * @param filepath The path to the file
778 * @param content Original content
779 * @param incomingContent New content
780 * @param callbacks Callbacks to run before and after writing
781 * @returns Whether the file was written
782 */
783export async function writeIfDifferent(
784 filepath: string,
785 content: string,
786 incomingContent: string,
787 callbacks?: { beforeWrite?: () => void; afterWrite?: () => void },
788): Promise<boolean> {
789 if (content !== incomingContent) {
790 callbacks?.beforeWrite?.()
791 await fsp.writeFile(filepath, incomingContent)
792 callbacks?.afterWrite?.()
793 return true
794 }
795 return false
797​
798/**
799 * This function formats the source code using the default formatter (Prettier).
800 *
801 * @param source The content to format
802 * @param config The configuration object
803 * @returns The formatted content
804 */
805export async function format(
806 source: string,
807 config: {
808 quoteStyle: 'single' | 'double'
809 semicolons: boolean
810 },
811): Promise<string> {
812 const prettierOptions: prettier.Config = {
813 semi: config.semicolons,
814 singleQuote: config.quoteStyle === 'single',
815 parser: 'typescript',
816 }
817 return prettier.format(source, prettierOptions)
819​
820/**
821 * This function resets the regex index to 0 so that it can be reused
822 * without having to create a new regex object or worry about the last
823 * state when using the global flag.
824 *
825 * @param regex The regex object to reset
826 * @returns
827 */
828export function resetRegex(regex: RegExp) {
829 regex.lastIndex = 0
830 return
832​
833/**
834 * This function checks if a file exists.
835 *
836 * @param file The path to the file
837 * @returns Whether the file exists
838 */
839export async function checkFileExists(file: string) {
840 try {
841 await fsp.access(file, fsp.constants.F_OK)
842 return true
843 } catch {
844 return false
845 }
847​
848const possiblyNestedRouteGroupPatternRegex = /\([^/]+\)\/?/g
849export function removeGroups(s: string) {
850 return s.replace(possiblyNestedRouteGroupPatternRegex, '')
852​
853/**
854 * Removes all segments from a given path that start with an underscore ('_').
855 *
856 * @param {string} routePath - The path from which to remove segments. Defaults to '/'.
857 * @returns {string} The path with all underscore-prefixed segments removed.
858 * @example
859 * removeLayoutSegments('/workspace/_auth/foo') // '/workspace/foo'
860 */
861export function removeLayoutSegments(routePath: string = '/'): string {
862 const segments = routePath.split('/')
863 const newSegments = segments.filter((segment) => !segment.startsWith('_'))
864 return newSegments.join('/')
866​
867/**
868 * The `node.path` is used as the `id` in the route definition.
869 * This function checks if the given node has a parent and if so, it determines the correct path for the given node.
870 * @param node - The node to determine the path for.
871 * @returns The correct path for the given node.
872 */
873export function determineNodePath(node: RouteNode) {
874 return (node.path = node.parent
875 ? node.routePath?.replace(node.parent.routePath ?? '', '') || '/'
876 : node.routePath)
878​
879/**
880 * Removes the last segment from a given path. Segments are considered to be separated by a '/'.
881 *
882 * @param {string} routePath - The path from which to remove the last segment. Defaults to '/'.
883 * @returns {string} The path with the last segment removed.
884 * @example
885 * removeLastSegmentFromPath('/workspace/_auth/foo') // '/workspace/_auth'
886 */
887export function removeLastSegmentFromPath(routePath: string = '/'): string {
888 const segments = routePath.split('/')
889 segments.pop() // Remove the last segment
890 return segments.join('/')
892​
893/**
894 * Find parent route using RoutePrefixMap for O(k) lookups instead of O(n).
895 */
896export function hasParentRoute(
897 prefixMap: RoutePrefixMap,
898 node: RouteNode,
899 routePathToCheck: string | undefined,
900): RouteNode | null {
901 if (!routePathToCheck || routePathToCheck === '/') {
902 return null
903 }
904​
905 return prefixMap.findParent(routePathToCheck)
907​
908/**
909 * Gets the final variable name for a route
910 */
911export const getResolvedRouteNodeVariableName = (
912 routeNode: RouteNode,
913): string => {
914 return routeNode.children?.length
915 ? `${routeNode.variableName}RouteWithChildren`
916 : `${routeNode.variableName}Route`
918​
919/**
920 * Infers the path for use by TS
921 */
922const inferPath = (routeNode: RouteNode): string => {
923 if (routeNode.cleanedPath === '/') {
924 return routeNode.cleanedPath ?? ''
925 }
926 return routeNode.cleanedPath?.replace(/\/$/, '') ?? ''
928​
929/**
930 * Infers the full path for use by TS
931 */
932export const inferFullPath = (routeNode: RouteNode): string => {
933 const fullPath = removeGroups(
934 removeLayoutSegmentsAndUnderscoresWithEscape(
935 routeNode.routePath,
936 routeNode.originalRoutePath,
937 routeNode._routePathSegmentMetadata,
938 ),
939 )
940​
941 if (fullPath === '') {
942 return '/'
943 }
944​
945 // Preserve trailing slash for index routes (routePath ends with '/')
946 // This ensures types match runtime behavior
947 const isIndexRoute = routeNode.routePath?.endsWith('/')
948 if (isIndexRoute) {
949 return fullPath
950 }
951​
952 return fullPath.replace(/\/$/, '')
954​
955const shouldPreferIndexRoute = (
956 current: RouteNode,
957 existing: RouteNode,
958): boolean => {
959 return existing.cleanedPath === '/' && current.cleanedPath !== '/'
961​
962const isIndexRouteNode = (routeNode: RouteNode): boolean => {
963 return routeNode.routePath?.endsWith('/') ?? false
965​
966const isPathlessRouteNode = (routeNode: RouteNode): boolean => {
967 return routeNode._fsRouteType === 'pathless_layout'
969​
970const shouldReplaceRouteNodeForTo = (
971 current: RouteNode,
972 existing: RouteNode,
973): boolean => {
974 const currentIsIndex = isIndexRouteNode(current)
975 const existingIsIndex = isIndexRouteNode(existing)
976 if (currentIsIndex !== existingIsIndex) {
977 return currentIsIndex
978 }
979​
980 const currentIsPathless = isPathlessRouteNode(current)
981 const existingIsPathless = isPathlessRouteNode(existing)
982 if (currentIsPathless !== existingIsPathless) {
983 return !currentIsPathless
984 }
985​
986 return true
988​
989const shouldReplaceRouteNodeForFullPath = (
990 current: RouteNode,
991 existing: RouteNode,
992): boolean => {
993 const currentIsPathless = isPathlessRouteNode(current)
994 const existingIsPathless = isPathlessRouteNode(existing)
995 if (currentIsPathless !== existingIsPathless) {
996 return !currentIsPathless
997 }
998​
999 return true
1001​
1002/**
1003 * Creates a map from fullPath to routeNode
1004 */
1005export const createRouteNodesByFullPath = (
1006 routeNodes: Array<RouteNode>,
1007): Map<string, RouteNode> => {
1008 const map = new Map<string, RouteNode>()
1009​
1010 for (const routeNode of routeNodes) {
1011 const fullPath = inferFullPath(routeNode)
1012​
1013 if (fullPath === '/' && map.has('/')) {
1014 const existing = map.get('/')!
1015 if (shouldPreferIndexRoute(routeNode, existing)) {
1016 continue
1019​
1020 const existing = map.get(fullPath)
1021 if (existing && !shouldReplaceRouteNodeForFullPath(routeNode, existing)) {
1022 continue
1024​
1025 map.set(fullPath, routeNode)
1027​
1028 return map
1030​
1031/**
1032 * Create a map from 'to' to a routeNode
1033 */
1034export const createRouteNodesByTo = (
1035 routeNodes: Array<RouteNode>,
1036): Map<string, RouteNode> => {
1037 const map = new Map<string, RouteNode>()
1038​
1039 for (const routeNode of dedupeBranchesAndIndexRoutes(routeNodes)) {
1040 const to = inferTo(routeNode)
1041​
1042 const existing = map.get(to)
1043 if (existing && !shouldReplaceRouteNodeForTo(routeNode, existing)) {
1044 continue
1046​
1047 map.set(to, routeNode)
1049​
1050 return map
1052​
1053/**
1054 * Create a map from 'id' to a routeNode
1055 */
1056export const createRouteNodesById = (
1057 routeNodes: Array<RouteNode>,
1058): Map<string, RouteNode> => {
1059 return new Map(
1060 routeNodes.map((routeNode) => {
1061 const id = routeNode.routePath ?? ''
1062 return [id, routeNode]
1063 }),
1066​
1067/**
1068 * Infers to path
1069 */
1070const inferTo = (routeNode: RouteNode): string => {
1071 const fullPath = inferFullPath(routeNode)
1072​
1073 if (fullPath === '/') return fullPath
1074​
1075 return fullPath.replace(/\/$/, '')
1077​
1078/**
1079 * Dedupes branches and index routes
1080 */
1081const dedupeBranchesAndIndexRoutes = (
1082 routes: Array<RouteNode>,
1083): Array<RouteNode> => {
1084 return routes.filter((route) => {
1085 if (route.children?.find((child) => child.cleanedPath === '/')) return false
1086 return true
1087 })
1089​
1090function checkUnique<TElement>(routes: Array<TElement>, key: keyof TElement) {
1091 // Check no two routes have the same `key`
1092 // if they do, throw an error with the conflicting filePaths
1093 const keys = routes.map((d) => d[key])
1094 const uniqueKeys = new Set(keys)
1095 if (keys.length !== uniqueKeys.size) {
1096 const duplicateKeys = keys.filter((d, i) => keys.indexOf(d) !== i)
1097 const conflictingFiles = routes.filter((d) =>
1098 duplicateKeys.includes(d[key]),
1100 return conflictingFiles
1102 return undefined
1104​
1105export function checkRouteFullPathUniqueness(
1106 _routes: Array<RouteNode>,
1107 config: Config,
1108) {
1109 const emptyPathRoutes = _routes.filter((d) => d.routePath === '')
1110 if (emptyPathRoutes.length) {
1111 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.
1112Conflicting files: \n ${emptyPathRoutes
1113 .map((d) => path.resolve(config.routesDirectory, d.filePath))
1114 .join('\n ')}\n`
1115 throw new Error(errorMessage)
1117​
1118 const routes = _routes.map((d) => {
1119 const inferredFullPath = inferFullPath(d)
1120 return { ...d, inferredFullPath }
1121 })
1122​
1123 const conflictingFiles = checkUnique(routes, 'inferredFullPath')
1124​
1125 if (conflictingFiles !== undefined) {
1126 const errorMessage = `Conflicting configuration paths were found for the following route${conflictingFiles.length > 1 ? 's' : ''}: ${conflictingFiles
1127 .map((p) => `"${p.inferredFullPath}"`)
1128 .join(', ')}.
1129Please ensure each Route has a unique full path.
1130Conflicting files: \n ${conflictingFiles.map((d) => path.resolve(config.routesDirectory, d.filePath)).join('\n ')}\n`
1131 throw new Error(errorMessage)
1134​
1135export function buildRouteTreeConfig(
1136 nodes: Array<RouteNode>,
1137 disableTypes: boolean,
1138 depth = 1,
1139): Array<string> {
1140 const children = nodes.map((node) => {
1141 if (node._fsRouteType === '__root') {
1142 return
1144​
1145 if (node._fsRouteType === 'pathless_layout' && !node.children?.length) {
1146 return
1148​
1149 const route = `${node.variableName}`
1150​
1151 if (node.children?.length) {
1152 const childConfigs = buildRouteTreeConfig(
1153 node.children,
1154 disableTypes,
1155 depth + 1,
1157​
1158 const childrenDeclaration = disableTypes
1159 ? ''
1160 : `interface ${route}RouteChildren {
1161 ${node.children
1162 .map(
1163 (child) =>
1164 `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`,
1166 .join(',')}
1168​
1169 const children = `const ${route}RouteChildren${disableTypes ? '' : `: ${route}RouteChildren`} = {
1170 ${node.children
1171 .map(
1172 (child) =>
1173 `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`,
1175 .join(',')}
1177​
1178 const routeWithChildren = `const ${route}RouteWithChildren = ${route}Route._addFileChildren(${route}RouteChildren)`
1179​
1180 return [
1181 childConfigs.join('\n'),
1182 childrenDeclaration,
1183 children,
1184 routeWithChildren,
1185 ].join('\n\n')
1187​
1188 return undefined
1189 })
1190​
1191 return children.filter((x) => x !== undefined)
1193​
1194export function buildImportString(
1195 importDeclaration: ImportDeclaration,
1196): string {
1197 const { source, specifiers, importKind } = importDeclaration
1198 return specifiers.length
1199 ? `import ${importKind === 'type' ? 'type ' : ''}{ ${specifiers.map((s) => (s.local ? `${s.imported} as ${s.local}` : s.imported)).join(', ')} } from '${source}'`
1200 : ''
1202​
1203export function mergeImportDeclarations(
1204 imports: Array<ImportDeclaration>,
1205): Array<ImportDeclaration> {
1206 const merged = new Map<string, ImportDeclaration>()
1207​
1208 for (const imp of imports) {
1209 const key = `${imp.source}-${imp.importKind ?? ''}`
1210 let existing = merged.get(key)
1211 if (!existing) {
1212 existing = { ...imp, specifiers: [] }
1213 merged.set(key, existing)
1215​
1216 const existingSpecs = existing.specifiers
1217 for (const specifier of imp.specifiers) {
1218 let found = false
1219 for (let i = 0; i < existingSpecs.length; i++) {
1220 const e = existingSpecs[i]!
1221 if (e.imported === specifier.imported && e.local === specifier.local) {
1222 found = true
1223 break
1226 if (!found) {
1227 existingSpecs.push(specifier)
1231​
1232 return [...merged.values()]
1234​
1235export const findParent = (node: RouteNode | undefined): string => {
1236 if (!node) {
1237 return `rootRouteImport`
1239 if (node.parent) {
1240 return `${node.parent.variableName}Route`
1242 return findParent(node.parent)
1244​
1245export function buildFileRoutesByPathInterface(opts: {
1246 routeNodes: Array<RouteNode>
1247 module: string
1248 interfaceName: string
1249 config?: Pick<Config, 'routeToken'>
1250}): string {
1251 return `declare module '${opts.module}' {
1252 interface ${opts.interfaceName} {
1253 ${opts.routeNodes
1254 .map((routeNode) => {
1255 const filePathId = routeNode.routePath
1256 const preloaderRoute = `typeof ${routeNode.variableName}RouteImport`
1257​
1258 const parent = findParent(routeNode)
1259​
1260 return `'${filePathId}': {
1261 id: '${filePathId}'
1262 path: '${inferPath(routeNode)}'
1263 fullPath: '${inferFullPath(routeNode)}'
1264 preLoaderRoute: ${preloaderRoute}
1265 parentRoute: typeof ${parent}
1266 }`
1267 })
1268 .join('\n')}
1272​
1273function getImportPath(
1274 node: RouteNode,
1275 config: Config,
1276 generatedRouteTreePath: string,
1277): string {
1278 return replaceBackslash(
1279 removeExt(
1280 path.relative(
1281 path.dirname(generatedRouteTreePath),
1282 path.resolve(config.routesDirectory, node.filePath),
1283 ),
1284 config.addExtensions,
1285 ),
1288​
1289export function getImportForRouteNode(
1290 node: RouteNode,
1291 config: Config,
1292 generatedRouteTreePath: string,
1293 root: string,
1294): ImportDeclaration {
1295 let source = ''
1296 if (config.importRoutesUsingAbsolutePaths) {
1297 source = replaceBackslash(
1298 removeExt(
1299 path.resolve(root, config.routesDirectory, node.filePath),
1300 config.addExtensions,
1301 ),
1303 } else {
1304 source = `./${getImportPath(node, config, generatedRouteTreePath)}`
1306 return {
1307 source,
1308 specifiers: [
1310 imported: 'Route',
1311 local: `${node.variableName}RouteImport`,
1312 },
1313 ],
1314 } satisfies ImportDeclaration