Unverified Commit f464e32e authored by James Argarin's avatar James Argarin Committed by GitHub

fix(typegen): merge cacheLife types into next/cache instead of shadowing it (#98252)

parent 64596d1f
......@@ -20,6 +20,8 @@ import { cacheTag } from 'next/dist/server/use-cache/cache-tag'
export { cacheTag }
export interface CacheLifeProfiles {}
/**
* Cache this `"use cache"` for a timespan defined by the `"default"` profile.
* ```
......@@ -128,7 +130,9 @@ export function cacheLife(profile: 'max'): void
*
* You can define custom profiles in `next.config.ts`.
*/
export function cacheLife(profile: string): void
export function cacheLife(
profile: keyof CacheLifeProfiles extends never ? string : never
): void
/**
* Cache this `"use cache"` using a custom timespan.
......
......@@ -71,6 +71,7 @@ function formatTimespanWithSeconds(seconds: undefined | number): string {
export function generateCacheLifeTypes(cacheLife: {
[profile: string]: CacheLife
}): string {
let profileKeys = ''
let overloads = ''
const profileNames = Object.keys(cacheLife)
......@@ -81,6 +82,9 @@ export function generateCacheLifeTypes(cacheLife: {
continue
}
profileKeys += `
${JSON.stringify(profileName)}: true`
let description = ''
if (profile.stale === undefined) {
......@@ -136,58 +140,21 @@ export function generateCacheLifeTypes(cacheLife: {
`
}
overloads += `
/**
* Cache this \`"use cache"\` using a custom timespan.
* \`\`\`
* stale: ... // seconds
* revalidate: ... // seconds
* expire: ... // seconds
* \`\`\`
*
* This is similar to Cache-Control: max-age=\`stale\`,s-max-age=\`revalidate\`,stale-while-revalidate=\`expire-revalidate\`
*
* If a value is left out, the lowest of other cacheLife() calls or the default, is used instead.
*/
export function cacheLife(profile: {
/**
* This cache may be stale on clients for ... seconds before checking with the server.
*/
stale?: number,
/**
* If the server receives a new request after ... seconds, start revalidating new values in the background.
*/
revalidate?: number,
/**
* If this entry has no traffic for ... seconds it will expire. The next request will recompute it.
*/
expire?: number
}): void
`
// Redefine the cacheLife() accepted arguments.
// The top-level `export {}` makes this file a module, which in turn makes
// the block below a module augmentation that merges into the `next/cache`
// types. Without it the file is a script, the block is a standalone ambient
// module declaration, and it shadows `next/cache` instead of merging: every
// other export then has to be redeclared here, and TypeScript offers two
// identical auto-import completions for each of them, one from this file and
// one from the package's own types.
return `// Type definitions for Next.js cacheLife configs
declare module 'next/cache' {
export { unstable_cache } from 'next/dist/server/web/spec-extension/unstable-cache'
export {
updateTag,
revalidateTag,
revalidatePath,
refresh,
} from 'next/dist/server/web/spec-extension/revalidate'
export { unstable_noStore } from 'next/dist/server/web/spec-extension/unstable-no-store'
export { io } from 'next/dist/server/request/io'
export { unstable_navigation } from 'next/dist/server/request/cache-stages'
export { unstable_prefetch } from 'next/dist/server/request/cache-stages'
export {}
declare module 'next/cache' {
export interface CacheLifeProfiles {${profileKeys}
}
${overloads}
import { cacheTag } from 'next/dist/server/use-cache/cache-tag'
export { cacheTag }
export const unstable_cacheTag: typeof cacheTag
export const unstable_cacheLife: typeof cacheLife
}
`
}
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import execa from 'execa'
describe('cache-life-typecheck', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('accepts configured cacheLife profiles and rejects unknown ones', async () => {
const $ = await next.render$('/')
expect($('p').text()).toBe('hello world')
await retry(async () => {
await next.readFile(`${next.distDir}/types/cache-life.d.ts`)
}, 10_000)
await next.stop()
try {
const { stdout, stderr } = await execa('pnpm', ['tsc', '--noEmit'], {
cwd: next.testDir,
reject: false,
})
expect({ stdout, stderr }).toEqual({ stdout: '', stderr: '' })
} finally {
await next.start()
}
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheLife: {
blog: {
stale: 300,
revalidate: 900,
expire: 3600,
},
},
}
module.exports = nextConfig
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"incremental": true,
"module": "esnext",
"esModuleInterop": true,
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"plugins": [{ "name": "next" }]
},
"include": ["next-env.d.ts", "**/*.mts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
import { cacheLife, unstable_cacheLife } from 'next/cache'
export function validate() {
cacheLife('blog')
cacheLife('minutes')
cacheLife({ stale: 30, revalidate: 60, expire: 120 })
unstable_cacheLife('blog')
// @ts-expect-error unknown profile
cacheLife('bogus')
// @ts-expect-error unknown profile
unstable_cacheLife('bogus')
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment