Unverified Commit 9822f78f authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Resolve metadata fields (#45237)

## Feature

- [x] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [x]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)
parent f879e093
...@@ -2,17 +2,18 @@ import type { ResolvedMetadata } from '../types/metadata-interface' ...@@ -2,17 +2,18 @@ import type { ResolvedMetadata } from '../types/metadata-interface'
import React from 'react' import React from 'react'
export function ResolvedAlternatesMetadata({ export function AlternatesMetadata({
metadata, alternates,
}: { }: {
metadata: ResolvedMetadata alternates: ResolvedMetadata['alternates']
}) { }) {
if (!alternates) return null
return ( return (
<> <>
{metadata.alternates.canonical ? ( {alternates.canonical ? (
<link rel="canonical" href={metadata.alternates.canonical.toString()} /> <link rel="canonical" href={alternates.canonical.toString()} />
) : null} ) : null}
{Object.entries(metadata.alternates.languages).map(([locale, url]) => {Object.entries(alternates.languages).map(([locale, url]) =>
url ? ( url ? (
<link <link
key={locale} key={locale}
...@@ -22,8 +23,8 @@ export function ResolvedAlternatesMetadata({ ...@@ -22,8 +23,8 @@ export function ResolvedAlternatesMetadata({
/> />
) : null ) : null
)} )}
{metadata.alternates.media {alternates.media
? Object.entries(metadata.alternates.media).map(([media, url]) => ? Object.entries(alternates.media).map(([media, url]) =>
url ? ( url ? (
<link <link
key={media} key={media}
...@@ -34,8 +35,8 @@ export function ResolvedAlternatesMetadata({ ...@@ -34,8 +35,8 @@ export function ResolvedAlternatesMetadata({
) : null ) : null
) )
: null} : null}
{metadata.alternates.types {alternates.types
? Object.entries(metadata.alternates.types).map(([type, url]) => ? Object.entries(alternates.types).map(([type, url]) =>
url ? ( url ? (
<link <link
key={type} key={type}
......
...@@ -3,11 +3,7 @@ import type { ResolvedMetadata } from '../types/metadata-interface' ...@@ -3,11 +3,7 @@ import type { ResolvedMetadata } from '../types/metadata-interface'
import React from 'react' import React from 'react'
import { Meta } from './meta' import { Meta } from './meta'
export function ResolvedBasicMetadata({ export function BasicMetadata({ metadata }: { metadata: ResolvedMetadata }) {
metadata,
}: {
metadata: ResolvedMetadata
}) {
return ( return (
<> <>
<meta charSet="utf-8" /> <meta charSet="utf-8" />
...@@ -25,7 +21,8 @@ export function ResolvedBasicMetadata({ ...@@ -25,7 +21,8 @@ export function ResolvedBasicMetadata({
<Meta name="viewport" content={metadata.viewport} /> <Meta name="viewport" content={metadata.viewport} />
<Meta name="creator" content={metadata.creator} /> <Meta name="creator" content={metadata.creator} />
<Meta name="publisher" content={metadata.publisher} /> <Meta name="publisher" content={metadata.publisher} />
<Meta name="robots" content={metadata.robots} /> <Meta name="robots" content={metadata.robots?.basic} />
<Meta name="googlebot" content={metadata.robots?.googleBot} />
<Meta name="abstract" content={metadata.abstract} /> <Meta name="abstract" content={metadata.abstract} />
{metadata.archives {metadata.archives
? metadata.archives.map((archive) => ( ? metadata.archives.map((archive) => (
...@@ -44,13 +41,84 @@ export function ResolvedBasicMetadata({ ...@@ -44,13 +41,84 @@ export function ResolvedBasicMetadata({
: null} : null}
<Meta name="category" content={metadata.category} /> <Meta name="category" content={metadata.category} />
<Meta name="classification" content={metadata.classification} /> <Meta name="classification" content={metadata.classification} />
{Object.entries(metadata.other).map(([name, content]) => ( {metadata.other
<Meta ? Object.entries(metadata.other).map(([name, content]) => (
key={name} <Meta
name={name} key={name}
content={Array.isArray(content) ? content.join(',') : content} name={name}
content={Array.isArray(content) ? content.join(',') : content}
/>
))
: null}
</>
)
}
export function ItunesMeta({ itunes }: { itunes: ResolvedMetadata['itunes'] }) {
if (!itunes) return null
const { appId, appArgument } = itunes
let content = `app-id=${appId}`
if (appArgument) {
content += `, app-argument=${appArgument}`
}
return <meta name="apple-itunes-app" content={content} />
}
const formatDetectionKeys = [
'telephone',
'date',
'address',
'email',
'url',
] as const
export function FormatDetectionMeta({
formatDetection,
}: {
formatDetection: ResolvedMetadata['formatDetection']
}) {
if (!formatDetection) return null
let content = ''
for (const key of formatDetectionKeys) {
if (formatDetection[key]) {
if (content) content += ', '
content += `${key}=no`
}
}
return <meta name="format-detection" content={content} />
}
export function AppleWebAppMeta({
appleWebApp,
}: {
appleWebApp: ResolvedMetadata['appleWebApp']
}) {
if (!appleWebApp) return null
const { capable, title, startupImage, statusBarStyle } = appleWebApp
return (
<>
{capable ? (
<meta name="apple-mobile-web-app-capable" content="yes" />
) : null}
{title ? (
<meta name="apple-mobile-web-app-title" content={title} />
) : null}
{startupImage
? startupImage.map((image, index) => (
<link
key={index}
href={image.url}
media={image.media}
rel="apple-touch-startup-image"
/>
))
: null}
{statusBarStyle ? (
<meta
name="apple-mobile-web-app-status-bar-style"
content={statusBarStyle}
/> />
))} ) : null}
</> </>
) )
} }
...@@ -22,11 +22,7 @@ function IconLink({ rel, icon }: { rel?: string; icon: Icon }) { ...@@ -22,11 +22,7 @@ function IconLink({ rel, icon }: { rel?: string; icon: Icon }) {
} }
} }
export function ResolvedIconsMetadata({ export function IconsMetadata({ icons }: { icons: ResolvedMetadata['icons'] }) {
icons,
}: {
icons: ResolvedMetadata['icons']
}) {
if (!icons) return null if (!icons) return null
const shortcutList = icons.shortcut const shortcutList = icons.shortcut
......
...@@ -20,6 +20,43 @@ export function Meta({ ...@@ -20,6 +20,43 @@ export function Meta({
return null return null
} }
type ExtendMetaContent = Record<
string,
undefined | string | URL | number | boolean | null | undefined
>
type MultiMetaContent =
| (ExtendMetaContent | string | URL | number)[]
| null
| undefined
export function ExtendMeta({
content,
namePrefix,
propertyPrefix,
}: {
content?: ExtendMetaContent
namePrefix?: string
propertyPrefix?: string
}) {
const keyPrefix = namePrefix || propertyPrefix
if (!content) return null
return (
<React.Fragment>
{Object.entries(content).map(([k, v], index) => {
return typeof v === 'undefined' ? null : (
<Meta
key={keyPrefix + ':' + k + '_' + index}
{...(propertyPrefix
? { property: propertyPrefix + ':' + k }
: { name: namePrefix + ':' + k })}
content={typeof v === 'string' ? v : v?.toString()}
/>
)
})}
</React.Fragment>
)
}
export function MultiMeta({ export function MultiMeta({
propertyPrefix, propertyPrefix,
namePrefix, namePrefix,
...@@ -27,15 +64,7 @@ export function MultiMeta({ ...@@ -27,15 +64,7 @@ export function MultiMeta({
}: { }: {
propertyPrefix?: string propertyPrefix?: string
namePrefix?: string namePrefix?: string
contents: contents?: MultiMetaContent | null
| (
| Record<string, undefined | string | URL | number>
| string
| URL
| number
)[]
| null
| undefined
}) { }) {
if (typeof contents === 'undefined' || contents === null) { if (typeof contents === 'undefined' || contents === null) {
return null return null
...@@ -61,19 +90,11 @@ export function MultiMeta({ ...@@ -61,19 +90,11 @@ export function MultiMeta({
) )
} else { } else {
return ( return (
<React.Fragment key={keyPrefix + '_' + index}> <ExtendMeta
{Object.entries(content).map(([k, v]) => { namePrefix={namePrefix}
return typeof v === 'undefined' ? null : ( propertyPrefix={propertyPrefix}
<Meta content={content}
key={keyPrefix + ':' + k + '_' + index} />
{...(propertyPrefix
? { property: propertyPrefix + ':' + k }
: { name: namePrefix + ':' + k })}
content={typeof v === 'string' ? v : v.toString()}
/>
)
})}
</React.Fragment>
) )
} }
})} })}
......
import type { ResolvedMetadata } from '../types/metadata-interface' import type { ResolvedMetadata } from '../types/metadata-interface'
import React from 'react' import React from 'react'
import { Meta, MultiMeta } from './meta' import { ExtendMeta, Meta, MultiMeta } from './meta'
import { TwitterAppDescriptor } from '../types/twitter-types'
export function ResolvedOpenGraphMetadata({ export function OpenGraphMetadata({
openGraph, openGraph,
}: { }: {
openGraph: ResolvedMetadata['openGraph'] openGraph: ResolvedMetadata['openGraph']
...@@ -221,3 +222,97 @@ export function ResolvedOpenGraphMetadata({ ...@@ -221,3 +222,97 @@ export function ResolvedOpenGraphMetadata({
</> </>
) )
} }
function TwitterAppItem({
app,
type,
}: {
app: TwitterAppDescriptor
type: 'iphone' | 'ipad' | 'googleplay'
}) {
return (
<>
<Meta name={`twitter:app:name:${type}`} content={app.name} />
<ExtendMeta namePrefix="twitter:app:id" content={app.id} />
<ExtendMeta namePrefix="twitter:app:url" content={app.url} />
</>
)
}
export function TwitterMetadata({
twitter,
}: {
twitter: ResolvedMetadata['twitter']
}) {
if (!twitter) return null
const { card } = twitter
return (
<>
<Meta name="twitter:card" content={card} />
<Meta name="twitter:site" content={twitter.site} />
<Meta name="twitter:site:id" content={twitter.siteId} />
<Meta name="twitter:creator" content={twitter.creator} />
<Meta name="twitter:creator:id" content={twitter.creatorId} />
<Meta name="twitter:title" content={twitter.title?.absolute} />
<Meta name="twitter:description" content={twitter.description} />
{twitter.images
? twitter.images.map((image) => (
<>
<Meta name="twitter:image" content={image.url} />
<Meta name="twitter:image:alt" content={image.alt} />
</>
))
: null}
{card === 'player'
? twitter.players.map((player) => (
<>
<Meta
name="twitter:player"
content={player.playerUrl.toString()}
/>
<Meta
name="twitter:player:stream"
content={player.streamUrl.toString()}
/>
<Meta name="twitter:player:width" content={player.width} />
<Meta name="twitter:player:height" content={player.height} />
</>
))
: null}
{card === 'app' ? (
<>
<TwitterAppItem app={twitter.app} type="iphone" />
<TwitterAppItem app={twitter.app} type="ipad" />
<TwitterAppItem app={twitter.app} type="googleplay" />
</>
) : null}
</>
)
}
export function AppLinksMeta({
appLinks,
}: {
appLinks: ResolvedMetadata['appLinks']
}) {
if (!appLinks) return null
return (
<>
<MultiMeta propertyPrefix="al:ios" contents={appLinks.ios} />
<MultiMeta propertyPrefix="al:iphone" contents={appLinks.iphone} />
<MultiMeta propertyPrefix="al:ipad" contents={appLinks.ipad} />
<MultiMeta propertyPrefix="al:android" contents={appLinks.android} />
<MultiMeta
propertyPrefix="al:windows_phone"
contents={appLinks.windows_phone}
/>
<MultiMeta propertyPrefix="al:windows" contents={appLinks.windows} />
<MultiMeta
propertyPrefix="al:windows_universal"
contents={appLinks.windows_universal}
/>
<MultiMeta propertyPrefix="al:web" contents={appLinks.web} />
</>
)
}
export function resolveAsArrayOrUndefined<T = any>( export function resolveAsArrayOrUndefined<
value: T | T[] | undefined | null T extends unknown | readonly unknown[]
): undefined | T[] { >(value: T | T[] | undefined | null): undefined | T[] {
if (typeof value === 'undefined' || value === null) { if (typeof value === 'undefined' || value === null) {
return undefined return undefined
} }
......
import type { ResolvedMetadata } from './types/metadata-interface' import type { ResolvedMetadata } from './types/metadata-interface'
import React from 'react' import React from 'react'
import { ResolvedBasicMetadata } from './generate/basic' import {
import { ResolvedAlternatesMetadata } from './generate/alternate' AppleWebAppMeta,
import { ResolvedOpenGraphMetadata } from './generate/opengraph' FormatDetectionMeta,
ItunesMeta,
BasicMetadata,
} from './generate/basic'
import { AlternatesMetadata } from './generate/alternate'
import {
OpenGraphMetadata,
TwitterMetadata,
AppLinksMeta,
} from './generate/opengraph'
import { resolveMetadata } from './resolve-metadata' import { resolveMetadata } from './resolve-metadata'
import { ResolvedIconsMetadata } from './generate/icons' import { IconsMetadata } from './generate/icons'
// Generate the actual React elements from the resolved metadata. // Generate the actual React elements from the resolved metadata.
export async function Metadata({ metadata }: { metadata: any }) { export async function Metadata({ metadata }: { metadata: any }) {
...@@ -14,10 +23,15 @@ export async function Metadata({ metadata }: { metadata: any }) { ...@@ -14,10 +23,15 @@ export async function Metadata({ metadata }: { metadata: any }) {
const resolved: ResolvedMetadata = await resolveMetadata(metadata) const resolved: ResolvedMetadata = await resolveMetadata(metadata)
return ( return (
<> <>
<ResolvedBasicMetadata metadata={resolved} /> <BasicMetadata metadata={resolved} />
<ResolvedAlternatesMetadata metadata={resolved} /> <AlternatesMetadata alternates={resolved.alternates} />
<ResolvedOpenGraphMetadata openGraph={resolved.openGraph} /> <ItunesMeta itunes={resolved.itunes} />
<ResolvedIconsMetadata icons={resolved.icons} /> <FormatDetectionMeta formatDetection={resolved.formatDetection} />
<AppleWebAppMeta appleWebApp={resolved.appleWebApp} />
<OpenGraphMetadata openGraph={resolved.openGraph} />
<TwitterMetadata twitter={resolved.twitter} />
<AppLinksMeta appLinks={resolved.appLinks} />
<IconsMetadata icons={resolved.icons} />
</> </>
) )
} }
...@@ -16,6 +16,10 @@ import { resolveOpenGraph } from './resolve-opengraph' ...@@ -16,6 +16,10 @@ import { resolveOpenGraph } from './resolve-opengraph'
import { mergeTitle } from './resolve-title' import { mergeTitle } from './resolve-title'
import { resolveAsArrayOrUndefined } from './generate/utils' import { resolveAsArrayOrUndefined } from './generate/utils'
type FieldResolver<Key extends keyof Metadata> = (
T: Metadata[Key]
) => ResolvedMetadata[Key]
const viewPortKeys = { const viewPortKeys = {
width: 'width', width: 'width',
height: 'height', height: 'height',
...@@ -54,9 +58,7 @@ type Item = ...@@ -54,9 +58,7 @@ type Item =
path?: string path?: string
} }
function resolveViewport( const resolveViewport: FieldResolver<'viewport'> = (viewport) => {
viewport: Metadata['viewport']
): ResolvedMetadata['viewport'] {
let resolved: ResolvedMetadata['viewport'] = null let resolved: ResolvedMetadata['viewport'] = null
if (typeof viewport === 'string') { if (typeof viewport === 'string') {
...@@ -74,19 +76,44 @@ function resolveViewport( ...@@ -74,19 +76,44 @@ function resolveViewport(
return resolved return resolved
} }
function isUrlIcon(icon: any): icon is string | URL { const resolveVerification: FieldResolver<'verification'> = (verification) => {
const google = resolveAsArrayOrUndefined(verification?.google)
const yahoo = resolveAsArrayOrUndefined(verification?.yahoo)
let other: Record<string, (string | number)[]> | undefined
if (verification?.other) {
other = {}
for (const key in verification.other) {
const value = resolveAsArrayOrUndefined(verification.other[key])
if (value) other[key] = value
}
}
return {
google,
yahoo,
other,
}
}
function isStringOrURL(icon: any): icon is string | URL {
return typeof icon === 'string' || icon instanceof URL return typeof icon === 'string' || icon instanceof URL
} }
function resolveIcon(icon: Icon): IconDescriptor { function resolveIcon(icon: Icon): IconDescriptor {
if (isUrlIcon(icon)) return { url: icon } if (isStringOrURL(icon)) return { url: icon }
else if (Array.isArray(icon)) return icon else if (Array.isArray(icon)) return icon
return icon return icon
} }
const IconKeys = ['icon', 'shortcut', 'apple', 'other'] as (keyof Icons)[] const IconKeys = ['icon', 'shortcut', 'apple', 'other'] as (keyof Icons)[]
const TwitterBasicInfoKeys = [
'site',
'siteId',
'creator',
'creatorId',
'description',
] as const
function resolveIcons(icons: Metadata['icons']): ResolvedMetadata['icons'] { const resolveIcons: FieldResolver<'icons'> = (icons) => {
if (!icons) { if (!icons) {
return null return null
} }
...@@ -94,7 +121,7 @@ function resolveIcons(icons: Metadata['icons']): ResolvedMetadata['icons'] { ...@@ -94,7 +121,7 @@ function resolveIcons(icons: Metadata['icons']): ResolvedMetadata['icons'] {
const resolved: ResolvedMetadata['icons'] = {} const resolved: ResolvedMetadata['icons'] = {}
if (Array.isArray(icons)) { if (Array.isArray(icons)) {
resolved.icon = icons.map(resolveIcon).filter(Boolean) resolved.icon = icons.map(resolveIcon).filter(Boolean)
} else if (isUrlIcon(icons)) { } else if (isStringOrURL(icons)) {
resolved.icon = [resolveIcon(icons)] resolved.icon = [resolveIcon(icons)]
} else { } else {
for (const key of IconKeys) { for (const key of IconKeys) {
...@@ -105,6 +132,107 @@ function resolveIcons(icons: Metadata['icons']): ResolvedMetadata['icons'] { ...@@ -105,6 +132,107 @@ function resolveIcons(icons: Metadata['icons']): ResolvedMetadata['icons'] {
return resolved return resolved
} }
const resolveAppleWebApp: FieldResolver<'appleWebApp'> = (appWebApp) => {
if (!appWebApp) return null
if (appWebApp === true) {
return {
capable: true,
}
}
const startupImages = resolveAsArrayOrUndefined(appWebApp.startupImage)?.map(
(item) => (typeof item === 'string' ? { url: item } : item)
)
return {
capable: 'capable' in appWebApp ? !!appWebApp.capable : true,
title: appWebApp.title || null,
startupImage: startupImages || null,
statusBarStyle: appWebApp.statusBarStyle || 'default',
}
}
const resolveTwitter: FieldResolver<'twitter'> = (twitter) => {
if (!twitter) return null
const resolved = {
title: twitter.title,
} as ResolvedTwitterMetadata
for (const infoKey of TwitterBasicInfoKeys) {
resolved[infoKey] = twitter[infoKey] || null
}
resolved.images = resolveAsArrayOrUndefined(twitter.images)?.map((item) => {
if (isStringOrURL(item))
return {
url: item.toString(),
}
else {
return {
url: item.url.toString(),
alt: item.alt,
}
}
})
if ('card' in twitter) {
resolved.card = twitter.card
switch (twitter.card) {
case 'player': {
// @ts-ignore
resolved.players = resolveAsArrayOrUndefined(twitter.players) || []
break
}
case 'app': {
// @ts-ignore
resolved.app = twitter.app || {}
break
}
default:
break
}
} else {
resolved.card = 'summary'
}
return resolved
}
const resolveAppLinks: FieldResolver<'appLinks'> = (appLinks) => {
if (!appLinks) return null
for (const key in appLinks) {
// @ts-ignore // TODO: type infer
appLinks[key] = resolveAsArrayOrUndefined(appLinks[key])
}
return appLinks as ResolvedMetadata['appLinks']
}
const resolveRobotsValue: (robots: Metadata['robots']) => string | null = (
robots
) => {
if (!robots) return null
if (typeof robots === 'string') return robots
const values = []
if (robots.index) values.push('index')
else if (typeof robots.index === 'boolean') values.push('noindex')
if (robots.follow) values.push('follow')
else if (typeof robots.follow === 'boolean') values.push('nofollow')
if (robots.noarchive) values.push('noarchive')
if (robots.nosnippet) values.push('nosnippet')
if (robots.noimageindex) values.push('noimageindex')
if (robots.nocache) values.push('nocache')
return values.join(', ')
}
const resolveRobots: FieldResolver<'robots'> = (robots) => {
if (!robots) return null
return {
basic: resolveRobotsValue(robots),
googleBot:
typeof robots !== 'string' ? resolveRobotsValue(robots.googleBot) : null,
}
}
// Merge the source metadata into the resolved target metadata. // Merge the source metadata into the resolved target metadata.
function merge( function merge(
target: ResolvedMetadata, target: ResolvedMetadata,
...@@ -119,10 +247,6 @@ function merge( ...@@ -119,10 +247,6 @@ function merge(
const key = key_ as keyof Metadata const key = key_ as keyof Metadata
switch (key) { switch (key) {
case 'other': {
Object.assign(target.other, source.other)
break
}
case 'title': { case 'title': {
if (source.title) { if (source.title) {
target.title = source.title as AbsoluteTemplateString target.title = source.title as AbsoluteTemplateString
...@@ -142,14 +266,15 @@ function merge( ...@@ -142,14 +266,15 @@ function merge(
break break
} }
case 'twitter': { case 'twitter': {
if (source.twitter) { target.twitter = resolveTwitter(source.twitter)
target.twitter = source.twitter as ResolvedTwitterMetadata if (target.twitter) {
mergeTitle(target.twitter, templateStrings.twitter) mergeTitle(target.twitter, templateStrings.twitter)
} else {
target.twitter = null
} }
break break
} }
case 'verification':
target.verification = resolveVerification(source.verification)
break
case 'viewport': { case 'viewport': {
target.viewport = resolveViewport(source.viewport) target.viewport = resolveViewport(source.viewport)
break break
...@@ -158,12 +283,46 @@ function merge( ...@@ -158,12 +283,46 @@ function merge(
target.icons = resolveIcons(source.icons) target.icons = resolveIcons(source.icons)
break break
} }
default: { case 'appleWebApp':
// TODO: Make sure the type is correct. target.appleWebApp = resolveAppleWebApp(source.appleWebApp)
break
case 'appLinks':
target.appLinks = resolveAppLinks(source.appLinks)
break
case 'robots': {
target.robots = resolveRobots(source.robots)
break
}
case 'archives':
case 'assets':
case 'bookmarks':
case 'keywords':
case 'authors': {
// FIXME: type inferring
// @ts-ignore // @ts-ignore
target[key] = source[key] target[key] = resolveAsArrayOrUndefined(source[key]) || null
break break
} }
// directly assign fields that fallback to null
case 'applicationName':
case 'description':
case 'generator':
case 'themeColor':
case 'creator':
case 'publisher':
case 'category':
case 'classification':
case 'referrer':
case 'colorScheme':
case 'itunes':
case 'alternates':
case 'formatDetection':
case 'other':
// @ts-ignore TODO: support inferring
target[key] = source[key] || null
break
default:
break
} }
} }
} }
......
...@@ -12,6 +12,16 @@ export type AppLinks = { ...@@ -12,6 +12,16 @@ export type AppLinks = {
windows_universal?: AppLinksWindows | Array<AppLinksWindows> windows_universal?: AppLinksWindows | Array<AppLinksWindows>
web?: AppLinksWeb | Array<AppLinksWeb> web?: AppLinksWeb | Array<AppLinksWeb>
} }
export type ResolvedAppLinks = {
ios?: Array<AppLinksApple>
iphone?: Array<AppLinksApple>
ipad?: Array<AppLinksApple>
android?: Array<AppLinksAndroid>
windows_phone?: Array<AppLinksWindows>
windows?: Array<AppLinksWindows>
windows_universal?: Array<AppLinksWindows>
web?: Array<AppLinksWeb>
}
export type AppLinksApple = { export type AppLinksApple = {
url: string | URL url: string | URL
app_store_id?: string | number app_store_id?: string | number
...@@ -68,6 +78,13 @@ export type AppleImageDescriptor = { ...@@ -68,6 +78,13 @@ export type AppleImageDescriptor = {
media?: string media?: string
} }
export type ResolvedAppleWebApp = {
capable: boolean
title?: string | null
startupImage?: AppleImageDescriptor[] | null
statusBarStyle?: 'default' | 'black' | 'black-translucent'
}
// Format Detection // Format Detection
// This is a poorly specified metadata export type that is supposed to // This is a poorly specified metadata export type that is supposed to
// control whether the device attempts to conver text that matches // control whether the device attempts to conver text that matches
......
...@@ -7,6 +7,8 @@ import type { ...@@ -7,6 +7,8 @@ import type {
AppLinks, AppLinks,
FormatDetection, FormatDetection,
ItunesApp, ItunesApp,
ResolvedAppleWebApp,
ResolvedAppLinks,
Viewport, Viewport,
} from './extra-types' } from './extra-types'
import type { import type {
...@@ -18,7 +20,9 @@ import type { ...@@ -18,7 +20,9 @@ import type {
IconURL, IconURL,
ReferrerEnum, ReferrerEnum,
ResolvedIcons, ResolvedIcons,
ResolvedVerification,
Robots, Robots,
ResolvedRobots,
TemplateString, TemplateString,
Verification, Verification,
} from './metadata-types' } from './metadata-types'
...@@ -38,7 +42,7 @@ export interface Metadata { ...@@ -38,7 +42,7 @@ export interface Metadata {
// Standard metadata names // Standard metadata names
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name
applicationName?: null | string | Array<string> applicationName?: null | string
authors?: null | Author | Array<Author> authors?: null | Author | Array<Author>
generator?: null | string generator?: null | string
// if you provide an array it will be flattened into a single tag with comma separation // if you provide an array it will be flattened into a single tag with comma separation
...@@ -54,7 +58,7 @@ export interface Metadata { ...@@ -54,7 +58,7 @@ export interface Metadata {
robots?: null | string | Robots robots?: null | string | Robots
// The canonical and alternate URLs for this location // The canonical and alternate URLs for this location
alternates: AlternateURLs alternates?: null | AlternateURLs
// Defaults to rel="icon" but the Icons type can be used // Defaults to rel="icon" but the Icons type can be used
// to get more specific about rel types // to get more specific about rel types
...@@ -140,10 +144,10 @@ export interface ResolvedMetadata { ...@@ -140,10 +144,10 @@ export interface ResolvedMetadata {
publisher: null | string publisher: null | string
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name#other_metadata_names // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name#other_metadata_names
robots: null | string robots: null | ResolvedRobots
// The canonical and alternate URLs for this location // The canonical and alternate URLs for this location
alternates: ResolvedAlternateURLs alternates: null | ResolvedAlternateURLs
// Defaults to rel="icon" but the Icons type can be used // Defaults to rel="icon" but the Icons type can be used
// to get more specific about rel types // to get more specific about rel types
...@@ -154,11 +158,11 @@ export interface ResolvedMetadata { ...@@ -154,11 +158,11 @@ export interface ResolvedMetadata {
twitter: null | ResolvedTwitterMetadata twitter: null | ResolvedTwitterMetadata
// common verification tokens // common verification tokens
verification: Verification verification: null | ResolvedVerification
// Apple web app metadata // Apple web app metadata
// https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html // https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html
appleWebApp: null | AppleWebApp appleWebApp: null | ResolvedAppleWebApp
// Should devices try to interpret various formats and make actionable links // Should devices try to interpret various formats and make actionable links
// out of them? The canonical example is telephone numbers on mobile that can // out of them? The canonical example is telephone numbers on mobile that can
...@@ -175,7 +179,7 @@ export interface ResolvedMetadata { ...@@ -175,7 +179,7 @@ export interface ResolvedMetadata {
abstract: null | string abstract: null | string
// Facebook AppLinks // Facebook AppLinks
appLinks: null | AppLinks appLinks: null | ResolvedAppLinks
// link rel properties // link rel properties
archives: null | Array<string> archives: null | Array<string>
...@@ -187,7 +191,7 @@ export interface ResolvedMetadata { ...@@ -187,7 +191,7 @@ export interface ResolvedMetadata {
classification: null | string classification: null | string
// Arbitrary name/value pairs // Arbitrary name/value pairs
other: { other: null | {
[name: string]: string | number | Array<string | number> [name: string]: string | number | Array<string | number>
} }
......
...@@ -45,7 +45,7 @@ export type ColorSchemeEnum = ...@@ -45,7 +45,7 @@ export type ColorSchemeEnum =
| 'dark light' | 'dark light'
| 'only light' | 'only light'
export type Robots = { type RobotsInfo = {
// all and none will be inferred from index/follow boolean options // all and none will be inferred from index/follow boolean options
index?: boolean index?: boolean
follow?: boolean follow?: boolean
...@@ -59,9 +59,15 @@ export type Robots = { ...@@ -59,9 +59,15 @@ export type Robots = {
nosnippet?: boolean nosnippet?: boolean
noimageindex?: boolean noimageindex?: boolean
nocache?: boolean nocache?: boolean
}
export type Robots = RobotsInfo & {
// if you want to specify an alternate robots just for google // if you want to specify an alternate robots just for google
googleBot?: string | Robots googleBot?: string | RobotsInfo
}
export type ResolvedRobots = {
basic: string | null
googleBot: string | null
} }
export type IconURL = string | URL export type IconURL = string | URL
...@@ -93,6 +99,14 @@ export type Verification = { ...@@ -93,6 +99,14 @@ export type Verification = {
} }
} }
export type ResolvedVerification = {
google?: null | (string | number)[]
yahoo?: null | (string | number)[]
other?: {
[name: string]: (string | number)[]
}
}
export type ResolvedIcons = { export type ResolvedIcons = {
icon?: IconDescriptor[] icon?: IconDescriptor[]
shortcut?: IconDescriptor[] shortcut?: IconDescriptor[]
......
// Reference: https://developer.twitter.com/en/docs/twitter-for-websites/cards/overview/markup
import type { AbsoluteTemplateString, TemplateString } from './metadata-types' import type { AbsoluteTemplateString, TemplateString } from './metadata-types'
export type Twitter = export type Twitter =
...@@ -13,8 +15,8 @@ type TwitterMetadata = { ...@@ -13,8 +15,8 @@ type TwitterMetadata = {
siteId?: string // id for account associated to the site itself siteId?: string // id for account associated to the site itself
creator?: string // username for the account associated to the creator of the content on the site creator?: string // username for the account associated to the creator of the content on the site
creatorId?: string // id for the account associated to the creator of the content on the site creatorId?: string // id for the account associated to the creator of the content on the site
title?: string | TemplateString
description?: string description?: string
title?: string | TemplateString
images?: TwitterImage | Array<TwitterImage> images?: TwitterImage | Array<TwitterImage>
} }
type TwitterSummary = TwitterMetadata & { type TwitterSummary = TwitterMetadata & {
...@@ -31,7 +33,7 @@ type TwitterApp = TwitterMetadata & { ...@@ -31,7 +33,7 @@ type TwitterApp = TwitterMetadata & {
card: 'app' card: 'app'
app: TwitterAppDescriptor app: TwitterAppDescriptor
} }
type TwitterAppDescriptor = { export type TwitterAppDescriptor = {
id: { id: {
iphone?: string | number iphone?: string | number
ipad?: string | number ipad?: string | number
...@@ -42,14 +44,14 @@ type TwitterAppDescriptor = { ...@@ -42,14 +44,14 @@ type TwitterAppDescriptor = {
ipad?: string | URL ipad?: string | URL
googleplay?: string | URL googleplay?: string | URL
} }
country?: string name?: string
} }
type TwitterImage = string | TwitterImageDescriptor | URL type TwitterImage = string | TwitterImageDescriptor | URL
type TwitterImageDescriptor = { type TwitterImageDescriptor = {
url: string | URL url: string | URL
secureUrl?: string | URL
alt?: string alt?: string
secureUrl?: string | URL
type?: string type?: string
width?: string | number width?: string | number
height?: string | number height?: string | number
...@@ -61,6 +63,26 @@ type TwitterPlayerDescriptor = { ...@@ -61,6 +63,26 @@ type TwitterPlayerDescriptor = {
height: number height: number
} }
export type ResolvedTwitterMetadata = Omit<TwitterMetadata, 'title'> & { type ResolvedTwitterImage = {
title: AbsoluteTemplateString | null url: string
alt?: string
}
type ResolvedTwitterSummary = {
site: string | null
siteId: string | null
creator: string | null
creatorId: string | null
description: string | null
title: AbsoluteTemplateString
images?: Array<ResolvedTwitterImage>
} }
type ResolvedTwitterPlayer = ResolvedTwitterSummary & {
players: Array<TwitterPlayerDescriptor>
}
type ResolvedTwitterApp = ResolvedTwitterSummary & { app: TwitterAppDescriptor }
export type ResolvedTwitterMetadata =
| ({ card: 'summary' } & ResolvedTwitterSummary)
| ({ card: 'summary_large_image' } & ResolvedTwitterSummary)
| ({ card: 'player' } & ResolvedTwitterPlayer)
| ({ card: 'app' } & ResolvedTwitterApp)
...@@ -6,6 +6,7 @@ import type { FontLoaderManifest } from '../build/webpack/plugins/font-loader-ma ...@@ -6,6 +6,7 @@ import type { FontLoaderManifest } from '../build/webpack/plugins/font-loader-ma
// Import builtin react directly to avoid require cache conflicts // Import builtin react directly to avoid require cache conflicts
import React, { use } from 'next/dist/compiled/react' import React, { use } from 'next/dist/compiled/react'
import { NotFound as DefaultNotFound } from '../client/components/error' import { NotFound as DefaultNotFound } from '../client/components/error'
import { nanoid } from 'next/dist/compiled/nanoid/index.cjs'
// 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
...@@ -45,9 +46,9 @@ import { ...@@ -45,9 +46,9 @@ import {
RSC, RSC,
} from '../client/components/app-router-headers' } from '../client/components/app-router-headers'
import type { StaticGenerationAsyncStorage } from '../client/components/static-generation-async-storage' import type { StaticGenerationAsyncStorage } from '../client/components/static-generation-async-storage'
import type { RequestAsyncStorage } from '../client/components/request-async-storage'
import { formatServerError } from '../lib/format-server-error' import { formatServerError } from '../lib/format-server-error'
import { Metadata } from '../lib/metadata/metadata' import { Metadata } from '../lib/metadata/metadata'
import type { RequestAsyncStorage } from '../client/components/request-async-storage'
import { runWithRequestAsyncStorage } from './run-with-request-async-storage' import { runWithRequestAsyncStorage } from './run-with-request-async-storage'
import { runWithStaticGenerationAsyncStorage } from './run-with-static-generation-async-storage' import { runWithStaticGenerationAsyncStorage } from './run-with-static-generation-async-storage'
...@@ -977,6 +978,8 @@ export async function renderToHTMLOrFlight( ...@@ -977,6 +978,8 @@ export async function renderToHTMLOrFlight(
* The metadata items array created in next-app-loader with all relevant information * The metadata items array created in next-app-loader with all relevant information
* that we need to resolve the final metadata. * that we need to resolve the final metadata.
*/ */
const requestId = nanoid(12)
const metadataItems = ComponentMod.metadata const metadataItems = ComponentMod.metadata
stripInternalQueries(query) stripInternalQueries(query)
...@@ -1708,8 +1711,9 @@ export async function renderToHTMLOrFlight( ...@@ -1708,8 +1711,9 @@ export async function renderToHTMLOrFlight(
isFirst: true, isFirst: true,
rscPayloadHead: ( rscPayloadHead: (
<> <>
{/* Adding key={requestId} to make metadata remount for each render */}
{/* @ts-expect-error allow to use async server component */} {/* @ts-expect-error allow to use async server component */}
<Metadata metadata={metadataItems} /> <Metadata key={requestId} metadata={metadataItems} />
{rscPayloadHead} {rscPayloadHead}
</> </>
), ),
...@@ -1807,8 +1811,9 @@ export async function renderToHTMLOrFlight( ...@@ -1807,8 +1811,9 @@ export async function renderToHTMLOrFlight(
initialTree={initialTree} initialTree={initialTree}
initialHead={ initialHead={
<> <>
{/* Adding key={requestId} to make metadata remount for each render */}
{/* @ts-expect-error allow to use async server component */} {/* @ts-expect-error allow to use async server component */}
<Metadata metadata={metadataItems} /> <Metadata key={requestId} metadata={metadataItems} />
{initialHead} {initialHead}
</> </>
} }
......
export default function Page() { export default function Page() {
return <p>hello</p> return 'hello'
} }
export const metadata = { export const metadata = {
......
export default function Page() {
return 'app links'
}
export const metadata = {
appLinks: {
ios: {
url: 'https://example.com/ios',
app_store_id: 'app_store_id',
},
android: {
package: 'com.example.android/package',
app_name: 'app_name_android',
},
web: {
should_fallback: true,
},
},
}
export default function page() {
return 'apple'
}
export const metadata = {
itunes: {
appId: 'myAppStoreID',
appArgument: 'myAppArgument',
},
appleWebApp: {
title: 'Apple Web App',
statusBarStyle: 'black-translucent',
startupImage: [
'/assets/startup/apple-touch-startup-image-768x1004.png',
{
url: '/assets/startup/apple-touch-startup-image-1536x2008.png',
media: '(device-width: 768px) and (device-height: 1024px)',
},
],
},
}
...@@ -22,4 +22,9 @@ export const metadata = { ...@@ -22,4 +22,9 @@ export const metadata = {
creator: 'shu', creator: 'shu',
publisher: 'vercel', publisher: 'vercel',
robots: 'index, follow', robots: 'index, follow',
formatDetection: {
email: 'no',
address: 'no',
telephone: 'no',
},
} }
export default function Page() { export default function Page() {
return <p>hello</p> return 'opengraph-article'
} }
export const metadata = { export const metadata = {
......
export default function Page() { export default function Page() {
return <p>hello</p> return 'opengraph'
} }
export const metadata = { export const metadata = {
......
import React from 'react'
import Link from 'next/link' import Link from 'next/link'
export default function Page() { export default function Page() {
......
export default function page() {
return 'robots'
}
export const metadata = {
robots: {
index: false,
follow: true,
nocache: true,
googleBot: {
index: true,
follow: false,
noimageindex: true,
},
},
}
export default function Page() { export default function Page() {
return <p>hello</p> return 'extra'
} }
export const metadata = { export const metadata = {
......
export default function Page() { export default function Page() {
return <p>hello</p> return 'title template'
} }
export const metadata = { export const metadata = {
......
import React from 'react'
import Link from 'next/link' import Link from 'next/link'
export default function Page() { export default function Page() {
......
export default function page() {
return 'twitter app'
}
export const metadata = {
twitter: {
card: 'app',
title: 'Twitter Title',
description: 'Twitter Description',
siteId: 'siteId',
creator: 'creator',
creatorId: 'creatorId',
images: [
'https://twitter.com/image-100x100.png',
'https://twitter.com/image-200x200.png',
],
app: {
name: 'twitter_app',
id: {
iphone: 'twitter_app://iphone',
ipad: 'twitter_app://ipad',
googleplay: 'twitter_app://googleplay',
},
url: {
iphone: 'https://iphone_url',
ipad: 'https://ipad_url',
},
},
},
}
export default function page() {
return 'twitter summary_large_image'
}
export const metadata = {
twitter: {
card: 'summary_large_image',
title: 'Twitter Title',
description: 'Twitter Description',
siteId: 'siteId',
creator: 'creator',
creatorId: 'creatorId',
images: {
url: 'https://twitter.com/image.png',
alt: 'image-alt',
},
},
}
export default function page() {
return 'twitter summary'
}
export const metadata = {
twitter: {
title: 'Twitter Title',
description: 'Twitter Description',
siteId: 'siteId',
creator: 'creator',
creatorId: 'creatorId',
images: 'https://twitter.com/image.png',
},
}
export default function page() {
return 'twitter player'
}
export const metadata = {
twitter: {
card: 'player',
title: 'Twitter Title',
description: 'Twitter Description',
siteId: 'siteId',
creator: 'creator',
creatorId: 'creatorId',
images: 'https://twitter.com/image.png',
players: {
playerUrl: 'https://twitter.com/player',
streamUrl: 'https://twitter.com/stream',
width: 100,
height: 100,
},
},
}
export default function Page() { export default function Page() {
return <p>viewport</p> return 'viewport'
} }
export const metadata = { export const metadata = {
......
This diff is collapsed.
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