/
public.js
1454 lines (1296 loc) · 44.5 KB
/
public.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
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @flow
const chalk = require(`chalk`)
const _ = require(`lodash`)
const { stripIndent } = require(`common-tags`)
const report = require(`gatsby-cli/lib/reporter`)
const { platform } = require(`os`)
const path = require(`path`)
const { trueCasePathSync } = require(`true-case-path`)
const url = require(`url`)
const { slash, createContentDigest } = require(`gatsby-core-utils`)
const { hasNodeChanged } = require(`../../utils/nodes`)
const { getNode } = require(`../../datastore`)
const sanitizeNode = require(`../../utils/sanitize-node`)
const { store } = require(`../index`)
const { validatePageComponent } = require(`../../utils/validate-page-component`)
import { nodeSchema } from "../../joi-schemas/joi"
const { generateComponentChunkName } = require(`../../utils/js-chunk-names`)
const {
getCommonDir,
truncatePath,
tooLongSegmentsInPath,
} = require(`../../utils/path`)
const apiRunnerNode = require(`../../utils/api-runner-node`)
const { trackCli } = require(`gatsby-telemetry`)
const { getNonGatsbyCodeFrame } = require(`../../utils/stack-trace-utils`)
const { getPageMode } = require(`../../utils/page-mode`)
const normalizePath = require(`../../utils/normalize-path`).default
import { createJobV2FromInternalJob } from "./internal"
import { maybeSendJobToMainProcess } from "../../utils/jobs/worker-messaging"
import { reportOnce } from "../../utils/report-once"
import { wrapNode } from "../../utils/detect-node-mutations"
const isNotTestEnv = process.env.NODE_ENV !== `test`
const isTestEnv = process.env.NODE_ENV === `test`
// Memoize function used to pick shadowed page components to avoid expensive I/O.
// Ideally, we should invalidate memoized values if there are any FS operations
// on files that are in shadowing chain, but webpack currently doesn't handle
// shadowing changes during develop session, so no invalidation is not a deal breaker.
const shadowCreatePagePath = _.memoize(
require(`../../internal-plugins/webpack-theme-component-shadowing/create-page`)
)
const { createInternalJob } = require(`../../utils/jobs/manager`)
const actions = {}
const isWindows = platform() === `win32`
const ensureWindowsDriveIsUppercase = filePath => {
const segments = filePath.split(`:`).filter(s => s !== ``)
return segments.length > 0
? segments.shift().toUpperCase() + `:` + segments.join(`:`)
: filePath
}
const findChildren = initialChildren => {
const children = [...initialChildren]
const queue = [...initialChildren]
const traversedNodes = new Set()
while (queue.length > 0) {
const currentChild = getNode(queue.pop())
if (!currentChild || traversedNodes.has(currentChild.id)) {
continue
}
traversedNodes.add(currentChild.id)
const newChildren = currentChild.children
if (_.isArray(newChildren) && newChildren.length > 0) {
children.push(...newChildren)
queue.push(...newChildren)
}
}
return children
}
import type { Plugin } from "./types"
type Job = {
id: string,
}
type JobV2 = {
name: string,
inputPaths: string[],
outputDir: string,
args: Object,
}
type PageInput = {
path: string,
component: string,
context?: Object,
ownerNodeId?: string,
defer?: boolean,
}
type PageMode = "SSG" | "DSG" | "SSR"
type Page = {
path: string,
matchPath: ?string,
component: string,
context: Object,
internalComponentName: string,
componentChunkName: string,
updatedAt: number,
ownerNodeId?: string,
mode: PageMode,
}
type ActionOptions = {
traceId: ?string,
parentSpan: ?Object,
followsSpan: ?Object,
}
type PageData = {
id: string,
resultHash: string,
}
type PageDataRemove = {
id: string,
}
/**
* Delete a page
* @param {Object} page a page object
* @param {string} page.path The path of the page
* @param {string} page.component The absolute path to the page component
* @example
* deletePage(page)
*/
actions.deletePage = (page: PageInput) => {
return {
type: `DELETE_PAGE`,
payload: page,
}
}
const hasWarnedForPageComponentInvalidContext = new Set()
const hasWarnedForPageComponentInvalidCasing = new Set()
const hasErroredBecauseOfNodeValidation = new Set()
const pageComponentCache = new Map()
const reservedFields = [
`path`,
`matchPath`,
`component`,
`componentChunkName`,
`pluginCreator___NODE`,
`pluginCreatorId`,
]
/**
* Create a page. See [the guide on creating and modifying pages](/docs/creating-and-modifying-pages/)
* for detailed documentation about creating pages.
* @param {Object} page a page object
* @param {string} page.path Any valid URL. Must start with a forward slash
* @param {string} page.matchPath Path that Reach Router uses to match the page on the client side.
* Also see docs on [matchPath](/docs/gatsby-internals-terminology/#matchpath)
* @param {string} page.ownerNodeId The id of the node that owns this page. This is used for routing users to previews via the unstable_createNodeManifest public action. Since multiple nodes can be queried on a single page, this allows the user to tell us which node is the main node for the page. Note that the ownerNodeId must be for a node which is queried on this page via a GraphQL query.
* @param {string} page.component The absolute path to the component for this page
* @param {Object} page.context Context data for this page. Passed as props
* to the component `this.props.pageContext` as well as to the graphql query
* as graphql arguments.
* @param {boolean} page.defer When set to `true`, Gatsby will exclude the page from the build step and instead generate it during the first HTTP request. Default value is `false`. Also see docs on [Deferred Static Generation](/docs/reference/rendering-options/deferred-static-generation/).
* @example
* createPage({
* path: `/my-sweet-new-page/`,
* component: path.resolve(`./src/templates/my-sweet-new-page.js`),
* ownerNodeId: `123456`,
* // The context is passed as props to the component as well
* // as into the component's GraphQL query.
* context: {
* id: `123456`,
* },
* })
*/
actions.createPage = (
page: PageInput,
plugin?: Plugin,
actionOptions?: ActionOptions
) => {
let name = `The plugin "${plugin.name}"`
if (plugin.name === `default-site-plugin`) {
name = `Your site's "gatsby-node.js"`
}
if (!page.path) {
const message = `${name} must set the page path when creating a page`
// Don't log out when testing
if (isNotTestEnv) {
report.panic({
id: `11323`,
context: {
pluginName: name,
pageObject: page,
message,
},
})
} else {
return message
}
}
// Validate that the context object doesn't overlap with any core page fields
// as this will cause trouble when running graphql queries.
if (page.context && typeof page.context === `object`) {
const invalidFields = reservedFields.filter(field => field in page.context)
if (invalidFields.length > 0) {
const error = `${
invalidFields.length === 1
? `${name} used a reserved field name in the context object when creating a page:`
: `${name} used reserved field names in the context object when creating a page:`
}
${invalidFields.map(f => ` * "${f}"`).join(`\n`)}
${JSON.stringify(page, null, 4)}
Data in "context" is passed to GraphQL as potential arguments when running the
page query.
When arguments for GraphQL are constructed, the context object is combined with
the page object so *both* page object and context data are available as
arguments. So you don't need to add the page "path" to the context as it's
already available in GraphQL. If a context field duplicates a field already
used by the page object, this can break functionality within Gatsby so must be
avoided.
Please choose another name for the conflicting fields.
The following fields are used by the page object and should be avoided.
${reservedFields.map(f => ` * "${f}"`).join(`\n`)}
`
if (isTestEnv) {
return error
// Only error if the context version is different than the page
// version. People in v1 often thought that they needed to also pass
// the path to context for it to be available in GraphQL
} else if (invalidFields.some(f => page.context[f] !== page[f])) {
report.panic({
id: `11324`,
context: {
message: error,
},
})
} else {
if (!hasWarnedForPageComponentInvalidContext.has(page.component)) {
report.warn(error)
hasWarnedForPageComponentInvalidContext.add(page.component)
}
}
}
}
// Check if a component is set.
if (!page.component) {
if (isNotTestEnv) {
report.panic({
id: `11322`,
context: {
pluginName: name,
pageObject: page,
},
})
} else {
// For test
return `A component must be set when creating a page`
}
}
const pageComponentPath = shadowCreatePagePath(page.component)
if (pageComponentPath) {
page.component = pageComponentPath
}
const rootPath = store.getState().program.directory
const { error, message, panicOnBuild } = validatePageComponent(
page,
rootPath,
name
)
if (error) {
if (isNotTestEnv) {
if (panicOnBuild) {
report.panicOnBuild(error)
} else {
report.panic(error)
}
}
return message
}
// check if we've processed this component path
// before, before running the expensive "trueCasePath"
// operation
//
// Skip during testing as the paths don't exist on disk.
if (isNotTestEnv) {
if (pageComponentCache.has(page.component)) {
page.component = pageComponentCache.get(page.component)
} else {
const originalPageComponent = page.component
// normalize component path
page.component = slash(page.component)
// check if path uses correct casing - incorrect casing will
// cause issues in query compiler and inconsistencies when
// developing on Mac or Windows and trying to deploy from
// linux CI/CD pipeline
let trueComponentPath
try {
// most systems
trueComponentPath = slash(trueCasePathSync(page.component))
} catch (e) {
// systems where user doesn't have access to /
const commonDir = getCommonDir(rootPath, page.component)
// using `path.win32` to force case insensitive relative path
const relativePath = slash(
path.win32.relative(commonDir, page.component)
)
trueComponentPath = slash(trueCasePathSync(relativePath, commonDir))
}
if (isWindows) {
page.component = ensureWindowsDriveIsUppercase(page.component)
}
if (trueComponentPath !== page.component) {
if (!hasWarnedForPageComponentInvalidCasing.has(page.component)) {
const markers = page.component
.split(``)
.map((letter, index) => {
if (letter !== trueComponentPath[index]) {
return `^`
}
return ` `
})
.join(``)
report.warn(
stripIndent`
${name} created a page with a component path that doesn't match the casing of the actual file. This may work locally, but will break on systems which are case-sensitive, e.g. most CI/CD pipelines.
page.component: "${page.component}"
path in filesystem: "${trueComponentPath}"
${markers}
`
)
hasWarnedForPageComponentInvalidCasing.add(page.component)
}
page.component = trueComponentPath
}
pageComponentCache.set(originalPageComponent, page.component)
}
}
let internalComponentName
if (page.path === `/`) {
internalComponentName = `ComponentIndex`
} else {
internalComponentName = `Component${page.path}`
}
const invalidPathSegments = tooLongSegmentsInPath(page.path)
if (invalidPathSegments.length > 0) {
const truncatedPath = truncatePath(page.path)
report.warn(
report.stripIndent(`
The path to the following page is longer than the supported limit on most
operating systems and will cause an ENAMETOOLONG error. The path has been
truncated to prevent this.
Original Path: ${page.path}
Truncated Path: ${truncatedPath}
`)
)
page.path = truncatedPath
}
const internalPage: Page = {
internalComponentName,
path: page.path,
matchPath: page.matchPath,
component: normalizePath(page.component),
componentPath: normalizePath(page.component),
componentChunkName: generateComponentChunkName(page.component),
isCreatedByStatefulCreatePages:
actionOptions?.traceId === `initial-createPagesStatefully`,
// Ensure the page has a context object
context: page.context || {},
updatedAt: Date.now(),
// Link page to its plugin.
pluginCreator___NODE: plugin.id ?? ``,
pluginCreatorId: plugin.id ?? ``,
}
if (_CFLAGS_.GATSBY_MAJOR === `4`) {
if (page.defer) {
internalPage.defer = true
}
// Note: mode is updated in the end of the build after we get access to all page components,
// see materializePageMode in utils/page-mode.ts
internalPage.mode = getPageMode(internalPage)
}
if (page.ownerNodeId) {
internalPage.ownerNodeId = page.ownerNodeId
}
// If the path doesn't have an initial forward slash, add it.
if (internalPage.path[0] !== `/`) {
internalPage.path = `/${internalPage.path}`
}
const oldPage: Page = store.getState().pages.get(internalPage.path)
const contextModified =
!!oldPage && !_.isEqual(oldPage.context, internalPage.context)
const alternateSlashPath = page.path.endsWith(`/`)
? page.path.slice(0, -1)
: page.path + `/`
if (store.getState().pages.has(alternateSlashPath)) {
report.warn(
chalk.bold.yellow(`Non-deterministic routing danger: `) +
`Attempting to create page: "${page.path}", but page "${alternateSlashPath}" already exists\n` +
chalk.bold.yellow(
`This could lead to non-deterministic routing behavior`
)
)
}
// just so it's easier to c&p from createPage action creator for now - ideally it's DRYed
const { updatedAt, ...node } = internalPage
node.children = []
node.internal = {
type: `SitePage`,
contentDigest: createContentDigest(node),
}
node.id = `SitePage ${internalPage.path}`
const oldNode = getNode(node.id)
let deleteActions
let updateNodeAction
if (oldNode && !hasNodeChanged(node.id, node.internal.contentDigest)) {
updateNodeAction = {
...actionOptions,
plugin,
type: `TOUCH_NODE`,
payload: node.id,
}
} else {
// Remove any previously created descendant nodes as they're all due
// to be recreated.
if (oldNode) {
const createDeleteAction = node => {
return {
...actionOptions,
type: `DELETE_NODE`,
plugin,
payload: node,
}
}
deleteActions = findChildren(oldNode.children)
.map(getNode)
.map(createDeleteAction)
}
node.internal.counter = getNextNodeCounter()
updateNodeAction = {
...actionOptions,
type: `CREATE_NODE`,
plugin,
oldNode,
payload: node,
}
}
const actions = [
{
...actionOptions,
type: `CREATE_PAGE`,
contextModified,
plugin,
payload: internalPage,
},
]
if (deleteActions && deleteActions.length) {
actions.push(...deleteActions)
}
actions.push(updateNodeAction)
return actions
}
const deleteNodeDeprecationWarningDisplayedMessages = new Set()
/**
* Delete a node
* @param {object} node A node object. See the "createNode" action for more information about the node object details.
* @example
* deleteNode(node)
*/
actions.deleteNode = (node: any, plugin?: Plugin) => {
const id = node && node.id
// Always get node from the store, as the node we get as an arg
// might already have been deleted.
const internalNode = getNode(id)
if (plugin) {
const pluginName = plugin.name
if (
internalNode &&
typeOwners[internalNode.internal.type] &&
typeOwners[internalNode.internal.type] !== pluginName
)
throw new Error(stripIndent`
The plugin "${pluginName}" deleted a node of a type owned by another plugin.
The node type "${internalNode.internal.type}" is owned by "${
typeOwners[internalNode.internal.type]
}".
The node object passed to "deleteNode":
${JSON.stringify(internalNode, null, 4)}
The plugin deleting the node:
${JSON.stringify(plugin, null, 4)}
`)
}
const createDeleteAction = node => {
return {
type: `DELETE_NODE`,
plugin,
payload: node,
}
}
const deleteAction = createDeleteAction(internalNode)
// It's possible the file node was never created as sometimes tools will
// write and then immediately delete temporary files to the file system.
const deleteDescendantsActions =
internalNode &&
findChildren(internalNode.children).map(getNode).map(createDeleteAction)
if (deleteDescendantsActions && deleteDescendantsActions.length) {
return [...deleteDescendantsActions, deleteAction]
} else {
return deleteAction
}
}
// We add a counter to node.internal for fast comparisons/intersections
// of various node slices. The counter must increase even across builds.
function getNextNodeCounter() {
const lastNodeCounter = store.getState().status.LAST_NODE_COUNTER ?? 0
if (lastNodeCounter >= Number.MAX_SAFE_INTEGER) {
throw new Error(
`Could not create more nodes. Maximum node count is reached: ${lastNodeCounter}`
)
}
return lastNodeCounter + 1
}
const typeOwners = {}
// memberof notation is added so this code can be referenced instead of the wrapper.
/**
* Create a new node.
* @memberof actions
* @param {Object} node a node object
* @param {string} node.id The node's ID. Must be globally unique.
* @param {string} node.parent The ID of the parent's node. If the node is
* derived from another node, set that node as the parent. Otherwise it can
* just be `null`.
* @param {Array} node.children An array of children node IDs. If you're
* creating the children nodes while creating the parent node, add the
* children node IDs here directly. If you're adding a child node to a
* parent node created by a plugin, you can't mutate this value directly
* to add your node id, instead use the action creator `createParentChildLink`.
* @param {Object} node.internal node fields that aren't generally
* interesting to consumers of node data but are very useful for plugin writers
* and Gatsby core. Only fields described below are allowed in `internal` object.
* Using any type of custom fields will result in validation errors.
* @param {string} node.internal.mediaType An optional field to indicate to
* transformer plugins that your node has raw content they can transform.
* Use either an official media type (we use mime-db as our source
* (https://www.npmjs.com/package/mime-db) or a made-up one if your data
* doesn't fit in any existing bucket. Transformer plugins use node media types
* for deciding if they should transform a node into a new one. E.g.
* markdown transformers look for media types of
* `text/markdown`.
* @param {string} node.internal.type An arbitrary globally unique type
* chosen by the plugin creating the node. Should be descriptive of the
* node as the type is used in forming GraphQL types so users will query
* for nodes based on the type chosen here. Nodes of a given type can
* only be created by one plugin.
* @param {string} node.internal.content An optional field. This is rarely
* used. It is used when a source plugin sources data it doesn't know how
* to transform e.g. a markdown string pulled from an API. The source plugin
* can defer the transformation to a specialized transformer plugin like
* gatsby-transformer-remark. This `content` field holds the raw content
* (so for the markdown case, the markdown string).
*
* Data that's already structured should be added to the top-level of the node
* object and _not_ added here. You should not `JSON.stringify` your node's
* data here.
*
* If the content is very large and can be lazy-loaded, e.g. a file on disk,
* you can define a `loadNodeContent` function for this node and the node
* content will be lazy loaded when it's needed.
* @param {string} node.internal.contentDigest the digest for the content
* of this node. Helps Gatsby avoid doing extra work on data that hasn't
* changed.
* @param {string} node.internal.description An optional field. Human
* readable description of what this node represent / its source. It will
* be displayed when type conflicts are found, making it easier to find
* and correct type conflicts.
* @returns {Promise} The returned Promise resolves when all cascading
* `onCreateNode` API calls triggered by `createNode` have finished.
* @example
* createNode({
* // Data for the node.
* field1: `a string`,
* field2: 10,
* field3: true,
* ...arbitraryOtherData,
*
* // Required fields.
* id: `a-node-id`,
* parent: `the-id-of-the-parent-node`, // or null if it's a source node without a parent
* children: [],
* internal: {
* type: `CoolServiceMarkdownField`,
* contentDigest: crypto
* .createHash(`md5`)
* .update(JSON.stringify(fieldData))
* .digest(`hex`),
* mediaType: `text/markdown`, // optional
* content: JSON.stringify(fieldData), // optional
* description: `Cool Service: "Title of entry"`, // optional
* }
* })
*/
const createNode = (
node: any,
plugin?: Plugin,
actionOptions?: ActionOptions = {}
) => {
if (!_.isObject(node)) {
return console.log(
chalk.bold.red(
`The node passed to the "createNode" action creator must be an object`
)
)
}
// Ensure the new node has an internals object.
if (!node.internal) {
node.internal = {}
}
// Ensure the new node has a children array.
if (!node.array && !_.isArray(node.children)) {
node.children = []
}
// Ensure the new node has a parent field
if (!node.parent) {
node.parent = null
}
// Tell user not to set the owner name themself.
if (node.internal.owner) {
report.error(JSON.stringify(node, null, 4))
report.panic(
chalk.bold.red(
`The node internal.owner field is set automatically by Gatsby and not by plugins`
)
)
}
const trackParams = {}
// Add the plugin name to the internal object.
if (plugin) {
node.internal.owner = plugin.name
trackParams[`pluginName`] = `${plugin.name}@${plugin.version}`
}
trackCli(`CREATE_NODE`, trackParams, { debounce: true })
const result = nodeSchema.validate(node)
if (result.error) {
if (!hasErroredBecauseOfNodeValidation.has(result.error.message)) {
const errorObj = {
id: `11467`,
context: {
validationErrorMessage: result.error.message,
node,
},
}
const possiblyCodeFrame = getNonGatsbyCodeFrame()
if (possiblyCodeFrame) {
errorObj.context.codeFrame = possiblyCodeFrame.codeFrame
errorObj.filePath = possiblyCodeFrame.fileName
errorObj.location = {
start: {
line: possiblyCodeFrame.line,
column: possiblyCodeFrame.column,
},
}
}
report.error(errorObj)
hasErroredBecauseOfNodeValidation.add(result.error.message)
}
return { type: `VALIDATION_ERROR`, error: true }
}
// Ensure node isn't directly setting fields.
if (node.fields) {
throw new Error(
stripIndent`
Plugins creating nodes can not set data on the reserved field "fields"
as this is reserved for plugins which wish to extend your nodes.
If your plugin didn't add "fields" you're probably seeing this
error because you're reusing an old node object.
Node:
${JSON.stringify(node, null, 4)}
Plugin that created the node:
${JSON.stringify(plugin, null, 4)}
`
)
}
node = sanitizeNode(node)
const oldNode = getNode(node.id)
// Ensure the plugin isn't creating a node type owned by another
// plugin. Type "ownership" is first come first served.
if (plugin) {
const pluginName = plugin.name
if (!typeOwners[node.internal.type])
typeOwners[node.internal.type] = pluginName
else if (typeOwners[node.internal.type] !== pluginName)
throw new Error(stripIndent`
The plugin "${pluginName}" created a node of a type owned by another plugin.
The node type "${node.internal.type}" is owned by "${
typeOwners[node.internal.type]
}".
If you copy and pasted code from elsewhere, you'll need to pick a new type name
for your new node(s).
The node object passed to "createNode":
${JSON.stringify(node, null, 4)}
The plugin creating the node:
${JSON.stringify(plugin, null, 4)}
`)
// If the node has been created in the past, check that
// the current plugin is the same as the previous.
if (oldNode && oldNode.internal.owner !== pluginName) {
throw new Error(
stripIndent`
Nodes can only be updated by their owner. Node "${node.id}" is
owned by "${oldNode.internal.owner}" and another plugin "${pluginName}"
tried to update it.
`
)
}
}
if (actionOptions.parentSpan) {
actionOptions.parentSpan.setTag(`nodeId`, node.id)
actionOptions.parentSpan.setTag(`nodeType`, node.id)
}
let deleteActions
let updateNodeAction
// Check if the node has already been processed.
if (oldNode && !hasNodeChanged(node.id, node.internal.contentDigest)) {
updateNodeAction = {
...actionOptions,
plugin,
type: `TOUCH_NODE`,
payload: node.id,
}
} else {
// Remove any previously created descendant nodes as they're all due
// to be recreated.
if (oldNode) {
const createDeleteAction = node => {
return {
...actionOptions,
type: `DELETE_NODE`,
plugin,
payload: node,
}
}
deleteActions = findChildren(oldNode.children)
.map(getNode)
.map(createDeleteAction)
}
node.internal.counter = getNextNodeCounter()
updateNodeAction = {
...actionOptions,
type: `CREATE_NODE`,
plugin,
oldNode,
payload: node,
}
}
if (deleteActions && deleteActions.length) {
return [...deleteActions, updateNodeAction]
} else {
return updateNodeAction
}
}
actions.createNode =
(...args) =>
dispatch => {
const actions = createNode(...args)
dispatch(actions)
const createNodeAction = (
Array.isArray(actions) ? actions : [actions]
).find(action => action.type === `CREATE_NODE`)
if (!createNodeAction) {
return undefined
}
const { payload: node, traceId, parentSpan } = createNodeAction
return apiRunnerNode(`onCreateNode`, {
node: wrapNode(node),
traceId,
parentSpan,
traceTags: { nodeId: node.id, nodeType: node.internal.type },
})
}
const touchNodeDeprecationWarningDisplayedMessages = new Set()
/**
* "Touch" a node. Tells Gatsby a node still exists and shouldn't
* be garbage collected. Primarily useful for source plugins fetching
* nodes from a remote system that can return only nodes that have
* updated. The source plugin then touches all the nodes that haven't
* updated but still exist so Gatsby knows to keep them.
* @param {Object} node A node object. See the "createNode" action for more information about the node object details.
* @example
* touchNode(node)
*/
actions.touchNode = (node: any, plugin?: Plugin) => {
if (node && !typeOwners[node.internal.type]) {
typeOwners[node.internal.type] = node.internal.owner
}
const nodeId = node?.id
if (!nodeId) {
// if we don't have a node id, we don't want to dispatch this action
return []
}
return {
type: `TOUCH_NODE`,
plugin,
payload: nodeId,
}
}
type CreateNodeInput = {
node: Object,
name?: string,
value: any,
}
/**
* Extend another node. The new node field is placed under the `fields`
* key on the extended node object.
*
* Once a plugin has claimed a field name the field name can't be used by
* other plugins. Also since nodes are immutable, you can't mutate the node
* directly. So to extend another node, use this.
* @param {Object} $0
* @param {Object} $0.node the target node object
* @param {string} $0.name the name for the field
* @param {any} $0.value the value for the field
* @example
* createNodeField({
* node,
* name: `happiness`,
* value: `is sweet graphql queries`
* })
*
* // The field value is now accessible at node.fields.happiness
*/
actions.createNodeField = (
{ node, name, value }: CreateNodeInput,
plugin: Plugin,
actionOptions?: ActionOptions
) => {
// Ensure required fields are set.
if (!node.internal.fieldOwners) {
node.internal.fieldOwners = {}
}
if (!node.fields) {
node.fields = {}
}
// Normalized name of the field that will be used in schema
const schemaFieldName = _.includes(name, `___NODE`)
? name.split(`___`)[0]
: name
// Check that this field isn't owned by another plugin.
const fieldOwner = node.internal.fieldOwners[schemaFieldName]
if (fieldOwner && fieldOwner !== plugin.name) {
throw new Error(
stripIndent`
A plugin tried to update a node field that it doesn't own:
Node id: ${node.id}
Plugin: ${plugin.name}
name: ${name}
value: ${value}
`
)
}
// Update node
node.fields[name] = value
node.internal.fieldOwners[schemaFieldName] = plugin.name
node = sanitizeNode(node)
return {
...actionOptions,
type: `ADD_FIELD_TO_NODE`,
plugin,
payload: node,
addedField: name,
}
}
/**
* Creates a link between a parent and child node. This is used when you
* transform content from a node creating a new child node. You need to add
* this new child node to the `children` array of the parent but since you
* don't have direct access to the immutable parent node, use this action
* instead.
* @param {Object} $0
* @param {Object} $0.parent the parent node object
* @param {Object} $0.child the child node object
* @example
* createParentChildLink({ parent: parentNode, child: childNode })
*/
actions.createParentChildLink = (
{ parent, child }: { parent: any, child: any },
plugin?: Plugin
) => {
if (!parent.children.includes(child.id)) {
parent.children.push(child.id)
}