-
Notifications
You must be signed in to change notification settings - Fork 26.8k
/
flight-manifest-plugin.ts
329 lines (289 loc) · 10.4 KB
/
flight-manifest-plugin.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { FLIGHT_MANIFEST } from '../../../shared/lib/constants'
import { clientComponentRegex } from '../loaders/utils'
import { relative } from 'path'
// This is the module that will be used to anchor all client references to.
// I.e. it will have all the client files as async deps from this point on.
// We use the Flight client implementation because you can't get to these
// without the client runtime so it's the first time in the loading sequence
// you might want them.
// const clientFileName = require.resolve('../');
interface Options {
dev: boolean
appDir: boolean
pageExtensions: string[]
}
/**
* Webpack module id
*/
// TODO-APP ensure `null` is included as it is used.
type ModuleId = string | number /*| null*/
export type ManifestChunks = Array<`${string}:${string}` | string>
interface ManifestNode {
[moduleExport: string]: {
/**
* Webpack module id
*/
id: ModuleId
/**
* Export name
*/
name: string
/**
* Chunks for the module. JS and CSS.
*/
chunks: ManifestChunks
}
}
export type FlightManifest = {
__ssr_module_mapping__: {
[moduleId: string]: ManifestNode
}
} & {
[modulePath: string]: ManifestNode
}
export type FlightCSSManifest = {
[modulePath: string]: string[]
}
const PLUGIN_NAME = 'FlightManifestPlugin'
export class FlightManifestPlugin {
dev: Options['dev'] = false
pageExtensions: Options['pageExtensions']
appDir: Options['appDir'] = false
constructor(options: Options) {
this.dev = options.dev
this.appDir = options.appDir
this.pageExtensions = options.pageExtensions
}
apply(compiler: webpack.Compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(
(webpack as any).dependencies.ModuleDependency,
normalModuleFactory
)
compilation.dependencyTemplates.set(
(webpack as any).dependencies.ModuleDependency,
new (webpack as any).dependencies.NullDependency.Template()
)
}
)
compiler.hooks.make.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
// Have to be in the optimize stage to run after updating the CSS
// asset hash via extract mini css plugin.
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH,
},
(assets) => this.createAsset(assets, compilation, compiler.context)
)
})
}
createAsset(
assets: webpack.Compilation['assets'],
compilation: webpack.Compilation,
context: string
) {
const manifest: FlightManifest = {
__ssr_module_mapping__: {},
}
const appDir = this.appDir
const dev = this.dev
compilation.chunkGroups.forEach((chunkGroup) => {
function recordModule(
chunk: webpack.Chunk,
id: ModuleId,
mod: webpack.NormalModule
) {
// if appDir is enabled we shouldn't process chunks from
// the pages dir
if (chunk.name?.startsWith('pages/') && appDir) {
return
}
const isCSSModule =
mod.type === 'css/mini-extract' ||
(mod.loaders &&
(dev
? mod.loaders.some((item) =>
item.loader.includes('next-style-loader/index.js')
)
: mod.loaders.some((item) =>
item.loader.includes('mini-css-extract-plugin/loader.js')
)))
const resource =
mod.type === 'css/mini-extract'
? // @ts-expect-error TODO: use `identifier()` instead.
mod._identifier.slice(mod._identifier.lastIndexOf('!') + 1)
: mod.resource
if (!resource) return
const moduleExports = manifest[resource] || {}
const moduleIdMapping = manifest.__ssr_module_mapping__
// Note that this isn't that reliable as webpack is still possible to assign
// additional queries to make sure there's no conflict even using the `named`
// module ID strategy.
let ssrNamedModuleId = relative(
context,
mod.resourceResolveData?.path || resource
)
if (!ssrNamedModuleId.startsWith('.'))
// TODO use getModuleId instead
ssrNamedModuleId = `./${ssrNamedModuleId.replace(/\\/g, '/')}`
if (isCSSModule) {
if (!manifest[resource]) {
const chunks = [...chunk.files].filter((f) => f.endsWith('.css'))
manifest[resource] = {
default: {
id,
name: 'default',
chunks,
},
}
moduleIdMapping[id] = moduleIdMapping[id] || {}
moduleIdMapping[id]['default'] = {
id: ssrNamedModuleId,
name: 'default',
chunks,
}
manifest.__ssr_module_mapping__ = moduleIdMapping
}
return
}
// TODO: Hook into deps instead of the target module.
// That way we know by the type of dep whether to include.
// It also resolves conflicts when the same module is in multiple chunks.
if (!clientComponentRegex.test(resource)) {
return
}
const exportsInfo = compilation.moduleGraph.getExportsInfo(mod)
const cjsExports = [
...new Set([
...mod.dependencies.map((dep) => {
// Match CommonJsSelfReferenceDependency
if (dep.type === 'cjs self exports reference') {
// @ts-expect-error: TODO: Fix Dependency type
if (dep.base === 'module.exports') {
return 'default'
}
// `exports.foo = ...`, `exports.default = ...`
// @ts-expect-error: TODO: Fix Dependency type
if (dep.base === 'exports') {
// @ts-expect-error: TODO: Fix Dependency type
return dep.names.filter((name: any) => name !== '__esModule')
}
}
return null
}),
]),
]
const moduleExportedKeys = ['', '*']
.concat(
[...exportsInfo.exports]
.filter((exportInfo) => exportInfo.provided)
.map((exportInfo) => exportInfo.name),
...cjsExports
)
.filter((name) => name !== null)
// Get all CSS files imported from the module's dependencies.
const visitedModule = new Set()
const cssChunks: Set<string> = new Set()
function collectClientImportedCss(module: any) {
if (!module) return
const modRequest = module.userRequest
if (visitedModule.has(modRequest)) return
visitedModule.add(modRequest)
if (/\.css$/.test(modRequest)) {
// collect relative imported css chunks
compilation.chunkGraph.getModuleChunks(module).forEach((c) => {
;[...c.files]
.filter((file) => file.endsWith('.css'))
.forEach((file) => cssChunks.add(file))
})
}
const connections = Array.from(
compilation.moduleGraph.getOutgoingConnections(module)
)
connections.forEach((connection) => {
collectClientImportedCss(
compilation.moduleGraph.getResolvedModule(connection.dependency!)
)
})
}
collectClientImportedCss(mod)
moduleExportedKeys.forEach((name) => {
let requiredChunks: ManifestChunks = []
if (!moduleExports[name]) {
const isRelatedChunk = (c: webpack.Chunk) =>
// If current chunk is a page, it should require the related page chunk;
// If current chunk is a component, it should filter out the related page chunk;
chunk.name?.startsWith('pages/') || !c.name?.startsWith('pages/')
if (appDir) {
requiredChunks = chunkGroup.chunks
.filter(isRelatedChunk)
.map((requiredChunk: webpack.Chunk) => {
return (
requiredChunk.id +
':' +
(requiredChunk.name || requiredChunk.id) +
(dev ? '' : '-' + requiredChunk.hash)
)
})
}
moduleExports[name] = {
id,
name,
chunks: requiredChunks.concat([...cssChunks]),
}
}
moduleIdMapping[id] = moduleIdMapping[id] || {}
if (!moduleIdMapping[id][name]) {
moduleIdMapping[id][name] = {
...moduleExports[name],
id: ssrNamedModuleId,
}
}
})
manifest[resource] = moduleExports
manifest.__ssr_module_mapping__ = moduleIdMapping
}
chunkGroup.chunks.forEach((chunk: webpack.Chunk) => {
const chunkModules = compilation.chunkGraph.getChunkModulesIterable(
chunk
// TODO: Update type so that it doesn't have to be cast.
) as Iterable<webpack.NormalModule>
for (const mod of chunkModules) {
const modId = compilation.chunkGraph.getModuleId(mod)
recordModule(chunk, modId, mod)
// If this is a concatenation, register each child to the parent ID.
// TODO: remove any
const anyModule = mod as any
if (anyModule.modules) {
anyModule.modules.forEach((concatenatedMod: any) => {
recordModule(chunk, modId, concatenatedMod)
})
}
}
})
})
const file = 'server/' + FLIGHT_MANIFEST
const json = JSON.stringify(manifest)
assets[file + '.js'] = new sources.RawSource(
'self.__RSC_MANIFEST=' + json
// Work around webpack 4 type of RawSource being used
// TODO: use webpack 5 type by default
) as unknown as webpack.sources.RawSource
assets[file + '.json'] = new sources.RawSource(
json
// Work around webpack 4 type of RawSource being used
// TODO: use webpack 5 type by default
) as unknown as webpack.sources.RawSource
}
}