-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
load-plugins.ts
680 lines (613 loc) · 19.2 KB
/
load-plugins.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
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
import { loadPlugins } from "../index"
import { slash } from "gatsby-core-utils"
import reporter from "gatsby-cli/lib/reporter"
import { IFlattenedPlugin } from "../types"
import { silent as resolveFrom } from "resolve-from"
const mockNonIncompatibleWarn = jest.fn()
jest.mock(`gatsby-cli/lib/reporter`, () => {
return {
error: jest.fn(),
panic: jest.fn(),
panicOnBuild: jest.fn(),
log: jest.fn(),
warn: jest.fn((...args) => {
// filter out compatible warnings as we get a lot of
// Plugin X is not compatible with your gatsby version X - It requires X
// right now
if (!args[0].includes(`is not compatible with your gatsby version`)) {
mockNonIncompatibleWarn(...args)
}
}),
success: jest.fn(),
info: jest.fn(),
}
})
// Previously babel transpiled src ts plugin files (e.g. gatsby-node files) on the fly,
// making them require-able/test-able without running compileGatsbyFiles prior (as would happen in a real scenario).
// After switching to import to support esm, point file path resolution to the real compiled JS files in dist instead.
jest.mock(`../../resolve-js-file-path`, () => {
return {
resolveJSFilepath: jest.fn(
({ filePath }) => `${filePath.replace(`src`, `dist`)}.js`
),
maybeAddFileProtocol: jest.fn(val => val),
}
})
jest.mock(`resolve-from`)
const mockProcessExit = jest.spyOn(process, `exit`).mockImplementation(() => {})
afterEach(() => {
Object.keys(reporter).forEach(method => {
reporter[method].mockClear()
})
resolveFrom.mockClear()
mockProcessExit.mockClear()
})
describe(`Load plugins`, () => {
/**
* Replace the resolve path and version string.
* Resolve path will vary depending on platform.
* Version can be updated (we use external plugin in default config).
* Both will cause snapshots to differ.
*/
const replaceFieldsThatCanVary = (
plugins: Array<IFlattenedPlugin>
): Array<IFlattenedPlugin> =>
plugins.map(plugin => {
if (plugin.pluginOptions && plugin.pluginOptions.path) {
plugin.pluginOptions = {
...plugin.pluginOptions,
path: plugin.pluginOptions.path.replace(
slash(process.cwd()),
`<PROJECT_ROOT>`
),
}
}
return {
...plugin,
id: ``,
resolve: ``,
version: `1.0.0`,
}
})
it(`Load plugins for a site`, async () => {
let plugins = await loadPlugins({ plugins: [] }, process.cwd())
plugins = replaceFieldsThatCanVary(plugins)
expect(plugins).toMatchSnapshot()
})
it(`Loads plugins defined with an object but without an options key`, async () => {
const config = {
plugins: [
{
resolve: `___TEST___`,
},
],
}
let plugins = await loadPlugins(config, process.cwd())
plugins = replaceFieldsThatCanVary(plugins)
expect(plugins).toMatchSnapshot()
})
it(`Throws an error when a plugin is defined with an option key`, async () => {
expect.assertions(1)
const config = {
plugins: [
{
resolve: `___TEST___`,
option: {
test: true,
},
},
],
}
try {
await loadPlugins(config, process.cwd())
} catch (err) {
expect(err.message).toMatchSnapshot()
}
})
it(`Overrides the options for gatsby-plugin-page-creator`, async () => {
const config = {
plugins: [
{
resolve: `gatsby-plugin-page-creator`,
options: {
path: `${__dirname}/src/pages`,
ignore: [`___Test___.(js|ts)?(x)`],
},
},
],
}
let plugins = await loadPlugins(config, process.cwd())
plugins = replaceFieldsThatCanVary(plugins)
expect(plugins).toMatchSnapshot()
})
describe(`TypeScript support`, () => {
it(`loads gatsby-plugin-typescript if not provided`, async () => {
const config = {
plugins: [],
}
let plugins = await loadPlugins(config, process.cwd())
plugins = replaceFieldsThatCanVary(plugins)
expect(plugins).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: `gatsby-plugin-typescript`,
}),
])
)
})
it(`uses the user provided plugin-typescript if provided`, async () => {
const config = {
plugins: [
{
resolve: `gatsby-plugin-typescript`,
options: {
jsxPragma: `h`,
},
},
],
}
let plugins = await loadPlugins(config, process.cwd())
plugins = replaceFieldsThatCanVary(plugins)
expect(plugins).toEqual(
expect.arrayContaining([
expect.objectContaining({
browserAPIs: [],
id: ``,
name: `gatsby-plugin-typescript`,
nodeAPIs: [
`pluginOptionsSchema`,
`resolvableExtensions`,
`onCreateBabelConfig`,
`onCreateWebpackConfig`,
],
pluginOptions: {
allExtensions: false,
isTSX: false,
jsxPragma: `h`,
plugins: [],
},
resolve: ``,
ssrAPIs: [],
version: `1.0.0`,
}),
])
)
})
it(`does not add gatsby-plugin-typescript if it exists in config.plugins`, async () => {
const config = {
plugins: [
`gatsby-plugin-typescript`,
{ resolve: `gatsby-plugin-typescript` },
],
}
let plugins = await loadPlugins(config, process.cwd())
plugins = replaceFieldsThatCanVary(plugins)
const tsplugins = plugins.filter(
(plugin: { name: string }) => plugin.name === `gatsby-plugin-typescript`
)
// TODO: I think we should probably be de-duping, so this should be 1.
// But this test is mostly here to ensure we don't add an _additional_ gatsby-plugin-typescript
expect(tsplugins.length).toEqual(2)
})
})
describe(`gatsby-plugin-gatsby-cloud support`, () => {
it(`doesn't load gatsby-plugin-gatsby-cloud if not installed`, async () => {
resolveFrom.mockImplementation(() => undefined)
const config = {
plugins: [],
}
let plugins = await loadPlugins(config, process.cwd())
plugins = replaceFieldsThatCanVary(plugins)
expect(plugins).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
name: `gatsby-plugin-gatsby-cloud`,
}),
])
)
})
it(`doesn't load gatsby-plugin-gatsby-cloud if not provided and installed`, async () => {
resolveFrom.mockImplementation(
(rootDir, pkg) => rootDir + `/node_modules/` + pkg
)
const config = {
plugins: [],
}
let plugins = await loadPlugins(config, process.cwd())
plugins = replaceFieldsThatCanVary(plugins)
expect(plugins).toEqual(
expect.arrayContaining([
expect.not.objectContaining({
name: `gatsby-plugin-gatsby-cloud`,
}),
])
)
})
it(`loads gatsby-plugin-gatsby-cloud if not provided and installed on gatsby-cloud`, async () => {
resolveFrom.mockImplementation((rootDir, pkg) => {
if (pkg !== `gatsby-plugin-gatsby-cloud`) {
return undefined
}
return rootDir + `/node_modules/` + pkg
})
const config = {
plugins: [],
}
process.env.GATSBY_CLOUD = `true`
let plugins = await loadPlugins(config, process.cwd())
delete process.env.GATSBY_CLOUD
plugins = replaceFieldsThatCanVary(plugins)
expect(plugins).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: `gatsby-plugin-gatsby-cloud`,
}),
])
)
})
it(`uses the user provided plugin-gatsby-cloud if provided`, async () => {
resolveFrom.mockImplementation((rootDir, pkg) => {
if (pkg !== `gatsby-plugin-gatsby-cloud`) {
return undefined
}
return rootDir + `/node_modules/` + pkg
})
const config = {
plugins: [
{
resolve: `gatsby-plugin-gatsby-cloud`,
options: {
generateMatchPathRewrites: false,
},
},
],
}
process.env.GATSBY_CLOUD = `true`
let plugins = await loadPlugins(config, process.cwd())
delete process.env.GATSBY_CLOUD
plugins = replaceFieldsThatCanVary(plugins)
expect(plugins).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: `gatsby-plugin-gatsby-cloud`,
pluginOptions: {
generateMatchPathRewrites: false,
plugins: [],
},
}),
])
)
})
it(`does not add gatsby-plugin-gatsby-cloud if it exists in config.plugins`, async () => {
resolveFrom.mockImplementation((rootDir, pkg) => {
if (pkg !== `gatsby-plugin-gatsby-cloud`) {
return undefined
}
return rootDir + `/node_modules/` + pkg
})
const config = {
plugins: [
`gatsby-plugin-gatsby-cloud`,
{ resolve: `gatsby-plugin-gatsby-cloud` },
],
}
let plugins = await loadPlugins(config, process.cwd())
plugins = replaceFieldsThatCanVary(plugins)
const cloudPlugins = plugins.filter(
(plugin: { name: string }) =>
plugin.name === `gatsby-plugin-gatsby-cloud`
)
// TODO: I think we should probably be de-duping, so this should be 1.
// But this test is mostly here to ensure we don't add an _additional_ gatsby-plugin-typescript
expect(cloudPlugins.length).toEqual(2)
})
})
describe(`plugin options validation`, () => {
it(`throws a structured error with invalid plugin options`, async () => {
const invalidPlugins = [
{
resolve: `gatsby-plugin-google-analytics`,
options: {
trackingId: 123,
anonymize: `not a boolean`,
},
},
{
resolve: `gatsby-plugin-google-analytics`,
options: {
anonymize: `still not a boolean`,
},
},
]
await loadPlugins(
{
plugins: invalidPlugins,
},
process.cwd()
)
expect(reporter.error as jest.Mock).toHaveBeenCalledTimes(
invalidPlugins.length
)
expect((reporter.error as jest.Mock).mock.calls[0])
.toMatchInlineSnapshot(`
Array [
Object {
"context": Object {
"configDir": null,
"pluginName": "gatsby-plugin-google-analytics",
"validationErrors": Array [
Object {
"context": Object {
"key": "trackingId",
"label": "trackingId",
"value": 123,
},
"message": "\\"trackingId\\" must be a string",
"path": Array [
"trackingId",
],
"type": "string.base",
},
Object {
"context": Object {
"key": "anonymize",
"label": "anonymize",
"value": "not a boolean",
},
"message": "\\"anonymize\\" must be a boolean",
"path": Array [
"anonymize",
],
"type": "boolean.base",
},
],
},
"id": "11331",
},
]
`)
expect((reporter.error as jest.Mock).mock.calls[1])
.toMatchInlineSnapshot(`
Array [
Object {
"context": Object {
"configDir": null,
"pluginName": "gatsby-plugin-google-analytics",
"validationErrors": Array [
Object {
"context": Object {
"key": "trackingId",
"label": "trackingId",
},
"message": "\\"trackingId\\" is required",
"path": Array [
"trackingId",
],
"type": "any.required",
},
Object {
"context": Object {
"key": "anonymize",
"label": "anonymize",
"value": "still not a boolean",
},
"message": "\\"anonymize\\" must be a boolean",
"path": Array [
"anonymize",
],
"type": "boolean.base",
},
],
},
"id": "11331",
},
]
`)
expect(mockProcessExit).toHaveBeenCalledWith(1)
})
it(`allows unknown options`, async () => {
const plugins = [
{
resolve: `gatsby-plugin-google-analytics`,
options: {
trackingId: `yes`,
doesThisExistInTheSchema: `no`,
},
},
]
await loadPlugins(
{
plugins,
},
process.cwd()
)
expect(reporter.error as jest.Mock).toHaveBeenCalledTimes(0)
expect(mockNonIncompatibleWarn as jest.Mock).toHaveBeenCalledTimes(1)
expect((mockNonIncompatibleWarn as jest.Mock).mock.calls[0])
.toMatchInlineSnapshot(`
Array [
"Warning: there are unknown plugin options for \\"gatsby-plugin-google-analytics\\": doesThisExistInTheSchema
Please open an issue at https://ghub.io/gatsby-plugin-google-analytics if you believe this option is valid.",
]
`)
expect(mockProcessExit).not.toHaveBeenCalled()
})
it(`defaults plugin options to the ones defined in the schema`, async () => {
let plugins = await loadPlugins(
{
plugins: [
{
resolve: `gatsby-plugin-google-analytics`,
options: {
trackingId: `fake`,
},
},
],
},
process.cwd()
)
plugins = replaceFieldsThatCanVary(plugins)
expect(
plugins.find(plugin => plugin.name === `gatsby-plugin-google-analytics`)
.pluginOptions
).toEqual({
// All the options that have defaults are defined
anonymize: false,
enableWebVitalsTracking: false,
exclude: [],
head: false,
pageTransitionDelay: 0,
plugins: [],
respectDNT: false,
trackingId: `fake`,
})
})
it(`validates subplugin schemas`, async () => {
await loadPlugins(
{
plugins: [
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-autolink-headers`,
options: {
maintainCase: `should be boolean`,
},
},
],
},
},
],
},
process.cwd()
)
expect(reporter.error as jest.Mock).toHaveBeenCalledTimes(1)
expect((reporter.error as jest.Mock).mock.calls[0])
.toMatchInlineSnapshot(`
Array [
Object {
"context": Object {
"configDir": null,
"pluginName": "gatsby-remark-autolink-headers",
"validationErrors": Array [
Object {
"context": Object {
"key": "maintainCase",
"label": "maintainCase",
"value": "should be boolean",
},
"message": "\\"maintainCase\\" must be a boolean",
"path": Array [
"maintainCase",
],
"type": "boolean.base",
},
],
},
"id": "11331",
},
]
`)
expect(mockProcessExit).toHaveBeenCalledWith(1)
})
it(`subplugins are resolved using "main" in package.json`, async () => {
// in fixtures/subplugins/node_modules/gatsby-plugin-child-with-main/package.json
// "main" field points to "lib/index.js"
const plugins = await loadPlugins(
{
plugins: [
{
resolve: `gatsby-plugin-parent`,
options: {
testSubplugins: [
`gatsby-plugin-child-no-main`,
`gatsby-plugin-child-with-main`,
],
},
},
],
},
__dirname + `/fixtures/subplugins`
)
// "module.exports" in entry files for subplugins contain just a string
// for tests purposes (so we can assert "module" field on subplugins items)
expect(
plugins.find(plugin => plugin.name === `gatsby-plugin-parent`)
?.pluginOptions?.testSubplugins
).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: `gatsby-plugin-child-with-main`,
module: `export-test-gatsby-plugin-child-with-main`,
modulePath: expect.stringMatching(
/gatsby-plugin-child-with-main[/\\]lib[/\\]index\.js$/
),
}),
expect.objectContaining({
name: `gatsby-plugin-child-no-main`,
module: `export-test-gatsby-plugin-child-no-main`,
modulePath: expect.stringMatching(
/gatsby-plugin-child-no-main[/\\]index\.js$/
),
}),
])
)
})
it(`validates local plugin schemas using require.resolve`, async () => {
await loadPlugins(
{
plugins: [
{
resolve: require.resolve(`./fixtures/local-plugin`),
options: {
optionalString: 1234,
},
},
],
},
process.cwd()
)
expect(reporter.error as jest.Mock).toHaveBeenCalledTimes(1)
expect((reporter.error as jest.Mock).mock.calls[0])
.toMatchInlineSnapshot(`
Array [
Object {
"context": Object {
"configDir": null,
"pluginName": "<PROJECT_ROOT>/packages/gatsby/src/bootstrap/load-plugins/__tests__/fixtures/local-plugin/index.js",
"validationErrors": Array [
Object {
"context": Object {
"key": "required",
"label": "required",
},
"message": "\\"required\\" is required",
"path": Array [
"required",
],
"type": "any.required",
},
Object {
"context": Object {
"key": "optionalString",
"label": "optionalString",
"value": 1234,
},
"message": "\\"optionalString\\" must be a string",
"path": Array [
"optionalString",
],
"type": "string.base",
},
],
},
"id": "11331",
},
]
`)
expect(mockProcessExit).toHaveBeenCalledWith(1)
})
})
})