Unverified Commit 5325afa6 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[metadata] refactor to remove async metadata (#78495)

parent 286eefe6
...@@ -3,15 +3,6 @@ ...@@ -3,15 +3,6 @@
import { Suspense, use } from 'react' import { Suspense, use } from 'react'
import type { StreamingMetadataResolvedState } from './types' import type { StreamingMetadataResolvedState } from './types'
export const AsyncMetadata =
typeof window === 'undefined'
? (
require('./server-inserted-metadata') as typeof import('./server-inserted-metadata')
).ServerInsertMetadata
: (
require('./browser-resolved-metadata') as typeof import('./browser-resolved-metadata')
).BrowserResolvedMetadata
function MetadataOutlet({ function MetadataOutlet({
promise, promise,
}: { }: {
......
import { use } from 'react'
import type { StreamingMetadataResolvedState } from './types'
export function BrowserResolvedMetadata({
promise,
}: {
promise: Promise<StreamingMetadataResolvedState>
}) {
const { metadata, error } = use(promise)
// If there's metadata error on client, discard the browser metadata
// and let metadata outlet deal with the error. This will avoid the duplication metadata.
if (error) return null
return metadata
}
import { use, useContext } from 'react'
import {
type MetadataResolver,
ServerInsertedMetadataContext,
} from '../../../shared/lib/server-inserted-metadata.shared-runtime'
import type { StreamingMetadataResolvedState } from './types'
// Receives a metadata resolver setter from the context, and will pass the metadata resolving promise to
// the context where we gonna use it to resolve the metadata, and render as string to append in <body>.
const useServerInsertedMetadata = (metadataResolver: MetadataResolver) => {
const setMetadataResolver = useContext(ServerInsertedMetadataContext)
if (setMetadataResolver) {
setMetadataResolver(metadataResolver)
}
}
export function ServerInsertMetadata({
promise,
}: {
promise: Promise<StreamingMetadataResolvedState>
}) {
// Apply use() to the metadata promise to suspend the rendering in SSR.
const { metadata } = use(promise)
// Insert metadata into the HTML stream through the `useServerInsertedMetadata`
useServerInsertedMetadata(() => metadata)
return null
}
'use client'
// This is a client component that only renders during SSR,
// but will be replaced during streaming with an icon insertion script tag.
// We don't want it to be presented anywhere so it's only visible during streaming,
// right after the icon meta tags so that browser can pick it up as soon as it's rendered.
// Note: we don't just emit the script here because we only need the script if it's not in the head,
// and we need it to be hoistable alongside the other metadata but sync scripts are not hoistable.
export const IconMark = () => {
if (typeof window !== 'undefined') {
return null
}
return <meta name="«nxt-icon»" />
}
import type { ResolvedMetadata } from '../types/metadata-interface' import type { ResolvedMetadata } from '../types/metadata-interface'
import type { Icon, IconDescriptor } from '../types/metadata-types' import type { Icon, IconDescriptor } from '../types/metadata-types'
import { IconMark } from './icon-mark'
import { MetaFilter } from './meta' import { MetaFilter } from './meta'
...@@ -27,6 +28,14 @@ export function IconsMetadata({ icons }: { icons: ResolvedMetadata['icons'] }) { ...@@ -27,6 +28,14 @@ export function IconsMetadata({ icons }: { icons: ResolvedMetadata['icons'] }) {
const appleList = icons.apple const appleList = icons.apple
const otherList = icons.other const otherList = icons.other
const hasIcon = Boolean(
shortcutList?.length ||
iconList?.length ||
appleList?.length ||
otherList?.length
)
if (!hasIcon) return null
return MetaFilter([ return MetaFilter([
shortcutList shortcutList
? shortcutList.map((icon) => IconLink({ rel: 'shortcut icon', icon })) ? shortcutList.map((icon) => IconLink({ rel: 'shortcut icon', icon }))
...@@ -36,5 +45,6 @@ export function IconsMetadata({ icons }: { icons: ResolvedMetadata['icons'] }) { ...@@ -36,5 +45,6 @@ export function IconsMetadata({ icons }: { icons: ResolvedMetadata['icons'] }) {
? appleList.map((icon) => IconLink({ rel: 'apple-touch-icon', icon })) ? appleList.map((icon) => IconLink({ rel: 'apple-touch-icon', icon }))
: null, : null,
otherList ? otherList.map((icon) => IconDescriptorLink({ icon })) : null, otherList ? otherList.map((icon) => IconDescriptorLink({ icon })) : null,
hasIcon ? <IconMark /> : null,
]) ])
} }
...@@ -38,10 +38,7 @@ import { ...@@ -38,10 +38,7 @@ import {
METADATA_BOUNDARY_NAME, METADATA_BOUNDARY_NAME,
VIEWPORT_BOUNDARY_NAME, VIEWPORT_BOUNDARY_NAME,
} from './metadata-constants' } from './metadata-constants'
import { import { AsyncMetadataOutlet } from '../../client/components/metadata/async-metadata'
AsyncMetadata,
AsyncMetadataOutlet,
} from '../../client/components/metadata/async-metadata'
import { isPostpone } from '../../server/lib/router-utils/is-postpone' import { isPostpone } from '../../server/lib/router-utils/is-postpone'
import { createServerSearchParamsForMetadata } from '../../server/request/search-params' import { createServerSearchParamsForMetadata } from '../../server/request/search-params'
import { createServerPathnameForMetadata } from '../../server/request/pathname' import { createServerPathnameForMetadata } from '../../server/request/pathname'
...@@ -211,18 +208,22 @@ export function createMetadataComponents({ ...@@ -211,18 +208,22 @@ export function createMetadataComponents({
} }
} }
} }
async function Metadata() {
const promise = resolveFinalMetadata() function Metadata() {
if (serveStreamingMetadata) { if (!serveStreamingMetadata) {
return <MetadataResolver />
}
return ( return (
<div hidden> <div hidden>
<Suspense fallback={null}> <Suspense fallback={null}>
<AsyncMetadata promise={promise} /> <MetadataResolver />
</Suspense> </Suspense>
</div> </div>
) )
} }
const metadataState = await promise
async function MetadataResolver() {
const metadataState = await resolveFinalMetadata()
return metadataState.metadata return metadataState.metadata
} }
......
...@@ -985,7 +985,7 @@ async function getErrorRSCPayload( ...@@ -985,7 +985,7 @@ async function getErrorRSCPayload(
const seedData: CacheNodeSeedData = [ const seedData: CacheNodeSeedData = [
initialTree[0], initialTree[0],
<html id="__next_error__"> <html id="__next_error__">
<head>{metadata}</head> <head></head>
<body> <body>
{process.env.NODE_ENV !== 'production' && err ? ( {process.env.NODE_ENV !== 'production' && err ? (
<template <template
...@@ -1043,7 +1043,6 @@ function App<T>({ ...@@ -1043,7 +1043,6 @@ function App<T>({
preinitScripts, preinitScripts,
clientReferenceManifest, clientReferenceManifest,
ServerInsertedHTMLProvider, ServerInsertedHTMLProvider,
ServerInsertedMetadataProvider,
gracefullyDegrade, gracefullyDegrade,
nonce, nonce,
}: { }: {
...@@ -1051,7 +1050,6 @@ function App<T>({ ...@@ -1051,7 +1050,6 @@ function App<T>({
preinitScripts: () => void preinitScripts: () => void
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']> clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }> ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }>
ServerInsertedMetadataProvider: React.ComponentType<{ children: JSX.Element }>
gracefullyDegrade: boolean gracefullyDegrade: boolean
nonce?: string nonce?: string
}): JSX.Element { }): JSX.Element {
...@@ -1091,7 +1089,6 @@ function App<T>({ ...@@ -1091,7 +1089,6 @@ function App<T>({
nonce, nonce,
}} }}
> >
<ServerInsertedMetadataProvider>
<ServerInsertedHTMLProvider> <ServerInsertedHTMLProvider>
<AppRouter <AppRouter
actionQueue={actionQueue} actionQueue={actionQueue}
...@@ -1100,7 +1097,6 @@ function App<T>({ ...@@ -1100,7 +1097,6 @@ function App<T>({
gracefullyDegrade={gracefullyDegrade} gracefullyDegrade={gracefullyDegrade}
/> />
</ServerInsertedHTMLProvider> </ServerInsertedHTMLProvider>
</ServerInsertedMetadataProvider>
</HeadManagerContext.Provider> </HeadManagerContext.Provider>
) )
} }
...@@ -1112,7 +1108,6 @@ function ErrorApp<T>({ ...@@ -1112,7 +1108,6 @@ function ErrorApp<T>({
reactServerStream, reactServerStream,
preinitScripts, preinitScripts,
clientReferenceManifest, clientReferenceManifest,
ServerInsertedMetadataProvider,
ServerInsertedHTMLProvider, ServerInsertedHTMLProvider,
gracefullyDegrade, gracefullyDegrade,
nonce, nonce,
...@@ -1120,7 +1115,6 @@ function ErrorApp<T>({ ...@@ -1120,7 +1115,6 @@ function ErrorApp<T>({
reactServerStream: BinaryStreamOf<T> reactServerStream: BinaryStreamOf<T>
preinitScripts: () => void preinitScripts: () => void
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']> clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
ServerInsertedMetadataProvider: React.ComponentType<{ children: JSX.Element }>
ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }> ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }>
gracefullyDegrade: boolean gracefullyDegrade: boolean
nonce?: string nonce?: string
...@@ -1152,7 +1146,6 @@ function ErrorApp<T>({ ...@@ -1152,7 +1146,6 @@ function ErrorApp<T>({
const actionQueue = createMutableActionQueue(initialState, null) const actionQueue = createMutableActionQueue(initialState, null)
return ( return (
<ServerInsertedMetadataProvider>
<ServerInsertedHTMLProvider> <ServerInsertedHTMLProvider>
<AppRouter <AppRouter
actionQueue={actionQueue} actionQueue={actionQueue}
...@@ -1161,7 +1154,6 @@ function ErrorApp<T>({ ...@@ -1161,7 +1154,6 @@ function ErrorApp<T>({
gracefullyDegrade={gracefullyDegrade} gracefullyDegrade={gracefullyDegrade}
/> />
</ServerInsertedHTMLProvider> </ServerInsertedHTMLProvider>
</ServerInsertedMetadataProvider>
) )
} }
...@@ -1781,8 +1773,7 @@ async function renderToStream( ...@@ -1781,8 +1773,7 @@ async function renderToStream(
const { ServerInsertedHTMLProvider, renderServerInsertedHTML } = const { ServerInsertedHTMLProvider, renderServerInsertedHTML } =
createServerInsertedHTML() createServerInsertedHTML()
const { ServerInsertedMetadataProvider, getServerInsertedMetadata } = const getServerInsertedMetadata = createServerInsertedMetadata(nonce)
createServerInsertedMetadata(nonce)
const tracingMetadata = getTracedMetadata( const tracingMetadata = getTracedMetadata(
getTracer().getTracePropagationData(), getTracer().getTracePropagationData(),
...@@ -1979,7 +1970,6 @@ async function renderToStream( ...@@ -1979,7 +1970,6 @@ async function renderToStream(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
nonce={nonce} nonce={nonce}
gracefullyDegrade={!!botType} gracefullyDegrade={!!botType}
/>, />,
...@@ -2018,7 +2008,6 @@ async function renderToStream( ...@@ -2018,7 +2008,6 @@ async function renderToStream(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType} gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
...@@ -2171,7 +2160,6 @@ async function renderToStream( ...@@ -2171,7 +2160,6 @@ async function renderToStream(
element: ( element: (
<ErrorApp <ErrorApp
reactServerStream={errorServerStream} reactServerStream={errorServerStream}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
preinitScripts={errorPreinitScripts} preinitScripts={errorPreinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
...@@ -2276,7 +2264,6 @@ async function spawnDynamicValidationInDev( ...@@ -2276,7 +2264,6 @@ async function spawnDynamicValidationInDev(
// that are provided during the actual prerenderToStream. // that are provided during the actual prerenderToStream.
const preinitScripts = () => {} const preinitScripts = () => {}
const { ServerInsertedHTMLProvider } = createServerInsertedHTML() const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const { ServerInsertedMetadataProvider } = createServerInsertedMetadata(nonce)
const rootParams = getRootParams( const rootParams = getRootParams(
ComponentMod.tree, ComponentMod.tree,
...@@ -2443,7 +2430,6 @@ async function spawnDynamicValidationInDev( ...@@ -2443,7 +2430,6 @@ async function spawnDynamicValidationInDev(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType} gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
...@@ -2596,7 +2582,6 @@ async function spawnDynamicValidationInDev( ...@@ -2596,7 +2582,6 @@ async function spawnDynamicValidationInDev(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType} gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
...@@ -2746,8 +2731,7 @@ async function prerenderToStream( ...@@ -2746,8 +2731,7 @@ async function prerenderToStream(
const { ServerInsertedHTMLProvider, renderServerInsertedHTML } = const { ServerInsertedHTMLProvider, renderServerInsertedHTML } =
createServerInsertedHTML() createServerInsertedHTML()
const { ServerInsertedMetadataProvider, getServerInsertedMetadata } = const getServerInsertedMetadata = createServerInsertedMetadata(nonce)
createServerInsertedMetadata(nonce)
const tracingMetadata = getTracedMetadata( const tracingMetadata = getTracedMetadata(
getTracer().getTracePropagationData(), getTracer().getTracePropagationData(),
...@@ -3039,7 +3023,6 @@ async function prerenderToStream( ...@@ -3039,7 +3023,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType} gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
...@@ -3200,7 +3183,6 @@ async function prerenderToStream( ...@@ -3200,7 +3183,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType} gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
...@@ -3333,7 +3315,6 @@ async function prerenderToStream( ...@@ -3333,7 +3315,6 @@ async function prerenderToStream(
preinitScripts={() => {}} preinitScripts={() => {}}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType} gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
...@@ -3432,7 +3413,6 @@ async function prerenderToStream( ...@@ -3432,7 +3413,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType} gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
...@@ -3565,7 +3545,6 @@ async function prerenderToStream( ...@@ -3565,7 +3545,6 @@ async function prerenderToStream(
preinitScripts={() => {}} preinitScripts={() => {}}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType} gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
...@@ -3645,7 +3624,6 @@ async function prerenderToStream( ...@@ -3645,7 +3624,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts} preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType} gracefullyDegrade={!!botType}
nonce={nonce} nonce={nonce}
/>, />,
...@@ -3807,7 +3785,6 @@ async function prerenderToStream( ...@@ -3807,7 +3785,6 @@ async function prerenderToStream(
element: ( element: (
<ErrorApp <ErrorApp
reactServerStream={errorServerStream} reactServerStream={errorServerStream}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
preinitScripts={errorPreinitScripts} preinitScripts={errorPreinitScripts}
clientReferenceManifest={clientReferenceManifest} clientReferenceManifest={clientReferenceManifest}
......
import React from 'react'
import { renderToReadableStream } from 'react-dom/server.edge'
import {
ServerInsertedMetadataContext,
type MetadataResolver,
} from '../../../shared/lib/server-inserted-metadata.shared-runtime'
import { renderToString } from '../render-to-string'
/** /**
* For chromium based browsers (Chrome, Edge, etc.) and Safari, * For chromium based browsers (Chrome, Edge, etc.) and Safari,
* icons need to stay under <head> to be picked up by the browser. * icons need to stay under <head> to be picked up by the browser.
...@@ -15,42 +7,14 @@ const REINSERT_ICON_SCRIPT = `\ ...@@ -15,42 +7,14 @@ const REINSERT_ICON_SCRIPT = `\
document.querySelectorAll('body link[rel="icon"], body link[rel="apple-touch-icon"]').forEach(el => document.head.appendChild(el))` document.querySelectorAll('body link[rel="icon"], body link[rel="apple-touch-icon"]').forEach(el => document.head.appendChild(el))`
export function createServerInsertedMetadata(nonce: string | undefined) { export function createServerInsertedMetadata(nonce: string | undefined) {
let metadataResolver: MetadataResolver | null = null let inserted = false
let metadataToFlush: React.ReactNode = null
const setMetadataResolver = (resolver: MetadataResolver): void => {
metadataResolver = resolver
}
return { return async function getServerInsertedMetadata(): Promise<string> {
ServerInsertedMetadataProvider: ({ if (inserted) {
children,
}: {
children: React.ReactNode
}) => {
return (
<ServerInsertedMetadataContext.Provider value={setMetadataResolver}>
{children}
</ServerInsertedMetadataContext.Provider>
)
},
async getServerInsertedMetadata(): Promise<string> {
if (!metadataResolver || metadataToFlush) {
return '' return ''
} }
metadataToFlush = metadataResolver() inserted = true
const html = await renderToString({ return `<script nonce="${nonce}">${REINSERT_ICON_SCRIPT}</script>`
renderToReadableStream,
element: (
<>
{metadataToFlush}
<script nonce={nonce}>{REINSERT_ICON_SCRIPT}</script>
</>
),
})
return html
},
} }
} }
...@@ -155,7 +155,7 @@ import { ...@@ -155,7 +155,7 @@ import {
getBuiltinRequestContext, getBuiltinRequestContext,
type WaitUntil, type WaitUntil,
} from './after/builtin-request-context' } from './after/builtin-request-context'
import { ENCODED_TAGS } from './stream-utils/encodedTags' import { ENCODED_TAGS } from './stream-utils/encoded-tags'
import { NextRequestHint } from './web/adapter' import { NextRequestHint } from './web/adapter'
import { getRevalidateReason } from './instrumentation/utils' import { getRevalidateReason } from './instrumentation/utils'
import { RouteKind } from './route-kind' import { RouteKind } from './route-kind'
......
export * as HeadManagerContext from '../../../../../shared/lib/head-manager-context.shared-runtime' export * as HeadManagerContext from '../../../../../shared/lib/head-manager-context.shared-runtime'
export * as ServerInsertedHtml from '../../../../../shared/lib/server-inserted-html.shared-runtime' export * as ServerInsertedHtml from '../../../../../shared/lib/server-inserted-html.shared-runtime'
export * as ServerInsertedMetadata from '../../../../../shared/lib/server-inserted-metadata.shared-runtime'
export * as AppRouterContext from '../../../../../shared/lib/app-router-context.shared-runtime' export * as AppRouterContext from '../../../../../shared/lib/app-router-context.shared-runtime'
export * as HooksClientContext from '../../../../../shared/lib/hooks-client-context.shared-runtime' export * as HooksClientContext from '../../../../../shared/lib/hooks-client-context.shared-runtime'
export * as RouterContext from '../../../../../shared/lib/router-context.shared-runtime' export * as RouterContext from '../../../../../shared/lib/router-context.shared-runtime'
......
...@@ -18,4 +18,13 @@ export const ENCODED_TAGS = { ...@@ -18,4 +18,13 @@ export const ENCODED_TAGS = {
60, 47, 98, 111, 100, 121, 62, 60, 47, 104, 116, 109, 108, 62, 60, 47, 98, 111, 100, 121, 62, 60, 47, 104, 116, 109, 108, 62,
]), ]),
}, },
META: {
// Only the match the prefix cause the suffix can be different wether it's xml compatible or not ">" or "/>"
// <meta name="«nxt-icon»"
// This is a special mark that will be replaced by the icon insertion script tag.
ICON_MARK: new Uint8Array([
60, 109, 101, 116, 97, 32, 110, 97, 109, 101, 61, 34, 194, 171, 110, 120,
116, 45, 105, 99, 111, 110, 194, 187, 34,
]),
},
} as const } as const
...@@ -2,7 +2,7 @@ import { getTracer } from '../lib/trace/tracer' ...@@ -2,7 +2,7 @@ import { getTracer } from '../lib/trace/tracer'
import { AppRenderSpan } from '../lib/trace/constants' import { AppRenderSpan } from '../lib/trace/constants'
import { DetachedPromise } from '../../lib/detached-promise' import { DetachedPromise } from '../../lib/detached-promise'
import { scheduleImmediate, atLeastOneTask } from '../../lib/scheduler' import { scheduleImmediate, atLeastOneTask } from '../../lib/scheduler'
import { ENCODED_TAGS } from './encodedTags' import { ENCODED_TAGS } from './encoded-tags'
import { import {
indexOfUint8Array, indexOfUint8Array,
isEquivalentUint8Arrays, isEquivalentUint8Arrays,
...@@ -193,6 +193,89 @@ export function renderToInitialFizzStream({ ...@@ -193,6 +193,89 @@ export function renderToInitialFizzStream({
) )
} }
function createMetadataTransformStream(
insert: () => Promise<string> | string
): TransformStream<Uint8Array, Uint8Array> {
let chunkIndex = -1
let isMarkRemoved = false
return new TransformStream({
async transform(chunk, controller) {
let iconMarkIndex = -1
let closedHeadIndex = -1
chunkIndex++
if (isMarkRemoved) {
controller.enqueue(chunk)
return
}
let iconMarkLength = 0
// Only search for the closed head tag once
if (iconMarkIndex === -1) {
iconMarkIndex = indexOfUint8Array(chunk, ENCODED_TAGS.META.ICON_MARK)
if (iconMarkIndex === -1) {
controller.enqueue(chunk)
return
} else {
// When we found the `<meta name="«nxt-icon»"` tag prefix, we will remove it from the chunk.
// Its close tag could either be `/>` or `>`, checking the next char to ensure we cover both cases.
iconMarkLength = ENCODED_TAGS.META.ICON_MARK.length
// Check if next char is /, this is for xml mode.
if (chunk[iconMarkIndex + iconMarkLength] === 47) {
iconMarkLength += 2
} else {
// The last char is `>`
iconMarkLength++
}
}
}
// Check if icon mark is inside <head> tag in the first chunk.
if (chunkIndex === 0) {
closedHeadIndex = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)
// The mark icon is located in the 1st chunk before the head tag.
// We do not need to insert the script tag in this case because it's in the head.
// Just remove the icon mark from the chunk.
if (iconMarkIndex < closedHeadIndex && iconMarkIndex !== -1) {
const replaced = new Uint8Array(chunk.length - iconMarkLength)
// Remove the icon mark from the chunk.
replaced.set(chunk.subarray(0, iconMarkIndex))
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex
)
chunk = replaced
isMarkRemoved = true
}
} else {
// When it's appeared in the following chunks, we'll need to
// remove the mark and then insert the script tag at that position.
const insertion = await insert()
const encodedInsertion = encoder.encode(insertion)
const insertionLength = encodedInsertion.length
// Replace the icon mark with the hoist script or empty string.
const replaced = new Uint8Array(
chunk.length - iconMarkLength + insertionLength
)
// Set the first part of the chunk, before the icon mark.
replaced.set(chunk.subarray(0, iconMarkIndex))
// Set the insertion after the icon mark.
replaced.set(encodedInsertion, iconMarkIndex)
// Set the rest of the chunk after the icon mark.
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex + insertionLength
)
chunk = replaced
isMarkRemoved = true
}
controller.enqueue(chunk)
},
})
}
function createHeadInsertionTransformStream( function createHeadInsertionTransformStream(
insert: () => Promise<string> insert: () => Promise<string>
): TransformStream<Uint8Array, Uint8Array> { ): TransformStream<Uint8Array, Uint8Array> {
...@@ -564,8 +647,8 @@ export async function continueFizzStream( ...@@ -564,8 +647,8 @@ export async function continueFizzStream(
// Buffer everything to avoid flushing too frequently // Buffer everything to avoid flushing too frequently
createBufferedTransformStream(), createBufferedTransformStream(),
// Insert generated metadata // Transform metadata
createHeadInsertionTransformStream(getServerInsertedMetadata), createMetadataTransformStream(getServerInsertedMetadata),
// Insert suffix content // Insert suffix content
suffixUnclosed != null && suffixUnclosed.length > 0 suffixUnclosed != null && suffixUnclosed.length > 0
...@@ -607,10 +690,8 @@ export async function continueDynamicPrerender( ...@@ -607,10 +690,8 @@ export async function continueDynamicPrerender(
.pipeThrough(createStripDocumentClosingTagsTransform()) .pipeThrough(createStripDocumentClosingTagsTransform())
// Insert generated tags to head // Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML)) .pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML))
// Insert generated metadata // Transform metadata
.pipeThrough( .pipeThrough(createMetadataTransformStream(getServerInsertedMetadata))
createHeadInsertionTransformStream(getServerInsertedMetadata)
)
) )
} }
...@@ -634,10 +715,8 @@ export async function continueStaticPrerender( ...@@ -634,10 +715,8 @@ export async function continueStaticPrerender(
.pipeThrough(createBufferedTransformStream()) .pipeThrough(createBufferedTransformStream())
// Insert generated tags to head // Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML)) .pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML))
// Insert generated metadata to head // Transform metadata
.pipeThrough( .pipeThrough(createMetadataTransformStream(getServerInsertedMetadata))
createHeadInsertionTransformStream(getServerInsertedMetadata)
)
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML // Insert the inlined data (Flight data, form state, etc.) stream into the HTML
.pipeThrough(createMergedTransformStream(inlinedDataStream)) .pipeThrough(createMergedTransformStream(inlinedDataStream))
// Close tags should always be deferred to the end // Close tags should always be deferred to the end
...@@ -665,10 +744,8 @@ export async function continueDynamicHTMLResume( ...@@ -665,10 +744,8 @@ export async function continueDynamicHTMLResume(
.pipeThrough(createBufferedTransformStream()) .pipeThrough(createBufferedTransformStream())
// Insert generated tags to head // Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML)) .pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML))
// Insert generated metadata to body // Transform metadata
.pipeThrough( .pipeThrough(createMetadataTransformStream(getServerInsertedMetadata))
createHeadInsertionTransformStream(getServerInsertedMetadata)
)
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML // Insert the inlined data (Flight data, form state, etc.) stream into the HTML
.pipeThrough(createMergedTransformStream(inlinedDataStream)) .pipeThrough(createMergedTransformStream(inlinedDataStream))
// Close tags should always be deferred to the end // Close tags should always be deferred to the end
......
'use client'
import type React from 'react'
import { createContext } from 'react'
export type MetadataResolver = () => React.ReactNode
type MetadataResolverSetter = (m: MetadataResolver) => void
export const ServerInsertedMetadataContext =
createContext<MetadataResolverSetter | null>(null)
...@@ -491,6 +491,12 @@ describe('app dir - css', () => { ...@@ -491,6 +491,12 @@ describe('app dir - css', () => {
const matches = initialHtml const matches = initialHtml
.match(/\/_next\/static\/css\/.+?\.css/g) .match(/\/_next\/static\/css\/.+?\.css/g)
// The same css chunk could be split into 2 RSC script
// normalize "/_next/static/css/app/\"])</script><script>self.__next_f.push([1,\"not-found.css"
// to "/_next/static/css/app/not-found.css"
.map((href) =>
href.replace('"])</script><script>self.__next_f.push([1,"', '')
)
.sort() .sort()
// Heavy on testing React implementation details. // Heavy on testing React implementation details.
......
...@@ -44,6 +44,27 @@ describe('app-dir - metadata-icons', () => { ...@@ -44,6 +44,27 @@ describe('app-dir - metadata-icons', () => {
}) })
}) })
it('should not contain icon insertion script when metadata is rendered in head', async () => {
const iconInsertionScript = `document.querySelectorAll('body link[rel="icon"], body link[rel="apple-touch-icon"]').forEach(el => document.head.appendChild(el))`
const suspendedHtml = await next.render('/custom-icon')
expect(suspendedHtml).toContain(iconInsertionScript)
})
it('should not contain icon replacement mark in html or after hydration', async () => {
const html = await next.render('/custom-icon')
expect(html).not.toContain('<meta name="«nxt-icon»" content=""/>')
expect(html).not.toContain('«nxt-icon»')
const browser = await next.browser('/custom-icon')
const metaTags = await browser.elementsByCss('meta')
// none of them has [name="«nxt-icon»"]
const names = await Promise.all(
metaTags.map((el) => el.getAttribute('name'))
)
expect(names).not.toContain('«nxt-icon»')
})
it('should re-insert the apple icons into the head after navigation', async () => { it('should re-insert the apple icons into the head after navigation', async () => {
const browser = await next.browser('/custom-icon') const browser = await next.browser('/custom-icon')
await browser.elementByCss('#custom-icon-sub-link').click() await browser.elementByCss('#custom-icon-sub-link').click()
......
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
...@@ -15,7 +15,9 @@ describe('app-dir - metadata-streaming', () => { ...@@ -15,7 +15,9 @@ describe('app-dir - metadata-streaming', () => {
const $ = await next.render$('/parallel-routes') const $ = await next.render$('/parallel-routes')
expect($('title').length).toBe(1) expect($('title').length).toBe(1)
expect($('head title').text()).toBe('parallel title') // We can't ensure if it's inserted into head or body since it's a race condition,
// where sometimes the metadata can be suspended.
expect($('title').text()).toBe('parallel title')
// validate behavior remains the same on client navigations // validate behavior remains the same on client navigations
await browser.elementByCss('[href="/parallel-routes/test-page"]').click() await browser.elementByCss('[href="/parallel-routes/test-page"]').click()
......
...@@ -157,8 +157,10 @@ describe('app-dir - metadata-streaming', () => { ...@@ -157,8 +157,10 @@ describe('app-dir - metadata-streaming', () => {
describe('static', () => { describe('static', () => {
it('should render static metadata in the head', async () => { it('should render static metadata in the head', async () => {
const $ = await next.render$('/static/full') const $ = await next.render$('/static/full')
// We can't ensure if it's inserted into head or body since it's a race condition,
// where sometimes the metadata can be suspended.
expect($('title').length).toBe(1) expect($('title').length).toBe(1)
expect($('head title').text()).toBe('static page') expect($('title').text()).toBe('static page')
}) })
it('should determine dynamic metadata in build and render in the body', async () => { it('should determine dynamic metadata in build and render in the body', async () => {
......
...@@ -10,13 +10,18 @@ describe('app dir - metadata dynamic routes suspense', () => { ...@@ -10,13 +10,18 @@ describe('app dir - metadata dynamic routes suspense', () => {
return return
} }
it('should render metadata in head even root layout is wrapped with Suspense', async () => { it('should render metadata in head when root layout is wrapped with Suspense for bot requests', async () => {
const $ = await next.render$('/') const $ = await next.render$('/', undefined, {
headers: {
'User-Agent': 'Discordbot/2.0;',
},
})
expect($('head title').text()).toBe('My title') expect($('head title').text()).toBe('My title')
expect($('head meta[name="application-name"]').attr('content')).toBe( expect($('head meta[name="application-name"]').attr('content')).toBe(
'suspense-app' 'suspense-app'
) )
expect($('body meta').length).toBe(0) // unique title
expect($('title').length).toBe(1)
}) })
}) })
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"], "lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
"strict": false, "strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true, "noEmit": true,
"incremental": true, "incremental": true,
"esModuleInterop": true,
"module": "esnext", "module": "esnext",
"moduleResolution": "bundler", "esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "preserve", "jsx": "preserve",
...@@ -17,9 +17,8 @@ ...@@ -17,9 +17,8 @@
{ {
"name": "next" "name": "next"
} }
], ]
"target": "ES2017"
}, },
"include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"], "include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"] "exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
} }
export default function Page() { export default function Page() {
return <h1>I'm still a valid page</h1> return <h1>I am still a valid page</h1>
} }
...@@ -22,7 +22,7 @@ describe('app dir - not-found - conflict route', () => { ...@@ -22,7 +22,7 @@ describe('app dir - not-found - conflict route', () => {
it('should allow to have a valid /not-found route', async () => { it('should allow to have a valid /not-found route', async () => {
const html = await next.render('/not-found') const html = await next.render('/not-found')
expect(html).toContain("I'm still a valid page") expect(html).toContain('I am still a valid page')
}) })
} }
......
...@@ -169,7 +169,7 @@ describe('opentelemetry', () => { ...@@ -169,7 +169,7 @@ describe('opentelemetry', () => {
}, },
{ {
attributes: { attributes: {
'next.clientComponentLoadCount': 8, 'next.clientComponentLoadCount': 7,
'next.span_type': 'next.span_type':
'NextNodeServer.clientComponentLoading', 'NextNodeServer.clientComponentLoading',
}, },
......
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