-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
helpers.js
453 lines (363 loc) · 11.7 KB
/
helpers.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
import { getStore, withPluginKey } from "~/store"
import { typeDefinitionFilters } from "./type-filters"
import { getPluginOptions } from "~/utils/get-gatsby-api"
import { cloneDeep, merge } from "lodash"
import { diffString } from "json-diff"
import { formatLogMessage } from "../../utils/format-log-message"
import { CODES } from "../../utils/report"
export const buildInterfacesListForType = type => {
let shouldAddNodeType = false
const list = (type?.interfaces || [])
.filter(interfaceType => {
const interfaceTypeSettings = getTypeSettingsByType(interfaceType)
return (
!interfaceTypeSettings.exclude && fieldOfTypeWasFetched(interfaceType)
)
})
.map(({ name }) => {
if (name === `Node`) {
shouldAddNodeType = true
}
return buildTypeName(name)
})
if (shouldAddNodeType) {
list.push(`Node`)
}
return list
}
let ceIntCache = null
const isWpgqlOneThirteenZeroPlus = () => {
if (ceIntCache !== null) {
return ceIntCache
}
const { typeMap } = getStore().getState().remoteSchema
const connectionInterface = !!typeMap.get(`Connection`)
const edgeInterface = !!typeMap.get(`Edge`)
const isWpgqlOneThirteenZeroPlus = connectionInterface || edgeInterface
ceIntCache = isWpgqlOneThirteenZeroPlus
return isWpgqlOneThirteenZeroPlus
}
/**
* This function namespaces typenames with a prefix
*/
export const buildTypeName = (name, prefix) => {
if (!name || typeof name !== `string`) {
return null
}
if (!prefix) {
prefix = getPluginOptions().schema.typePrefix
}
// this is for our namespace type on the root { wp { ...fields } }
if (name === prefix) {
return name
}
// Gatsby makes the same type, so we need to rename it to prevent conflicts
if (name === `Filter`) {
name = `FilterType`
}
if (
// Starting in WPGraphQL 1.13.0, Gatsby and WPGraphQL both generate types ending in these strings for every node type in the schema, so we need to rename types to prevent conflicts.
// for users on older versions of WPGraphQL we should try to keep the schema how it was before
isWpgqlOneThirteenZeroPlus() &&
(name.endsWith(`Connection`) ||
name.endsWith(`Edge`) ||
name.endsWith(`PageInfo`))
) {
name += `Type`
}
if (name.startsWith(prefix)) {
return name
}
return prefix + name
}
/**
* Find the first type kind of a Type definition pulled via introspection
* @param {object} type
*/
export const findTypeKind = type => {
if (type?.kind) {
return type.kind
}
if (type?.ofType) {
return findTypeKind(type.ofType)
}
return null
}
export const findNamedType = type => {
if (!type) {
return null
}
if (type.ofType) {
return findNamedType(type.ofType)
}
return type
}
export const findNamedTypeName = type => {
const namedType = findNamedType(type)
return namedType?.name
}
export const fieldOfTypeWasFetched = type => {
const { fetchedTypes } = getStore().getState().remoteSchema
const typeName = findNamedTypeName(type)
const typeWasFetched = !!fetchedTypes.get(typeName)
return typeWasFetched
}
const implementingTypeCache = new Map()
export const getTypesThatImplementInterfaceType = type => {
if (implementingTypeCache.has(type.name)) {
return implementingTypeCache.get(type.name)
}
const state = getStore().getState()
const { typeMap } = state.remoteSchema
const allTypes = typeMap.values()
const implementingTypes = Array.from(allTypes)
.filter(
({ interfaces }) =>
interfaces &&
// find types that implement this interface type
interfaces.find(singleInterface => singleInterface.name === type.name)
)
.map(type => typeMap.get(type.name))
.filter(
type =>
type.kind !== `UNION` ||
// if this is a union type, make sure the union type has one or more member types, otherwise schema customization will throw an error
(!!type.possibleTypes && !!type.possibleTypes.length)
)
implementingTypeCache.set(type.name, implementingTypes)
return implementingTypes
}
const supportedScalars = [
`Int`,
`Float`,
`String`,
`Boolean`,
`ID`,
`Date`,
`JSON`,
]
export const typeIsABuiltInScalar = type =>
// @todo the next function and this one are redundant.
// see the next todo on how to fix the issue. If that todo is resolved, these functions will be identical. :(
supportedScalars.includes(findNamedTypeName(type))
export const typeIsASupportedScalar = type => {
if (findTypeKind(type) !== `SCALAR`) {
// @todo returning true here seems wrong since a type that is not a scalar can't be a supported scalar... so there is some other logic elsewhere that is wrong
// making this return false causes errors in the schema
return true
}
return supportedScalars.includes(findNamedTypeName(type))
}
const typeSettingCache = new Map()
// retrieves plugin settings for the provided type
export const getTypeSettingsByType = type => {
if (!type) {
return {}
}
const typeName = findNamedTypeName(type)
if (!typeName) {
return {}
}
const cachedTypeSettings = typeSettingCache.get(typeName)
if (cachedTypeSettings) {
return cachedTypeSettings
}
// the plugin options object containing every type setting
const allTypeSettings = getStore().getState().gatsbyApi.pluginOptions.type
const typeSettings = cloneDeep(allTypeSettings[typeName] || {})
// the type.__all plugin option which is applied to every type setting
const __allTypeSetting = cloneDeep(allTypeSettings.__all || {})
if (typeName === `MediaItem`) {
delete __allTypeSetting.limit
delete typeSettings.limit
}
if (typeSettings) {
const mergedSettings = merge(__allTypeSetting, typeSettings)
typeSettingCache.set(typeName, mergedSettings)
return mergedSettings
}
typeSettingCache.set(typeName, __allTypeSetting)
return __allTypeSetting
}
/**
* This is used to filter the automatically generated type definitions before they're added to the schema customization api.
*/
export const filterTypeDefinition = (
typeDefinition,
typeBuilderApi,
typeKind
) => {
const filters = typeDefinitionFilters.filter(filter =>
[typeBuilderApi.type.name, `__all`].includes(filter.typeName)
)
if (filters?.length) {
filters.forEach(filter => {
if (filter && typeof filter.typeDef === `function`) {
typeDefinition = filter.typeDef(
typeDefinition,
typeBuilderApi,
typeKind
)
}
})
}
return typeDefinition
}
// we should be using graphql-js for this kind of thing, but unfortunately this project didn't use it from the beginning so it would be a huge lift to refactor to use it now. In the future we will be rewriting this plugin using a new Gatsby source plugin toolkit, and at that time we'll use graphql-js.
// from introspection field types this will return a value like:
// `String` or `[String]` or `[String!]!` or `[String]!` or `[[String]]` or `[[String]!]!` or `[[String]!]`, etc
export const introspectionFieldTypeToSDL = fieldType => {
const openingTagsList = []
const closingTagsList = []
let reference = fieldType
while (reference) {
switch (reference.kind) {
case `SCALAR`: {
const normalizedTypeName = supportedScalars.includes(reference.name)
? reference.name
: `JSON`
openingTagsList.push(normalizedTypeName)
break
}
case `OBJECT`:
case `INTERFACE`:
case `UNION`:
openingTagsList.push(buildTypeName(reference.name))
break
case `NON_NULL`:
closingTagsList.push(`!`)
break
case `LIST`:
openingTagsList.push(`[`)
closingTagsList.push(`]`)
break
default:
break
}
reference = reference.ofType
}
return openingTagsList.join(``) + closingTagsList.reverse().join(``)
}
/**
* This is an expensive fn but it doesn't matter because it's only to show a debugging warning message when something is wrong.
*/
function mergeDuplicateTypesAndReturnDedupedList(typeDefs) {
const clonedDefs = cloneDeep(typeDefs)
const newList = []
for (const def of clonedDefs) {
if (!def) {
continue
}
const duplicateDefs = clonedDefs.filter(
d => d.config.name === def.config.name
)
const newDef = {}
for (const dDef of duplicateDefs) {
merge(newDef, dDef)
}
newList.push(newDef)
}
return newList
}
/**
* Diffs the built types between this build and the last one with the same remote schema hash.
* This is to catch and add helpful error messages for when an inconsistent schema between builds is inadvertently created due to some bug
*/
export async function diffBuiltTypeDefs(typeDefs) {
if (
process.env.NODE_ENV !== `development` &&
process.env.WP_DIFF_SCHEMA_CUSTOMIZATION !== `true`
) {
return
}
const state = getStore().getState()
const {
gatsbyApi: {
helpers: { cache, reporter },
},
remoteSchema,
} = state
const previousTypeDefsKey = withPluginKey(`previousTypeDefinitions`)
const previousTypeDefinitions = await cache.get(previousTypeDefsKey)
const typeDefString = JSON.stringify(typeDefs)
const typeNames = typeDefs.map(typeDef => typeDef.config.name)
const remoteSchemaChanged =
!previousTypeDefinitions ||
previousTypeDefinitions?.schemaHash !== remoteSchema.schemaHash
if (remoteSchemaChanged) {
await cache.set(previousTypeDefsKey, {
schemaHash: remoteSchema.schemaHash,
typeDefString,
typeNames,
})
return
}
// type defs are the same as last time, so don't check for missing/inconsistent types
if (previousTypeDefinitions?.typeDefString === typeDefString) {
return
}
const missingTypeNames = previousTypeDefinitions.typeNames.filter(
name => !typeNames.includes(name)
)
const previousTypeDefJson = mergeDuplicateTypesAndReturnDedupedList(
JSON.parse(previousTypeDefinitions.typeDefString)
)
const newParsedTypeDefs = mergeDuplicateTypesAndReturnDedupedList(
JSON.parse(typeDefString)
)
const changedTypeDefs = newParsedTypeDefs
.map(typeDef => {
const previousTypeDef = previousTypeDefJson.find(
previousTypeDef => previousTypeDef.config.name === typeDef.config.name
)
const isDifferent = diffString(previousTypeDef, typeDef)
if (isDifferent) {
return `Typename ${typeDef.config.name} diff:\n${diffString(
previousTypeDef,
typeDef,
{
// diff again to also show unchanged lines
full: true,
}
)}`
}
return null
})
.filter(Boolean)
let errorMessage = formatLogMessage(
`The remote WPGraphQL schema hasn't changed but local generated type definitions have. This is a bug, please open an issue on Github${
missingTypeNames.length || changedTypeDefs.length
? ` and include the following text.`
: ``
}.${
missingTypeNames.length
? `\n\nMissing type names: ${missingTypeNames.join(`\n`)}\n`
: ``
}${
changedTypeDefs.length
? `\n\nChanged type defs:\n\n${changedTypeDefs.join(`\n`)}`
: ``
}`
)
const maxErrorLength = 5000
if (errorMessage.length > maxErrorLength) {
errorMessage =
errorMessage.substring(0, maxErrorLength) +
`\n\n...\n[Diff exceeded ${maxErrorLength} characters and was truncated]`
}
if (process.env.WP_INCONSISTENT_SCHEMA_WARN !== `true`) {
reporter.info(
formatLogMessage(
`Panicking due to inconsistent schema customization. Turn this into a warning by setting process.env.WP_INCONSISTENT_SCHEMA_WARN to a string of "true"`
)
)
reporter.panic({
id: CODES.InconsistentSchemaCustomization,
context: {
sourceMessage: errorMessage,
},
})
} else {
reporter.warn(errorMessage)
}
}