-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathcompile-gatsby-files.ts
247 lines (220 loc) · 6.52 KB
/
compile-gatsby-files.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
import { Parcel } from "@parcel/core"
import path from "path"
import type { Diagnostic } from "@parcel/diagnostic"
import reporter from "gatsby-cli/lib/reporter"
import { ensureDir, emptyDir, existsSync, remove, readdir } from "fs-extra"
import telemetry from "gatsby-telemetry"
import { isNearMatch } from "../is-near-match"
export const COMPILED_CACHE_DIR = `.cache/compiled`
export const PARCEL_CACHE_DIR = `.cache/.parcel-cache`
export const gatsbyFileRegex = `gatsby-+(node|config).ts`
const RETRY_COUNT = 5
function getCacheDir(siteRoot: string): string {
return `${siteRoot}/${PARCEL_CACHE_DIR}`
}
function exponentialBackoff(retry: number): Promise<void> {
if (retry === 0) {
return Promise.resolve()
}
const timeout = 50 * Math.pow(2, retry)
return new Promise(resolve => setTimeout(resolve, timeout))
}
/**
* Construct Parcel with config.
* @see {@link https://parceljs.org/features/targets/}
*/
export function constructParcel(siteRoot: string): Parcel {
return new Parcel({
entries: [
`${siteRoot}/${gatsbyFileRegex}`,
`${siteRoot}/plugins/**/${gatsbyFileRegex}`,
],
defaultConfig: require.resolve(`gatsby-parcel-config`),
mode: `production`,
targets: {
root: {
outputFormat: `commonjs`,
includeNodeModules: false,
sourceMap: false,
engines: {
node: `>= 14.15.0`,
},
distDir: `${siteRoot}/${COMPILED_CACHE_DIR}`,
},
},
cacheDir: getCacheDir(siteRoot),
})
}
/**
* Compile known gatsby-* files (e.g. `gatsby-config`, `gatsby-node`)
* and output in `<SITE_ROOT>/.cache/compiled`.
*/
export async function compileGatsbyFiles(
siteRoot: string,
retry: number = 0
): Promise<void> {
try {
// Check for gatsby-node.jsx and gatsby-node.tsx (or other misnamed variations)
const files = await readdir(siteRoot)
let nearMatch = ``
const configName = `gatsby-node`
for (const file of files) {
if (nearMatch) {
break
}
const { name } = path.parse(file)
// Of course, allow valid gatsby-node files
if (file === `gatsby-node.js` || file === `gatsby-node.ts`) {
break
}
if (isNearMatch(name, configName, 3)) {
nearMatch = file
}
}
// gatsby-node is misnamed
if (nearMatch) {
const isTSX = nearMatch.endsWith(`.tsx`)
reporter.panic({
id: `10128`,
context: {
configName,
nearMatch,
isTSX,
},
})
}
const distDir = `${siteRoot}/${COMPILED_CACHE_DIR}`
await ensureDir(distDir)
await emptyDir(distDir)
await exponentialBackoff(retry)
const parcel = constructParcel(siteRoot)
const { bundleGraph } = await parcel.run()
await exponentialBackoff(retry)
const bundles = bundleGraph.getBundles()
if (bundles.length === 0) return
let compiledTSFilesCount = 0
for (const bundle of bundles) {
// validate that output exists and is valid
try {
delete require.cache[bundle.filePath]
require(bundle.filePath)
} catch (e) {
if (retry >= RETRY_COUNT) {
reporter.panic({
id: `11904`,
context: {
siteRoot,
retries: RETRY_COUNT,
compiledFileLocation: bundle.filePath,
sourceFileLocation: bundle.getMainEntry()?.filePath,
},
})
} else if (retry > 0) {
// first retry is most flaky and it seems it always get in good state
// after that - most likely cache clearing is the trick that fixes the problem
reporter.verbose(
`Failed to import compiled file "${
bundle.filePath
}" after retry, attempting another retry (#${
retry + 1
} of ${RETRY_COUNT}) - "${e.message}"`
)
}
// sometimes parcel cache gets in weird state
await remove(getCacheDir(siteRoot))
await compileGatsbyFiles(siteRoot, retry + 1)
return
}
const mainEntry = bundle.getMainEntry()?.filePath
// mainEntry won't exist for shared chunks
if (mainEntry) {
if (mainEntry.endsWith(`.ts`)) {
compiledTSFilesCount = compiledTSFilesCount + 1
}
}
}
if (telemetry.isTrackingEnabled()) {
telemetry.trackCli(`PARCEL_COMPILATION_END`, {
valueInteger: compiledTSFilesCount,
name: `count of compiled ts files`,
})
}
} catch (error) {
if (error.diagnostics) {
handleErrors(error.diagnostics)
} else {
reporter.panic({
id: `11903`,
error,
context: {
siteRoot,
sourceMessage: error.message,
},
})
}
}
}
function handleErrors(diagnostics: Array<Diagnostic>): void {
diagnostics.forEach(err => {
if (err.codeFrames) {
err.codeFrames.forEach(c => {
// Assuming that codeHighlights only ever has one entry in the array. Local tests only ever showed one
const codeHighlightsMessage = c?.codeHighlights[0]?.message
// If both messages are the same don't print the specific, otherwise they would be duplicate
const specificMessage =
codeHighlightsMessage === err.message
? undefined
: codeHighlightsMessage
reporter.panic({
id: `11901`,
context: {
filePath: c?.filePath,
generalMessage: err.message,
specificMessage,
origin: err?.origin,
hints: err?.hints,
},
})
})
} else {
reporter.panic({
id: `11901`,
context: {
generalMessage: err.message,
origin: err?.origin,
hints: err?.hints,
},
})
}
})
}
export function getResolvedFieldsForPlugin(
rootDir: string,
pluginName: string
): {
resolvedCompiledGatsbyNode?: string
} {
return {
resolvedCompiledGatsbyNode: findCompiledLocalPluginModule(
rootDir,
pluginName,
`gatsby-node`
),
}
}
export function findCompiledLocalPluginModule(
rootDir: string,
pluginName: string,
moduleName: "gatsby-config" | "gatsby-node"
): string | undefined {
const compiledPathForPlugin =
pluginName === `default-site-plugin`
? `${rootDir}/${COMPILED_CACHE_DIR}`
: `${rootDir}/${COMPILED_CACHE_DIR}/plugins/${pluginName}`
const compiledPathForModule = `${compiledPathForPlugin}/${moduleName}.js`
const isCompiled = existsSync(compiledPathForModule)
if (isCompiled) {
return compiledPathForModule
}
return undefined
}