This repository has been archived by the owner on May 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
main.js
2703 lines (2327 loc) · 89.2 KB
/
main.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
const { mkdir, readFile, chmod, symlink, unlink, rename, stat, writeFile } = require('fs').promises
const { tmpdir } = require('os')
const { basename, dirname, isAbsolute, join, normalize, resolve, sep } = require('path')
const { arch, env, platform, version: nodeVersion } = require('process')
const { pathToFileURL } = require('url')
const test = require('ava')
const cpy = require('cpy')
const merge = require('deepmerge')
const del = require('del')
const execa = require('execa')
const pEvery = require('p-every')
const pathExists = require('path-exists')
const semver = require('semver')
const sinon = require('sinon')
const sortOn = require('sort-on')
const { dir: getTmpDir, tmpName } = require('tmp-promise')
const unixify = require('unixify')
require('source-map-support').install()
// We must require this file first because we need to stub it before the main
// functions are required.
// eslint-disable-next-line import/order
const { shellUtils } = require('../dist/utils/shell.js')
const shellUtilsStub = sinon.stub(shellUtils, 'runCommand')
// eslint-disable-next-line import/order
const { zipFunction, listFunctions, listFunctionsFiles, listFunction } = require('../dist/main.js')
const { ESBUILD_LOG_LIMIT } = require('../dist/runtimes/node/bundlers/esbuild/bundler.js')
const { detectEsModule } = require('../dist/runtimes/node/utils/detect_es_module.js')
const {
getRequires,
zipNode,
zipFixture,
unzipFiles,
zipCheckFunctions,
FIXTURES_DIR,
BINARY_PATH,
importFunctionFile,
} = require('./helpers/main.js')
const { computeSha1 } = require('./helpers/sha.js')
const { makeTestMany } = require('./helpers/test_many.js')
const EXECUTABLE_PERMISSION = 0o755
const normalizeFiles = function (fixtureDir, { name, mainFile, runtime, extension, srcFile, schedule }) {
const mainFileA = normalize(`${fixtureDir}/${mainFile}`)
const srcFileA = srcFile === undefined ? {} : { srcFile: normalize(`${fixtureDir}/${srcFile}`) }
return { name, mainFile: mainFileA, runtime, extension, schedule, ...srcFileA }
}
const getZipChecksum = async function (t, bundler) {
const {
files: [{ path }],
} = await zipFixture(t, 'many-dependencies', { opts: { config: { '*': { nodeBundler: bundler } } } })
const sha1sum = computeSha1(path)
return sha1sum
}
test.after.always(async () => {
if (env.ZISI_KEEP_TEMP_DIRS === undefined) {
await del(`${tmpdir()}/zip-it-test-bundler-*`, { force: true })
}
})
test.afterEach(() => {
shellUtilsStub.resetHistory()
})
// Convenience method for running a test for multiple variations.
const testMany = makeTestMany(test, {
bundler_default: {
config: { '*': { nodeBundler: undefined } },
},
bundler_default_nft: {
config: { '*': { nodeBundler: undefined } },
featureFlags: { traceWithNft: true },
},
bundler_esbuild: {
config: { '*': { nodeBundler: 'esbuild' } },
},
bundler_esbuild_zisi: {
config: { '*': { nodeBundler: 'esbuild_zisi' } },
},
bundler_nft: {
config: { '*': { nodeBundler: 'nft' } },
},
})
const getNodeBundlerString = (variation) => {
switch (variation) {
case 'bundler_esbuild':
case 'bundler_esbuild_zisi':
return 'esbuild'
case 'bundler_nft':
case 'bundler_default_nft':
return 'nft'
default:
return 'zisi'
}
}
testMany(
'Zips Node.js function files',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const fixtureName = 'simple'
const { files } = await zipNode(t, fixtureName, { opts: options })
t.is(files.length, 1)
t.is(files[0].runtime, 'js')
t.is(files[0].mainFile, join(FIXTURES_DIR, fixtureName, 'function.js'))
},
)
testMany(
'Handles Node module with native bindings (buildtime marker module)',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const bundler = options.config['*'].nodeBundler
const fixtureDir = 'node-module-native-buildtime'
const { files, tmpDir } = await zipNode(t, fixtureDir, {
opts: options,
})
const requires = await getRequires({ filePath: resolve(tmpDir, 'function.js') })
const normalizedRequires = new Set(requires.map(unixify))
t.is(files.length, 1)
t.is(files[0].runtime, 'js')
const moduleWithNodeFile = resolve(FIXTURES_DIR, `${fixtureDir}/node_modules/module-with-node-file`)
t.true(await pathExists(`${tmpDir}/node_modules/module-with-node-file/native.node`))
t.true(await pathExists(`${tmpDir}/node_modules/module-with-node-file/side-file.js`))
t.true(normalizedRequires.has('module-with-node-file'))
const moduleWithNodeGypPath = resolve(FIXTURES_DIR, `${fixtureDir}/node_modules/module-with-node-gyp`)
t.true(await pathExists(`${tmpDir}/node_modules/module-with-node-gyp/native.node`))
t.true(await pathExists(`${tmpDir}/node_modules/module-with-node-gyp/side-file.js`))
t.true(normalizedRequires.has('module-with-node-gyp'))
const moduleWithPrebuildPath = resolve(FIXTURES_DIR, `${fixtureDir}/node_modules/module-with-prebuild`)
t.true(await pathExists(`${tmpDir}/node_modules/module-with-prebuild/native.node`))
t.true(await pathExists(`${tmpDir}/node_modules/module-with-prebuild/side-file.js`))
t.true(normalizedRequires.has('module-with-prebuild'))
// We can only detect native modules when using esbuild.
if (bundler === 'esbuild' || bundler === 'esbuild_zisi') {
t.deepEqual(files[0].nativeNodeModules, {
'module-with-node-file': { [moduleWithNodeFile]: '3.0.0' },
'module-with-node-gyp': { [moduleWithNodeGypPath]: '1.0.0' },
'module-with-prebuild': { [moduleWithPrebuildPath]: '2.0.0' },
})
}
},
)
testMany(
'Handles Node module with native bindings (runtime marker module)',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const bundler = options.config['*'].nodeBundler
const fixtureDir = 'node-module-native-runtime'
const { files, tmpDir } = await zipNode(t, fixtureDir, {
opts: options,
})
const requires = await getRequires({ filePath: resolve(tmpDir, 'function.js') })
const normalizedRequires = new Set(requires.map(unixify))
const modulePath = resolve(FIXTURES_DIR, `${fixtureDir}/node_modules/test`)
t.is(files.length, 1)
t.is(files[0].runtime, 'js')
t.true(await pathExists(`${tmpDir}/node_modules/test/native.node`))
t.true(await pathExists(`${tmpDir}/node_modules/test/side-file.js`))
t.true(normalizedRequires.has('test'))
// We can only detect native modules when using esbuild.
if (bundler === 'esbuild' || bundler === 'esbuild_zisi') {
t.deepEqual(files[0].nativeNodeModules, { test: { [modulePath]: '1.0.0' } })
}
},
)
testMany(
'Can require node modules',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'local-node-module', { opts: options })
},
)
testMany(
'Can require deep paths in node modules',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const { tmpDir } = await zipNode(t, 'local-node-module-deep-require', {
opts: options,
})
const func = await importFunctionFile(`${tmpDir}/function.js`)
t.deepEqual(func, { mock: { stack: 'jam' }, stack: 'jam' })
},
)
testMany(
'Can require Node modules with destructuring expressions',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, `local-node-module-destructure-require`, {
opts: options,
})
},
)
testMany(
'Can require scoped node modules',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'node-module-scope', { opts: options })
},
)
testMany(
'Can require node modules nested files',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'node-module-path', { opts: options })
},
)
testMany(
'Can require dynamically generated node modules',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'side-module', { opts: options })
},
)
testMany(
'Ignore some excluded node modules',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const fixtureName = 'node-module-excluded'
const opts = merge(options, {
basePath: join(FIXTURES_DIR, fixtureName),
})
const { tmpDir } = await zipNode(t, fixtureName, { opts })
t.false(await pathExists(`${tmpDir}/node_modules/aws-sdk`))
try {
const func = await importFunctionFile(`${tmpDir}/function.js`)
func()
t.fail('Running the function should fail due to the missing module')
} catch (error) {
t.is(error.code, 'MODULE_NOT_FOUND')
}
},
)
testMany(
'Ignore TypeScript types',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const { tmpDir } = await zipNode(t, 'node-module-typescript-types', {
opts: options,
})
t.false(await pathExists(`${tmpDir}/node_modules/@types/node`))
},
)
testMany(
'Throws on runtime errors',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await t.throwsAsync(zipNode(t, 'node-module-error', { opts: options }))
},
)
testMany(
'Throws on missing dependencies',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await t.throwsAsync(zipNode(t, 'node-module-missing', { opts: options }))
},
)
testMany(
'Throws on missing dependencies with no optionalDependencies',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await t.throwsAsync(zipNode(t, 'node-module-missing-package', { opts: options }))
},
)
testMany(
'Throws on missing conditional dependencies',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await t.throwsAsync(zipNode(t, 'node-module-missing-conditional', { opts: options }))
},
)
testMany(
"Throws on missing dependencies' dependencies",
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await t.throwsAsync(zipNode(t, 'node-module-missing-deep', { opts: options }))
},
)
testMany(
'Ignore missing optional dependencies',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'node-module-missing-optional', { opts: options })
},
)
testMany(
'Ignore modules conditional dependencies',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'node-module-deep-conditional', { opts: options })
},
)
testMany(
'Ignore missing optional peer dependencies',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'node-module-peer-optional', { opts: options })
},
)
testMany(
'Throws on missing optional peer dependencies with no peer dependencies',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await t.throwsAsync(zipNode(t, 'node-module-peer-optional-none', { opts: options }))
},
)
testMany(
'Throws on missing non-optional peer dependencies',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await t.throwsAsync(zipNode(t, 'node-module-peer-not-optional', { opts: options }))
},
)
testMany(
'Resolves dependencies from .netlify/plugins/node_modules when using `zipFunctions()`',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'node-module-next-image', { opts: options })
},
)
testMany(
'Resolves dependencies from .netlify/plugins/node_modules when using `zipFunction()`',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const { path: tmpDir } = await getTmpDir({ prefix: 'zip-it-test' })
const mainFile = join(FIXTURES_DIR, 'node-module-next-image', 'function', 'function.js')
const result = await zipFunction(mainFile, tmpDir, options)
await unzipFiles([result])
const func = await importFunctionFile(join(tmpDir, 'function.js'))
t.true(func)
},
)
// We persist `package.json` as `package.json.txt` in git. Otherwise ESLint
// tries to load when linting sibling JavaScript files. In this test, we
// temporarily rename it to an actual `package.json`.
testMany(
'Throws on invalid package.json',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi'],
async (options, t) => {
const fixtureDir = await tmpName({ prefix: 'zip-it-test' })
await cpy('**', `${fixtureDir}/invalid-package-json`, {
cwd: `${FIXTURES_DIR}/invalid-package-json`,
parents: true,
})
const invalidPackageJsonDir = `${fixtureDir}/invalid-package-json`
const srcPackageJson = `${invalidPackageJsonDir}/package.json.txt`
const distPackageJson = `${invalidPackageJsonDir}/package.json`
await rename(srcPackageJson, distPackageJson)
try {
await t.throwsAsync(zipNode(t, 'invalid-package-json', { opts: options, fixtureDir }), {
message: /(invalid JSON|package.json:1:1: error: Expected string but found "{")/,
})
} finally {
await rename(distPackageJson, srcPackageJson)
}
},
)
testMany(
'Ignore invalid require()',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'invalid-require', { opts: options })
},
)
testMany('Can use dynamic import() with esbuild', ['bundler_esbuild'], async (options, t) => {
await zipNode(t, 'dynamic-import', { opts: options })
})
testMany(
'Can require local files',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'local-require', { opts: options })
},
)
testMany(
'Can bundle ESM functions and transpile them to CJS when the Node version is <14',
['bundler_default', 'bundler_esbuild', 'bundler_nft'],
async (options, t) => {
const length = 4
const fixtureName = 'local-require-esm'
const opts = merge(options, {
basePath: join(FIXTURES_DIR, fixtureName),
config: {
'*': {
nodeVersion: 'nodejs12.x',
},
},
featureFlags: { zisi_detect_esm: true, zisi_pure_esm: false },
})
const { files, tmpDir } = await zipFixture(t, fixtureName, {
length,
opts,
})
await unzipFiles(files, (path) => `${path}/../${basename(path)}_out`)
const functionPaths = [
join(tmpDir, 'function.zip_out', 'function.js'),
join(tmpDir, 'function_cjs.zip_out', 'function_cjs.js'),
join(tmpDir, 'function_export_only.zip_out', 'function_export_only.js'),
join(tmpDir, 'function_import_only.zip_out', 'function_import_only.js'),
]
const func1 = () => importFunctionFile(functionPaths[0])
const func2 = () => importFunctionFile(functionPaths[1])
const func3 = () => importFunctionFile(functionPaths[2])
const func4 = () => importFunctionFile(functionPaths[3])
const functionsAreESM = await Promise.all(
functionPaths.map((functionPath) => detectEsModule({ mainFile: functionPath })),
)
// None of the functions should be ESM since we're transpiling them to CJS.
t.false(functionsAreESM.some(Boolean))
// Dynamic imports are not supported in Node <13.2.0.
if (semver.gte(nodeVersion, '13.2.0')) {
const func2Default = await func2()
t.is(await func2Default(), 0)
}
const { ZERO } = await func1()
t.is(ZERO, 0)
const { howdy } = await func3()
t.is(typeof howdy, 'string')
t.deepEqual(await func4(), {})
},
)
testMany(
'Can bundle ESM functions and transpile them to CJS when the Node version is <14 and `archiveType` is `none`',
['bundler_default', 'bundler_esbuild', 'bundler_nft'],
async (options, t) => {
const length = 4
const fixtureName = 'local-require-esm'
const opts = merge(options, {
archiveFormat: 'none',
basePath: join(FIXTURES_DIR, fixtureName),
config: {
'*': {
nodeVersion: 'nodejs12.x',
},
},
featureFlags: { zisi_detect_esm: true, zisi_pure_esm: false },
})
const { tmpDir } = await zipFixture(t, fixtureName, {
length,
opts,
})
const functionPaths = [
join(tmpDir, 'function', 'function.js'),
join(tmpDir, 'function_cjs', 'function_cjs.js'),
join(tmpDir, 'function_export_only', 'function_export_only.js'),
join(tmpDir, 'function_import_only', 'function_import_only.js'),
]
const func1 = () => importFunctionFile(functionPaths[0])
const func2 = () => importFunctionFile(functionPaths[1])
const func3 = () => importFunctionFile(functionPaths[2])
const func4 = () => importFunctionFile(functionPaths[3])
const functionsAreESM = await Promise.all(
functionPaths.map((functionPath) => detectEsModule({ mainFile: functionPath })),
)
// None of the functions should be ESM since we're transpiling them to CJS.
t.false(functionsAreESM.some(Boolean))
// Dynamic imports are not supported in Node <13.2.0.
if (semver.gte(nodeVersion, '13.2.0')) {
const func2Default = await func2()
t.is(await func2Default(), 0)
}
const { ZERO } = await func1()
t.is(ZERO, 0)
const { howdy } = await func3()
t.is(typeof howdy, 'string')
t.deepEqual(await func4(), {})
},
)
testMany(
'Can bundle CJS functions that import ESM files with an `import()` expression',
['bundler_default', 'bundler_esbuild', 'bundler_nft'],
async (options, t) => {
const fixtureName = 'node-cjs-importing-mjs'
const opts = merge(options, {
featureFlags: { zisi_detect_esm: true },
})
const { files, tmpDir } = await zipFixture(t, fixtureName, {
opts,
})
await unzipFiles(files)
const func = await importFunctionFile(join(tmpDir, 'function.js'))
// Dynamic imports were added in Node v13.2.0.
if (semver.gte(nodeVersion, '13.2.0')) {
const { body, statusCode } = await func.handler()
t.is(body, 'Hello world')
t.is(statusCode, 200)
}
},
)
testMany(
'Can bundle native ESM functions when the Node version is >=14 and the `zisi_pure_esm` flag is on',
['bundler_default', 'bundler_nft', 'bundler_esbuild'],
async (options, t) => {
const length = 2
const fixtureName = 'node-esm'
const opts = merge(options, {
basePath: join(FIXTURES_DIR, fixtureName),
featureFlags: { zisi_detect_esm: true, zisi_pure_esm: true },
})
const { files, tmpDir } = await zipFixture(t, fixtureName, {
length,
opts,
})
await unzipFiles(files, (path) => `${path}/../${basename(path)}_out`)
const functionPaths = [join(tmpDir, 'func1.zip_out', 'func1.js'), join(tmpDir, 'func2.zip_out', 'func2.js')]
const func1 = await import(pathToFileURL(functionPaths[0]))
const func2 = await import(pathToFileURL(functionPaths[1]))
t.true(func1.handler())
t.true(func2.handler())
const functionsAreESM = await Promise.all(
functionPaths.map((functionPath) => detectEsModule({ mainFile: functionPath })),
)
t.true(functionsAreESM.every(Boolean))
},
)
testMany(
'Can bundle ESM functions and transpile them to CJS when the Node version is >=14 and the `zisi_pure_esm` flag is off',
['bundler_default', 'bundler_esbuild', 'bundler_nft'],
async (options, t) => {
const length = 2
const fixtureName = 'node-esm'
const opts = merge(options, {
basePath: join(FIXTURES_DIR, fixtureName),
featureFlags: { zisi_detect_esm: true },
})
const { files, tmpDir } = await zipFixture(t, fixtureName, {
length,
opts,
})
await unzipFiles(files, (path) => `${path}/../${basename(path)}_out`)
const functionPaths = [join(tmpDir, 'func1.zip_out', 'func1.js'), join(tmpDir, 'func2.zip_out', 'func2.js')]
const func1 = await import(pathToFileURL(functionPaths[0]))
const func2 = await import(pathToFileURL(functionPaths[1]))
t.true(func1.handler())
t.true(func2.handler())
const functionsAreESM = await Promise.all(
functionPaths.map((functionPath) => detectEsModule({ mainFile: functionPath })),
)
t.false(functionsAreESM.some(Boolean))
},
)
testMany(
'Can require local files deeply',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'local-deep-require', { opts: options })
},
)
testMany(
'Can require local files in the parent directories',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'local-parent-require', { opts: options })
},
)
testMany(
'Ignore missing critters dependency for Next.js 10',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'node-module-next10-critters', { opts: options })
},
)
testMany(
'Ignore missing critters dependency for Next.js exact version 10.0.5',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'node-module-next10-critters-exact', { opts: options })
},
)
testMany(
'Ignore missing critters dependency for Next.js with range ^10.0.5',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'node-module-next10-critters-10.0.5-range', {
opts: options,
})
},
)
testMany(
"Ignore missing critters dependency for Next.js with version='latest'",
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'node-module-next10-critters-latest', { opts: options })
},
)
// Need to create symlinks dynamically because they sometimes get lost when
// committed on Windows
if (platform !== 'win32') {
testMany(
'Can require symlinks',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const fixtureDir = await tmpName({ prefix: 'zip-it-test' })
const opts = merge(options, {
basePath: `${fixtureDir}/symlinks`,
})
await cpy('**', `${fixtureDir}/symlinks`, {
cwd: `${FIXTURES_DIR}/symlinks`,
parents: true,
})
const symlinkDir = `${fixtureDir}/symlinks/function`
const symlinkFile = `${symlinkDir}/file.js`
const targetFile = `${symlinkDir}/target.js`
if (!(await pathExists(symlinkFile))) {
await symlink(targetFile, symlinkFile)
}
try {
await zipNode(t, 'symlinks', { opts, fixtureDir })
} finally {
await unlink(symlinkFile)
}
},
)
}
testMany(
'Can target a directory with a main file with the same name',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const fixtureName = 'directory-handler'
const { files } = await zipNode(t, fixtureName, { opts: options })
t.is(files[0].mainFile, join(FIXTURES_DIR, fixtureName, 'function', 'function.js'))
},
)
testMany(
'Can target a directory with an index.js file',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const fixtureName = 'index-handler'
const { files, tmpDir } = await zipFixture(t, fixtureName, {
opts: options,
})
await unzipFiles(files)
const returnValue = await importFunctionFile(`${tmpDir}/function.js`)
t.true(returnValue)
t.is(files[0].mainFile, join(FIXTURES_DIR, fixtureName, 'function', 'index.js'))
},
)
testMany(
'Keeps non-required files inside the target directory',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const { tmpDir } = await zipNode(t, 'keep-dir-files', { opts: options })
t.true(await pathExists(`${tmpDir}/function.js`))
},
)
testMany(
'Ignores non-required node_modules inside the target directory',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const { tmpDir } = await zipNode(t, 'ignore-dir-node-modules', {
opts: options,
})
t.false(await pathExists(`${tmpDir}/node_modules`))
},
)
testMany(
'Ignores deep non-required node_modules inside the target directory',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const { tmpDir } = await zipNode(t, 'ignore-deep-dir-node-modules', {
opts: options,
})
t.false(await pathExists(`${tmpDir}/deep/node_modules`))
},
)
testMany(
'Works with many dependencies',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'many-dependencies', { opts: options })
},
)
testMany(
'Works with many function files',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const names = new Set(['one', 'two', 'three', 'four', 'five', 'six'])
const { files } = await zipNode(t, 'many-functions', {
opts: options,
length: TEST_FUNCTIONS_LENGTH,
})
files.forEach(({ name }) => {
t.true(names.has(name))
})
},
)
const TEST_FUNCTIONS_LENGTH = 6
testMany(
'Produces deterministic checksums',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const bundler = options.config['*'].nodeBundler
const [checksumOne, checksumTwo] = await Promise.all([getZipChecksum(t, bundler), getZipChecksum(t, bundler)])
t.is(checksumOne, checksumTwo)
},
)
testMany(
'Throws when the source folder does not exist',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await t.throwsAsync(zipNode(t, 'does-not-exist', { opts: options }), {
message: /Functions folder does not exist/,
})
},
)
testMany(
'Works even if destination folder does not exist',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'simple', { opts: options })
},
)
testMany(
'Do not consider node_modules as a function file',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'ignore-node-modules', { opts: options })
},
)
testMany(
'Ignore directories without a main file',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'ignore-directories', { opts: options })
},
)
testMany(
'Remove useless files',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const { tmpDir } = await zipNode(t, 'useless', { opts: options })
t.false(await pathExists(`${tmpDir}/Desktop.ini`))
},
)
testMany(
'Works on empty directories',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipNode(t, 'empty', { opts: options, length: 0 })
},
)
testMany(
'Works when no package.json is present',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const fixtureDir = await tmpName({ prefix: 'zip-it-test' })
const opts = merge(options, {
basePath: fixtureDir,
})
await cpy('**', `${fixtureDir}/no-package-json`, { cwd: `${FIXTURES_DIR}/no-package-json`, parents: true })
await zipNode(t, 'no-package-json', { opts, length: 1, fixtureDir })
},
)
testMany(
'Copies already zipped files',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const tmpDir = await tmpName({ prefix: 'zip-it-test' })
const { files } = await zipCheckFunctions(t, 'keep-zip', { tmpDir })
t.true(files.every(({ runtime }) => runtime === 'js'))
t.true(
await pEvery(files, async ({ path }) => {
const fileContents = await readFile(path, 'utf8')
return fileContents.trim() === 'test'
}),
)
},
)
testMany(
'Ignore unsupported programming languages',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
await zipFixture(t, 'unsupported', { length: 0, opts: options })
},
)
testMany(
'Can reduce parallelism',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const opts = merge(options, { parallelLimit: 1 })
await zipNode(t, 'simple', { length: 1, opts })
},
)
testMany(
'Can use zipFunction()',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t, variation) => {
const bundler = options.config['*'].nodeBundler
const { path: tmpDir } = await getTmpDir({ prefix: 'zip-it-test' })
const mainFile = join(FIXTURES_DIR, 'simple', 'function.js')
const result = await zipFunction(mainFile, tmpDir, options)
const bundlerUsed = getNodeBundlerString(variation)
t.is(result.name, 'function')
t.is(result.runtime, 'js')
t.is(result.bundler, bundlerUsed)
t.is(result.mainFile, mainFile)
t.deepEqual(result.config, bundler === undefined ? {} : { nodeBundler: bundlerUsed })
},
)
test('Can list function main files with listFunctions()', async (t) => {
const fixtureDir = `${FIXTURES_DIR}/list`
const functions = await listFunctions(fixtureDir)
t.deepEqual(
functions,
[
{ schedule: undefined, name: 'test', mainFile: 'test.zip', runtime: 'js', extension: '.zip' },
{ schedule: undefined, name: 'test', mainFile: 'test.js', runtime: 'js', extension: '.js' },
{ schedule: undefined, name: 'five', mainFile: 'five/index.ts', runtime: 'js', extension: '.ts' },
{ schedule: undefined, name: 'four', mainFile: 'four.js/four.js.js', runtime: 'js', extension: '.js' },
{ schedule: undefined, name: 'one', mainFile: 'one/index.js', runtime: 'js', extension: '.js' },
{ schedule: undefined, name: 'two', mainFile: 'two/two.js', runtime: 'js', extension: '.js' },
{ schedule: undefined, name: 'test', mainFile: 'test', runtime: 'go', extension: '' },
].map(normalizeFiles.bind(null, fixtureDir)),
)
})
test('Can list function main files from multiple source directories with listFunctions()', async (t) => {
const fixtureDir = `${FIXTURES_DIR}/multiple-src-directories`
const functions = await listFunctions([
join(fixtureDir, '.netlify', 'internal-functions'),
join(fixtureDir, 'netlify', 'functions'),
])
t.deepEqual(
functions,
[
{
schedule: undefined,
name: 'function',
mainFile: '.netlify/internal-functions/function.js',
runtime: 'js',
extension: '.js',
},
{
schedule: undefined,
name: 'function_internal',
mainFile: '.netlify/internal-functions/function_internal.js',
runtime: 'js',
extension: '.js',
},
{
schedule: undefined,
name: 'function',
mainFile: 'netlify/functions/function.js',
runtime: 'js',
extension: '.js',
},
{
schedule: undefined,
name: 'function_user',
mainFile: 'netlify/functions/function_user.js',
runtime: 'js',
extension: '.js',
},
].map(normalizeFiles.bind(null, fixtureDir)),
)
})
testMany(
'Can list all function files with listFunctionsFiles()',
['bundler_default', 'bundler_esbuild', 'bundler_esbuild_zisi', 'bundler_default_nft', 'bundler_nft'],
async (options, t) => {
const fixtureDir = `${FIXTURES_DIR}/list`
const opts = merge(options, {
basePath: fixtureDir,
})
const bundler = options.config['*'].nodeBundler
const files = await listFunctionsFiles(fixtureDir, opts)
const sortedFiles = sortOn(files, ['mainFile', 'srcFile'])
const expectedFiles = [
{
name: 'five',
mainFile: 'five/index.ts',
runtime: 'js',
extension: '.ts',
schedule: undefined,
srcFile: 'five/index.ts',
},