-
Notifications
You must be signed in to change notification settings - Fork 26k
/
next-flight-server-loader.ts
283 lines (253 loc) · 8.24 KB
/
next-flight-server-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
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
import { builtinModules } from 'module'
import { parse } from '../../swc'
import {
buildExports,
clientComponentRegex,
serverComponentRegex,
isNextBuiltinClientComponent,
} from './utils'
function createFlightServerRequest(
request: string,
options?: { client: 1 | undefined }
) {
return `next-flight-server-loader${
options ? '?' + JSON.stringify(options) : ''
}!${request}`
}
function hasFlightLoader(request: string, type: 'client' | 'server') {
return request.includes(`next-flight-${type}-loader`)
}
async function parseModuleInfo({
resourcePath,
source,
isClientCompilation,
resolver,
}: {
resourcePath: string
source: string
isClientCompilation: boolean
resolver: (req: string) => Promise<string>
}): Promise<{
source: string
imports: string[]
isEsm: boolean
__N_SSP: boolean
pageRuntime: 'edge' | 'nodejs' | null
}> {
const ast = await parse(source, {
filename: resourcePath,
isModule: 'unknown',
})
const { type, body } = ast
const beginPos = ast.span.start
let transformedSource = ''
let lastIndex = 0
let imports = []
let __N_SSP = false
let pageRuntime = null
let isBuiltinModule
let isNodeModuleImport
const isEsm = type === 'Module'
async function getModuleType(path: string) {
const isBuiltinModule_ = builtinModules.includes(path)
const resolvedPath = isBuiltinModule_ ? path : await resolver(path)
const isNodeModuleImport_ =
/[\\/]node_modules[\\/]/.test(resolvedPath) &&
// exclude next built-in modules
!isNextBuiltinClientComponent(resolvedPath)
return [isBuiltinModule_, isNodeModuleImport_] as const
}
function addClientImport(path: string) {
if (serverComponentRegex.test(path) || hasFlightLoader(path, 'server')) {
// If it's a server component, we recursively import its dependencies.
imports.push(path)
} else if (clientComponentRegex.test(path)) {
// Client component.
imports.push(path)
} else {
// Shared component.
imports.push(createFlightServerRequest(path, { client: 1 }))
}
}
for (let i = 0; i < body.length; i++) {
const node = body[i]
switch (node.type) {
case 'ImportDeclaration':
const importSource = node.source.value
;[isBuiltinModule, isNodeModuleImport] = await getModuleType(
importSource
)
// matching node_module package but excluding react cores since react is required to be shared
const isReactImports = [
'react',
'react/jsx-runtime',
'react/jsx-dev-runtime',
].includes(importSource)
if (!isClientCompilation) {
// Server compilation for .server.js.
if (serverComponentRegex.test(importSource)) {
continue
}
const importDeclarations = source.substring(
lastIndex,
node.source.span.start - beginPos
)
if (clientComponentRegex.test(importSource)) {
transformedSource += importDeclarations
transformedSource += JSON.stringify(
`next-flight-client-loader!${importSource}`
)
imports.push(importSource)
} else {
// A shared component. It should be handled as a server component.
const serverImportSource =
isReactImports || isBuiltinModule
? importSource
: createFlightServerRequest(importSource)
transformedSource += importDeclarations
transformedSource += JSON.stringify(serverImportSource)
// TODO: support handling RSC components from node_modules
if (!isNodeModuleImport) {
imports.push(importSource)
}
}
} else {
// For now we assume there is no .client.js inside node_modules.
// TODO: properly handle this.
if (isNodeModuleImport || isBuiltinModule) continue
addClientImport(importSource)
}
lastIndex = node.source.span.end - beginPos
break
case 'ExportDeclaration':
if (isClientCompilation) {
// Keep `__N_SSG` and `__N_SSP` exports.
if (node.declaration?.type === 'VariableDeclaration') {
for (const declaration of node.declaration.declarations) {
if (declaration.type === 'VariableDeclarator') {
if (declaration.id?.type === 'Identifier') {
const value = declaration.id.value
if (value === '__N_SSP') {
__N_SSP = true
} else if (value === 'config') {
const props = declaration.init.properties
const runtimeKeyValue = props.find(
(prop: any) => prop.key.value === 'runtime'
)
const runtime = runtimeKeyValue?.value?.value
if (runtime === 'nodejs' || runtime === 'edge') {
pageRuntime = runtime
}
}
}
}
}
}
}
break
case 'ExportNamedDeclaration':
if (isClientCompilation) {
if (node.source) {
// export { ... } from '...'
const path = node.source.value
;[isBuiltinModule, isNodeModuleImport] = await getModuleType(path)
if (!isBuiltinModule && !isNodeModuleImport) {
addClientImport(path)
}
}
}
break
default:
break
}
}
if (!isClientCompilation) {
transformedSource += source.substring(lastIndex)
}
return { source: transformedSource, imports, isEsm, __N_SSP, pageRuntime }
}
export default async function transformSource(
this: any,
source: string
): Promise<string> {
const { client: isClientCompilation } = this.getOptions()
const { resourcePath, resolve: resolveFn, context } = this
const resolver = (req: string): Promise<string> => {
return new Promise((resolve, reject) => {
resolveFn(context, req, (err: any, result: string) => {
if (err) return reject(err)
resolve(result)
})
})
}
if (typeof source !== 'string') {
throw new Error('Expected source to have been transformed to a string.')
}
const hasAppliedFlightServerLoader = this.loaders.some((loader: any) => {
return hasFlightLoader(loader.path, 'server')
})
const isServerExt = serverComponentRegex.test(resourcePath)
if (!isClientCompilation) {
// We only apply the loader to server components, or shared components that
// are imported by a server component.
if (!isServerExt && !hasAppliedFlightServerLoader) {
return source
}
}
const {
source: transformedSource,
imports,
isEsm,
__N_SSP,
pageRuntime,
} = await parseModuleInfo({
resourcePath,
source,
isClientCompilation,
resolver,
})
/**
* For .server.js files, we handle this loader differently.
*
* Server compilation output:
* (The content of the Server Component module will be kept.)
* export const __next_rsc__ = { __webpack_require__, _: () => { ... }, server: true }
*
* Client compilation output:
* (The content of the Server Component module will be removed.)
* export const __next_rsc__ = { __webpack_require__, _: () => { ... }, server: false }
*/
const rscExports: any = {
__next_rsc__: `{
__webpack_require__,
_: () => {
${imports
.map(
(importSource) =>
`import(/* webpackMode: "eager" */ ${JSON.stringify(
importSource
)});`
)
.join('\n')}
},
server: ${isServerExt ? 'true' : 'false'}
}`,
}
if (isClientCompilation) {
rscExports.default = 'function RSC() {}'
if (pageRuntime === 'edge') {
// Currently for the Edge runtime, we treat all RSC pages as SSR pages.
rscExports.__N_SSP = 'true'
} else {
if (__N_SSP) {
rscExports.__N_SSP = 'true'
} else {
// Server component pages are always considered as SSG by default because
// the flight data is needed for client navigation.
rscExports.__N_SSG = 'true'
}
}
}
const output = transformedSource + '\n' + buildExports(rscExports, isEsm)
return output
}