Skip to content

Commit dec27c2

Browse files
committed
fix(router-core): disambiguate symbol paths, add caller-level tests
A symbol rendered as `["Symbol(a)"]`, the same as the string key `'Symbol(a)'`, which is the ambiguity this formatter is supposed to remove. Symbols now render unquoted, `[Symbol(a)]`, and a per-call namer gives a second distinct symbol sharing a description a counter. The formatter tests ran in isolation, so a call site going back to JSON.stringify would still have passed. Added tests through router search validation whose issues carry a bigint: they fail with "Do not know how to serialize a BigInt" against the old code.
1 parent 2d9633c commit dec27c2

3 files changed

Lines changed: 150 additions & 14 deletions

File tree

‎packages/router-core/src/standardSchemaIssues.ts‎

Lines changed: 47 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -37,37 +37,71 @@ function readSegmentKey(segment: unknown): IssuePathKey | undefined {
3737
return undefined
3838
}
3939

40+
/**
41+
* Names symbols for one formatting call. Two symbols can share a description,
42+
* so the first of a description renders as `Symbol(a)` and any later, distinct
43+
* symbol with that same description gets a counter, `Symbol(a)#2`. Identity is
44+
* remembered, so the same symbol always renders the same way within the call.
45+
*/
46+
function createSymbolNamer(): (key: symbol) => string {
47+
const rendered = new Map<symbol, string>()
48+
const countsByDescription = new Map<string, number>()
49+
return (key) => {
50+
const cached = rendered.get(key)
51+
if (cached !== undefined) return cached
52+
const description = key.toString()
53+
const seen = countsByDescription.get(description) ?? 0
54+
countsByDescription.set(description, seen + 1)
55+
const name = seen === 0 ? description : `${description}#${seen + 1}`
56+
rendered.set(key, name)
57+
return name
58+
}
59+
}
60+
4061
/**
4162
* Renders one key. Bracket-quoting anything that is not a plain identifier is
4263
* what keeps paths unambiguous: the two-key path `['a', 'b']` renders `a.b`,
4364
* while the single key `'a.b'` renders `["a.b"]`, so they can never collide.
4465
* A numeric key renders as an index, and the string `'0'` renders as `["0"]`,
45-
* keeping those distinct too.
66+
* keeping those distinct too. A symbol renders unquoted, `[Symbol(a)]`, so it
67+
* cannot be confused with the string key `'Symbol(a)'`, which stays quoted.
4668
*/
47-
function renderKey(key: IssuePathKey, isFirst: boolean): string {
69+
function renderKey(
70+
key: IssuePathKey,
71+
isFirst: boolean,
72+
nameSymbol: (key: symbol) => string,
73+
): string {
4874
if (typeof key === 'number') {
4975
return `[${key}]`
5076
}
51-
const text = typeof key === 'symbol' ? key.toString() : key
52-
if (typeof key === 'string' && SAFE_KEY_RE.test(key)) {
53-
return isFirst ? text : `.${text}`
77+
if (typeof key === 'symbol') {
78+
return `[${nameSymbol(key)}]`
79+
}
80+
if (SAFE_KEY_RE.test(key)) {
81+
return isFirst ? key : `.${key}`
5482
}
55-
return `[${JSON.stringify(text)}]`
83+
return `[${JSON.stringify(key)}]`
5684
}
5785

58-
function formatIssuePath(path: ReadonlyArray<unknown>): string {
86+
function formatIssuePath(
87+
path: ReadonlyArray<unknown>,
88+
nameSymbol: (key: symbol) => string,
89+
): string {
5990
let rendered = ''
6091
let isFirst = true
6192
for (const segment of path) {
6293
const key = readSegmentKey(segment)
6394
if (key === undefined) continue
64-
rendered += renderKey(key, isFirst)
95+
rendered += renderKey(key, isFirst, nameSymbol)
6596
isFirst = false
6697
}
6798
return rendered
6899
}
69100

70-
function formatIssue(issue: unknown): string {
101+
function formatIssue(
102+
issue: unknown,
103+
nameSymbol: (key: symbol) => string,
104+
): string {
71105
let message = ''
72106
try {
73107
const raw = (issue as { message?: unknown } | null | undefined)?.message
@@ -80,7 +114,8 @@ function formatIssue(issue: unknown): string {
80114
let path = ''
81115
try {
82116
const raw = (issue as { path?: unknown } | null | undefined)?.path
83-
if (Array.isArray(raw) && raw.length > 0) path = formatIssuePath(raw)
117+
if (Array.isArray(raw) && raw.length > 0)
118+
path = formatIssuePath(raw, nameSymbol)
84119
} catch {
85120
// an unreadable path is reported as a root issue
86121
}
@@ -101,9 +136,10 @@ export function formatStandardSchemaIssues(
101136
issues: ReadonlyArray<AnyStandardSchemaValidateIssue> | undefined,
102137
): string {
103138
if (!issues || issues.length === 0) return 'Validation failed'
139+
const nameSymbol = createSymbolNamer()
104140
const lines: Array<string> = []
105141
for (const issue of issues) {
106-
lines.push(formatIssue(issue))
142+
lines.push(formatIssue(issue, nameSymbol))
107143
}
108144
return lines.join('\n')
109145
}

‎packages/router-core/tests/standardSchemaIssues.test.ts‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,11 +71,35 @@ describe('formatStandardSchemaIssues', () => {
7171
).toBe('__proto__.constructor: x')
7272
})
7373

74-
it('renders a symbol key', () => {
74+
it('renders a symbol key unquoted', () => {
7575
const key = Symbol('secret')
76+
expect(formatStandardSchemaIssues([{ message: 'x', path: [key] }])).toBe(
77+
'[Symbol(secret)]: x',
78+
)
79+
})
80+
81+
it('does not let a symbol collide with a string of the same text', () => {
82+
const asSymbol = formatStandardSchemaIssues([
83+
{ message: 'x', path: [Symbol('secret')] },
84+
])
85+
const asString = formatStandardSchemaIssues([
86+
{ message: 'x', path: ['Symbol(secret)'] },
87+
])
88+
expect(asSymbol).toBe('[Symbol(secret)]: x')
89+
expect(asString).toBe('["Symbol(secret)"]: x')
90+
expect(asSymbol).not.toBe(asString)
91+
})
92+
93+
it('distinguishes two symbols that share a description', () => {
94+
const first = Symbol('dup')
95+
const second = Symbol('dup')
7696
expect(
77-
formatStandardSchemaIssues([{ message: 'x', path: [key] }]),
78-
).toBe('["Symbol(secret)"]: x')
97+
formatStandardSchemaIssues([
98+
{ message: 'a', path: [first] },
99+
{ message: 'b', path: [second] },
100+
{ message: 'c', path: [first] },
101+
]),
102+
).toBe('[Symbol(dup)]: a\n[Symbol(dup)#2]: b\n[Symbol(dup)]: c')
79103
})
80104

81105
it('joins several issues one per line', () => {
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import { expect, test } from 'vitest'
2+
import { createMemoryHistory } from '@tanstack/history'
3+
import { BaseRootRoute, BaseRoute } from '../src'
4+
import { createTestRouter } from './routerTestUtils'
5+
6+
/**
7+
* A Standard Schema validator whose issue carries a bigint. `JSON.stringify`
8+
* throws on one, so this is what catches a call site going back to serializing
9+
* the issues raw: the failure would surface as a complaint about serializing a
10+
* BigInt rather than the validation message.
11+
*/
12+
function failingValidator(issues: Array<Record<string, unknown>>) {
13+
return {
14+
'~standard': {
15+
validate: () => ({ issues }),
16+
},
17+
}
18+
}
19+
20+
function buildRouter(validateSearch: unknown, initialEntry: string) {
21+
const rootRoute = new BaseRootRoute({})
22+
const indexRoute = new BaseRoute({
23+
getParentRoute: () => rootRoute,
24+
path: '/',
25+
})
26+
const dashboardRoute = new BaseRoute({
27+
getParentRoute: () => rootRoute,
28+
path: '/dashboard',
29+
validateSearch: validateSearch as any,
30+
})
31+
const history = createMemoryHistory({ initialEntries: [initialEntry] })
32+
const router = createTestRouter({
33+
routeTree: rootRoute.addChildren([indexRoute, dashboardRoute]),
34+
history,
35+
})
36+
return { router, dashboardRoute }
37+
}
38+
39+
test('search validation reports the issue rather than failing to serialize it', async () => {
40+
const { router, dashboardRoute } = buildRouter(
41+
failingValidator([
42+
{ message: 'Expected number', path: ['page'], received: 1n },
43+
]),
44+
'/dashboard?page=abc',
45+
)
46+
47+
await router.load()
48+
49+
const match = router.state.matches.find(
50+
(m) => m.routeId === dashboardRoute.id,
51+
)
52+
const error = match?.searchError as Error | undefined
53+
expect(error).toBeInstanceOf(Error)
54+
expect(error?.message).toBe('page: Expected number')
55+
expect(error?.message).not.toMatch(/BigInt|serialize/i)
56+
})
57+
58+
test('search validation reports every issue with its path', async () => {
59+
const { router, dashboardRoute } = buildRouter(
60+
failingValidator([
61+
{ message: 'Required', path: ['page'] },
62+
{ message: 'Too long', path: ['filters', 0, 'name'] },
63+
{ message: 'Invalid input' },
64+
]),
65+
'/dashboard',
66+
)
67+
68+
await router.load()
69+
70+
const match = router.state.matches.find(
71+
(m) => m.routeId === dashboardRoute.id,
72+
)
73+
expect((match?.searchError as Error | undefined)?.message).toBe(
74+
'page: Required\nfilters[0].name: Too long\nInvalid input',
75+
)
76+
})

0 commit comments

Comments
 (0)