-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
bundle-webpack.ts
279 lines (261 loc) · 9.05 KB
/
bundle-webpack.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
/* eslint-disable @typescript-eslint/naming-convention */
import * as path from "path"
import * as fs from "fs-extra"
import webpack, { Module, NormalModule, Compilation } from "webpack"
import ConcatenatedModule from "webpack/lib/optimize/ConcatenatedModule"
import { printQueryEnginePlugins } from "./print-plugins"
import mod from "module"
import { WebpackLoggingPlugin } from "../../utils/webpack/plugins/webpack-logging"
import reporter from "gatsby-cli/lib/reporter"
import { schemaCustomizationAPIs } from "./print-plugins"
import type { GatsbyNodeAPI } from "../../redux/types"
import * as nodeApis from "../../utils/api-node-docs"
type Reporter = typeof reporter
const extensions = [`.mjs`, `.js`, `.json`, `.node`, `.ts`, `.tsx`]
const outputDir = path.join(process.cwd(), `.cache`, `query-engine`)
const cacheLocation = path.join(
process.cwd(),
`.cache`,
`webpack`,
`query-engine`
)
function getApisToRemoveForQueryEngine(): Array<GatsbyNodeAPI> {
const apisToKeep = new Set(schemaCustomizationAPIs)
apisToKeep.add(`onPluginInit`)
const apisToRemove = (Object.keys(nodeApis) as Array<GatsbyNodeAPI>).filter(
api => !apisToKeep.has(api)
)
return apisToRemove
}
export async function createGraphqlEngineBundle(
rootDir: string,
reporter: Reporter,
isVerbose?: boolean
): Promise<webpack.Compilation | undefined> {
const schemaSnapshotString = await fs.readFile(
path.join(rootDir, `.cache`, `schema.gql`),
`utf-8`
)
await printQueryEnginePlugins()
const assetRelocatorUseEntry = {
loader: require.resolve(`@vercel/webpack-asset-relocator-loader`),
options: {
outputAssetBase: `assets`,
},
}
const gatsbyPluginTSRequire = mod.createRequire(
require.resolve(`gatsby-plugin-typescript`)
)
const compiler = webpack({
name: `Query Engine`,
// mode: `production`,
mode: `none`,
entry: path.join(__dirname, `entry.js`),
output: {
path: outputDir,
filename: `index.js`,
libraryTarget: `commonjs`,
},
target: `node`,
externalsPresets: {
node: false,
},
cache: {
type: `filesystem`,
name: `graphql-engine`,
cacheLocation,
buildDependencies: {
config: [__filename],
},
},
// those are required in some runtime paths, but we don't need them
externals: [
`cbor-x`, // optional dep of lmdb-store, but we are using `msgpack` (default) encoding, so we don't need it
`babel-runtime/helpers/asyncToGenerator`, // undeclared dep of yurnalist (but used in code path we don't use)
`electron`, // :shrug: `got` seems to have electron specific code path
mod.builtinModules.reduce((acc, builtinModule) => {
if (builtinModule === `fs`) {
acc[builtinModule] = `global _actualFsWrapper`
acc[`node:${builtinModule}`] = `global _actualFsWrapper`
} else {
acc[builtinModule] = `commonjs ${builtinModule}`
acc[`node:${builtinModule}`] = `commonjs ${builtinModule}`
}
return acc
}, {}),
],
module: {
rules: [
{
oneOf: [
{
// specific set of loaders for LMBD - our custom patch to massage lmdb to work with relocator -> relocator
test: /node_modules[/\\]lmdb[/\\].*\.[cm]?js/,
// it is recommended for Node builds to turn off AMD support
parser: { amd: false },
use: [
assetRelocatorUseEntry,
{
loader: require.resolve(`./lmdb-bundling-patch`),
},
],
},
{
// specific set of loaders for gatsby-node files - our babel transform that removes lifecycles not needed for engine -> relocator
test: /gatsby-node\.(cjs|mjs|js|ts)$/,
// it is recommended for Node builds to turn off AMD support
parser: { amd: false },
use: [
assetRelocatorUseEntry,
{
loader: require.resolve(
`../../utils/webpack/loaders/webpack-remove-exports-loader`
),
options: {
remove: getApisToRemoveForQueryEngine(),
jsx: false,
},
},
],
},
{
// generic loader for all other cases than lmdb or gatsby-node - we don't do anything special other than using relocator on it
// For node binary relocations, include ".node" files as well here
test: /\.(cjs|mjs|js|ts|node)$/,
// it is recommended for Node builds to turn off AMD support
parser: { amd: false },
use: assetRelocatorUseEntry,
},
],
},
{
test: /\.ts$/,
exclude: /node_modules/,
use: {
loader: require.resolve(`babel-loader`),
options: {
presets: [
gatsbyPluginTSRequire.resolve(`@babel/preset-typescript`),
],
},
},
},
{
test: /\.m?js$/,
type: `javascript/auto`,
resolve: {
byDependency: {
esm: {
fullySpecified: false,
},
},
},
},
{
test: /\.txt/,
type: `asset/resource`,
},
{
test: /\.(graphqls?|gqls?)$/,
use: {
loader: require.resolve(`graphql-tag/loader`),
},
},
],
},
resolve: {
extensions,
alias: {
".cache": process.cwd() + `/.cache/`,
[require.resolve(`gatsby-cli/lib/reporter/loggers/ink/index.js`)]:
false,
inquirer: false,
// only load one version of lmdb
lmdb: require.resolve(`lmdb`),
"ts-node": require.resolve(`./shims/ts-node`),
"gatsby-sharp$": require.resolve(`./shims/gatsby-sharp`),
"graphql-import-node$": require.resolve(`./shims/no-op-module`),
"graphql-import-node/register$":
require.resolve(`./shims/no-op-module`),
},
},
plugins: [
new webpack.EnvironmentPlugin([`GATSBY_CLOUD_IMAGE_CDN`]),
new webpack.DefinePlugin({
// "process.env.GATSBY_LOGGER": JSON.stringify(`yurnalist`),
"process.env.GATSBY_SKIP_WRITING_SCHEMA_TO_FILE": `true`,
"process.env.NODE_ENV": JSON.stringify(`production`),
SCHEMA_SNAPSHOT: JSON.stringify(schemaSnapshotString),
"process.env.GATSBY_LOGGER": JSON.stringify(`yurnalist`),
"process.env.GATSBY_SLICES": JSON.stringify(
!!process.env.GATSBY_SLICES
),
}),
process.env.GATSBY_WEBPACK_LOGGING?.includes(`query-engine`) &&
new WebpackLoggingPlugin(rootDir, reporter, isVerbose),
].filter(Boolean) as Array<webpack.WebpackPluginInstance>,
})
return new Promise((resolve, reject) => {
compiler.run((err, stats): void => {
function getResourcePath(
webpackModule?: Module | NormalModule | ConcatenatedModule | null
): string | undefined {
if (webpackModule && !(webpackModule instanceof ConcatenatedModule)) {
return (webpackModule as NormalModule).resource
}
if (webpackModule?.modules) {
// ConcatenatedModule is a collection of modules so we have to go deeper to actually get a path,
// at this point we won't know which one so we just grab first module here
const [firstSubModule] = webpackModule.modules
return getResourcePath(firstSubModule)
}
return undefined
}
function iterateModules(
webpackModules: Set<Module>,
compilation: Compilation
): void {
for (const webpackModule of webpackModules) {
if (webpackModule instanceof ConcatenatedModule) {
iterateModules(
(webpackModule as ConcatenatedModule).modules,
compilation
)
} else {
const resourcePath = getResourcePath(webpackModule)
if (resourcePath?.includes(`ts-node`)) {
const importedBy = getResourcePath(
compilation.moduleGraph.getIssuer(webpackModule)
)
const structuredError = {
id: `98011`,
context: {
package: `ts-node`,
importedBy,
advisory: `Gatsby is supporting TypeScript natively (see https://gatsby.dev/typescript). "ts-node" might not be needed anymore at all, consider removing it.`,
},
}
throw structuredError
}
}
}
}
try {
if (stats?.compilation.modules) {
iterateModules(stats.compilation.modules, stats.compilation)
}
compiler.close(closeErr => {
if (err) {
return reject(err)
}
if (closeErr) {
return reject(closeErr)
}
return resolve(stats?.compilation)
})
} catch (e) {
reject(e)
}
})
})
}