Skip to content
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

Refactor freezing metadata while resolving and fix title merging #45965

Merged
merged 9 commits into from
Feb 17, 2023
Merged
Changes from 1 commit
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
29 changes: 16 additions & 13 deletions packages/next/src/lib/metadata/resolve-metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,40 +248,43 @@ export async function collectMetadata(
export async function accumulateMetadata(
huozhi marked this conversation as resolved.
Show resolved Hide resolved
metadataItems: MetadataItems
): Promise<ResolvedMetadata> {
const deepClone: <T>(v: T) => T =
process.env.NODE_ENV === 'development'
? require('next/dist/compiled/@edge-runtime/primitives/structured-clone')
.structuredClone
: (v) => v
const resolvedMetadata = createDefaultMetadata()

let parentPromise = Promise.resolve(resolvedMetadata)
let chainPromise = Promise.resolve(resolvedMetadata)

for (const item of metadataItems) {
huozhi marked this conversation as resolved.
Show resolved Hide resolved
const [metadataExport, staticFilesMetadata] = item

// Freeze the parent metadata to avoid accidental mutation to it
let resolvingMetadata = chainPromise
if (process.env.NODE_ENV === 'development') {
const deepClone =
require('next/dist/compiled/@edge-runtime/primitives/structured-clone').structuredClone
resolvingMetadata = chainPromise.then((resolved) =>
Object.freeze(deepClone(resolved))
)
}

const currentMetadata =
typeof metadataExport === 'function'
? metadataExport(parentPromise)
? metadataExport(resolvingMetadata)
: metadataExport
const layerMetadataPromise =
currentMetadata instanceof Promise
? currentMetadata
: Promise.resolve(currentMetadata)

parentPromise = parentPromise.then((resolved) => {
chainPromise = chainPromise.then((resolved) => {
return layerMetadataPromise.then((metadata) => {
resolved = deepClone(resolved)
merge(resolved, metadata, staticFilesMetadata, {
title: resolved.title?.template || null,
openGraph: resolved.openGraph?.title?.template || null,
twitter: resolved.twitter?.title?.template || null,
})
return process.env.NODE_ENV === 'development'
? Object.freeze(resolved)
: resolved
return resolved
})
})
}

return await parentPromise
return await chainPromise
}