This repository has been archived by the owner on Nov 3, 2022. It is now read-only.
/
index.js
861 lines (794 loc) · 26 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
const t = require('tap')
// hackedy hacky hack
const fs = require('fs')
const { readFile } = fs
fs.readFile = (path, ...args) => {
if (path.match(/WEIRD-ERROR/)) {
const cb = args.pop()
cb(Object.assign(new Error('weird error'), { code: 'EWEIRD' }))
} else
return readFile(path, ...args)
}
// when running with `npm test` it adds environment variables that
// mess with the things we expect here, so delete all of those.
Object.keys(process.env)
.filter(k => /^npm_/.test(k))
.forEach(k => delete process.env[k])
delete process.env.PREFIX
delete process.env.DESTDIR
const shorthands = require('./fixtures/shorthands.js')
const types = require('./fixtures/types.js')
const typeDefs = require('../lib/type-defs.js')
const defaults = require('./fixtures/defaults.js')
const { readFileSync } = require('fs')
const { resolve, join, dirname } = require('path')
const Config = require('../')
t.equal(typeDefs, Config.typeDefs, 'exposes type definitions')
t.test('construct with no settings, get default values for stuff', t => {
const npmPath = t.testdir()
const c = new Config({
shorthands: {},
defaults: {},
types: {},
npmPath,
})
t.test('default some values from process object', t => {
const { env, argv, execPath, platform } = process
const cwd = process.cwd()
t.equal(c.env, env, 'env')
t.equal(c.execPath, execPath, 'execPath')
t.equal(c.cwd, cwd, 'cwd')
t.equal(c.platform, platform, 'platform')
t.end()
})
t.test('not loaded yet', t => {
t.equal(c.loaded, false, 'not loaded yet')
t.throws(() => c.get('foo'), {
message: 'call config.load() before reading values',
})
t.throws(() => c.find('foo'), {
message: 'call config.load() before reading values',
})
t.throws(() => c.set('foo', 'bar'), {
message: 'call config.load() before setting values',
})
t.throws(() => c.delete('foo'), {
message: 'call config.load() before deleting values',
})
t.rejects(() => c.save('user'), {
message: 'call config.load() before saving',
})
t.throws(() => c.data.set('user', {}), {
message: 'cannot change internal config data structure',
})
t.throws(() => c.data.delete('user'), {
message: 'cannot change internal config data structure',
})
t.end()
})
t.test('data structure all wired up properly', t => {
// verify that the proto objects are all wired up properly
c.list.forEach((data, i) => {
t.equal(Object.getPrototypeOf(data), c.list[i + 1] || null)
})
t.equal(c.data.get('default').data, c.list[c.list.length - 1])
t.equal(c.data.get('cli').data, c.list[0])
t.end()
})
t.end()
})
t.test('load from files and environment variables', t => {
// need to get the dir because we reference it in the contents
const path = t.testdir()
t.testdir({
npm: {
npmrc: `
builtin-config = true
foo = from-builtin
userconfig = ${path}/user/.npmrc-from-builtin
`
},
global: {
etc: {
npmrc: `
global-config = true
foo = from-global
userconfig = ${path}/should-not-load-this-file
`
},
},
user: {
'.npmrc': `
default-user-config-in-home = true
foo = from-default-userconfig
prefix = ${path}/global
`,
'.npmrc-from-builtin': `
user-config-from-builtin = true
foo = from-custom-userconfig
globalconfig = ${path}/global/etc/npmrc
`
},
project: {
node_modules: {},
'.npmrc': `
project-config = true
foo = from-project-config
loglevel = yolo
`
},
'project-no-config': {
'package.json': '{"name":"@scope/project"}',
},
})
const logs = []
const log = {
warn: (...msg) => logs.push(['warn', ...msg]),
verbose: (...msg) => logs.push(['verbose', ...msg]),
}
const argv = [
process.execPath,
__filename,
'-v',
'--no-audit',
'config',
'get',
'foo',
'--registry=hello',
'--omit=cucumber',
'--access=blueberry',
'--multiple-numbers=what kind of fruit is not a number',
'--multiple-numbers=a baNaNa!!',
'-C',
]
t.test('dont let userconfig be the same as builtin config', async t => {
const config = new Config({
npmPath: `${path}/npm`,
env: {},
argv: [process.execPath, __filename, '--userconfig', `${path}/npm/npmrc`],
cwd: `${path}/project`,
types,
shorthands,
defaults,
})
await t.rejects(() => config.load(), {
message: `double-loading config "${resolve(path, 'npm/npmrc')}" as "user", previously loaded as "builtin"`,
})
})
t.test('verbose log if config file read is weird error', async t => {
const config = new Config({
npmPath: path,
env: {},
argv: [process.execPath, __filename, '--userconfig', `${path}/WEIRD-ERROR`],
cwd: path,
log,
types,
shorthands,
defaults,
})
logs.length = 0
await config.load()
t.match(logs, [[ 'verbose','config', 'error loading user config', {
message: 'weird error',
}]])
logs.length = 0
})
t.test('load configs from all files, cli, and env', async t => {
const env = {
npm_config_foo: 'from-env',
npm_config_global: '',
npm_config_prefix: '/something',
}
const config = new Config({
npmPath: `${path}/npm`,
env,
argv,
log,
cwd: `${path}/project`,
types,
shorthands,
defaults,
})
t.equal(config.globalPrefix, null, 'globalPrefix missing before load')
await config.load()
t.equal(config.globalPrefix, resolve('/something'), 'env-defined prefix should have been loaded')
t.equal(config.get('global', 'env'), undefined, 'empty env is missing')
t.equal(config.get('global'), false, 'empty env is missing')
config.set('asdf', 'quux', 'global')
await config.save('global')
const gres = readFileSync(`${path}/global/etc/npmrc`, 'utf8')
t.match(gres, 'asdf=quux')
const cliData = config.data.get('cli')
t.throws(() => cliData.loadError = true, {
message: 'cannot set ConfigData loadError after load',
})
t.throws(() => cliData.source = 'foo', {
message: 'cannot set ConfigData source more than once',
})
t.throws(() => cliData.raw = 1234, {
message: 'cannot set ConfigData raw after load',
})
config.argv = []
t.throws(() => config.loadCLI(), {
message: 'double-loading "cli" configs from command line options, previously loaded from command line options'
})
t.rejects(() => config.loadUserConfig(), {
message: `double-loading "user" configs from ${resolve(path, 'should-not-load-this-file')}, previously loaded from ${resolve(path, 'user/.npmrc-from-builtin')}`
})
t.equal(config.loaded, true, 'config is loaded')
await t.rejects(() => config.load(), {
message: 'attempting to load npm config multiple times',
})
t.equal(config.find('no config value here'), null)
t.equal(config.prefix, config.localPrefix, 'prefix is local prefix when not global')
config.set('global', true)
t.equal(config.prefix, config.globalPrefix, 'prefix is global prefix when global')
config.set('global', false)
t.equal(config.find('global'), 'cli')
config.delete('global')
t.equal(config.find('global'), 'default')
t.throws(() => config.get('foo', 'barbaz'), {
message: 'invalid config location param: barbaz',
})
t.throws(() => config.set('foo', 1234, 'barbaz'), {
message: 'invalid config location param: barbaz',
})
t.throws(() => config.delete('foo', 'barbaz'), {
message: 'invalid config location param: barbaz',
})
t.match(config.sources, new Map([
['default values', 'default'],
[resolve(path, 'npm/npmrc'), 'builtin'],
['command line options', 'cli'],
['environment', 'env'],
[resolve(path, 'project/.npmrc'), 'project'],
[resolve(path, 'user/.npmrc-from-builtin'), 'user'],
[resolve(path, 'global/etc/npmrc'), 'global'],
]))
t.strictSame({
version: config.get('version'),
audit: config.get('audit'),
'project-config': config.get('project-config'),
foo: config.get('foo'),
'user-config-from-builtin': config.get('user-config-from-builtin'),
'global-config': config.get('global-config'),
'builtin-config': config.get('builtin-config'),
all: config.get('all'),
}, {
version: true,
audit: false,
'project-config': true,
foo: 'from-env',
'user-config-from-builtin': true,
'global-config': true,
'builtin-config': true,
all: config.get('all'),
})
t.match(env, {
npm_config_user_config_from_builtin: 'true',
npm_config_audit: '',
npm_config_version: 'true',
npm_config_foo: 'from-env',
npm_config_builtin_config: 'true',
}, 'set env values')
t.strictSame(logs, [
[ 'warn', 'invalid config', 'registry="hello"', 'set in command line options' ],
[ 'warn', 'invalid config', 'Must be', 'full url with "http://"' ],
[ 'warn', 'invalid config', 'omit="cucumber"', 'set in command line options' ],
[ 'warn', 'invalid config', 'Must be one or more of:', 'dev, optional, peer' ],
[ 'warn', 'invalid config', 'access="blueberry"', 'set in command line options' ],
[ 'warn', 'invalid config', 'Must be one of:', 'null, restricted, public' ],
[ 'warn', 'invalid config', 'multiple-numbers="what kind of fruit is not a number"', 'set in command line options' ],
[ 'warn', 'invalid config', 'Must be one or more', 'numeric value' ],
[ 'warn', 'invalid config', 'multiple-numbers="a baNaNa!!"', 'set in command line options' ],
[ 'warn', 'invalid config', 'Must be one or more', 'numeric value' ],
[ 'warn', 'invalid config', 'prefix=true', 'set in command line options' ],
[ 'warn', 'invalid config', 'Must be', 'valid filesystem path' ],
[ 'warn', 'invalid config', 'loglevel="yolo"',
`set in ${resolve(path, 'project/.npmrc')}`],
[ 'warn', 'invalid config', 'Must be one of:',
[ 'silent', 'error', 'warn', 'notice', 'http', 'timing', 'info',
'verbose', 'silly' ].join(', '),
],
])
t.equal(config.valid, false)
logs.length = 0
})
t.test('do not double-load project/user config', async t => {
const env = {
npm_config_foo: 'from-env',
npm_config_globalconfig: '/this/path/does/not/exist',
}
const config = new Config({
npmPath: `${path}/npm`,
env,
argv: [process.execPath, __filename, '--userconfig', `${path}/project/.npmrc`],
cwd: `${path}/project`,
types,
shorthands,
defaults,
})
await config.load()
config.argv = []
t.equal(config.loaded, true, 'config is loaded')
t.match(config.data.get('global').loadError, { code: 'ENOENT' })
t.strictSame(config.data.get('env').raw, Object.assign(Object.create(null), {
foo: 'from-env',
globalconfig: '/this/path/does/not/exist',
}))
t.match(config.sources, new Map([
['default values', 'default'],
[resolve(path, 'npm/npmrc'), 'builtin'],
['command line options', 'cli'],
['environment', 'env'],
['(same as "user" config, ignored)', 'project'],
[resolve(path, 'project/.npmrc'), 'user'],
]))
t.rejects(() => config.save('yolo'), {
message: 'invalid config location param: yolo',
})
t.equal(config.valid, false)
})
t.test('load configs from files, cli, and env, no builtin or project', async t => {
const env = {
npm_config_foo: 'from-env',
HOME: `${path}/user`,
}
const config = new Config({
// no builtin
npmPath: path,
env,
argv,
log,
cwd: `${path}/project-no-config`,
// should prepend DESTDIR to /global
DESTDIR: path,
PREFIX: '/global',
platform: 'posix',
types,
shorthands,
defaults,
})
await config.load()
t.match(config.sources, new Map([
['default values', 'default'],
['command line options', 'cli'],
['environment', 'env'],
[resolve(path, 'user/.npmrc'), 'user'],
[resolve(path, 'global/etc/npmrc'), 'global'],
]))
// no builtin or project config
t.strictEqual(config.sources.get(resolve(path, 'npm/npmrc')), undefined)
t.strictEqual(config.sources.get(resolve(path, 'project/.npmrc')), undefined)
t.strictSame({
version: config.get('version'),
audit: config.get('audit'),
'project-config': config.get('project-config'),
foo: config.get('foo'),
'user-config-from-builtin': config.get('user-config-from-builtin'),
'default-user-config-in-home': config.get('default-user-config-in-home'),
'global-config': config.get('global-config'),
'builtin-config': config.get('builtin-config'),
all: config.get('all'),
}, {
version: true,
audit: false,
'project-config': undefined,
foo: 'from-env',
'user-config-from-builtin': undefined,
'default-user-config-in-home': true,
'global-config': true,
'builtin-config': undefined,
all: config.get('all'),
})
t.strictSame(logs, [
[ 'warn', 'invalid config', 'registry="hello"', 'set in command line options' ],
[ 'warn', 'invalid config', 'Must be', 'full url with "http://"' ],
[ 'warn', 'invalid config', 'omit="cucumber"', 'set in command line options' ],
[ 'warn', 'invalid config', 'Must be one or more of:', 'dev, optional, peer' ],
[ 'warn', 'invalid config', 'access="blueberry"', 'set in command line options' ],
[ 'warn', 'invalid config', 'Must be one of:', 'null, restricted, public' ],
[ 'warn', 'invalid config', 'multiple-numbers="what kind of fruit is not a number"', 'set in command line options' ],
[ 'warn', 'invalid config', 'Must be one or more', 'numeric value' ],
[ 'warn', 'invalid config', 'multiple-numbers="a baNaNa!!"', 'set in command line options' ],
[ 'warn', 'invalid config', 'Must be one or more', 'numeric value' ],
[ 'warn', 'invalid config', 'prefix=true', 'set in command line options' ],
[ 'warn', 'invalid config', 'Must be', 'valid filesystem path' ]
])
})
t.end()
})
t.test('cafile loads as ca (and some saving tests)', async t => {
const cafile = resolve(__dirname, 'fixtures', 'cafile')
const dir = t.testdir({
'.npmrc': `cafile = ${cafile}
_authToken = deadbeefcafebadfoobarbaz42069
`,
})
const expect = `cafile=${cafile}
//registry.npmjs.org/:_authToken=deadbeefcafebadfoobarbaz42069
`
const config = new Config({
shorthands,
types,
defaults,
npmPath: __dirname,
env: { HOME: dir, PREFIX: dir },
})
await config.load()
const ca = config.get('ca')
t.equal(ca.join('\n').replace(/\r\n/g, '\n').trim(), readFileSync(cafile, 'utf8').replace(/\r\n/g, '\n').trim())
await config.save('user')
const res = readFileSync(`${dir}/.npmrc`, 'utf8').replace(/\r\n/g, '\n')
t.equal(res, expect, 'did not write back ca, only cafile')
// while we're here, test that saving an empty config file deletes it
config.delete('cafile', 'user')
config.clearCredentialsByURI(config.get('registry'))
await config.save('user')
t.throws(() => readFileSync(`${dir}/.npmrc`, 'utf8'), { code: 'ENOENT' })
// do it again to verify we ignore the unlink error
await config.save('user')
t.throws(() => readFileSync(`${dir}/.npmrc`, 'utf8'), { code: 'ENOENT' })
t.equal(config.valid, true)
})
t.test('cafile ignored if ca set', async t => {
const cafile = resolve(__dirname, 'fixtures', 'cafile')
const dir = t.testdir({
'.npmrc': `cafile = ${cafile}`,
})
const ca = `
-----BEGIN CERTIFICATE-----
fakey mc fakerson
-----END CERTIFICATE-----
`
const config = new Config({
shorthands,
types,
defaults,
npmPath: __dirname,
env: {
HOME: dir,
npm_config_ca: ca,
},
})
await config.load()
t.strictSame(config.get('ca'), [ca.trim()])
await config.save('user')
const res = readFileSync(`${dir}/.npmrc`, 'utf8')
t.equal(res.trim(), `cafile=${cafile}`)
})
t.test('ignore cafile if it does not load', async t => {
const cafile = resolve(__dirname, 'fixtures', 'cafile-does-not-exist')
const dir = t.testdir({
'.npmrc': `cafile = ${cafile}`,
})
const config = new Config({
shorthands,
types,
defaults,
npmPath: __dirname,
env: { HOME: dir },
})
await config.load()
t.equal(config.get('ca'), null)
await config.save('user')
const res = readFileSync(`${dir}/.npmrc`, 'utf8')
t.equal(res.trim(), `cafile=${cafile}`)
})
t.test('raise error if reading ca file error other than ENOENT', async t => {
const cafile = resolve(__dirname, 'fixtures', 'WEIRD-ERROR')
const dir = t.testdir({
'.npmrc': `cafile = ${cafile}`,
})
const config = new Config({
shorthands,
types,
defaults,
npmPath: __dirname,
env: { HOME: dir },
})
t.rejects(() => config.load(), { code: 'EWEIRD' })
})
t.test('credentials management', async t => {
const fixtures = {
nerfed_authToken: { '.npmrc': '//registry.example/:_authToken = 0bad1de4' },
nerfed_lcAuthToken: { '.npmrc': '//registry.example/:_authtoken = 0bad1de4' },
nerfed_userpass: {
'.npmrc': `//registry.example/:username = hello
//registry.example/:_password = ${Buffer.from('world').toString('base64')}
//registry.example/:email = i@izs.me
//registry.example/:always-auth = "false"`,
},
nerfed_auth: { // note: does not load, because we don't do _auth per reg
'.npmrc': `//registry.example/:_auth = ${Buffer.from('hello:world').toString('base64')}`,
},
def_userpass: {
'.npmrc': `username = hello
_password = ${Buffer.from('world').toString('base64')}
email = i@izs.me
//registry.example/:always-auth = true
`,
},
def_userNoPass: {
'.npmrc': `username = hello
email = i@izs.me
//registry.example/:always-auth = true
`,
},
def_passNoUser: {
'.npmrc': `_password = ${Buffer.from('world').toString('base64')}
email = i@izs.me
//registry.example/:always-auth = true
`,
},
def_auth: {
'.npmrc': `_auth = ${Buffer.from('hello:world').toString('base64')}
always-auth = true`,
},
none_authToken: { '.npmrc': '_authToken = 0bad1de4' },
none_lcAuthToken: { '.npmrc': '_authtoken = 0bad1de4' },
none_emptyConfig: { '.npmrc': '' },
none_noConfig: {},
}
const path = t.testdir(fixtures)
const defReg = 'https://registry.example/'
const otherReg = 'https://other.registry/'
for (const testCase of Object.keys(fixtures)) {
t.test(testCase, async t => {
const c = new Config({
npmPath: path,
shorthands,
types,
defaults,
env: { HOME: resolve(path, testCase) },
argv: ['node', 'file', '--registry', defReg],
})
await c.load()
// only have to do this the first time, it's redundant otherwise
if (testCase === 'none_noConfig') {
t.throws(() => c.setCredentialsByURI('http://x.com', {
username: 'foo',
email: 'bar@baz.com',
}), { message: 'must include password' })
t.throws(() => c.setCredentialsByURI('http://x.com', {
password: 'foo',
email: 'bar@baz.com',
}), { message: 'must include username' })
c.setCredentialsByURI('http://x.com', {
username: 'foo',
password: 'bar',
email: 'asdf@quux.com',
})
t.equal(c.getCredentialsByURI('http://x.com').alwaysAuth, false)
}
const d = c.getCredentialsByURI(defReg)
const o = c.getCredentialsByURI(otherReg)
t.matchSnapshot(d, 'default registry')
t.matchSnapshot(o, 'other registry')
c.clearCredentialsByURI(defReg)
const defAfterDelete = c.getCredentialsByURI(defReg)
t.strictSame(Object.keys(defAfterDelete), ['alwaysAuth'])
c.clearCredentialsByURI(otherReg)
const otherAfterDelete = c.getCredentialsByURI(otherReg)
t.strictSame(Object.keys(otherAfterDelete), ['alwaysAuth'])
// we can have email on its own, but need both or none of user/pass
if (!d.token && (!d.email || (!!d.username !== !!d.password)))
t.throws(() => c.setCredentialsByURI(defReg, d))
else {
c.setCredentialsByURI(defReg, d)
t.matchSnapshot(c.getCredentialsByURI(defReg), 'default registry after set')
}
if (!o.token && (!o.email || (!!o.username !== !!o.password)))
t.throws(() => c.setCredentialsByURI(otherReg, o))
else {
c.setCredentialsByURI(otherReg, o)
t.matchSnapshot(c.getCredentialsByURI(otherReg), 'other registry after set')
}
})
}
t.end()
})
t.test('finding the global prefix', t => {
const npmPath = __dirname
t.test('load from PREFIX env', t => {
const c = new Config({
env: {
PREFIX: '/prefix/env'
},
shorthands,
types,
defaults,
npmPath,
})
c.loadGlobalPrefix()
t.throws(() => c.loadGlobalPrefix(), {
message: 'cannot load default global prefix more than once',
})
t.equal(c.globalPrefix, '/prefix/env')
t.end()
})
t.test('load from execPath, win32', t => {
const c = new Config({
platform: 'win32',
execPath: '/path/to/nodejs/node.exe',
shorthands,
types,
defaults,
npmPath,
})
c.loadGlobalPrefix()
t.equal(c.globalPrefix, dirname('/path/to/nodejs/node.exe'))
t.end()
})
t.test('load from execPath, posix', t => {
const c = new Config({
platform: 'posix',
execPath: '/path/to/nodejs/bin/node',
shorthands,
types,
defaults,
npmPath,
})
c.loadGlobalPrefix()
t.equal(c.globalPrefix, dirname(dirname('/path/to/nodejs/bin/node')))
t.end()
})
t.test('load from execPath with destdir, posix', t => {
const c = new Config({
platform: 'posix',
execPath: '/path/to/nodejs/bin/node',
env: { DESTDIR: '/some/dest/dir' },
shorthands,
types,
defaults,
npmPath,
})
c.loadGlobalPrefix()
t.equal(c.globalPrefix, join('/some/dest/dir', dirname(dirname('/path/to/nodejs/bin/node'))))
t.end()
})
t.end()
})
t.test('finding the local prefix', t => {
const path = t.testdir({
hasNM: {
node_modules: {},
x: { y: { z: {}}},
},
hasPJ: {
'package.json': '{}',
x: { y: { z: {}}},
},
})
t.test('explicit cli prefix', async t => {
const c = new Config({
argv: [process.execPath, __filename, '-C', path],
types,
shorthands,
defaults,
npmPath: path,
})
await c.load()
t.equal(c.localPrefix, resolve(path))
})
t.test('has node_modules', async t => {
const c = new Config({
cwd: `${path}/hasNM/x/y/z`,
types,
shorthands,
defaults,
npmPath: path,
})
await c.load()
t.equal(c.localPrefix, resolve(path, 'hasNM'))
})
t.test('has package.json', async t => {
const c = new Config({
cwd: `${path}/hasPJ/x/y/z`,
types,
shorthands,
defaults,
npmPath: path,
})
await c.load()
t.equal(c.localPrefix, resolve(path, 'hasPJ'))
})
t.test('nada, just use cwd', async t => {
const c = new Config({
cwd: '/this/path/does/not/exist/x/y/z',
types,
shorthands,
defaults,
npmPath: path,
})
await c.load()
t.equal(c.localPrefix, '/this/path/does/not/exist/x/y/z')
})
t.end()
})
t.test('setting basic auth creds and email', async t => {
const registry = 'https://registry.npmjs.org/'
const path = t.testdir()
const _auth = Buffer.from('admin:admin').toString('base64')
const opts = {
shorthands: {},
argv: ['node', __filename, `--userconfig=${path}/.npmrc`],
defaults: {
registry,
'always-auth': false,
},
types: {},
npmPath: process.cwd(),
}
const c = new Config(opts)
await c.load()
t.throws(() => c.set('_auth'), 'cannot set _auth without first setting email')
c.set('email', 'name@example.com', 'user')
t.equal(c.get('email', 'user'), 'name@example.com', 'email was set')
await c.save('user')
t.equal(c.get('email', 'user'), undefined, 'email no longer top-level')
t.strictSame(c.getCredentialsByURI(registry), { email: 'name@example.com', alwaysAuth: false })
const d = new Config(opts)
await d.load()
t.strictSame(d.getCredentialsByURI(registry), { email: 'name@example.com', alwaysAuth: false })
d.set('_auth', _auth, 'user')
t.equal(d.get('_auth', 'user'), _auth, '_auth was set')
await d.save('user')
t.equal(d.get('_auth', 'user'), undefined, 'un-nerfed _auth deleted')
t.strictSame(d.getCredentialsByURI(registry), {
email: 'name@example.com',
username: 'admin',
password: 'admin',
auth: _auth,
alwaysAuth: false,
}, 'credentials saved and nerfed')
})
t.test('setting username/password/email individually', async t => {
const registry = 'https://registry.npmjs.org/'
const path = t.testdir()
const _auth = Buffer.from('admin:admin').toString('base64')
const opts = {
shorthands: {},
argv: ['node', __filename, `--userconfig=${path}/.npmrc`],
defaults: {
registry,
'always-auth': false,
},
types: {},
npmPath: process.cwd(),
}
const c = new Config(opts)
await c.load()
c.set('email', 'name@example.com', 'user')
t.equal(c.get('email'), 'name@example.com')
c.set('username', 'admin', 'user')
t.equal(c.get('username'), 'admin')
c.set('_password', Buffer.from('admin').toString('base64'), 'user')
t.equal(c.get('_password'), Buffer.from('admin').toString('base64'))
t.equal(c.get('_auth'), undefined)
await c.save('user')
t.equal(c.get('email'), undefined)
t.equal(c.get('username'), undefined)
t.equal(c.get('_password'), undefined)
t.equal(c.get('_auth'), undefined)
t.strictSame(c.getCredentialsByURI(registry), {
alwaysAuth: false,
email: 'name@example.com',
username: 'admin',
password: 'admin',
auth: Buffer.from('admin:admin').toString('base64'),
})
const d = new Config(opts)
await d.load()
t.equal(d.get('email'), undefined)
t.equal(d.get('username'), undefined)
t.equal(d.get('_password'), undefined)
t.equal(d.get('_auth'), undefined)
t.strictSame(d.getCredentialsByURI(registry), {
alwaysAuth: false,
email: 'name@example.com',
username: 'admin',
password: 'admin',
auth: Buffer.from('admin:admin').toString('base64'),
})
})