/
gatsby-node.js
249 lines (219 loc) · 8 KB
/
gatsby-node.js
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
const {
setActions,
// queue: jobQueue,
// reportError,
_unstable_createJob,
_lazyJobsEnabled,
} = require(`./index`)
const { pathExists } = require(`fs-extra`)
const { slash } = require(`gatsby-core-utils`)
const { setPluginOptions } = require(`./plugin-options`)
const path = require(`path`)
let coreSupportsOnPluginInit
try {
const { isGatsbyNodeLifecycleSupported } = require(`gatsby-plugin-utils`)
coreSupportsOnPluginInit = isGatsbyNodeLifecycleSupported(
`unstable_onPluginInit`
)
} catch (e) {
coreSupportsOnPluginInit = false
}
function removeCachedValue(cache, key) {
if (cache?.del) {
// if cache expose ".del" method directly on public interface
return cache.del(key)
} else if (cache?.cache?.del) {
// legacy - using internal cache instance and calling ".del" on it directly
return cache.cache.del(key)
}
return Promise.reject(
new Error(`Cache instance doesn't expose ".del" function`)
)
}
exports.onCreateDevServer = async ({ app, cache, reporter }) => {
if (!_lazyJobsEnabled()) {
return
}
app.use(async (req, res, next) => {
const decodedURI = decodeURIComponent(req.path)
const pathOnDisk = path.resolve(path.join(`./public/`, decodedURI))
if (await pathExists(pathOnDisk)) {
return res.sendFile(pathOnDisk)
}
const jobContentDigest = await cache.get(decodedURI)
const cacheResult = jobContentDigest
? await cache.get(jobContentDigest)
: null
if (!cacheResult) {
return next()
}
// We are going to run a job for a single operation only
// and postpone all other operations
// This speeds up the loading of lazy images in the browser and
// also helps to free up the browser connection queue earlier.
const {
matchingJob,
jobWithRemainingOperations,
} = splitOperationsByRequestedFile(cacheResult, pathOnDisk)
await _unstable_createJob(matchingJob, { reporter })
await removeCachedValue(cache, decodedURI)
if (jobWithRemainingOperations.args.operations.length > 0) {
// There are still some operations pending for this job - replace the cached job
await cache.set(jobContentDigest, jobWithRemainingOperations)
} else {
// No operations left to process - purge the cache
await removeCachedValue(cache, jobContentDigest)
}
return res.sendFile(pathOnDisk)
})
}
// Split the job into two jobs:
// - first job with a single operation matching requestedPathOnDisk
// - second job with all other operations
// so the two resulting jobs are only different by their operations
function splitOperationsByRequestedFile(job, requestedPathOnDisk) {
const matchingJob = {
...job,
args: { ...job.args, operations: [] },
}
const jobWithRemainingOperations = {
...job,
args: { ...job.args, operations: [] },
}
job.args.operations.forEach(op => {
const operationPath = path.resolve(path.join(job.outputDir, op.outputPath))
if (operationPath === requestedPathOnDisk) {
matchingJob.args.operations.push(op)
} else {
jobWithRemainingOperations.args.operations.push(op)
}
})
if (matchingJob.args.operations.length === 0) {
throw new Error(
`Could not find matching operation for ${requestedPathOnDisk}`
)
}
return { matchingJob, jobWithRemainingOperations }
}
// So something is wrong with the reporter, when I do this in preBootstrap,
// the progressbar gets not updated
exports.onPostBootstrap = async ({ reporter, cache, store }) => {
if (process.env.gatsby_executing_command !== `develop`) {
// recreate jobs that haven't been triggered by develop yet
// removing stale jobs has already kicked in so we know these still need to process
for (const [contentDigest] of store.getState().jobsV2.complete) {
const job = await cache.get(contentDigest)
if (job) {
// we don't have to await, gatsby does this for us
_unstable_createJob(job, { reporter })
}
}
}
}
if (coreSupportsOnPluginInit) {
// to properly initialize plugin in worker (`onPreBootstrap` won't run in workers)
exports.unstable_onPluginInit = async ({ actions }, pluginOptions) => {
setActions(actions)
setPluginOptions(pluginOptions)
}
}
exports.onPreBootstrap = async ({ actions, emitter, cache }, pluginOptions) => {
setActions(actions)
setPluginOptions(pluginOptions)
// below is a hack / hot fix for confusing progress bar behaviour
// that doesn't recognize duplicate jobs, as it's now
// in gatsby core internals (if `createJobV2` is available)
// we should remove this or make this code path not hit
// (we should never use emitter in plugins)
// as soon as possible (possibly by moving progress bar handling
// inside jobs-manager in core)
if (emitter) {
// track how many image transformation each job has
// END_JOB_V2 doesn't contain that information
// so we store it in <JobContentHash, TransformsCount> map
// when job is created. Then retrieve that when job finishes
// and remove that entry from the map.
const imageCountInJobsMap = new Map()
emitter.on(`CREATE_JOB_V2`, action => {
if (action.plugin.name === `gatsby-plugin-sharp`) {
if (action.payload.job.args.isLazy) {
// we have to remove some internal pieces
const job = {
name: action.payload.job.name,
inputPaths: action.payload.job.inputPaths.map(input => input.path),
outputDir: action.payload.job.outputDir,
args: {
...action.payload.job.args,
isLazy: false,
},
}
cache.set(action.payload.job.contentDigest, job)
action.payload.job.args.operations.forEach(op => {
const cacheKey = slash(
path.relative(
path.join(process.cwd(), `public`),
path.join(action.payload.job.outputDir, op.outputPath)
)
)
cache.set(`/${cacheKey}`, action.payload.job.contentDigest)
})
return
}
const job = action.payload.job
const imageCount = job.args.operations.length
imageCountInJobsMap.set(job.contentDigest, imageCount)
}
})
emitter.on(`END_JOB_V2`, action => {
if (action.plugin.name === `gatsby-plugin-sharp`) {
const jobContentDigest = action.payload.jobContentDigest
// when it's lazy we didn't set it
if (!imageCountInJobsMap.has(jobContentDigest)) {
return
}
imageCountInJobsMap.delete(jobContentDigest)
}
})
}
// normalizedOptions = setPluginOptions(pluginOptions)
}
exports.pluginOptionsSchema = ({ Joi }) =>
Joi.object({
base64Width: Joi.number()
.default(20)
.description(`The width of the generated base64 preview image`),
forceBase64Format: Joi.any()
.valid(`png`, `jpg`, `webp`)
.description(
`Force a different format for the generated base64 image. Defaults to the same format as the input image`
),
useMozJpeg: Joi.boolean().description(
`The the mozJpeg library for encoding. Defaults to false, unless \`process.env.GATSBY_JPEG_ENCODER\` === \`MOZJPEG\``
),
stripMetadata: Joi.boolean().default(true),
defaultQuality: Joi.number().default(50),
failOnError: Joi.boolean().default(true),
defaults: Joi.object({
formats: Joi.array().items(
Joi.string().valid(`auto`, `png`, `jpg`, `webp`, `avif`)
),
placeholder: Joi.string().valid(
`tracedSVG`,
`dominantColor`,
`blurred`,
`none`
),
quality: Joi.number(),
breakpoints: Joi.array().items(Joi.number()),
backgroundColor: Joi.string(),
transformOptions: Joi.object(),
tracedSVGOptions: Joi.object(),
blurredOptions: Joi.object(),
jpgOptions: Joi.object(),
pngOptions: Joi.object(),
webpOptions: Joi.object(),
avifOptions: Joi.object(),
}).description(
`Default options used by gatsby-plugin-image. \nSee https://gatsbyjs.com/docs/reference/built-in-components/gatsby-plugin-image/`
),
})