/
flight-client-entry-plugin.ts
211 lines (188 loc) · 6.75 KB
/
flight-client-entry-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
import { stringify } from 'querystring'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import {
EDGE_RUNTIME_WEBPACK,
NEXT_CLIENT_SSR_ENTRY_SUFFIX,
} from '../../../shared/lib/constants'
import { clientComponentRegex } from '../loaders/utils'
import { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path'
import { denormalizePagePath } from '../../../shared/lib/page-path/denormalize-page-path'
import {
getInvalidator,
entries,
} from '../../../server/dev/on-demand-entry-handler'
import { getPageStaticInfo } from '../../analysis/get-page-static-info'
import { SERVER_RUNTIME } from '../../../lib/constants'
type Options = {
dev: boolean
isEdgeServer: boolean
}
const PLUGIN_NAME = 'ClientEntryPlugin'
export const injectedClientEntries = new Map()
const regexCSS = /\.css$/
export class FlightClientEntryPlugin {
dev: boolean = false
isEdgeServer: boolean
constructor(options: Options) {
if (typeof options.dev === 'boolean') {
this.dev = options.dev
}
this.isEdgeServer = options.isEdgeServer
}
apply(compiler: webpack5.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.finishMake.tapPromise(PLUGIN_NAME, (compilation) => {
return this.createClientEndpoints(compilation)
})
}
async createClientEndpoints(compilation: any) {
const context = (this as any).context
const promises: Array<Promise<void>> = []
// For each SC server compilation entry, we need to create its corresponding
// client component entry.
for (const [name, entry] of compilation.entries.entries()) {
// Check if the page entry is a server component or not.
const entryDependency = entry.dependencies?.[0]
const request = entryDependency?.request
if (request && entry.options?.layer === 'sc_server') {
const visited = new Set()
const clientComponentImports: string[] = []
function filterClientComponents(dependency: any) {
const mod = compilation.moduleGraph.getResolvedModule(dependency)
if (!mod) return
// Keep client imports as simple
// native or installed js module: -> raw request, e.g. next/head
// client js or css: -> user request
const rawRequest = mod.rawRequest || ''
const modRequest =
!rawRequest.endsWith('.css') &&
!rawRequest.startsWith('.') &&
!rawRequest.startsWith('/')
? rawRequest
: mod.resourceResolveData?.path
if (!modRequest || visited.has(modRequest)) return
visited.add(modRequest)
if (
clientComponentRegex.test(modRequest) ||
regexCSS.test(modRequest)
) {
clientComponentImports.push(modRequest)
}
compilation.moduleGraph
.getOutgoingConnections(mod)
.forEach((connection: any) => {
filterClientComponents(connection.dependency)
})
}
// Traverse the module graph to find all client components.
filterClientComponents(entryDependency)
const entryModule =
compilation.moduleGraph.getResolvedModule(entryDependency)
const routeInfo = entryModule.buildInfo.route || {
page: denormalizePagePath(name.replace(/^pages/, '')),
absolutePagePath: entryModule.resource,
}
// Parse gSSP and gSP exports from the page source.
const pageStaticInfo = this.isEdgeServer
? {}
: await getPageStaticInfo({
pageFilePath: routeInfo.absolutePagePath,
nextConfig: {},
isDev: this.dev,
})
const loaderOptions = {
modules: clientComponentImports,
runtime: this.isEdgeServer
? SERVER_RUNTIME.edge
: SERVER_RUNTIME.nodejs,
ssr: pageStaticInfo.ssr,
// Adding name here to make the entry key unique.
name,
}
const clientLoader = `next-flight-client-entry-loader?${stringify(
loaderOptions
)}!`
const clientSSRLoader = `next-flight-client-entry-loader?${stringify({
...loaderOptions,
server: true,
})}!`
const bundlePath = 'app' + normalizePagePath(routeInfo.page)
// Inject the entry to the client compiler.
if (this.dev) {
const pageKey = 'client' + routeInfo.page
if (!entries[pageKey]) {
entries[pageKey] = {
bundlePath,
absolutePagePath: routeInfo.absolutePagePath,
clientLoader,
dispose: false,
lastActiveTime: Date.now(),
} as any
const invalidator = getInvalidator()
if (invalidator) {
invalidator.invalidate()
}
}
} else {
injectedClientEntries.set(
bundlePath,
`next-client-pages-loader?${stringify({
isServerComponent: true,
page: denormalizePagePath(bundlePath.replace(/^pages/, '')),
absolutePagePath: clientLoader,
})}!` + clientLoader
)
}
// Inject the entry to the server compiler (__sc_client__).
const clientComponentEntryDep = (
webpack as any
).EntryPlugin.createDependency(clientSSRLoader, {
name: name + NEXT_CLIENT_SSR_ENTRY_SUFFIX,
})
promises.push(
new Promise<void>((res, rej) => {
compilation.addEntry(
context,
clientComponentEntryDep,
this.isEdgeServer
? {
name: name + NEXT_CLIENT_SSR_ENTRY_SUFFIX,
library: {
name: ['self._CLIENT_ENTRY'],
type: 'assign',
},
runtime: EDGE_RUNTIME_WEBPACK,
asyncChunks: false,
}
: {
name: name + NEXT_CLIENT_SSR_ENTRY_SUFFIX,
runtime: 'webpack-runtime',
},
(err: any) => {
if (err) {
rej(err)
} else {
res()
}
}
)
})
)
}
}
await Promise.all(promises)
}
}