Unverified Commit f6e37fd3 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Apply #40833 (#40872)

parent d4d9d915
...@@ -201,7 +201,7 @@ ...@@ -201,7 +201,7 @@
"taskr": "1.1.0", "taskr": "1.1.0",
"tree-kill": "1.2.2", "tree-kill": "1.2.2",
"tsec": "0.2.1", "tsec": "0.2.1",
"turbo": "1.3.2-canary.1", "turbo": "1.5.3",
"typescript": "4.8.2", "typescript": "4.8.2",
"wait-port": "0.2.2", "wait-port": "0.2.2",
"webpack": "5.74.0", "webpack": "5.74.0",
......
...@@ -193,6 +193,7 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -193,6 +193,7 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
} }
export const staticGenerationAsyncStorage = require('next/dist/client/components/static-generation-async-storage.js').staticGenerationAsyncStorage export const staticGenerationAsyncStorage = require('next/dist/client/components/static-generation-async-storage.js').staticGenerationAsyncStorage
export const requestAsyncStorage = require('next/dist/client/components/request-async-storage.js').requestAsyncStorage
export const serverHooks = require('next/dist/client/components/hooks-server-context.js') export const serverHooks = require('next/dist/client/components/hooks-server-context.js')
......
...@@ -13,38 +13,3 @@ export class DynamicServerError extends Error { ...@@ -13,38 +13,3 @@ export class DynamicServerError extends Error {
super(`Dynamic server usage: ${type}`) super(`Dynamic server usage: ${type}`)
} }
} }
// Ensure serverContext is not created more than once as React will throw when creating it more than once
// https://github.com/facebook/react/blob/dd2d6522754f52c70d02c51db25eb7cbd5d1c8eb/packages/react/src/ReactServerContext.js#L101
const createContext = <T>(name: string, defaultValue: T | null = null) => {
// @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global
if (!global.__NEXT_SERVER_CONTEXT__) {
// @ts-expect-error __NEXT_SERVER_CONTEXT__ is a global
global.__NEXT_SERVER_CONTEXT__ = {}
}
// @ts-expect-error __NEXT_SERVER_CONTEXT__ is a global
if (!global.__NEXT_SERVER_CONTEXT__[name]) {
// @ts-expect-error __NEXT_SERVER_CONTEXT__ is a global
global.__NEXT_SERVER_CONTEXT__[name] = createServerContext(
name,
defaultValue
)
}
// @ts-expect-error __NEXT_SERVER_CONTEXT__ is a global
return global.__NEXT_SERVER_CONTEXT__[name]
}
export const CONTEXT_NAMES = {
HeadersContext: 'HeadersContext',
PreviewDataContext: 'PreviewDataContext',
CookiesContext: 'CookiesContext',
FetchRevalidateContext: 'FetchRevalidateContext',
} as const
export const HeadersContext = createContext(CONTEXT_NAMES.HeadersContext)
export const PreviewDataContext = createContext(
CONTEXT_NAMES.PreviewDataContext
)
export const CookiesContext = createContext(CONTEXT_NAMES.CookiesContext)
import { useContext } from 'react' import { DynamicServerError } from './hooks-server-context'
import { import { requestAsyncStorage } from './request-async-storage'
HeadersContext,
PreviewDataContext,
CookiesContext,
DynamicServerError,
} from './hooks-server-context'
import { staticGenerationAsyncStorage } from './static-generation-async-storage' import { staticGenerationAsyncStorage } from './static-generation-async-storage'
function useStaticGenerationBailout(reason: string) { function staticGenerationBailout(reason: string) {
const staticGenerationStore = const staticGenerationStore =
staticGenerationAsyncStorage && 'getStore' in staticGenerationAsyncStorage staticGenerationAsyncStorage && 'getStore' in staticGenerationAsyncStorage
? staticGenerationAsyncStorage?.getStore() ? staticGenerationAsyncStorage?.getStore()
...@@ -22,17 +17,31 @@ function useStaticGenerationBailout(reason: string) { ...@@ -22,17 +17,31 @@ function useStaticGenerationBailout(reason: string) {
} }
} }
export function useHeaders() { export function headers(): Headers {
useStaticGenerationBailout('useHeaders') staticGenerationBailout('headers')
return useContext(HeadersContext) const requestStore =
requestAsyncStorage && 'getStore' in requestAsyncStorage
? requestAsyncStorage.getStore()!
: requestAsyncStorage
return requestStore.headers
} }
export function usePreviewData() { export function previewData() {
useStaticGenerationBailout('usePreviewData') staticGenerationBailout('previewData')
return useContext(PreviewDataContext) const requestStore =
requestAsyncStorage && 'getStore' in requestAsyncStorage
? requestAsyncStorage.getStore()!
: requestAsyncStorage
return requestStore.previewData
} }
export function useCookies() { export function cookies() {
useStaticGenerationBailout('useCookies') staticGenerationBailout('cookies')
return useContext(CookiesContext) const requestStore =
requestAsyncStorage && 'getStore' in requestAsyncStorage
? requestAsyncStorage.getStore()!
: requestAsyncStorage
return requestStore.cookies
} }
import type { AsyncLocalStorage } from 'async_hooks'
import { Cookies } from '../../server/web/spec-extension/cookies'
export interface RequestStore {
headers: Headers
cookies: Cookies
previewData: any
}
export let requestAsyncStorage: AsyncLocalStorage<RequestStore> | RequestStore =
{} as any
if (process.env.NEXT_RUNTIME !== 'edge' && typeof window === 'undefined') {
requestAsyncStorage = new (require('async_hooks').AsyncLocalStorage)()
}
...@@ -28,8 +28,98 @@ import { ...@@ -28,8 +28,98 @@ import {
import { FlushEffectsContext } from '../shared/lib/flush-effects' import { FlushEffectsContext } from '../shared/lib/flush-effects'
import { stripInternalQueries } from './internal-utils' import { stripInternalQueries } from './internal-utils'
import type { ComponentsType } from '../build/webpack/loaders/next-app-loader' import type { ComponentsType } from '../build/webpack/loaders/next-app-loader'
import type { UnwrapPromise } from '../lib/coalesced-function'
import { REDIRECT_ERROR_CODE } from '../client/components/redirect' import { REDIRECT_ERROR_CODE } from '../client/components/redirect'
import { NextCookies } from './web/spec-extension/cookies'
const INTERNAL_HEADERS_INSTANCE = Symbol('internal for headers readonly')
function readonlyHeadersError() {
return new Error('ReadonlyHeaders cannot be modified')
}
class ReadonlyHeaders {
[INTERNAL_HEADERS_INSTANCE]: Headers
entries: Headers['entries']
forEach: Headers['forEach']
get: Headers['get']
has: Headers['has']
keys: Headers['keys']
values: Headers['values']
constructor(headers: IncomingHttpHeaders) {
// Since `new Headers` uses `this.append()` to fill the headers object ReadonlyHeaders can't extend from Headers directly as it would throw.
const headersInstance = new Headers(headers as any)
this[INTERNAL_HEADERS_INSTANCE] = headersInstance
this.entries = headersInstance.entries.bind(headersInstance)
this.forEach = headersInstance.forEach.bind(headersInstance)
this.get = headersInstance.get.bind(headersInstance)
this.has = headersInstance.has.bind(headersInstance)
this.keys = headersInstance.keys.bind(headersInstance)
this.values = headersInstance.values.bind(headersInstance)
}
[Symbol.iterator]() {
return this[INTERNAL_HEADERS_INSTANCE][Symbol.iterator]()
}
append() {
throw readonlyHeadersError()
}
delete() {
throw readonlyHeadersError()
}
set() {
throw readonlyHeadersError()
}
}
const INTERNAL_COOKIES_INSTANCE = Symbol('internal for cookies readonly')
function readonlyCookiesError() {
return new Error('ReadonlyCookies cannot be modified')
}
class ReadonlyNextCookies {
[INTERNAL_COOKIES_INSTANCE]: NextCookies
entries: NextCookies['entries']
forEach: NextCookies['forEach']
get: NextCookies['get']
getWithOptions: NextCookies['getWithOptions']
has: NextCookies['has']
keys: NextCookies['keys']
values: NextCookies['values']
constructor(request: {
headers: {
get(key: 'cookie'): string | null | undefined
}
}) {
// Since `new Headers` uses `this.append()` to fill the headers object ReadonlyHeaders can't extend from Headers directly as it would throw.
// Request overridden to not have to provide a fully request object.
const cookiesInstance = new NextCookies(request as Request)
this[INTERNAL_COOKIES_INSTANCE] = cookiesInstance
this.entries = cookiesInstance.entries.bind(cookiesInstance)
this.forEach = cookiesInstance.forEach.bind(cookiesInstance)
this.get = cookiesInstance.get.bind(cookiesInstance)
this.getWithOptions = cookiesInstance.getWithOptions.bind(cookiesInstance)
this.has = cookiesInstance.has.bind(cookiesInstance)
this.keys = cookiesInstance.keys.bind(cookiesInstance)
this.values = cookiesInstance.values.bind(cookiesInstance)
}
[Symbol.iterator]() {
return this[INTERNAL_COOKIES_INSTANCE][Symbol.iterator]()
}
clear() {
throw readonlyCookiesError()
}
delete() {
throw readonlyCookiesError()
}
set() {
throw readonlyCookiesError()
}
}
// this needs to be required lazily so that `next-server` can set // this needs to be required lazily so that `next-server` can set
// the env before we require // the env before we require
...@@ -541,6 +631,7 @@ export async function renderToHTMLOrFlight( ...@@ -541,6 +631,7 @@ export async function renderToHTMLOrFlight(
patchFetch(ComponentMod) patchFetch(ComponentMod)
const staticGenerationAsyncStorage = ComponentMod.staticGenerationAsyncStorage const staticGenerationAsyncStorage = ComponentMod.staticGenerationAsyncStorage
const requestAsyncStorage = ComponentMod.requestAsyncStorage
if ( if (
!('getStore' in staticGenerationAsyncStorage) && !('getStore' in staticGenerationAsyncStorage) &&
...@@ -589,9 +680,6 @@ export async function renderToHTMLOrFlight( ...@@ -589,9 +680,6 @@ export async function renderToHTMLOrFlight(
) )
} }
const { CONTEXT_NAMES } =
ComponentMod.serverHooks as typeof import('../client/components/hooks-server-context')
// TODO-APP: verify the tree is valid // TODO-APP: verify the tree is valid
// TODO-APP: verify query param is single value (not an array) // TODO-APP: verify query param is single value (not an array)
// TODO-APP: verify tree can't grow out of control // TODO-APP: verify tree can't grow out of control
...@@ -614,29 +702,10 @@ export async function renderToHTMLOrFlight( ...@@ -614,29 +702,10 @@ export async function renderToHTMLOrFlight(
| typeof import('../client/components/hot-reloader.client').default | typeof import('../client/components/hot-reloader.client').default
| null | null
const headers = headersWithoutFlight(req.headers)
// TODO-APP: fix type of req
// @ts-expect-error
const cookies = req.cookies
/** /**
* The tree created in next-app-loader that holds component segments and modules * The tree created in next-app-loader that holds component segments and modules
*/ */
const loaderTree: LoaderTree = ComponentMod.tree const loaderTree: LoaderTree = ComponentMod.tree
const tryGetPreviewData =
process.env.NEXT_RUNTIME === 'edge'
? () => false
: require('./api-utils/node').tryGetPreviewData
// Reads of this are cached on the `req` object, so this should resolve
// instantly. There's no need to pass this data down from a previous
// invoke, where we'd have to consider server & serverless.
const previewData = tryGetPreviewData(
req,
res,
(renderOpts as any).previewProps
)
/** /**
* Server Context is specifically only available in Server Components. * Server Context is specifically only available in Server Components.
* It has to hold values that can't change while rendering from the common layout down. * It has to hold values that can't change while rendering from the common layout down.
...@@ -645,9 +714,6 @@ export async function renderToHTMLOrFlight( ...@@ -645,9 +714,6 @@ export async function renderToHTMLOrFlight(
const serverContexts: Array<[string, any]> = [ const serverContexts: Array<[string, any]> = [
['WORKAROUND', null], // TODO-APP: First value has a bug currently where the value is not set on the second request: https://github.com/facebook/react/issues/24849 ['WORKAROUND', null], // TODO-APP: First value has a bug currently where the value is not set on the second request: https://github.com/facebook/react/issues/24849
[CONTEXT_NAMES.HeadersContext, headers],
[CONTEXT_NAMES.CookiesContext, cookies],
[CONTEXT_NAMES.PreviewDataContext, previewData],
] ]
type CreateSegmentPath = (child: FlightSegmentPath) => FlightSegmentPath type CreateSegmentPath = (child: FlightSegmentPath) => FlightSegmentPath
...@@ -1315,18 +1381,64 @@ export async function renderToHTMLOrFlight( ...@@ -1315,18 +1381,64 @@ export async function renderToHTMLOrFlight(
pathname, pathname,
} }
if ('getStore' in staticGenerationAsyncStorage) { const tryGetPreviewData =
return new Promise<UnwrapPromise<ReturnType<typeof renderToHTMLOrFlight>>>( process.env.NEXT_RUNTIME === 'edge'
(resolve, reject) => { ? () => false
: require('./api-utils/node').tryGetPreviewData
// Reads of this are cached on the `req` object, so this should resolve
// instantly. There's no need to pass this data down from a previous
// invoke, where we'd have to consider server & serverless.
const previewData = tryGetPreviewData(
req,
res,
(renderOpts as any).previewProps
)
const requestStore = {
headers: new ReadonlyHeaders(headersWithoutFlight(req.headers)),
cookies: new ReadonlyNextCookies({
headers: {
get: (key) => {
if (key !== 'cookie') {
throw new Error('Only cookie header is supported')
}
return req.headers.cookie
},
},
}),
previewData,
}
function handleRequestStoreRun<T>(fn: () => T): Promise<T> {
if ('getStore' in requestAsyncStorage) {
return new Promise((resolve, reject) => {
requestAsyncStorage.run(requestStore, () => {
return Promise.resolve(fn()).then(resolve).catch(reject)
})
})
} else {
Object.assign(requestAsyncStorage, requestStore)
return Promise.resolve(fn())
}
}
function handleStaticGenerationStoreRun<T>(fn: () => T): Promise<T> {
if ('getStore' in staticGenerationAsyncStorage) {
return new Promise((resolve, reject) => {
staticGenerationAsyncStorage.run(initialStaticGenerationStore, () => { staticGenerationAsyncStorage.run(initialStaticGenerationStore, () => {
return wrappedRender().then(resolve).catch(reject) return Promise.resolve(fn()).then(resolve).catch(reject)
}) })
} })
) } else {
} else { Object.assign(staticGenerationAsyncStorage, initialStaticGenerationStore)
Object.assign(staticGenerationAsyncStorage, initialStaticGenerationStore) return Promise.resolve(fn()).finally(() => {
return wrappedRender().finally(() => { staticGenerationAsyncStorage.inUse = false
staticGenerationAsyncStorage.inUse = false })
}) }
} }
return handleRequestStoreRun(() =>
handleStaticGenerationStoreRun(() => wrappedRender())
)
} }
This diff is collapsed.
import ClientComp from './client-component' import ClientComp from './client-component'
import { useHeaders } from 'next/dist/client/components/hooks-server' import { headers } from 'next/dist/client/components/hooks-server'
export default function Page() { export default function Page() {
// Opt-in to SSR. // Opt-in to SSR.
useHeaders() headers()
return <ClientComp /> return <ClientComp />
} }
'client' 'client'
import { useCookies } from 'next/dist/client/components/hooks-server' import { cookies } from 'next/dist/client/components/hooks-server'
export default function Page() { export default function Page() {
// This should throw an error. // This should throw an error.
useCookies() cookies()
return null return null
} }
import { useCookies } from 'next/dist/client/components/hooks-server' import { cookies } from 'next/dist/client/components/hooks-server'
export default function Page() { export default function Page() {
const cookies = useCookies() const cookiesList = cookies()
const cookie = cookiesList.get('use-cookies')
const hasCookie = const hasCookie = cookie === 'value'
'use-cookies' in cookies && cookies['use-cookies'] === 'value'
return ( return (
<> <>
......
'client' 'client'
import { useHeaders } from 'next/dist/client/components/hooks-server' import { headers } from 'next/dist/client/components/hooks-server'
export default function Page() { export default function Page() {
// This should throw an error. // This should throw an error.
useHeaders() headers()
return null return null
} }
import { useHeaders } from 'next/dist/client/components/hooks-server' import { headers } from 'next/dist/client/components/hooks-server'
export default function Page() { export default function Page() {
const headers = useHeaders() const headersList = headers()
const hasHeader = headersList.get('x-use-headers') === 'value'
const hasHeader = const referer = headersList.get('referer')
'x-use-headers' in headers && headers['x-use-headers'] === 'value'
return ( return (
<> <>
...@@ -14,9 +13,7 @@ export default function Page() { ...@@ -14,9 +13,7 @@ export default function Page() {
) : ( ) : (
<h2 id="does-not-have-header">Does not have x-use-headers header</h2> <h2 id="does-not-have-header">Does not have x-use-headers header</h2>
)} )}
{'referer' in headers && headers['referer'] && ( {referer && <h3 id="has-referer">Has referer header</h3>}
<h3 id="has-referer">Has referer header</h3>
)}
</> </>
) )
} }
'client' 'client'
import { usePreviewData } from 'next/dist/client/components/hooks-server' import { previewData } from 'next/dist/client/components/hooks-server'
export default function Page() { export default function Page() {
// This should throw an error. // This should throw an error.
usePreviewData() previewData()
return null return null
} }
import { usePreviewData } from 'next/dist/client/components/hooks-server' import { previewData } from 'next/dist/client/components/hooks-server'
export default function Page() { export default function Page() {
const data = usePreviewData() const data = previewData()
const hasData = !!data && data.key === 'value' const hasData = !!data && data.key === 'value'
......
...@@ -7,10 +7,10 @@ export default function Page() { ...@@ -7,10 +7,10 @@ export default function Page() {
<h1 id="render-id">{nanoid()}</h1> <h1 id="render-id">{nanoid()}</h1>
<h2 id="from-navigation">hello from /navigation</h2> <h2 id="from-navigation">hello from /navigation</h2>
<Link href="/hooks/use-cookies" id="use-cookies"> <Link href="/hooks/use-cookies" id="use-cookies">
useCookies Cookies
</Link> </Link>
<Link href="/hooks/use-headers" id="use-headers"> <Link href="/hooks/use-headers" id="use-headers">
useHeaders Headers
</Link> </Link>
</> </>
) )
......
// TODO-APP: enable when flight error serialization is implemented // TODO-APP: enable when flight error serialization is implemented
import ClientComp from './client-component' import ClientComp from './client-component'
import { useHeaders } from 'next/dist/client/components/hooks-server' import { headers } from 'next/dist/client/components/hooks-server'
export default function Page() { export default function Page() {
// Opt-in to SSR. // Opt-in to SSR.
useHeaders() headers()
return <ClientComp /> return <ClientComp />
} }
import { useCookies } from 'next/dist/client/components/hooks-server' import { cookies } from 'next/dist/client/components/hooks-server'
import Router from './router' import Router from './router'
export default function Page() { export default function Page() {
useCookies() cookies()
return ( return (
<div id="old-router"> <div id="old-router">
......
import ClientComp from './client-component' import ClientComp from './client-component'
import { useHeaders } from 'next/dist/client/components/hooks-server' import { headers } from 'next/dist/client/components/hooks-server'
export default function Page() { export default function Page() {
// Opt-in to SSR. // Opt-in to SSR.
useHeaders() headers()
return <ClientComp /> return <ClientComp />
} }
...@@ -799,8 +799,8 @@ describe('app dir', () => { ...@@ -799,8 +799,8 @@ describe('app dir', () => {
}) })
describe('hooks', () => { describe('hooks', () => {
describe('useCookies', () => { describe('cookies function', () => {
it('should retrive cookies in a server component', async () => { it('should retrieve cookies in a server component', async () => {
const browser = await webdriver(next.url, '/hooks/use-cookies') const browser = await webdriver(next.url, '/hooks/use-cookies')
try { try {
...@@ -852,7 +852,7 @@ describe('app dir', () => { ...@@ -852,7 +852,7 @@ describe('app dir', () => {
}) })
}) })
describe('useHeaders', () => { describe('headers function', () => {
it('should have access to incoming headers in a server component', async () => { it('should have access to incoming headers in a server component', async () => {
// Check to see that we can't see the header when it's not present. // Check to see that we can't see the header when it's not present.
let html = await renderViaHTTP( let html = await renderViaHTTP(
...@@ -889,7 +889,7 @@ describe('app dir', () => { ...@@ -889,7 +889,7 @@ describe('app dir', () => {
}) })
}) })
describe('usePreviewData', () => { describe('previewData function', () => {
it('should return no preview data when there is none', async () => { it('should return no preview data when there is none', async () => {
const browser = await webdriver(next.url, '/hooks/use-preview-data') const browser = await webdriver(next.url, '/hooks/use-preview-data')
...@@ -985,7 +985,7 @@ describe('app dir', () => { ...@@ -985,7 +985,7 @@ describe('app dir', () => {
describe('client components', () => { describe('client components', () => {
describe('hooks', () => { describe('hooks', () => {
describe('useCookies', () => { describe('cookies function', () => {
// TODO-APP: should enable when implemented // TODO-APP: should enable when implemented
it.skip('should throw an error when imported', async () => { it.skip('should throw an error when imported', async () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
...@@ -997,7 +997,7 @@ describe('app dir', () => { ...@@ -997,7 +997,7 @@ describe('app dir', () => {
}) })
}) })
describe('usePreviewData', () => { describe('previewData function', () => {
// TODO-APP: should enable when implemented // TODO-APP: should enable when implemented
it.skip('should throw an error when imported', async () => { it.skip('should throw an error when imported', async () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
...@@ -1009,7 +1009,7 @@ describe('app dir', () => { ...@@ -1009,7 +1009,7 @@ describe('app dir', () => {
}) })
}) })
describe('useHeaders', () => { describe('headers function', () => {
// TODO-APP: should enable when implemented // TODO-APP: should enable when implemented
it.skip('should throw an error when imported', async () => { it.skip('should throw an error when imported', async () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
......
import Nav from '../components/nav' import Nav from '../components/nav'
import { useHeaders } from 'next/dist/client/components/hooks-server' import { headers } from 'next/dist/client/components/hooks-server'
const envVar = process.env.ENV_VAR_TEST const envVar = process.env.ENV_VAR_TEST
const headerKey = 'x-next-test-client' const headerKey = 'x-next-test-client'
export default function Index(props) { export default function Index(props) {
const header = useHeaders()[headerKey] const headersList = headers()
const header = headersList.get(headerKey)
return ( return (
<div> <div>
......
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