Skip to content

fix(router-core, start-client-core): Additional types to help with types in head and warning in dev if unexpected keys provided. #4241

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/router-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,12 @@ export { encode, decode } from './qss'
export { rootRouteId } from './root'
export type { RootRouteId } from './root'

export { BaseRoute, BaseRouteApi, BaseRootRoute } from './route'
export {
BaseRoute,
BaseRouteApi,
BaseRootRoute,
routeOptionsHeadUnexpectedKeysWarning,
} from './route'
export type {
AnyPathParams,
SearchSchemaInput,
Expand Down
46 changes: 41 additions & 5 deletions packages/router-core/src/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1114,10 +1114,12 @@ export interface UpdatableRouteOptions<
TBeforeLoadFn,
TLoaderDeps
>,
) => {
links?: AnyRouteMatch['links']
scripts?: AnyRouteMatch['headScripts']
meta?: AnyRouteMatch['meta']
) => HeadResult & {
// prevent likely typos or accidental overrides since not able to force the shape of the return type using TypeScript
script?: never
link?: never
metas?: never
styles?: never
}
scripts?: (
ctx: AssetFnContextOptions<
Expand Down Expand Up @@ -1673,4 +1675,38 @@ export class BaseRootRoute<
}
}

//
/**
* Warns if the result of a route head option is not a valid RouteHeadOptionResult
* @param result The result of a route head option
* @returns void
*/
export function routeOptionsHeadUnexpectedKeysWarning(result: unknown): void {
if (process.env.NODE_ENV === 'development') {
const keys = Object.keys(result as HeadResult)
const unexpectedKeys = keys.filter(
(key) => !headExpectedKeys.includes(key as HeadExpectedKey),
)

if (unexpectedKeys.length === 0) {
return
}

console.warn(
`Route head option result has unexpected keys: "${unexpectedKeys.join('", "')}".`,
'Only "links", "scripts", and "meta" are allowed',
)
}
}

type HeadExpectedKey = keyof Required<HeadResult>
const headExpectedKeys = [
'links',
'scripts',
'meta',
] satisfies Array<HeadExpectedKey>

type HeadResult = {
links?: AnyRouteMatch['links']
scripts?: AnyRouteMatch['headScripts']
meta?: AnyRouteMatch['meta']
}
3 changes: 3 additions & 0 deletions packages/router-core/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
} from './path'
import { isNotFound } from './not-found'
import { setupScrollRestoration } from './scroll-restoration'
import { routeOptionsHeadUnexpectedKeysWarning } from './route'
import { defaultParseSearch, defaultStringifySearch } from './searchParams'
import { rootRouteId } from './root'
import { isRedirect, isResolvedRedirect } from './redirect'
Expand Down Expand Up @@ -2602,6 +2603,8 @@ export class RouterCore<
loaderData: match.loaderData,
}
const headFnContent = route.options.head?.(assetContext)
routeOptionsHeadUnexpectedKeysWarning(headFnContent)

const meta = headFnContent?.meta
const links = headFnContent?.links
const headScripts = headFnContent?.scripts
Expand Down
82 changes: 82 additions & 0 deletions packages/router-core/tests/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { routeOptionsHeadUnexpectedKeysWarning } from '../src/route'

describe('routeOptionsHeadUnexpectedKeysWarning', () => {
const originalEnv = process.env.NODE_ENV
const originalWarn = console.warn

beforeEach(() => {
console.warn = vi.fn()
})

afterEach(() => {
console.warn = originalWarn
process.env.NODE_ENV = originalEnv
})

it('should not warn when all keys are valid', () => {
process.env.NODE_ENV = 'development'
const validResult = {
links: [],
scripts: [],
meta: [],
}

routeOptionsHeadUnexpectedKeysWarning(validResult)
expect(console.warn).not.toHaveBeenCalled()
})

it('should warn when there are unexpected keys', () => {
process.env.NODE_ENV = 'development'
const invalidResult = {
links: [],
scripts: [],
meta: [],
unexpectedKey: 'value',
}

routeOptionsHeadUnexpectedKeysWarning(invalidResult)
expect(console.warn).toHaveBeenCalledWith(
'Route head option result has unexpected keys: "unexpectedKey".',
'Only "links", "scripts", and "meta" are allowed',
)
})

it('should not warn in production environment', () => {
process.env.NODE_ENV = 'production'
const invalidResult = {
links: [],
scripts: [],
meta: [],
unexpectedKey: 'value',
}

routeOptionsHeadUnexpectedKeysWarning(invalidResult)
expect(console.warn).not.toHaveBeenCalled()
})

it('should not warn when missing expected keys', () => {
process.env.NODE_ENV = 'development'
const partialResult = {
links: [],
// missing scripts and meta
}

routeOptionsHeadUnexpectedKeysWarning(partialResult)
expect(console.warn).not.toHaveBeenCalled()
})

it('should warn when all keys are unexpected', () => {
process.env.NODE_ENV = 'development'
const allInvalidResult = {
invalidKey1: 'value1',
invalidKey2: 'value2',
} as any

routeOptionsHeadUnexpectedKeysWarning(allInvalidResult)
expect(console.warn).toHaveBeenCalledWith(
'Route head option result has unexpected keys: "invalidKey1", "invalidKey2".',
'Only "links", "scripts", and "meta" are allowed',
)
})
})
2 changes: 2 additions & 0 deletions packages/start-client-core/src/ssr-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
MakeRouteMatch,
Manifest,
RouteContextOptions,
routeOptionsHeadUnexpectedKeysWarning,
} from '@tanstack/router-core'

declare global {
Expand Down Expand Up @@ -215,6 +216,7 @@ export function hydrate(router: AnyRouter) {
loaderData: match.loaderData,
}
const headFnContent = route.options.head?.(assetContext)
routeOptionsHeadUnexpectedKeysWarning(headFnContent)

const scripts = route.options.scripts?.(assetContext)

Expand Down
Loading