-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathindex.js
1694 lines (1473 loc) · 52.2 KB
/
index.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
jest.mock('../packages/runtime/src/helpers/utils', () => {
return {
...jest.requireActual('../packages/runtime/src/helpers/utils'),
isNextAuthInstalled: jest.fn(),
}
})
const Chance = require('chance')
const { writeJSON, unlink, existsSync, readFileSync, copy, ensureDir, readJson } = require('fs-extra')
const path = require('path')
const process = require('process')
const os = require('os')
const cpy = require('cpy')
const { dir: getTmpDir } = require('tmp-promise')
const { downloadFile } = require('../packages/runtime/src/templates/handlerUtils')
const { getExtendedApiRouteConfigs } = require('../packages/runtime/src/helpers/functions')
const nextRuntimeFactory = require('../packages/runtime/src')
const nextRuntime = nextRuntimeFactory({})
const { HANDLER_FUNCTION_NAME, ODB_FUNCTION_NAME, IMAGE_FUNCTION_NAME } = require('../packages/runtime/src/constants')
const { join } = require('pathe')
const {
matchMiddleware,
stripLocale,
matchesRedirect,
matchesRewrite,
patchNextFiles,
unpatchNextFiles,
} = require('../packages/runtime/src/helpers/files')
const {
getRequiredServerFiles,
updateRequiredServerFiles,
generateCustomHeaders,
} = require('../packages/runtime/src/helpers/config')
const { dirname } = require('path')
const { getProblematicUserRewrites } = require('../packages/runtime/src/helpers/verification')
const chance = new Chance()
const FIXTURES_DIR = `${__dirname}/fixtures`
const SAMPLE_PROJECT_DIR = `${__dirname}/../demos/default`
const constants = {
INTERNAL_FUNCTIONS_SRC: '.netlify/functions-internal',
PUBLISH_DIR: '.next',
FUNCTIONS_DIST: '.netlify/functions',
}
const utils = {
build: {
failBuild(message) {
throw new Error(message)
},
},
run: async () => void 0,
cache: {
save: jest.fn(),
restore: jest.fn(),
},
}
const REDIRECTS = [
{
source: '/:file((?!\\.well-known(?:/.*)?)(?:[^/]+/)*[^/]+\\.\\w+)/',
destination: '/:file',
locale: false,
internal: true,
statusCode: 308,
regex: '^(?:/((?!\\.well-known(?:/.*)?)(?:[^/]+/)*[^/]+\\.\\w+))/$',
},
{
source: '/:notfile((?!\\.well-known(?:/.*)?)(?:[^/]+/)*[^/\\.]+)',
destination: '/:notfile/',
locale: false,
internal: true,
statusCode: 308,
regex: '^(?:/((?!\\.well-known(?:/.*)?)(?:[^/]+/)*[^/\\.]+))$',
},
{
source: '/en/redirectme',
destination: '/',
statusCode: 308,
regex: '^(?!/_next)/en/redirectme(?:/)?$',
},
{
source: '/:nextInternalLocale(en|es|fr)/redirectme',
destination: '/:nextInternalLocale/',
statusCode: 308,
regex: '^(?!/_next)(?:/(en|es|fr))/redirectme(?:/)?$',
},
]
const REWRITES = [
{
source: '/:nextInternalLocale(en|es|fr)/old/:path*',
destination: '/:nextInternalLocale/:path*',
regex: '^(?:/(en|es|fr))/old(?:/((?:[^/]+?)(?:/(?:[^/]+?))*))?(?:/)?$',
},
]
// Temporary switch cwd
const changeCwd = function (cwd) {
const originalCwd = process.cwd()
process.chdir(cwd)
return () => {
process.chdir(originalCwd)
}
}
const onBuildHasRun = (netlifyConfig) =>
Boolean(netlifyConfig.functions[HANDLER_FUNCTION_NAME]?.included_files?.some((file) => file.includes('BUILD_ID')))
const rewriteAppDir = async function (dir = '.next') {
const manifest = path.join(dir, 'required-server-files.json')
const manifestContent = await readJson(manifest)
manifestContent.appDir = process.cwd()
await writeJSON(manifest, manifestContent)
}
// Move .next from sample project to current directory
export const moveNextDist = async function (dir = '.next') {
await stubModules(['next', 'sharp'])
await ensureDir(dirname(dir))
await copy(path.join(SAMPLE_PROJECT_DIR, '.next'), path.join(process.cwd(), dir))
await copy(path.join(SAMPLE_PROJECT_DIR, 'pages'), path.join(process.cwd(), 'pages'))
await rewriteAppDir(dir)
}
const stubModules = async function (modules) {
for (const mod of modules) {
const dir = path.join(process.cwd(), 'node_modules', mod)
await ensureDir(dir)
await writeJSON(path.join(dir, 'package.json'), { name: mod })
}
}
// Copy fixture files to the current directory
const useFixture = async function (fixtureName) {
const fixtureDir = `${FIXTURES_DIR}/${fixtureName}`
await cpy('**', process.cwd(), { cwd: fixtureDir, parents: true, overwrite: true, dot: true })
}
const netlifyConfig = { build: { command: 'npm run build' }, functions: {}, redirects: [], headers: [] }
const defaultArgs = {
netlifyConfig,
utils,
constants,
}
let restoreCwd
let cleanup
// In each test, we change cwd to a temporary directory.
// This allows us not to have to mock filesystem operations.
beforeEach(async () => {
const tmpDir = await getTmpDir({ unsafeCleanup: true })
restoreCwd = changeCwd(tmpDir.path)
cleanup = tmpDir.cleanup
netlifyConfig.build.publish = path.resolve('.next')
netlifyConfig.build.environment = {}
netlifyConfig.redirects = []
netlifyConfig.headers = []
netlifyConfig.functions[HANDLER_FUNCTION_NAME] && (netlifyConfig.functions[HANDLER_FUNCTION_NAME].included_files = [])
netlifyConfig.functions[ODB_FUNCTION_NAME] && (netlifyConfig.functions[ODB_FUNCTION_NAME].included_files = [])
netlifyConfig.functions['_api_*'] && (netlifyConfig.functions['_api_*'].included_files = [])
await useFixture('serverless_next_config')
})
afterEach(async () => {
jest.clearAllMocks()
jest.resetAllMocks()
// Cleans up the temporary directory from `getTmpDir()` and do not make it
// the current directory anymore
restoreCwd()
await cleanup()
})
describe('preBuild()', () => {
test('fails if publishing the root of the project', () => {
defaultArgs.netlifyConfig.build.publish = path.resolve('.')
expect(nextRuntime.onPreBuild(defaultArgs)).rejects.toThrowError(
/Your publish directory is pointing to the base directory of your site/,
)
})
test('fails if the build version is too old', () => {
expect(
nextRuntime.onPreBuild({
...defaultArgs,
constants: { IS_LOCAL: true, NETLIFY_BUILD_VERSION: '18.15.0' },
}),
).rejects.toThrow('This version of the Next Runtime requires netlify-cli')
})
test('passes if the build version is new enough', async () => {
expect(
nextRuntime.onPreBuild({
...defaultArgs,
constants: { IS_LOCAL: true, NETLIFY_BUILD_VERSION: '18.16.1' },
}),
).resolves.not.toThrow()
})
it('restores cache with right paths', async () => {
await useFixture('dist_dir_next_config')
const restore = jest.fn()
await nextRuntime.onPreBuild({
...defaultArgs,
utils: { ...utils, cache: { restore } },
})
expect(restore).toHaveBeenCalledWith(path.resolve('.next/cache'))
})
it('forces the target to "server"', async () => {
const netlifyConfig = { ...defaultArgs.netlifyConfig }
await nextRuntime.onPreBuild({ ...defaultArgs, netlifyConfig })
expect(netlifyConfig.build.environment.NEXT_PRIVATE_TARGET).toBe('server')
})
})
describe('onBuild()', () => {
const { isNextAuthInstalled } = require('../packages/runtime/src/helpers/utils')
beforeEach(() => {
isNextAuthInstalled.mockImplementation(() => {
return true
})
})
afterEach(() => {
delete process.env.DEPLOY_PRIME_URL
delete process.env.URL
delete process.env.CONTEXT
})
test('does not set NEXTAUTH_URL if value is already set', async () => {
const mockUserDefinedSiteUrl = chance.url()
process.env.DEPLOY_PRIME_URL = chance.url()
await moveNextDist()
const initialConfig = await getRequiredServerFiles(netlifyConfig.build.publish)
initialConfig.config.env.NEXTAUTH_URL = mockUserDefinedSiteUrl
await updateRequiredServerFiles(netlifyConfig.build.publish, initialConfig)
await nextRuntime.onBuild(defaultArgs)
expect(onBuildHasRun(netlifyConfig)).toBe(true)
const config = await getRequiredServerFiles(netlifyConfig.build.publish)
expect(config.config.env.NEXTAUTH_URL).toEqual(mockUserDefinedSiteUrl)
})
test("sets the NEXTAUTH_URL to the DEPLOY_PRIME_URL when CONTEXT env variable is not 'production'", async () => {
const mockUserDefinedSiteUrl = chance.url()
process.env.DEPLOY_PRIME_URL = mockUserDefinedSiteUrl
process.env.URL = chance.url()
// See https://docs.netlify.com/configure-builds/environment-variables/#build-metadata for all possible values
process.env.CONTEXT = 'deploy-preview'
await moveNextDist()
const initialConfig = await getRequiredServerFiles(netlifyConfig.build.publish)
initialConfig.config.env.NEXTAUTH_URL = mockUserDefinedSiteUrl
await updateRequiredServerFiles(netlifyConfig.build.publish, initialConfig)
await nextRuntime.onBuild(defaultArgs)
expect(onBuildHasRun(netlifyConfig)).toBe(true)
const config = await getRequiredServerFiles(netlifyConfig.build.publish)
expect(config.config.env.NEXTAUTH_URL).toEqual(mockUserDefinedSiteUrl)
})
test("sets the NEXTAUTH_URL to the user defined site URL when CONTEXT env variable is 'production'", async () => {
const mockUserDefinedSiteUrl = chance.url()
process.env.DEPLOY_PRIME_URL = chance.url()
process.env.URL = mockUserDefinedSiteUrl
// See https://docs.netlify.com/configure-builds/environment-variables/#build-metadata for all possible values
process.env.CONTEXT = 'production'
await moveNextDist()
const initialConfig = await getRequiredServerFiles(netlifyConfig.build.publish)
initialConfig.config.env.NEXTAUTH_URL = mockUserDefinedSiteUrl
await updateRequiredServerFiles(netlifyConfig.build.publish, initialConfig)
await nextRuntime.onBuild(defaultArgs)
expect(onBuildHasRun(netlifyConfig)).toBe(true)
const config = await getRequiredServerFiles(netlifyConfig.build.publish)
expect(config.config.env.NEXTAUTH_URL).toEqual(mockUserDefinedSiteUrl)
})
test('sets the NEXTAUTH_URL specified in the netlify.toml or in the Netlify UI', async () => {
const mockSiteUrl = chance.url()
process.env.NEXTAUTH_URL = mockSiteUrl
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
expect(onBuildHasRun(netlifyConfig)).toBe(true)
const config = await getRequiredServerFiles(netlifyConfig.build.publish)
expect(config.config.env.NEXTAUTH_URL).toEqual(mockSiteUrl)
delete process.env.NEXTAUTH_URL
})
test('sets NEXTAUTH_URL when next-auth package is detected', async () => {
const mockSiteUrl = chance.url()
// Value represents the main address to the site and is either
// a Netlify subdomain or custom domain set by the user.
// See https://docs.netlify.com/configure-builds/environment-variables/#deploy-urls-and-metadata
process.env.DEPLOY_PRIME_URL = mockSiteUrl
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
expect(onBuildHasRun(netlifyConfig)).toBe(true)
const config = await getRequiredServerFiles(netlifyConfig.build.publish)
expect(config.config.env.NEXTAUTH_URL).toEqual(mockSiteUrl)
})
test('includes the basePath on NEXTAUTH_URL when present', async () => {
const mockSiteUrl = chance.url()
process.env.DEPLOY_PRIME_URL = mockSiteUrl
await moveNextDist()
const initialConfig = await getRequiredServerFiles(netlifyConfig.build.publish)
initialConfig.config.basePath = '/foo'
await updateRequiredServerFiles(netlifyConfig.build.publish, initialConfig)
await nextRuntime.onBuild(defaultArgs)
expect(onBuildHasRun(netlifyConfig)).toBe(true)
const config = await getRequiredServerFiles(netlifyConfig.build.publish)
expect(config.config.env.NEXTAUTH_URL).toEqual(`${mockSiteUrl}/foo`)
})
test('skips setting NEXTAUTH_URL when next-auth package is not found', async () => {
isNextAuthInstalled.mockImplementation(() => {
return false
})
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
expect(onBuildHasRun(netlifyConfig)).toBe(true)
const config = await getRequiredServerFiles(netlifyConfig.build.publish)
expect(config.config.env.NEXTAUTH_URL).toBeUndefined()
})
test('runs onBuild', async () => {
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
expect(onBuildHasRun(netlifyConfig)).toBe(true)
})
test('skips if NETLIFY_NEXT_PLUGIN_SKIP is set', async () => {
process.env.NETLIFY_NEXT_PLUGIN_SKIP = 'true'
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
expect(onBuildHasRun(netlifyConfig)).toBe(false)
delete process.env.NETLIFY_NEXT_PLUGIN_SKIP
})
test('skips if NEXT_PLUGIN_FORCE_RUN is "false"', async () => {
process.env.NEXT_PLUGIN_FORCE_RUN = 'false'
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
expect(onBuildHasRun(netlifyConfig)).toBe(false)
delete process.env.NEXT_PLUGIN_FORCE_RUN
})
test("fails if BUILD_ID doesn't exist", async () => {
await moveNextDist()
await unlink(path.join(process.cwd(), '.next/BUILD_ID'))
const failBuild = jest.fn().mockImplementation((err) => {
throw new Error(err)
})
expect(() => nextRuntime.onBuild({ ...defaultArgs, utils: { ...utils, build: { failBuild } } })).rejects.toThrow(
`In most cases it should be set to ".next", unless you have chosen a custom "distDir" in your Next config.`,
)
expect(failBuild).toHaveBeenCalled()
})
test("fails with helpful warning if BUILD_ID doesn't exist and publish is 'out'", async () => {
await moveNextDist()
await unlink(path.join(process.cwd(), '.next/BUILD_ID'))
const failBuild = jest.fn().mockImplementation((err) => {
throw new Error(err)
})
netlifyConfig.build.publish = path.resolve('out')
expect(() => nextRuntime.onBuild({ ...defaultArgs, utils: { ...utils, build: { failBuild } } })).rejects.toThrow(
`Your publish directory is set to "out", but in most cases it should be ".next".`,
)
expect(failBuild).toHaveBeenCalled()
})
test('fails build if next export has run', async () => {
await moveNextDist()
await writeJSON(path.join(process.cwd(), '.next/export-detail.json'), {})
const failBuild = jest.fn()
await nextRuntime.onBuild({ ...defaultArgs, utils: { ...utils, build: { failBuild } } })
expect(failBuild).toHaveBeenCalled()
})
test('copy handlers to the internal functions directory', async () => {
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
expect(existsSync(`.netlify/functions-internal/___netlify-handler/___netlify-handler.js`)).toBeTruthy()
expect(existsSync(`.netlify/functions-internal/___netlify-handler/bridge.js`)).toBeTruthy()
expect(existsSync(`.netlify/functions-internal/___netlify-handler/handlerUtils.js`)).toBeTruthy()
expect(existsSync(`.netlify/functions-internal/___netlify-odb-handler/___netlify-odb-handler.js`)).toBeTruthy()
expect(existsSync(`.netlify/functions-internal/___netlify-odb-handler/bridge.js`)).toBeTruthy()
expect(existsSync(`.netlify/functions-internal/___netlify-odb-handler/handlerUtils.js`)).toBeTruthy()
})
test('writes correct redirects to netlifyConfig', async () => {
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
// Not ideal, because it doesn't test precedence, but unfortunately the exact order seems to
// be non-deterministic, as it depends on filesystem globbing across platforms.
const sorted = [...netlifyConfig.redirects].sort((a, b) => a.from.localeCompare(b.from))
expect(sorted).toMatchSnapshot()
})
test('publish dir is/has next dist', async () => {
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
expect(existsSync(path.resolve('.next/BUILD_ID'))).toBeTruthy()
})
test('generates static files manifest', async () => {
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
const manifestPath = path.resolve('.next/static-manifest.json')
expect(existsSync(manifestPath)).toBeTruthy()
const data = (await readJson(manifestPath)).sort()
expect(data).toMatchSnapshot()
})
test('moves static files to root', async () => {
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
const data = JSON.parse(readFileSync(path.resolve('.next/static-manifest.json'), 'utf8'))
data.forEach(([_, file]) => {
expect(existsSync(path.resolve(path.join('.next', file)))).toBeTruthy()
expect(existsSync(path.resolve(path.join('.next', 'server', 'pages', file)))).toBeFalsy()
})
})
test('copies default locale files to top level', async () => {
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
const data = JSON.parse(readFileSync(path.resolve('.next/static-manifest.json'), 'utf8'))
const locale = 'en/'
data.forEach(([_, file]) => {
if (!file.startsWith(locale)) {
return
}
const trimmed = file.substring(locale.length)
expect(existsSync(path.resolve(path.join('.next', trimmed)))).toBeTruthy()
})
})
// TODO - TO BE MOVED TO TEST AGAINST A PROJECT WITH MIDDLEWARE IN ANOTHER PR
test.skip('skips static files that match middleware', async () => {
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
expect(existsSync(path.resolve(path.join('.next', 'en', 'middle.html')))).toBeFalsy()
expect(existsSync(path.resolve(path.join('.next', 'server', 'pages', 'en', 'middle.html')))).toBeTruthy()
})
test('sets correct config', async () => {
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
const includes = [
'.env',
'.env.local',
'.env.production',
'.env.production.local',
'./public/locales/**',
'./next-i18next.config.js',
'.next/server/**',
'.next/serverless/**',
'.next/*.json',
'.next/BUILD_ID',
'.next/static/chunks/webpack-middleware*.js',
'!.next/server/**/*.js.nft.json',
'!.next/server/**/*.map',
'!**/node_modules/@next/swc*/**/*',
'!../../node_modules/next/dist/compiled/@ampproject/toolbox-optimizer/**/*',
`!node_modules/next/dist/server/lib/squoosh/**/*.wasm`,
`!node_modules/next/dist/next-server/server/lib/squoosh/**/*.wasm`,
'!node_modules/next/dist/compiled/webpack/bundle4.js',
'!node_modules/next/dist/compiled/webpack/bundle5.js',
'!node_modules/sharp/**/*',
]
// Relative paths in Windows are different
if (os.platform() !== 'win32') {
expect(netlifyConfig.functions[HANDLER_FUNCTION_NAME].included_files).toEqual(includes)
expect(netlifyConfig.functions[ODB_FUNCTION_NAME].included_files).toEqual(includes)
}
expect(netlifyConfig.functions[HANDLER_FUNCTION_NAME].node_bundler).toEqual('nft')
expect(netlifyConfig.functions[ODB_FUNCTION_NAME].node_bundler).toEqual('nft')
})
const excludesSharp = (includedFiles) => includedFiles.some((file) => file.startsWith('!') && file.includes('sharp'))
it("doesn't exclude sharp if manually included", async () => {
await moveNextDist()
const functions = [HANDLER_FUNCTION_NAME, ODB_FUNCTION_NAME, '_api_*']
await nextRuntime.onBuild(defaultArgs)
// Should exclude by default
for (const func of functions) {
expect(excludesSharp(netlifyConfig.functions[func].included_files)).toBeTruthy()
}
// ...but if the user has added it, we shouldn't exclude it
for (const func of functions) {
netlifyConfig.functions[func].included_files = ['node_modules/sharp/**/*']
}
await nextRuntime.onBuild(defaultArgs)
for (const func of functions) {
expect(excludesSharp(netlifyConfig.functions[func].included_files)).toBeFalsy()
}
// ...even if it's in a subdirectory
for (const func of functions) {
netlifyConfig.functions[func].included_files = ['subdirectory/node_modules/sharp/**/*']
}
await nextRuntime.onBuild(defaultArgs)
for (const func of functions) {
expect(excludesSharp(netlifyConfig.functions[func].included_files)).toBeFalsy()
}
})
it('generates a file referencing all page sources', async () => {
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
for (const route of ['_api_hello-background-background', '_api_hello-scheduled-handler']) {
const expected = path.resolve(constants.INTERNAL_FUNCTIONS_SRC, route, 'pages.js')
expect(existsSync(expected)).toBeTruthy()
expect(readFileSync(expected, 'utf8')).toMatchSnapshot(`for ${route}`)
}
})
test('generates a file referencing all API route sources', async () => {
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
const handlerPagesFile = path.join(constants.INTERNAL_FUNCTIONS_SRC, HANDLER_FUNCTION_NAME, 'pages.js')
const odbHandlerPagesFile = path.join(constants.INTERNAL_FUNCTIONS_SRC, ODB_FUNCTION_NAME, 'pages.js')
expect(existsSync(handlerPagesFile)).toBeTruthy()
expect(existsSync(odbHandlerPagesFile)).toBeTruthy()
expect(readFileSync(handlerPagesFile, 'utf8')).toMatchSnapshot()
expect(readFileSync(odbHandlerPagesFile, 'utf8')).toMatchSnapshot()
})
test('generates a file referencing all when publish dir is a subdirectory', async () => {
const dir = 'web/.next'
await moveNextDist(dir)
netlifyConfig.build.publish = path.resolve(dir)
const config = {
...defaultArgs,
netlifyConfig,
constants: { ...constants, PUBLISH_DIR: dir },
}
await nextRuntime.onBuild(config)
const handlerPagesFile = path.join(constants.INTERNAL_FUNCTIONS_SRC, HANDLER_FUNCTION_NAME, 'pages.js')
const odbHandlerPagesFile = path.join(constants.INTERNAL_FUNCTIONS_SRC, ODB_FUNCTION_NAME, 'pages.js')
expect(readFileSync(handlerPagesFile, 'utf8')).toMatchSnapshot()
expect(readFileSync(odbHandlerPagesFile, 'utf8')).toMatchSnapshot()
})
test('generates entrypoints with correct references', async () => {
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
const handlerFile = path.join(
constants.INTERNAL_FUNCTIONS_SRC,
HANDLER_FUNCTION_NAME,
`${HANDLER_FUNCTION_NAME}.js`,
)
const odbHandlerFile = path.join(constants.INTERNAL_FUNCTIONS_SRC, ODB_FUNCTION_NAME, `${ODB_FUNCTION_NAME}.js`)
expect(existsSync(handlerFile)).toBeTruthy()
expect(existsSync(odbHandlerFile)).toBeTruthy()
expect(readFileSync(handlerFile, 'utf8')).toMatch(`(config, "../../..", pageRoot, staticManifest, 'ssr')`)
expect(readFileSync(odbHandlerFile, 'utf8')).toMatch(`(config, "../../..", pageRoot, staticManifest, 'odb')`)
expect(readFileSync(handlerFile, 'utf8')).toMatch(`require("../../../.next/required-server-files.json")`)
expect(readFileSync(odbHandlerFile, 'utf8')).toMatch(`require("../../../.next/required-server-files.json")`)
})
test('handles empty routesManifest.staticRoutes', async () => {
await moveNextDist()
const manifestPath = path.resolve('.next/routes-manifest.json')
const routesManifest = await readJson(manifestPath)
delete routesManifest.staticRoutes
await writeJSON(manifestPath, routesManifest)
// The function is supposed to return undefined, but we want to check if it throws
expect(await nextRuntime.onBuild(defaultArgs)).toBeUndefined()
})
test('generates imageconfig file with entries for domains, remotePatterns, and custom response headers', async () => {
await moveNextDist()
const mockHeaderValue = chance.string()
const updatedArgs = {
...defaultArgs,
netlifyConfig: {
...defaultArgs.netlifyConfig,
headers: [
{
for: '/_next/image/',
values: {
'X-Foo': mockHeaderValue,
},
},
],
},
}
await nextRuntime.onBuild(updatedArgs)
const imageConfigPath = path.join(constants.INTERNAL_FUNCTIONS_SRC, IMAGE_FUNCTION_NAME, 'imageconfig.json')
const imageConfigJson = await readJson(imageConfigPath)
expect(imageConfigJson.domains.length).toBe(1)
expect(imageConfigJson.remotePatterns.length).toBe(1)
expect(imageConfigJson.responseHeaders).toStrictEqual({
'X-Foo': mockHeaderValue,
})
})
test('generates an ipx function by default', async () => {
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
expect(existsSync(path.join('.netlify', 'functions-internal', '_ipx', '_ipx.js'))).toBeTruthy()
})
test('does not generate an ipx function when DISABLE_IPX is set', async () => {
process.env.DISABLE_IPX = '1'
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
expect(existsSync(path.join('.netlify', 'functions-internal', '_ipx', '_ipx.js'))).toBeFalsy()
delete process.env.DISABLE_IPX
})
test('creates 404 redirect when DISABLE_IPX is set', async () => {
process.env.DISABLE_IPX = '1'
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
const nextImageRedirect = netlifyConfig.redirects.find((redirect) => redirect.from.includes('/_next/image'))
expect(nextImageRedirect).toBeDefined()
expect(nextImageRedirect.to).toEqual('/404.html')
expect(nextImageRedirect.status).toEqual(404)
expect(nextImageRedirect.force).toEqual(true)
delete process.env.DISABLE_IPX
})
test('generates an ipx edge function by default', async () => {
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
expect(existsSync(path.join('.netlify', 'edge-functions', 'ipx', 'index.ts'))).toBeTruthy()
})
test('does not generate an ipx edge function if the feature is disabled', async () => {
process.env.NEXT_DISABLE_EDGE_IMAGES = '1'
await moveNextDist()
await nextRuntime.onBuild(defaultArgs)
expect(existsSync(path.join('.netlify', 'edge-functions', 'ipx', 'index.ts'))).toBeFalsy()
delete process.env.NEXT_DISABLE_EDGE_IMAGES
})
test('does not generate an ipx edge function if Netlify Edge is disabled', async () => {
process.env.NEXT_DISABLE_NETLIFY_EDGE = '1'
await moveNextDist()
// We need to pretend there's no edge API routes, because otherwise it'll fail
// when we try to disable edge runtime.
const manifest = path.join('.next', 'server', 'middleware-manifest.json')
const manifestContent = await readJson(manifest)
manifestContent.functions = {}
await writeJSON(manifest, manifestContent)
await nextRuntime.onBuild(defaultArgs)
expect(existsSync(path.join('.netlify', 'edge-functions', 'ipx', 'index.ts'))).toBeFalsy()
delete process.env.NEXT_DISABLE_NETLIFY_EDGE
})
})
describe('onPostBuild', () => {
test('saves cache with right paths', async () => {
await moveNextDist()
const save = jest.fn()
await nextRuntime.onPostBuild({
...defaultArgs,
utils: { ...utils, cache: { save }, functions: { list: jest.fn().mockResolvedValue([]) } },
})
expect(save).toHaveBeenCalledWith(path.resolve('.next/cache'))
})
test('warns if old functions exist', async () => {
await moveNextDist()
const list = jest.fn().mockResolvedValue([
{
name: 'next_test',
mainFile: join(constants.INTERNAL_FUNCTIONS_SRC, 'next_test', 'next_test.js'),
runtime: 'js',
extension: '.js',
},
{
name: 'next_demo',
mainFile: join(constants.INTERNAL_FUNCTIONS_SRC, 'next_demo', 'next_demo.js'),
runtime: 'js',
extension: '.js',
},
])
const oldLog = console.log
const logMock = jest.fn()
console.log = logMock
await nextRuntime.onPostBuild({
...defaultArgs,
utils: { ...utils, cache: { save: jest.fn() }, functions: { list } },
})
expect(logMock).toHaveBeenCalledWith(
expect.stringContaining(
`We have found the following functions in your site that seem to be left over from the old Next.js plugin (v3). We have guessed this because the name starts with "next_".`,
),
)
console.log = oldLog
})
test('warns if NETLIFY_NEXT_PLUGIN_SKIP is set', async () => {
await moveNextDist()
process.env.NETLIFY_NEXT_PLUGIN_SKIP = 'true'
await moveNextDist()
const show = jest.fn()
await nextRuntime.onPostBuild({ ...defaultArgs, utils: { ...defaultArgs.utils, status: { show } } })
expect(show).toHaveBeenCalledWith({
summary: 'Next cache was stored, but all other functions were skipped because NETLIFY_NEXT_PLUGIN_SKIP is set',
title: 'Next Runtime did not run',
})
delete process.env.NETLIFY_NEXT_PLUGIN_SKIP
})
test('warns if NEXT_PLUGIN_FORCE_RUN is "false"', async () => {
await moveNextDist()
process.env.NEXT_PLUGIN_FORCE_RUN = 'false'
await moveNextDist()
const show = jest.fn()
await nextRuntime.onPostBuild({ ...defaultArgs, utils: { ...defaultArgs.utils, status: { show } } })
expect(show).toHaveBeenCalledWith({
summary:
'Next cache was stored, but all other functions were skipped because NEXT_PLUGIN_FORCE_RUN is set to false',
title: 'Next Runtime did not run',
})
delete process.env.NEXT_PLUGIN_FORCE_RUN
})
test('finds problematic user rewrites', async () => {
await moveNextDist()
const rewrites = getProblematicUserRewrites({
redirects: [
{ from: '/previous', to: '/rewrites-are-a-problem', status: 200 },
{ from: '/api', to: '/.netlify/functions/are-ok', status: 200 },
{ from: '/remote', to: 'http://example.com/proxying/is/ok', status: 200 },
{ from: '/old', to: '/redirects-are-fine' },
{ from: '/*', to: '/404-is-a-problem', status: 404 },
...netlifyConfig.redirects,
],
basePath: '',
})
expect(rewrites).toEqual([
{
from: '/previous',
status: 200,
to: '/rewrites-are-a-problem',
},
{
from: '/*',
status: 404,
to: '/404-is-a-problem',
},
])
})
test('adds headers to Netlify configuration', async () => {
await moveNextDist()
const show = jest.fn()
await nextRuntime.onPostBuild({
...defaultArgs,
utils: { ...defaultArgs.utils, status: { show }, functions: { list: jest.fn().mockResolvedValue([]) } },
})
expect(netlifyConfig.headers).toEqual([
{
for: '/',
values: {
'x-custom-header': 'my custom header value',
},
},
{
for: '/en/',
values: {
'x-custom-header': 'my custom header value',
},
},
{
for: '/es/',
values: {
'x-custom-header': 'my custom header value',
},
},
{
for: '/fr/',
values: {
'x-custom-header': 'my custom header value',
},
},
{
for: '/api/*',
values: {
'x-custom-api-header': 'my custom api header value',
},
},
{
for: '/en/api/*',
values: {
'x-custom-api-header': 'my custom api header value',
},
},
{
for: '/es/api/*',
values: {
'x-custom-api-header': 'my custom api header value',
},
},
{
for: '/fr/api/*',
values: {
'x-custom-api-header': 'my custom api header value',
},
},
{
for: '/*',
values: {
'x-custom-header-for-everything': 'my custom header for everything value',
},
},
{
for: '/en/*',
values: {
'x-custom-header-for-everything': 'my custom header for everything value',
},
},
{
for: '/es/*',
values: {
'x-custom-header-for-everything': 'my custom header for everything value',
},
},
{
for: '/fr/*',
values: {
'x-custom-header-for-everything': 'my custom header for everything value',
},
},
])
})
test('appends headers to existing headers in the Netlify configuration', async () => {
await moveNextDist()
netlifyConfig.headers = [
{
for: '/',
values: {
'x-existing-header-in-configuration': 'existing header in configuration value',
},
},
]
const show = jest.fn()
await nextRuntime.onPostBuild({
...defaultArgs,
utils: { ...defaultArgs.utils, status: { show }, functions: { list: jest.fn().mockResolvedValue([]) } },
})
expect(netlifyConfig.headers).toEqual([
{
for: '/',
values: {
'x-existing-header-in-configuration': 'existing header in configuration value',
},
},
{
for: '/',
values: {
'x-custom-header': 'my custom header value',
},
},
{
for: '/en/',
values: {
'x-custom-header': 'my custom header value',
},
},
{
for: '/es/',
values: {
'x-custom-header': 'my custom header value',
},
},
{
for: '/fr/',
values: {
'x-custom-header': 'my custom header value',
},
},
{
for: '/api/*',
values: {
'x-custom-api-header': 'my custom api header value',
},
},
{
for: '/en/api/*',
values: {
'x-custom-api-header': 'my custom api header value',
},
},
{
for: '/es/api/*',
values: {
'x-custom-api-header': 'my custom api header value',
},
},
{
for: '/fr/api/*',
values: {
'x-custom-api-header': 'my custom api header value',