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

utils.test.ts

1,078 lines32.7 KB

1import { describe, expect, it, vi } from 'vitest'
2import {
3 RoutePrefixMap,
4 cleanPath,
5 createLiteralRoutePathSegmentMetadata,
6 createRoutePathSegmentMetadata,
7 createRouteNodesByFullPath,
8 createRouteNodesByTo,
9 createTokenRegex,
10 determineInitialRoutePath,
11 determineInitialRoutePathFromExplicitPath,
12 hasEscapedLeadingUnderscore,
13 hasEscapedTrailingUnderscore,
14 inferFullPath,
15 isSegmentPathless,
16 mergeImportDeclarations,
17 multiSortBy,
18 removeExt,
19 removeLayoutSegmentsAndUnderscoresWithEscape,
20 removeLayoutSegmentsWithEscape,
21 removeLeadingUnderscores,
22 removeTrailingUnderscores,
23 removeUnderscores,
24 removeUnderscoresWithEscape,
25 routePathToVariable,
26 sortRouteNodes,
27} from '../src/utils'
28import type { ImportDeclaration, RouteNode } from '../src/types'
29​
30describe('cleanPath', () => {
31 it('keeps path with leading slash and trailing slash', () => {
32 expect(cleanPath('/test/')).toBe('/test/')
33 })
34})
35​
36describe('inferFullPath', () => {
37 it('returns "/" for pathless layouts under root', () => {
38 const node = {
39 routePath: '/_layout-a1',
40 originalRoutePath: '/_layout-a1',
41 cleanedPath: '',
42 _fsRouteType: 'pathless_layout',
43 } as unknown as RouteNode
44​
45 // This avoids inferred fullPath "" which breaks match.fullPath unions
46 expect(inferFullPath(node)).toBe('/')
47 })
48​
49 it('preserves escaped leading underscores after removing pathless ancestors', () => {
50 const node = {
51 routePath: '/_layout/_foo',
52 originalRoutePath: '/_layout/[_]foo',
53 } as unknown as RouteNode
54​
55 expect(inferFullPath(node)).toBe('/_foo')
56 })
57​
58 it('preserves multiple escaped leading underscores after removing pathless ancestors', () => {
59 const node = {
60 routePath: '/_layout/__foo',
61 originalRoutePath: '/_layout/[__foo]',
62 } as unknown as RouteNode
63​
64 expect(inferFullPath(node)).toBe('/__foo')
65 })
66​
67 it('preserves explicit literal leading underscores on index routes after removing pathless ancestors', () => {
68 const parent = {
69 routePath: '/_layout',
70 } as unknown as RouteNode
71 const node = {
72 routePath: '/_layout/_nested/',
73 originalRoutePath: '/_layout/_nested/',
74 _routePathSegmentMetadata: createLiteralRoutePathSegmentMetadata(
75 '/_layout/_nested',
76 parent,
77 true,
78 ),
79 } as unknown as RouteNode
80​
81 expect(inferFullPath(node)).toBe('/_nested/')
82 })
83​
84 it('removes pathless index route segments when they are not marked literal', () => {
85 const node = {
86 routePath: '/_layout/_nested/',
87 originalRoutePath: '/_layout/_nested/',
88 } as unknown as RouteNode
89​
90 expect(inferFullPath(node)).toBe('/')
91 })
92​
93 it('preserves escaped trailing underscores on index routes', () => {
94 const node = {
95 routePath: '/_layout/foo_/',
96 originalRoutePath: '/_layout/foo[_]/',
97 _routePathSegmentMetadata: createRoutePathSegmentMetadata(
98 '/_layout/foo_/',
99 '/_layout/foo[_]/',
100 ),
101 } as unknown as RouteNode
102​
103 expect(inferFullPath(node)).toBe('/foo_/')
104 })
105​
106 it('removes unescaped trailing underscores on index routes', () => {
107 const node = {
108 routePath: '/_layout/foo_/',
109 originalRoutePath: '/_layout/foo_/',
110 } as unknown as RouteNode
111​
112 expect(inferFullPath(node)).toBe('/foo/')
113 })
114})
115​
116describe('createRoutePathSegmentMetadata', () => {
117 it('preserves escaped trailing underscores on index routes', () => {
118 const metadata = createRoutePathSegmentMetadata('/foo_/', '/foo[_]/')
119​
120 expect(metadata).toHaveLength(3)
121 expect(metadata?.[1]).toEqual({ literalTrailingUnderscore: true })
122 })
123​
124 it('preserves mixed escaped leading and trailing underscores', () => {
125 const metadata = createRoutePathSegmentMetadata('/_foo_/', '/[_]foo[_]/')
126​
127 expect(metadata).toHaveLength(3)
128 expect(metadata?.[1]).toEqual({
129 literalLeadingUnderscore: true,
130 literalTrailingUnderscore: true,
131 })
132 })
133​
134 it('tracks multiple literal underscore segments independently', () => {
135 const metadata = createRoutePathSegmentMetadata(
136 '/_foo/bar_/_baz_/',
137 '/[_]foo/bar[_]/[_baz_]/',
138 )
139​
140 expect(metadata).toHaveLength(5)
141 expect(metadata?.[1]).toEqual({ literalLeadingUnderscore: true })
142 expect(metadata?.[2]).toEqual({ literalTrailingUnderscore: true })
143 expect(metadata?.[3]).toEqual({
144 literalLeadingUnderscore: true,
145 literalTrailingUnderscore: true,
146 })
147 })
148})
149​
150describe('createRouteNodesByTo', () => {
151 const createRoute = (
152 overrides: Partial<RouteNode> & { routePath: string },
153 ): RouteNode => ({
154 filePath: 'test.tsx',
155 fullPath: overrides.routePath,
156 variableName: 'Test',
157 _fsRouteType: 'static',
158 cleanedPath: overrides.routePath.endsWith('/')
159 ? '/'
160 : overrides.routePath.split('/').at(-1),
161 ...overrides,
162 })
163​
164 it('prefers index routes over pathless layouts for duplicate public to paths', () => {
165 const pathlessRoute = createRoute({
166 routePath: '/livestock/$farmId/medicine/_form',
167 _fsRouteType: 'pathless_layout',
168 variableName: 'Pathless',
169 })
170 const indexRoute = createRoute({
171 routePath: '/livestock/$farmId/medicine/',
172 cleanedPath: '/',
173 variableName: 'Index',
174 })
175​
176 const map = createRouteNodesByTo([pathlessRoute, indexRoute])
177​
178 expect(map.get('/livestock/$farmId/medicine')).toBe(indexRoute)
179 })
180})
181​
182describe('createRouteNodesByFullPath', () => {
183 const createRoute = (
184 overrides: Partial<RouteNode> & { routePath: string },
185 ): RouteNode => ({
186 filePath: 'test.tsx',
187 fullPath: overrides.routePath,
188 variableName: 'Test',
189 _fsRouteType: 'static',
190 cleanedPath: overrides.routePath.endsWith('/')
191 ? '/'
192 : overrides.routePath.split('/').at(-1),
193 ...overrides,
194 })
195​
196 it('prefers concrete routes over pathless layouts for duplicate full paths', () => {
197 const concreteRoute = createRoute({
198 routePath: '/livestock/$farmId/medicine',
199 variableName: 'Concrete',
200 })
201 const pathlessRoute = createRoute({
202 routePath: '/livestock/$farmId/medicine/_form',
203 _fsRouteType: 'pathless_layout',
204 variableName: 'Pathless',
205 })
206​
207 const map = createRouteNodesByFullPath([concreteRoute, pathlessRoute])
208​
209 expect(map.get('/livestock/$farmId/medicine')).toBe(concreteRoute)
210 })
211})
212​
213describe('determineInitialRoutePath', () => {
214 it('removes dots and adds slashes', () => {
215 expect(determineInitialRoutePath('test.test')).toStrictEqual({
216 routePath: '/test/test',
217 originalRoutePath: '/test/test',
218 })
219 })
220​
221 it('keeps leading slash', () => {
222 expect(determineInitialRoutePath('/test.test')).toStrictEqual({
223 routePath: '/test/test',
224 originalRoutePath: '/test/test',
225 })
226 })
227​
228 it('keeps trailing slash', () => {
229 expect(determineInitialRoutePath('test.test/')).toStrictEqual({
230 routePath: '/test/test/',
231 originalRoutePath: '/test/test/',
232 })
233 })
234​
235 it('removes dots and adds slashes with leading and trailing slashes', () => {
236 expect(determineInitialRoutePath('/test.test/')).toStrictEqual({
237 routePath: '/test/test/',
238 originalRoutePath: '/test/test/',
239 })
240 })
241​
242 it("returns '/' if path is empty", () => {
243 expect(determineInitialRoutePath('')).toStrictEqual({
244 routePath: '/',
245 originalRoutePath: '/',
246 })
247 })
248​
249 it("returns '/' if path is '.'", () => {
250 expect(determineInitialRoutePath('.')).toStrictEqual({
251 routePath: '/',
252 originalRoutePath: '/',
253 })
254 })
255​
256 it("returns '/' if path is './'", () => {
257 expect(determineInitialRoutePath('./')).toStrictEqual({
258 routePath: '/',
259 originalRoutePath: '/',
260 })
261 })
262​
263 it('throws on a disallowed escaped character instead of exiting the process', () => {
264 const consoleSpy = vi.spyOn(console, 'error')
265​
266 expect(() => determineInitialRoutePath('/a[/]')).toThrowError(
267 'Disallowed character "/" found in square brackets in route path "/a[/]".\n' +
268 'You cannot use any of the following characters in square brackets: /, \\, ?, #, :, *, <, >, |, !, $, %\n' +
269 'Please remove and/or replace them.',
270 )
271 expect(consoleSpy).not.toHaveBeenCalled()
272 // The next route path is checked from its start
273 expect(() => determineInitialRoutePath('/a-longer-path[%]')).toThrowError(
274 'Disallowed character "%"',
275 )
276 expect(() => determineInitialRoutePath('/b[%]')).toThrowError(
277 'Disallowed character "%"',
278 )
279​
280 consoleSpy.mockRestore()
281 })
282​
283 it('escapes characters correctly', () => {
284 expect(determineInitialRoutePath('/a[.]')).toStrictEqual({
285 routePath: '/a.',
286 originalRoutePath: '/a[.]',
287 })
288 })
289​
290 it('should handle trailing underscores correctly', () => {
291 expect(determineInitialRoutePath('a_')).toStrictEqual({
292 routePath: `/a_`,
293 originalRoutePath: '/a_',
294 })
295​
296 expect(determineInitialRoutePath('a_.route')).toStrictEqual({
297 routePath: `/a_/route`,
298 originalRoutePath: '/a_/route',
299 })
300​
301 expect(determineInitialRoutePath('a_.b.c')).toStrictEqual({
302 routePath: `/a_/b/c`,
303 originalRoutePath: '/a_/b/c',
304 })
305​
306 expect(determineInitialRoutePath('a.b_.c.d')).toStrictEqual({
307 routePath: `/a/b_/c/d`,
308 originalRoutePath: '/a/b_/c/d',
309 })
310​
311 expect(determineInitialRoutePath('a_.route.b')).toStrictEqual({
312 routePath: `/a_/route/b`,
313 originalRoutePath: '/a_/route/b',
314 })
315 })
316})
317​
318describe('determineInitialRoutePathFromExplicitPath', () => {
319 it('preserves dots as literal route path characters', () => {
320 expect(
321 determineInitialRoutePathFromExplicitPath('pathless.layout'),
322 ).toStrictEqual({
323 routePath: '/pathless.layout',
324 originalRoutePath: '/pathless.layout',
325 })
326 })
327​
328 it('resolves bracket escapes without applying file-route separators', () => {
329 expect(
330 determineInitialRoutePathFromExplicitPath('pathless[.]layout'),
331 ).toStrictEqual({
332 routePath: '/pathless.layout',
333 originalRoutePath: '/pathless[.]layout',
334 })
335 })
336})
337​
338describe('multiSortBy', () => {
339 it('sorts by single accessor', () => {
340 const arr = [{ v: 3 }, { v: 1 }, { v: 2 }]
341 const result = multiSortBy(arr, [(d) => d.v])
342 expect(result.map((d) => d.v)).toEqual([1, 2, 3])
343 })
344​
345 it('sorts by multiple accessors', () => {
346 const arr = [
347 { a: 2, b: 1 },
348 { a: 1, b: 2 },
349 { a: 1, b: 1 },
350 ]
351 const result = multiSortBy(arr, [(d) => d.a, (d) => d.b])
352 expect(result).toEqual([
353 { a: 1, b: 1 },
354 { a: 1, b: 2 },
355 { a: 2, b: 1 },
356 ])
357 })
358​
359 it('preserves original order for equal elements', () => {
360 const arr = [
361 { a: 1, id: 'first' },
362 { a: 1, id: 'second' },
363 { a: 1, id: 'third' },
364 ]
365 const result = multiSortBy(arr, [(d) => d.a])
366 expect(result.map((d) => d.id)).toEqual(['first', 'second', 'third'])
367 })
368​
369 it('handles undefined values', () => {
370 const arr = [{ v: 1 }, { v: undefined }, { v: 2 }]
371 const result = multiSortBy(arr, [(d) => d.v])
372 // undefined sorts to end
373 expect(result.map((d) => d.v)).toEqual([1, 2, undefined])
374 })
375​
376 it('handles empty array', () => {
377 const result = multiSortBy([], [(d) => d])
378 expect(result).toEqual([])
379 })
380​
381 it('handles single element array', () => {
382 const result = multiSortBy([{ v: 1 }], [(d) => d.v])
383 expect(result).toEqual([{ v: 1 }])
384 })
385​
386 it('uses default accessor when none provided', () => {
387 const arr = [3, 1, 2]
388 const result = multiSortBy(arr)
389 expect(result).toEqual([1, 2, 3])
390 })
391​
392 it('sorts strings correctly', () => {
393 const arr = [{ s: 'c' }, { s: 'a' }, { s: 'b' }]
394 const result = multiSortBy(arr, [(d) => d.s])
395 expect(result.map((d) => d.s)).toEqual(['a', 'b', 'c'])
396 })
397​
398 it('handles negative numbers in accessors for reverse sort', () => {
399 const arr = [{ v: 1 }, { v: 3 }, { v: 2 }]
400 const result = multiSortBy(arr, [(d) => -d.v])
401 expect(result.map((d) => d.v)).toEqual([3, 2, 1])
402 })
403})
404​
405describe('multiSortBy', () => {
406 it('sorts by multiple criteria', () => {
407 const data = [
408 { routePath: '/test/1/2/index', f: 'b' },
409 { routePath: '/test/1', f: 'b' },
410 { routePath: '/test/1/2/3/4/index', f: 'b' },
411 { routePath: '/test/1/2/3', f: 'b' },
412 { routePath: '/test/1/2/3/index', f: 'b' },
413 { routePath: '/test/1/2', f: 'b' },
414 { routePath: '/test/1/2/3/4', f: 'b' },
415 ]
416​
417 const sorted = multiSortBy(data, [
418 (d) => (d.routePath.includes('1') ? -1 : 1),
419 (d) => d.routePath.split('/').length,
420 (d) => (d.routePath.endsWith('index') ? -1 : 1),
421 (d) => d,
422 ])
423​
424 expect(sorted).toEqual([
425 { routePath: '/test/1', f: 'b' },
426 { routePath: '/test/1/2', f: 'b' },
427 { routePath: '/test/1/2/index', f: 'b' },
428 { routePath: '/test/1/2/3', f: 'b' },
429 { routePath: '/test/1/2/3/index', f: 'b' },
430 { routePath: '/test/1/2/3/4', f: 'b' },
431 { routePath: '/test/1/2/3/4/index', f: 'b' },
432 ])
433 })
434})
435​
436describe('removeExt', () => {
437 it('removes extension', () => {
438 expect(removeExt('test.ts')).toBe('test')
439 })
440​
441 it('does not remove extension if no extension', () => {
442 expect(removeExt('test')).toBe('test')
443 })
444​
445 it('removes extension with multiple dots', () => {
446 expect(removeExt('test.test.ts')).toBe('test.test')
447 })
448​
449 it('removes extension with leading dot', () => {
450 expect(removeExt('.test.ts')).toBe('.test')
451 })
452​
453 it('removes extension when in a route path', () => {
454 expect(removeExt('/test/test.ts')).toBe('/test/test')
455 })
456​
457 it('keeps extension when addExtensions is true', () => {
458 expect(removeExt('test.tsx', true)).toBe('test.tsx')
459 })
460​
461 it('keeps extension with route path when addExtensions is true', () => {
462 expect(removeExt('/routes/__root.tsx', true)).toBe('/routes/__root.tsx')
463 })
464​
465 it('replaces extension when addExtensions is a dot-prefixed string', () => {
466 expect(removeExt('test.tsx', '.js')).toBe('test.js')
467 })
468​
469 it('replaces extension with route path when addExtensions is a string', () => {
470 expect(removeExt('/routes/__root.tsx', '.js')).toBe('/routes/__root.js')
471 })
472​
473 it('replaces extension with multiple dots when addExtensions is a string', () => {
474 expect(removeExt('test.lazy.tsx', '.js')).toBe('test.lazy.js')
475 })
476​
477 it('returns unchanged when no extension and addExtensions is a string', () => {
478 expect(removeExt('test', '.js')).toBe('test')
479 })
480})
481​
482describe('removeUnderscores', () => {
483 it('removes leading underscore', () => {
484 expect(removeUnderscores('_test')).toBe('test')
485 })
486​
487 it('removes trailing underscore', () => {
488 expect(removeUnderscores('test_')).toBe('test')
489 })
490​
491 it('removes leading and trailing underscores', () => {
492 expect(removeUnderscores('_test_')).toBe('test')
493 })
494})
495​
496describe('removeLeadingUnderscores', () => {
497 it('removes leading underscore when not routeToken', () => {
498 expect(removeLeadingUnderscores('_test', 'route')).toBe('test')
499​
500 expect(removeLeadingUnderscores('/_test/abc/route/_d', 'route')).toBe(
501 '/test/abc/route/d',
502 )
503​
504 expect(removeLeadingUnderscores('/_test_/abc/_route_/d_/_e', 'route')).toBe(
505 '/test_/abc/route_/d_/e',
506 )
507​
508 expect(
509 removeLeadingUnderscores('/_test_/abc/_route_/d_/_e', '_route_'),
510 ).toBe('/test_/abc/_route_/d_/e')
511​
512 expect(
513 removeLeadingUnderscores('/_test_/abc/_route_/d_/_e', 'route_'),
514 ).toBe('/test_/abc/route_/d_/e')
515 })
516})
517​
518describe('removeTrailingUnderscores', () => {
519 it('removes trailing underscore when not routeToken', () => {
520 expect(removeTrailingUnderscores('test_', 'route')).toBe('test')
521​
522 expect(removeTrailingUnderscores('/_test_/abc_/route/_d', 'route')).toBe(
523 '/_test/abc/route/_d',
524 )
525​
526 expect(
527 removeTrailingUnderscores('/_test_/abc/_route_/d_/_e', 'route'),
528 ).toBe('/_test/abc/_route/d/_e')
529​
530 expect(
531 removeTrailingUnderscores('/_test_/abc/_route_/d_/_e', '_route_'),
532 ).toBe('/_test/abc/_route_/d/_e')
533​
534 expect(
535 removeTrailingUnderscores('/_test_/abc/_route_/d_/_e', '_route'),
536 ).toBe('/_test/abc/_route/d/_e')
537 })
538})
539​
540describe('hasEscapedLeadingUnderscore', () => {
541 it('returns true for [_] prefix pattern', () => {
542 expect(hasEscapedLeadingUnderscore('[_]layout')).toBe(true)
543 expect(hasEscapedLeadingUnderscore('[_]foo')).toBe(true)
544 expect(hasEscapedLeadingUnderscore('[_]')).toBe(true)
545 })
546​
547 it('returns true for fully escaped segment starting with underscore', () => {
548 expect(hasEscapedLeadingUnderscore('[_layout]')).toBe(true)
549 expect(hasEscapedLeadingUnderscore('[_foo]')).toBe(true)
550 expect(hasEscapedLeadingUnderscore('[__foo]')).toBe(true)
551 expect(hasEscapedLeadingUnderscore('[_1nd3x]')).toBe(true)
552 expect(hasEscapedLeadingUnderscore('[_]')).toBe(true)
553 })
554​
555 it('returns false for non-escaped leading underscore', () => {
556 expect(hasEscapedLeadingUnderscore('_layout')).toBe(false)
557 expect(hasEscapedLeadingUnderscore('_foo')).toBe(false)
558 })
559​
560 it('returns false for segments without leading underscore', () => {
561 expect(hasEscapedLeadingUnderscore('layout')).toBe(false)
562 expect(hasEscapedLeadingUnderscore('[layout]')).toBe(false)
563 expect(hasEscapedLeadingUnderscore('foo[_]')).toBe(false)
564 })
565​
566 it('returns false for partial escapes with nested brackets', () => {
567 expect(hasEscapedLeadingUnderscore('[_foo[bar]')).toBe(false)
568 expect(hasEscapedLeadingUnderscore('[_foo]bar]')).toBe(false)
569 })
570})
571​
572describe('hasEscapedTrailingUnderscore', () => {
573 it('returns true for [_] suffix pattern', () => {
574 expect(hasEscapedTrailingUnderscore('blog[_]')).toBe(true)
575 expect(hasEscapedTrailingUnderscore('foo[_]')).toBe(true)
576 expect(hasEscapedTrailingUnderscore('[_]')).toBe(true)
577 })
578​
579 it('returns true for fully escaped segment ending with underscore', () => {
580 expect(hasEscapedTrailingUnderscore('[blog_]')).toBe(true)
581 expect(hasEscapedTrailingUnderscore('[foo_]')).toBe(true)
582 expect(hasEscapedTrailingUnderscore('[foo__]')).toBe(true)
583 expect(hasEscapedTrailingUnderscore('[_r0ut3_]')).toBe(true)
584 expect(hasEscapedTrailingUnderscore('[_]')).toBe(true)
585 })
586​
587 it('returns false for non-escaped trailing underscore', () => {
588 expect(hasEscapedTrailingUnderscore('blog_')).toBe(false)
589 expect(hasEscapedTrailingUnderscore('foo_')).toBe(false)
590 })
591​
592 it('returns false for segments without trailing underscore', () => {
593 expect(hasEscapedTrailingUnderscore('blog')).toBe(false)
594 expect(hasEscapedTrailingUnderscore('[blog]')).toBe(false)
595 expect(hasEscapedTrailingUnderscore('[_]foo')).toBe(false)
596 })
597​
598 it('returns false for partial escapes with nested brackets', () => {
599 expect(hasEscapedTrailingUnderscore('[foo[bar]_]')).toBe(false)
600 expect(hasEscapedTrailingUnderscore('[foo]bar_]')).toBe(false)
601 })
602})
603​
604describe('isSegmentPathless', () => {
605 it('returns true for non-escaped leading underscore', () => {
606 expect(isSegmentPathless('_layout', '_layout')).toBe(true)
607 expect(isSegmentPathless('_foo', '_foo')).toBe(true)
608 })
609​
610 it('returns false for escaped leading underscore with [_] prefix', () => {
611 expect(isSegmentPathless('_layout', '[_]layout')).toBe(false)
612 expect(isSegmentPathless('_foo', '[_]foo')).toBe(false)
613 })
614​
615 it('returns false for fully escaped segment', () => {
616 expect(isSegmentPathless('_layout', '[_layout]')).toBe(false)
617 expect(isSegmentPathless('__layout', '[__layout]')).toBe(false)
618 expect(isSegmentPathless('_1nd3x', '[_1nd3x]')).toBe(false)
619 })
620​
621 it('returns false for segments not starting with underscore', () => {
622 expect(isSegmentPathless('layout', 'layout')).toBe(false)
623 expect(isSegmentPathless('foo', '[foo]')).toBe(false)
624 })
625})
626​
627describe('removeUnderscoresWithEscape', () => {
628 it('removes non-escaped leading underscores', () => {
629 expect(removeUnderscoresWithEscape('/_layout', '/_layout')).toBe('/layout')
630 expect(removeUnderscoresWithEscape('/_foo/_bar', '/_foo/_bar')).toBe(
631 '/foo/bar',
632 )
633 })
634​
635 it('removes non-escaped trailing underscores', () => {
636 expect(removeUnderscoresWithEscape('/blog_', '/blog_')).toBe('/blog')
637 expect(removeUnderscoresWithEscape('/foo_/bar_', '/foo_/bar_')).toBe(
638 '/foo/bar',
639 )
640 })
641​
642 it('preserves escaped leading underscores with [_] prefix', () => {
643 expect(removeUnderscoresWithEscape('/_layout', '/[_]layout')).toBe(
644 '/_layout',
645 )
646 expect(removeUnderscoresWithEscape('/_foo', '/[_]foo')).toBe('/_foo')
647 })
648​
649 it('preserves escaped trailing underscores with [_] suffix', () => {
650 expect(removeUnderscoresWithEscape('/blog_', '/blog[_]')).toBe('/blog_')
651 expect(removeUnderscoresWithEscape('/foo_', '/foo[_]')).toBe('/foo_')
652 })
653​
654 it('preserves fully escaped segments with underscores', () => {
655 expect(removeUnderscoresWithEscape('/_layout', '/[_layout]')).toBe(
656 '/_layout',
657 )
658 expect(removeUnderscoresWithEscape('/_r0ut3_', '/[_r0ut3_]')).toBe(
659 '/_r0ut3_',
660 )
661 })
662​
663 it('handles mixed escaped and non-escaped underscores', () => {
664 expect(
665 removeUnderscoresWithEscape('/_foo/_bar_/baz_', '/_foo/[_]bar_/baz[_]'),
666 ).toBe('/foo/_bar/baz_')
667 })
668​
669 it('falls back to removeUnderscores when no originalPath', () => {
670 expect(removeUnderscoresWithEscape('/_foo_')).toBe('/foo')
671 expect(removeUnderscoresWithEscape('/_foo_', undefined)).toBe('/foo')
672 })
673​
674 it('returns empty string for empty/undefined routePath', () => {
675 expect(removeUnderscoresWithEscape(undefined)).toBe('')
676 expect(removeUnderscoresWithEscape('')).toBe('')
677 })
678})
679​
680describe('removeLayoutSegmentsWithEscape', () => {
681 it('removes non-escaped layout segments', () => {
682 expect(removeLayoutSegmentsWithEscape('/_layout/foo', '/_layout/foo')).toBe(
683 '/foo',
684 )
685 expect(
686 removeLayoutSegmentsWithEscape(
687 '/_auth/_admin/dashboard',
688 '/_auth/_admin/dashboard',
689 ),
690 ).toBe('/dashboard')
691 })
692​
693 it('preserves escaped layout segments with [_] prefix', () => {
694 expect(
695 removeLayoutSegmentsWithEscape('/_layout/foo', '/[_]layout/foo'),
696 ).toBe('/_layout/foo')
697 expect(
698 removeLayoutSegmentsWithEscape('/_auth/dashboard', '/[_]auth/dashboard'),
699 ).toBe('/_auth/dashboard')
700 })
701​
702 it('preserves fully escaped segments starting with underscore', () => {
703 expect(
704 removeLayoutSegmentsWithEscape('/_layout/foo', '/[_layout]/foo'),
705 ).toBe('/_layout/foo')
706 expect(removeLayoutSegmentsWithEscape('/_1nd3x/bar', '/[_1nd3x]/bar')).toBe(
707 '/_1nd3x/bar',
708 )
709 })
710​
711 it('handles mixed escaped and non-escaped layout segments', () => {
712 expect(
713 removeLayoutSegmentsWithEscape(
714 '/_auth/_admin/dashboard',
715 '/[_]auth/_admin/dashboard',
716 ),
717 ).toBe('/_auth/dashboard')
718 expect(
719 removeLayoutSegmentsWithEscape('/_foo/_bar/_baz', '/_foo/[_bar]/_baz'),
720 ).toBe('/_bar')
721 })
722​
723 it('falls back to removeLayoutSegments when no originalPath', () => {
724 expect(removeLayoutSegmentsWithEscape('/_foo/bar/_baz')).toBe('/bar')
725 expect(removeLayoutSegmentsWithEscape('/_foo/bar/_baz', undefined)).toBe(
726 '/bar',
727 )
728 })
729​
730 it('handles root path', () => {
731 expect(removeLayoutSegmentsWithEscape('/')).toBe('/')
732 expect(removeLayoutSegmentsWithEscape()).toBe('/')
733 })
734})
735​
736describe('removeLayoutSegmentsAndUnderscoresWithEscape', () => {
737 it('removes layout segments and preserves escaped underscores in remaining segments', () => {
738 expect(
739 removeLayoutSegmentsAndUnderscoresWithEscape(
740 '/_layout/_foo',
741 '/_layout/[_]foo',
742 ),
743 ).toBe('/_foo')
744 })
745​
746 it('removes multiple layout segments before escaped underscores', () => {
747 expect(
748 removeLayoutSegmentsAndUnderscoresWithEscape(
749 '/_layout/_nested/_foo',
750 '/_layout/_nested/[_]foo',
751 ),
752 ).toBe('/_foo')
753 })
754​
755 it('preserves multiple escaped leading underscores in remaining segments', () => {
756 expect(
757 removeLayoutSegmentsAndUnderscoresWithEscape(
758 '/_layout/__foo',
759 '/_layout/[__foo]',
760 ),
761 ).toBe('/__foo')
762​
763 expect(
764 removeLayoutSegmentsAndUnderscoresWithEscape(
765 '/_layout/__foo',
766 '/_layout/[_][_]foo',
767 ),
768 ).toBe('/__foo')
769 })
770​
771 it('removes non-escaped underscores from remaining segments', () => {
772 expect(
773 removeLayoutSegmentsAndUnderscoresWithEscape(
774 '/_layout/foo_/bar_',
775 '/_layout/foo_/bar_',
776 ),
777 ).toBe('/foo/bar')
778 })
779​
780 it('preserves escaped trailing underscores after removing pathless ancestors', () => {
781 expect(
782 removeLayoutSegmentsAndUnderscoresWithEscape(
783 '/_layout/foo_/',
784 '/_layout/foo[_]/',
785 ),
786 ).toBe('/foo_/')
787 })
788​
789 it('preserves mixed escaped leading and trailing underscores after removing pathless ancestors', () => {
790 expect(
791 removeLayoutSegmentsAndUnderscoresWithEscape(
792 '/_layout/_foo_/',
793 '/_layout/[_]foo[_]/',
794 ),
795 ).toBe('/_foo_/')
796 })
797})
798​
799describe('routePathToVariable', () => {
800 it.each([
801 ['/test/$/index', 'TestSplatIndex'],
802 ['/test/$', 'TestSplat'],
803 ['/test/$/', 'TestSplat'],
804 ['/test/index', 'TestIndex'],
805 ['/test', 'Test'],
806 ['/test/', 'Test'],
807 ['/r0ut3', 'R0ut3'],
808 ])(`converts "%s" to "%s"`, (routePath, expected) => {
809 expect(routePathToVariable(routePath)).toBe(expected)
810 })
811})
812​
813describe('mergeImportDeclarations', () => {
814 it('merges imports with the same source but different specifiers', () => {
815 const imports: Array<ImportDeclaration> = [
816 { source: 'moduleA', specifiers: [{ imported: 'A' }] },
817 { source: 'moduleA', specifiers: [{ imported: 'B' }] },
818 ]
819​
820 const result = mergeImportDeclarations(imports)
821​
822 expect(result).toEqual([
823 {
824 source: 'moduleA',
825 specifiers: [{ imported: 'A' }, { imported: 'B' }],
826 },
827 ])
828 })
829​
830 it('merges imports with overlapping specifiers', () => {
831 const imports: Array<ImportDeclaration> = [
832 { source: 'moduleA', specifiers: [{ imported: 'A' }] },
833 { source: 'moduleA', specifiers: [{ imported: 'A' }, { imported: 'B' }] },
834 ]
835​
836 const result = mergeImportDeclarations(imports)
837​
838 expect(result).toEqual([
839 {
840 source: 'moduleA',
841 specifiers: [{ imported: 'A' }, { imported: 'B' }],
842 },
843 ])
844 })
845​
846 it('does not merge imports with mixed import kinds for the same source', () => {
847 const imports: Array<ImportDeclaration> = [
848 {
849 source: 'moduleA',
850 importKind: 'type',
851 specifiers: [{ imported: 'A' }],
852 },
853 { source: 'moduleA', specifiers: [{ imported: 'B' }] },
854 ]
855​
856 const result = mergeImportDeclarations(imports)
857​
858 expect(result).toEqual([
859 {
860 source: 'moduleA',
861 importKind: 'type',
862 specifiers: [{ imported: 'A' }],
863 },
864 { source: 'moduleA', specifiers: [{ imported: 'B' }] },
865 ])
866 })
867​
868 it('removes duplicate specifiers', () => {
869 const imports: Array<ImportDeclaration> = [
870 { source: 'moduleA', specifiers: [{ imported: 'A' }] },
871 { source: 'moduleA', specifiers: [{ imported: 'A' }] },
872 ]
873​
874 const result = mergeImportDeclarations(imports)
875​
876 expect(result).toEqual([
877 {
878 source: 'moduleA',
879 specifiers: [{ imported: 'A' }],
880 },
881 ])
882 })
883})
884​
885describe('RoutePrefixMap', () => {
886 const createRoute = (
887 overrides: Partial<RouteNode> & { routePath: string },
888 ): RouteNode => ({
889 filePath: 'test.tsx',
890 fullPath: overrides.routePath,
891 variableName: 'Test',
892 _fsRouteType: 'static',
893 ...overrides,
894 })
895​
896 describe('constructor', () => {
897 it('indexes routes by path', () => {
898 const routes = [
899 createRoute({ routePath: '/users' }),
900 createRoute({ routePath: '/users/profile' }),
901 ]
902 const map = new RoutePrefixMap(routes)
903​
904 expect(map.has('/users')).toBe(true)
905 expect(map.has('/users/profile')).toBe(true)
906 expect(map.has('/posts')).toBe(false)
907 })
908​
909 it('skips root path /__root', () => {
910 const routes = [createRoute({ routePath: '/__root' })]
911 const map = new RoutePrefixMap(routes)
912​
913 expect(map.has('/__root')).toBe(false)
914 })
915​
916 it('skips empty/undefined routePaths', () => {
917 const routes = [createRoute({ routePath: '' })]
918 const map = new RoutePrefixMap(routes)
919​
920 expect(map.has('')).toBe(false)
921 })
922​
923 it('tracks layout routes separately', () => {
924 const routes = [
925 createRoute({ routePath: '/app', _fsRouteType: 'layout' }),
926 createRoute({ routePath: '/admin', _fsRouteType: 'pathless_layout' }),
927 createRoute({ routePath: '/users', _fsRouteType: 'static' }),
928 ]
929 const map = new RoutePrefixMap(routes)
930​
931 // all indexed
932 expect(map.has('/app')).toBe(true)
933 expect(map.has('/admin')).toBe(true)
934 expect(map.has('/users')).toBe(true)
935 })
936 })
937​
938 describe('get', () => {
939 it('returns route by exact path', () => {
940 const route = createRoute({ routePath: '/users' })
941 const map = new RoutePrefixMap([route])
942​
943 expect(map.get('/users')).toBe(route)
944 expect(map.get('/other')).toBeUndefined()
945 })
946 })
947​
948 describe('findParent', () => {
949 it('returns null for root path', () => {
950 const map = new RoutePrefixMap([])
951​
952 expect(map.findParent('/')).toBeNull()
953 })
954​
955 it('returns null for empty path', () => {
956 const map = new RoutePrefixMap([])
957​
958 expect(map.findParent('')).toBeNull()
959 })
960​
961 it('finds immediate parent', () => {
962 const parent = createRoute({ routePath: '/users' })
963 const map = new RoutePrefixMap([parent])
964​
965 expect(map.findParent('/users/profile')).toBe(parent)
966 })
967​
968 it('finds ancestor when immediate parent missing', () => {
969 const grandparent = createRoute({ routePath: '/users' })
970 const map = new RoutePrefixMap([grandparent])
971​
972 expect(map.findParent('/users/settings/profile')).toBe(grandparent)
973 })
974​
975 it('finds closest ancestor with multiple levels', () => {
976 const grandparent = createRoute({ routePath: '/users' })
977 const parent = createRoute({ routePath: '/users/settings' })
978 const map = new RoutePrefixMap([grandparent, parent])
979​
980 expect(map.findParent('/users/settings/profile')).toBe(parent)
981 })
982​
983 it('returns null when no parent exists', () => {
984 const map = new RoutePrefixMap([createRoute({ routePath: '/posts' })])
985​
986 expect(map.findParent('/users/profile')).toBeNull()
987 })
988​
989 it('does not return self as parent', () => {
990 const route = createRoute({ routePath: '/users' })
991 const map = new RoutePrefixMap([route])
992​
993 expect(map.findParent('/users')).toBeNull()
994 })
995 })
996})
997​
998describe('sortRouteNodes', () => {
999 const indexTokenSegmentRegex = createTokenRegex('index', { type: 'segment' })
1000​
1001 const node = (routePath: string): RouteNode =>
1002 ({ routePath }) as unknown as RouteNode
1003​
1004 const sortPaths = (routePaths: Array<string>): Array<string | undefined> =>
1005 sortRouteNodes(routePaths.map(node), indexTokenSegmentRegex).map(
1006 (n) => n.routePath,
1008​
1009 /** Every distinct ordering of `arr` (Heap-free recursive permutation). */
1010 function permutations<T>(arr: Array<T>): Array<Array<T>> {
1011 if (arr.length <= 1) {
1012 return [arr]
1014 const result: Array<Array<T>> = []
1015 arr.forEach((item, i) => {
1016 const rest = [...arr.slice(0, i), ...arr.slice(i + 1)]
1017 for (const perm of permutations(rest)) {
1018 result.push([item, ...perm])
1020 })
1021 return result
1023​
1024 it('orders tied siblings by routePath', () => {
1025 // Same segment count, both non-index: they tie on every key before routePath.
1026 const expected = ['/account/beta-features', '/account/busy-guard']
1027 expect(
1028 sortPaths(['/account/busy-guard', '/account/beta-features']),
1029 ).toEqual(expected)
1030 expect(
1031 sortPaths(['/account/beta-features', '/account/busy-guard']),
1032 ).toEqual(expected)
1033 })
1034​
1035 it('applies root, segment-count and index precedence before the routePath tiebreaker', () => {
1036 const sorted = sortPaths([
1037 '/posts',
1038 '/account/busy-guard',
1039 '/index',
1040 '/__root',
1041 '/account/beta-features',
1042 '/about',
1043 '/posts/index',
1044 ])
1045​
1046 expect(sorted).toEqual([
1047 '/__root', // root always first
1048 '/index', // depth 1, index segment before non-index
1049 '/about', // depth 1, non-index, routePath tiebreak
1050 '/posts', // depth 1, non-index, routePath tiebreak
1051 '/posts/index', // depth 2, index segment before non-index
1052 '/account/beta-features', // depth 2, non-index, routePath tiebreak
1053 '/account/busy-guard', // depth 2, non-index, routePath tiebreak
1054 ])
1055 })
1056​
1057 it('is deterministic for every input permutation (stable sort)', () => {
1058 // Includes several sets that tie on all keys before routePath (the two
1059 // `/account/*` leaves, `/about` vs `/posts`) β€” exactly the case that the
1060 // former whole-object tiebreaker left in an engine- and input-order-
1061 // dependent order. `sortRouteNodes` must map every permutation to the
1062 // same output.
1063 const routePaths = [
1064 '/__root',
1065 '/index',
1066 '/about',
1067 '/posts',
1068 '/account/beta-features',
1069 '/account/busy-guard',
1071​
1072 const reference = sortPaths(routePaths)
1073​
1074 for (const permutation of permutations(routePaths)) {
1075 expect(sortPaths(permutation)).toEqual(reference)
1077 })