-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
node-manifest.ts
425 lines (364 loc) · 12.9 KB
/
node-manifest.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import type { ErrorId } from "gatsby-cli/lib/structured-errors/error-map"
import { getNode } from "./../datastore"
import { IGatsbyPage, INodeManifest } from "./../redux/types"
import reporter from "gatsby-cli/lib/reporter"
import { store } from "../redux/"
import { internalActions } from "../redux/actions"
import path from "path"
import fs from "fs-extra"
import fastq from "fastq"
interface INodeManifestPage {
path?: string
}
/**
* This it the output after processing calls to the public unstable_createNodeManifest action
*/
interface INodeManifestOut {
page: INodeManifestPage
node: {
id: string
}
foundPageBy: FoundPageBy
}
type FoundPageBy =
| `ownerNodeId`
| `filesystem-route-api`
// for these three we warn to use ownerNodeId instead
| `context.id`
| `context.slug`
| `queryTracking`
| `none`
/**
* Finds a final built page by nodeId or by node.slug as a fallback.
*
* Note that this function wont work properly in `gatsby develop`
* since develop no longer runs all page queries when creating pages.
* We use the node id to query mapping to find the right page but
* this mapping only exists once you've visited a page in your browser.
* When this fn is being used for routing to previews the user wont necessarily have
* visited the page in the browser yet.
*/
async function findPageOwnedByNode({
nodeId,
slug,
}: {
nodeId: string
slug?: string
}): Promise<{
page: INodeManifestPage
foundPageBy: FoundPageBy
}> {
const state = store.getState()
const { pages, nodes } = state
const { byNode } = state.queries
// in development queries are run on demand so we wont have an accurate nodeId->pages map until those pages are visited in the browser. We want this mapping before the page is visited in the browser so we can route to the right page in the browser.
// So in development we can just use the Map of all pages (pagePath -> pageNode)
// but for builds (preview inc builds or regular builds) we will have a full map
// of all nodeId's to pages they're queried on and we can use that instead since it
// will be a much smaller list of pages, resulting in better performance for large sites
const usingPagesMap: boolean = `development` === process.env.NODE_ENV
const pagePathSetOrMap = usingPagesMap
? // this is a Map of page path to page node
pages
: // this is a Set of page paths
byNode?.get(nodeId)
// the default page path is the first page found in
// node id to page query tracking
let pagePath = byNode?.get(nodeId)?.values()?.next()?.value
let foundPageBy: FoundPageBy = pagePath ? `queryTracking` : `none`
if (pagePathSetOrMap) {
let ownerPagePath: string | undefined
let foundOwnerNodeId = false
// for each page this nodeId is queried in
for (const pathOrPageObject of pagePathSetOrMap.values()) {
// if we haven't found a page with this nodeId
// set as page.ownerNodeId then run this logic.
// this condition is on foundOwnerNodeId instead of ownerPagePath
// in case we find a page with the nodeId in page.context.id/context.slug
// and then later in the loop there's a page with this nodeId
// set on page.ownerNodeId.
// We always want to prefer ownerPagePath over context.id/context.slug
if (foundOwnerNodeId) {
break
}
const path = (
usingPagesMap
? // in development we're using a Map, so the value here is a page object
(pathOrPageObject as IGatsbyPage).path
: // in builds we're using a Set so the page path is the value
pathOrPageObject
) as string
const fullPage: IGatsbyPage | undefined = pages.get(path)
foundOwnerNodeId = fullPage?.ownerNodeId === nodeId
const foundPageIdInContext = fullPage?.context?.id === nodeId
// querying by node.slug in GraphQL queries is common enough that we can search for it as a fallback after ownerNodeId, filesystem routes, and context.id
const foundPageSlugInContext = slug && fullPage?.context?.slug === slug
if (foundOwnerNodeId) {
foundPageBy = `ownerNodeId`
} else if (foundPageIdInContext && fullPage) {
const pageCreatedByPluginName = nodes.get(
fullPage.pluginCreatorId
)?.name
const pageCreatedByFilesystemPlugin =
pageCreatedByPluginName === `gatsby-plugin-page-creator`
foundPageBy = pageCreatedByFilesystemPlugin
? `filesystem-route-api`
: `context.id`
} else if (foundPageSlugInContext && fullPage) {
foundPageBy = `context.slug`
}
if (
fullPage &&
// first check for the ownerNodeId on the page. this is
// the defacto owner. Can't get more specific than this
(foundOwnerNodeId ||
// if there's no specified owner look to see if
// pageContext has an `id` variable which matches our
// nodeId. Using an "id" as a variable in queries is common
// and if we don't have an owner this is a better guess
// of an owner than grabbing the first page query we find
// that's mapped to this node id.
// this also makes this work with the filesystem Route API without
// changing that API.
foundPageIdInContext ||
foundPageSlugInContext)
) {
// save this path to use in our manifest!
ownerPagePath = fullPage.path
}
}
if (ownerPagePath) {
pagePath = ownerPagePath
}
}
return {
page: {
path: pagePath || null,
},
foundPageBy,
}
}
// these id's correspond to error id's in
// packages/gatsby-cli/src/structured-errors/error-map.ts
export const foundPageByToLogIds = {
none: `11801`,
[`context.id`]: `11802`,
[`context.slug`]: `11805`,
queryTracking: `11803`,
[`filesystem-route-api`]: `success`,
ownerNodeId: `success`,
}
/**
* Takes in some info about a node manifest and the page we did or didn't find for it, then warns and returns the warning string
*/
export function warnAboutNodeManifestMappingProblems({
inputManifest,
pagePath,
foundPageBy,
verbose,
}: {
inputManifest: INodeManifest
pagePath?: string
foundPageBy: FoundPageBy
verbose: boolean
}): { logId: string } {
let logId: ErrorId | `success`
switch (foundPageBy) {
case `none`:
case `context.id`:
case `context.slug`:
case `queryTracking`: {
logId = foundPageByToLogIds[foundPageBy]
if (verbose) {
reporter.error({
id: logId,
context: {
inputManifest,
pagePath,
},
})
}
break
}
case `filesystem-route-api`:
case `ownerNodeId`:
logId = `success`
break
default: {
throw Error(`Node Manifest mapping is in an impossible state`)
}
}
return {
logId,
}
}
/**
* Prepares and then writes out an individual node manifest file to be used for routing to previews. Manifest files are added via the public unstable_createNodeManifest action
*/
export async function processNodeManifest(
inputManifest: INodeManifest,
listOfUniqueErrorIds: Set<string>,
nodeManifestPagePathMap: Map<string, string>,
verboseLogs: boolean
): Promise<null | INodeManifestOut> {
const nodeId = inputManifest.node.id
const fullNode = getNode(nodeId)
const noNodeWarningId = `11804`
if (!fullNode) {
if (verboseLogs) {
reporter.error({
id: noNodeWarningId,
context: {
pluginName: inputManifest.pluginName,
nodeId,
},
})
} else {
listOfUniqueErrorIds.add(noNodeWarningId)
}
return null
}
// map the node to a page that was created
const { page: nodeManifestPage, foundPageBy } = await findPageOwnedByNode({
nodeId,
// querying by node.slug in GraphQL queries is common enough that we can search for it as a fallback after ownerNodeId, filesystem routes, and context.id
slug: fullNode?.slug as string,
})
const nodeManifestMappingProblemsContext = {
inputManifest,
pagePath: nodeManifestPage.path,
foundPageBy,
verbose: verboseLogs,
}
if (verboseLogs) {
warnAboutNodeManifestMappingProblems(nodeManifestMappingProblemsContext)
} else {
const { logId } = warnAboutNodeManifestMappingProblems(
nodeManifestMappingProblemsContext
)
if (logId !== `success`) {
listOfUniqueErrorIds.add(logId)
}
}
const finalManifest: INodeManifestOut = {
node: inputManifest.node,
page: nodeManifestPage,
foundPageBy,
}
const gatsbySiteDirectory = store.getState().program.directory
let fileNameBase = inputManifest.manifestId
/**
* Windows has a handful of special/reserved characters that are not valid in a file path
* @reference https://superuser.com/questions/358855/what-characters-are-safe-in-cross-platform-file-names-for-linux-windows-and-os
*
* The two exceptions to the list linked above are
* - the colon that is part of the hard disk partition name at the beginning of a file path (i.e. C:)
* - backslashes. We don't want to replace backslashes because those are used to delineate what the actual file path is
*
* During local development, node manifests can be written to disk but are generally unused as they are only used
* for Content Sync which runs in Gatsby Cloud. Gatsby cloud is a Linux environment in which these special chars are valid in
* filepaths. To avoid errors on Windows, we replace all instances of the special chars in the filepath (with the exception of the
* hard disk partition name) with "-" to ensure that local Windows development setups do not break when attempting
* to write one of these manifests to disk.
*/
if (process.platform === `win32`) {
fileNameBase = fileNameBase.replace(/:|\/|\*|\?|"|<|>|\||\\/g, `-`)
}
// write out the manifest file
const manifestFilePath = path.join(
gatsbySiteDirectory,
`public`,
`__node-manifests`,
inputManifest.pluginName,
`${fileNameBase}.json`
)
const manifestFileDir = path.dirname(manifestFilePath)
await fs.ensureDir(manifestFileDir)
await fs.writeJSON(manifestFilePath, finalManifest)
if (verboseLogs) {
reporter.info(
`Plugin ${inputManifest.pluginName} created a manifest with the id ${fileNameBase}`
)
}
if (nodeManifestPage.path) {
nodeManifestPagePathMap.set(nodeManifestPage.path, fileNameBase)
}
return finalManifest
}
/**
* Grabs all pending node manifests, processes them, writes them to disk,
* and then removes them from the store.
* Manifest files are added via the public unstable_createNodeManifest action in sourceNodes
*/
export async function processNodeManifests(): Promise<Map<
string,
string
> | null> {
const verboseLogs =
process.env.gatsby_log_level === `verbose` ||
process.env.VERBOSE_NODE_MANIFEST === `true`
const startTime = Date.now()
const { nodeManifests } = store.getState()
const totalManifests = nodeManifests.length
if (totalManifests === 0) {
return null
}
let totalProcessedManifests = 0
let totalFailedManifests = 0
const nodeManifestPagePathMap: Map<string, string> = new Map()
const listOfUniqueErrorIds: Set<string> = new Set()
async function processNodeManifestTask(
manifest: INodeManifest,
cb: fastq.done<any>
): Promise<void> {
const processedManifest = await processNodeManifest(
manifest,
listOfUniqueErrorIds,
nodeManifestPagePathMap,
verboseLogs
)
if (processedManifest) {
totalProcessedManifests++
} else {
totalFailedManifests++
}
// `setImmediate` below is a workaround against stack overflow
// occurring when there are many manifests
setImmediate(() => cb(null, true))
return
}
const processNodeManifestQueue = fastq(processNodeManifestTask, 25)
for (const manifest of nodeManifests) {
processNodeManifestQueue.push(manifest, () => {})
}
if (!processNodeManifestQueue.idle()) {
await new Promise(resolve => {
processNodeManifestQueue.drain = resolve as () => unknown
})
}
const pluralize = (length: number): string =>
length > 1 || length === 0 ? `s` : ``
const endTime = Date.now()
reporter.info(
`Wrote out ${totalProcessedManifests} node page manifest file${pluralize(
totalProcessedManifests
)} in ${endTime - startTime} ms. ${
totalFailedManifests > 0
? `. ${totalFailedManifests} manifest${pluralize(
totalFailedManifests
)} couldn't be processed.`
: ``
}`
)
reporter.info(
(!verboseLogs && listOfUniqueErrorIds.size > 0
? `unstable_createNodeManifest produced warnings [${[
...listOfUniqueErrorIds,
].join(`, `)}]. `
: ``) +
`To see full warning messages set process.env.VERBOSE_NODE_MANIFEST to "true".\nVisit https://gatsby.dev/nodemanifest for more info on Node Manifests.`
)
// clean up all pending manifests from the store
store.dispatch(internalActions.deleteNodeManifests())
return nodeManifestPagePathMap
}