-
Notifications
You must be signed in to change notification settings - Fork 27.3k
/
next-metadata-image-loader.ts
204 lines (180 loc) · 6.42 KB
/
next-metadata-image-loader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/*
* This loader is responsible for extracting the metadata image info for rendering in html
*/
import type webpack from 'webpack'
import type {
MetadataImageModule,
PossibleImageFileNameConvention,
} from './metadata/types'
import fs from 'fs/promises'
import path from 'path'
import loaderUtils from 'next/dist/compiled/loader-utils3'
import { getImageSize } from '../../../server/image-optimizer'
import { imageExtMimeTypeMap } from '../../../lib/mime-type'
import { fileExists } from '../../../lib/file-exists'
import { WEBPACK_RESOURCE_QUERIES } from '../../../lib/constants'
import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'
interface Options {
segment: string
type: PossibleImageFileNameConvention
pageExtensions: string[]
basePath: string
}
async function nextMetadataImageLoader(this: any, content: Buffer) {
const options: Options = this.getOptions()
const { type, segment, pageExtensions, basePath } = options
const { resourcePath, rootContext: context } = this
const { name: fileNameBase, ext } = path.parse(resourcePath)
const useNumericSizes = type === 'twitter' || type === 'openGraph'
let extension = ext.slice(1)
if (extension === 'jpg') {
extension = 'jpeg'
}
const opts = { context, content }
// No hash query for favicon.ico
const contentHash =
type === 'favicon'
? ''
: loaderUtils.interpolateName(this, '[contenthash]', opts)
const interpolatedName = loaderUtils.interpolateName(
this,
'[name].[ext]',
opts
)
const isDynamicResource = pageExtensions.includes(extension)
const pageSegment = isDynamicResource ? fileNameBase : interpolatedName
const hashQuery = contentHash ? '?' + contentHash : ''
const pathnamePrefix = normalizePathSep(path.join(basePath, segment))
if (isDynamicResource) {
const mod = await new Promise<webpack.NormalModule>((res, rej) => {
this.loadModule(
resourcePath,
(err: null | Error, _source: any, _sourceMap: any, module: any) => {
if (err) {
return rej(err)
}
res(module)
}
)
})
const exportedFieldsExcludingDefault =
mod.dependencies
?.filter((dep) => {
return (
[
'HarmonyExportImportedSpecifierDependency',
'HarmonyExportSpecifierDependency',
].includes(dep.constructor.name) &&
'name' in dep &&
dep.name !== 'default'
)
})
.map((dep: any) => {
return dep.name
}) || []
// re-export and spread as `exportedImageData` to avoid non-exported error
return `\
import {
${exportedFieldsExcludingDefault
.map((field) => `${field} as _${field}`)
.join(',')}
} from ${JSON.stringify(
// This is an arbitrary resource query to ensure it's a new request, instead
// of sharing the same module with next-metadata-route-loader.
// Since here we only need export fields such as `size`, `alt` and
// `generateImageMetadata`, avoid sharing the same module can make this entry
// smaller.
resourcePath + '?' + WEBPACK_RESOURCE_QUERIES.metadataImageMeta
)}
import { fillMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route'
const imageModule = {
${exportedFieldsExcludingDefault
.map((field) => `${field}: _${field}`)
.join(',')}
}
export default async function (props) {
const { __metadata_id__: _, ...params } = props.params
const imageUrl = fillMetadataSegment(${JSON.stringify(
pathnamePrefix
)}, params, ${JSON.stringify(pageSegment)})
const { generateImageMetadata } = imageModule
function getImageMetadata(imageMetadata, idParam) {
const data = {
alt: imageMetadata.alt,
type: imageMetadata.contentType || 'image/png',
url: imageUrl + (idParam ? ('/' + idParam) : '') + ${JSON.stringify(
hashQuery
)},
}
const { size } = imageMetadata
if (size) {
${
type === 'twitter' || type === 'openGraph'
? 'data.width = size.width; data.height = size.height;'
: 'data.sizes = size.width + "x" + size.height;'
}
}
return data
}
if (generateImageMetadata) {
const imageMetadataArray = await generateImageMetadata({ params })
return imageMetadataArray.map((imageMetadata, index) => {
const idParam = (imageMetadata.id || index) + ''
return getImageMetadata(imageMetadata, idParam)
})
} else {
return [getImageMetadata(imageModule, '')]
}
}`
}
const imageSize: { width?: number; height?: number } = await getImageSize(
content,
extension as 'avif' | 'webp' | 'png' | 'jpeg'
).catch((err) => err)
if (imageSize instanceof Error) {
const err = imageSize
err.name = 'InvalidImageFormatError'
throw err
}
const imageData: Omit<MetadataImageModule, 'url'> = {
...(extension in imageExtMimeTypeMap && {
type: imageExtMimeTypeMap[extension as keyof typeof imageExtMimeTypeMap],
}),
...(useNumericSizes && imageSize.width != null && imageSize.height != null
? imageSize
: {
sizes:
// For SVGs, skip sizes and use "any" to let it scale automatically based on viewport,
// For the images doesn't provide the size properly, use "any" as well.
// If the size is presented, use the actual size for the image.
extension !== 'svg' &&
imageSize.width != null &&
imageSize.height != null
? `${imageSize.width}x${imageSize.height}`
: 'any',
}),
}
if (type === 'openGraph' || type === 'twitter') {
const altPath = path.join(
path.dirname(resourcePath),
fileNameBase + '.alt.txt'
)
if (await fileExists(altPath)) {
imageData.alt = await fs.readFile(altPath, 'utf8')
}
}
return `\
import { fillMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route'
export default (props) => {
const imageData = ${JSON.stringify(imageData)}
const imageUrl = fillMetadataSegment(${JSON.stringify(
pathnamePrefix
)}, props.params, ${JSON.stringify(pageSegment)})
return [{
...imageData,
url: imageUrl + ${JSON.stringify(type === 'favicon' ? '' : hashQuery)},
}]
}`
}
export const raw = true
export default nextMetadataImageLoader