-
Notifications
You must be signed in to change notification settings - Fork 501
/
Copy pathconfig.js
1554 lines (1396 loc) · 48.9 KB
/
config.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
// config.js (c) 2010-2022 Loren West and other contributors
// May be freely distributed under the MIT license.
// For further details and documentation:
// http://lorenwest.github.com/node-config
// Dependencies
const DeferredConfig = require('../defer').DeferredConfig;
const RawConfig = require('../raw').RawConfig;
let Parser = require('../parser');
const Path = require('path');
const FileSystem = require('fs');
// Static members
const DEFAULT_CLONE_DEPTH = 20;
let CONFIG_DIR;
let NODE_ENV;
let APP_INSTANCE;
let CONFIG_SKIP_GITCRYPT;
let NODE_ENV_VAR_NAME;
let NODE_CONFIG_PARSER;
const env = {};
const configSources = []; // Configuration sources - array of {name, original, parsed}
let checkMutability = true; // Check for mutability/immutability on first get
const gitCryptTestRegex = /^.GITCRYPT/; // regular expression to test for gitcrypt files.
/**
* <p>Application Configurations</p>
*
* <p>
* The config module exports a singleton object representing all
* configurations for this application deployment.
* </p>
*
* <p>
* Application configurations are stored in files within the config directory
* of your application. The default configuration file is loaded, followed
* by files specific to the deployment type (development, testing, staging,
* production, etc.).
* </p>
*
* <p>
* For example, with the following config/default.yaml file:
* </p>
*
* <pre>
* ...
* customer:
* initialCredit: 500
* db:
* name: customer
* port: 5984
* ...
* </pre>
*
* <p>
* The following code loads the customer section into the CONFIG variable:
* <p>
*
* <pre>
* const CONFIG = require('config').customer;
* ...
* newCustomer.creditLimit = CONFIG.initialCredit;
* database.open(CONFIG.db.name, CONFIG.db.port);
* ...
* </pre>
*
* @module config
* @class Config
*/
/**
* <p>Get the configuration object.</p>
*
* <p>
* The configuration object is a shared singleton object within the application,
* attained by calling require('config').
* </p>
*
* <p>
* Usually you'll specify a CONFIG variable at the top of your .js file
* for file/module scope. If you want the root of the object, you can do this:
* </p>
* <pre>
* const CONFIG = require('config');
* </pre>
*
* <p>
* Sometimes you only care about a specific sub-object within the CONFIG
* object. In that case you could do this at the top of your file:
* </p>
* <pre>
* const CONFIG = require('config').customer;
* or
* const CUSTOMER_CONFIG = require('config').customer;
* </pre>
*
* <script type="text/javascript">
* document.getElementById("showProtected").style.display = "block";
* </script>
*
* @method constructor
* @return CONFIG {object} - The top level configuration object
*/
const Config = function() {
const t = this;
// Bind all utility functions to this
for (const fnName in util) {
if (typeof util[fnName] === 'function') {
util[fnName] = util[fnName].bind(t);
}
}
// Merge configurations into this
util.extendDeep(t, util.loadFileConfigs());
util.attachProtoDeep(t);
// Perform strictness checks and possibly throw an exception.
util.runStrictnessChecks(t);
};
/**
* Utilities are under the util namespace vs. at the top level
*/
const util = Config.prototype.util = {};
/**
* Underlying get mechanism
*
* @private
* @method getImpl
* @param object {object} - Object to get the property for
* @param property {string|string[]} - The property name to get (as an array or '.' delimited string)
* @return value {*} - Property value, including undefined if not defined.
*/
const getImpl= function(object, property) {
const t = this;
const elems = Array.isArray(property) ? property : property.split('.');
const name = elems[0];
const value = object[name];
if (elems.length <= 1) {
return value;
}
// Note that typeof null === 'object'
if (value === null || typeof value !== 'object') {
return undefined;
}
return getImpl(value, elems.slice(1));
};
/**
* <p>Get a configuration value</p>
*
* <p>
* This will return the specified property value, throwing an exception if the
* configuration isn't defined. It is used to assure configurations are defined
* before being used, and to prevent typos.
* </p>
*
* @method get
* @param property {string} - The configuration property to get. Can include '.' sub-properties.
* @return value {*} - The property value
*/
Config.prototype.get = function(property) {
if(property === null || typeof property === "undefined"){
throw new Error("Calling config.get with null or undefined argument");
}
// Make configurations immutable after first get (unless disabled)
if (checkMutability) {
if (!util.initParam('ALLOW_CONFIG_MUTATIONS', false)) {
util.makeImmutable(config);
}
checkMutability = false;
}
const t = this;
const value = getImpl(t, property);
// Produce an exception if the property doesn't exist
if (typeof value === "undefined") {
throw new Error('Configuration property "' + property + '" is not defined');
}
// Return the value
return value;
};
/**
* Test that a configuration parameter exists
*
* <pre>
* const config = require('config');
* if (config.has('customer.dbName')) {
* console.log('Customer database name: ' + config.customer.dbName);
* }
* </pre>
*
* @method has
* @param property {string} - The configuration property to test. Can include '.' sub-properties.
* @return isPresent {boolean} - True if the property is defined, false if not defined.
*/
Config.prototype.has = function(property) {
// While get() throws an exception for undefined input, has() is designed to test validity, so false is appropriate
if(property === null || typeof property === "undefined"){
return false;
}
const t = this;
return typeof getImpl(t, property) !== "undefined";
};
/**
* <p>
* Set default configurations for a node.js module.
* </p>
*
* <p>
* This allows module developers to attach their configurations onto the
* default configuration object so they can be configured by the consumers
* of the module.
* </p>
*
* <p>Using the function within your module:</p>
* <pre>
* const CONFIG = require("config");
* CONFIG.util.setModuleDefaults("MyModule", {
* templateName: "t-50",
* colorScheme: "green"
* });
* <br>
* // Template name may be overridden by application config files
* console.log("Template: " + CONFIG.MyModule.templateName);
* </pre>
*
* <p>
* The above example results in a "MyModule" element of the configuration
* object, containing an object with the specified default values.
* </p>
*
* @method setModuleDefaults
* @param moduleName {string} - Name of your module.
* @param defaultProperties {object} - The default module configuration.
* @return moduleConfig {object} - The module level configuration object.
*/
util.setModuleDefaults = function (moduleName, defaultProperties) {
// Copy the properties into a new object
const t = this;
const moduleConfig = util.cloneDeep(defaultProperties);
// Set module defaults into the first sources element
if (configSources.length === 0 || configSources[0].name !== 'Module Defaults') {
configSources.splice(0, 0, {
name: 'Module Defaults',
parsed: {}
});
}
util.setPath(configSources[0].parsed, moduleName.split('.'), {});
util.extendDeep(getImpl(configSources[0].parsed, moduleName), defaultProperties);
// Create a top level config for this module if it doesn't exist
util.setPath(t, moduleName.split('.'), getImpl(t, moduleName) || {});
// Extend local configurations into the module config
util.extendDeep(moduleConfig, getImpl(t, moduleName));
// Merge the extended configs without replacing the original
util.extendDeep(getImpl(t, moduleName), moduleConfig);
// reset the mutability check for "config.get" method.
// we are not making t[moduleName] immutable immediately,
// since there might be more modifications before the first config.get
if (!util.initParam('ALLOW_CONFIG_MUTATIONS', false)) {
checkMutability = true;
}
// Attach handlers & watchers onto the module config object
return util.attachProtoDeep(getImpl(t, moduleName));
};
/**
* <p>Make a configuration property hidden so it doesn't appear when enumerating
* elements of the object.</p>
*
* <p>
* The property still exists and can be read from and written to, but it won't
* show up in for ... in loops, Object.keys(), or JSON.stringify() type methods.
* </p>
*
* <p>
* If the property already exists, it will be made hidden. Otherwise it will
* be created as a hidden property with the specified value.
* </p>
*
* <p><i>
* This method was built for hiding configuration values, but it can be applied
* to <u>any</u> javascript object.
* </i></p>
*
* <p>Example:</p>
* <pre>
* const CONFIG = require('config');
* ...
*
* // Hide the Amazon S3 credentials
* CONFIG.util.makeHidden(CONFIG.amazonS3, 'access_id');
* CONFIG.util.makeHidden(CONFIG.amazonS3, 'secret_key');
* </pre>
*
* @method makeHidden
* @param object {object} - The object to make a hidden property into.
* @param property {string} - The name of the property to make hidden.
* @param value {*} - (optional) Set the property value to this (otherwise leave alone)
* @return object {object} - The original object is returned - for chaining.
*/
util.makeHidden = function(object, property, value) {
// If the new value isn't specified, just mark the property as hidden
if (typeof value === 'undefined') {
Object.defineProperty(object, property, {
enumerable : false
});
}
// Otherwise set the value and mark it as hidden
else {
Object.defineProperty(object, property, {
value : value,
enumerable : false
});
}
return object;
}
/**
* <p>Make a javascript object property immutable (assuring it cannot be changed
* from the current value).</p>
* <p>
* If the specified property is an object, all attributes of that object are
* made immutable, including properties of contained objects, recursively.
* If a property name isn't supplied, all properties of the object are made
* immutable.
* </p>
* <p>
*
* </p>
* <p>
* New properties can be added to the object and those properties will not be
* immutable unless this method is called on those new properties.
* </p>
* <p>
* This operation cannot be undone.
* </p>
*
* <p>Example:</p>
* <pre>
* const config = require('config');
* const myObject = {hello:'world'};
* config.util.makeImmutable(myObject);
* </pre>
*
* @method makeImmutable
* @param object {object} - The object to specify immutable properties for
* @param [property] {string | [string]} - The name of the property (or array of names) to make immutable.
* If not provided, all owned properties of the object are made immutable.
* @param [value] {* | [*]} - Property value (or array of values) to set
* the property to before making immutable. Only used when setting a single
* property. Retained for backward compatibility.
* @return object {object} - The original object is returned - for chaining.
*/
util.makeImmutable = function(object, property, value) {
if (Buffer.isBuffer(object)) {
return object;
}
let properties = null;
// Backwards compatibility mode where property/value can be specified
if (typeof property === 'string') {
return Object.defineProperty(object, property, {
value : (typeof value === 'undefined') ? object[property] : value,
writable : false,
configurable: false
});
}
// Get the list of properties to work with
if (Array.isArray(property)) {
properties = property;
}
else {
properties = Object.keys(object);
}
// Process each property
for (let i = 0; i < properties.length; i++) {
const propertyName = properties[i];
let value = object[propertyName];
if (value instanceof RawConfig) {
Object.defineProperty(object, propertyName, {
value: value.resolve(),
writable: false,
configurable: false
});
} else if (Array.isArray(value)) {
// Ensure object items of this array are also immutable.
value.forEach((item, index) => { if (util.isObject(item) || Array.isArray(item)) util.makeImmutable(item) })
Object.defineProperty(object, propertyName, {
value: Object.freeze(value)
});
} else {
// Call recursively if an object.
if (util.isObject(value)) {
// Create a proxy, to capture user updates of configuration options, and throw an exception for awareness, as per:
// https://github.com/lorenwest/node-config/issues/514
value = new Proxy(util.makeImmutable(value), {
get(target, property, receiver) {
// Config's own defined prototype properties and methods (e.g., `get`, `has`, etc.)
const ownProps = [
...Object.getOwnPropertyNames(Config.prototype),
...Object.getOwnPropertyNames(target),
]
// Bypass proxy receiver for properties directly on the target (e.g., RegExp.prototype.source)
// or properties that are not functions to prevent errors related to internal object methods.
if (ownProps.includes(property) || (property in target && typeof target[property] !== 'function')) {
return Reflect.get(target, property);
}
// Otherwise, use the proxy receiver to handle the property access
const ref = Reflect.get(target, property, receiver);
// Binds the method's `this` context to the target object (e.g., Date.prototype.toISOString)
// to ensure it behaves correctly when called on the proxy.
if (typeof ref === 'function') {
return ref.bind(target);
}
return ref;
},
set (target, name) {
const message = (Reflect.has(target, name) ? 'update' : 'add');
// Notify the user.
throw Error(`Can not ${message} runtime configuration property: "${name}". Configuration objects are immutable unless ALLOW_CONFIG_MUTATIONS is set.`)
}
})
}
Object.defineProperty(object, propertyName, {
value: value,
writable : false,
configurable: false
});
// Ensure new properties can not be added, as per:
// https://github.com/lorenwest/node-config/issues/505
Object.preventExtensions(object[propertyName])
}
}
return object;
};
/**
* Return the sources for the configurations
*
* <p>
* All sources for configurations are stored in an array of objects containing
* the source name (usually the filename), the original source (as a string),
* and the parsed source as an object.
* </p>
*
* @method getConfigSources
* @return configSources {Array[Object]} - An array of objects containing
* name, original, and parsed elements
*/
util.getConfigSources = function() {
const t = this;
return configSources.slice(0);
};
/**
* Looks into an options object for a specific attribute
*
* <p>
* This method looks into the options object, and if an attribute is defined, returns it,
* and if not, returns the default value
* </p>
*
* @method getOption
* @param options {Object | undefined} the options object
* @param optionName {string} the attribute name to look for
* @param defaultValue { any } the default in case the options object is empty, or the attribute does not exist.
* @return options[optionName] if defined, defaultValue if not.
*/
util.getOption = function(options, optionName, defaultValue) {
if (options !== undefined && typeof options[optionName] !== 'undefined'){
return options[optionName];
} else {
return defaultValue;
}
};
/**
* Load the individual file configurations.
*
* <p>
* This method builds a map of filename to the configuration object defined
* by the file. The search order is:
* </p>
*
* <pre>
* default.EXT
* (deployment).EXT
* (hostname).EXT
* (hostname)-(deployment).EXT
* local.EXT
* local-(deployment).EXT
* runtime.json
* </pre>
*
* <p>
* EXT can be yml, yaml, coffee, iced, json, cson or js signifying the file type.
* yaml (and yml) is in YAML format, coffee is a coffee-script, iced is iced-coffee-script,
* json is in JSON format, cson is in CSON format, properties is in .properties format
* (http://en.wikipedia.org/wiki/.properties), and js is a javascript executable file that is
* require()'d with module.exports being the config object.
* </p>
*
* <p>
* hostname is the $HOST environment variable (or --HOST command line parameter)
* if set, otherwise the $HOSTNAME environment variable (or --HOSTNAME command
* line parameter) if set, otherwise the hostname found from
* require('os').hostname().
* </p>
*
* <p>
* Once a hostname is found, everything from the first period ('.') onwards
* is removed. For example, abc.example.com becomes abc
* </p>
*
* <p>
* (deployment) is the deployment type, found in the $NODE_ENV environment
* variable (which can be overridden by using $NODE_CONFIG_ENV
* environment variable). Defaults to 'development'.
* </p>
*
* <p>
* The runtime.json file contains configuration changes made at runtime either
* manually, or by the application setting a configuration value.
* </p>
*
* <p>
* If the $NODE_APP_INSTANCE environment variable (or --NODE_APP_INSTANCE
* command line parameter) is set, then files with this appendage will be loaded.
* See the Multiple Application Instances section of the main documentation page
* for more information.
* </p>
*
* @protected
* @method loadFileConfigs
* @param configDir { string | null } the path to the directory containing the configurations to load
* @param options { object | undefined } parsing options. Current supported option: skipConfigSources: true|false
* @return config {Object} The configuration object
*/
util.loadFileConfigs = function(configDir, options) {
// Initialize
const t = this;
const config = {};
// Specify variables that can be used to define the environment
const node_env_var_names = ['NODE_CONFIG_ENV', 'NODE_ENV'];
// Loop through the variables to try and set environment
for (const node_env_var_name of node_env_var_names) {
NODE_ENV = util.initParam(node_env_var_name);
if (!!NODE_ENV) {
NODE_ENV_VAR_NAME = node_env_var_name;
break;
}
}
// If we haven't successfully set the environment using the variables, we'll default it
if (!NODE_ENV) {
NODE_ENV = 'development';
}
node_env_var_names.forEach(node_env_var_name => {
env[node_env_var_name] = NODE_ENV;
});
// Split files name, for loading multiple files.
NODE_ENV = NODE_ENV.split(',');
let dir = configDir || util.initParam('NODE_CONFIG_DIR', Path.join( process.cwd(), 'config') );
dir = _toAbsolutePath(dir);
APP_INSTANCE = util.initParam('NODE_APP_INSTANCE');
CONFIG_SKIP_GITCRYPT = util.initParam('CONFIG_SKIP_GITCRYPT');
// This is for backward compatibility
const runtimeFilename = util.initParam('NODE_CONFIG_RUNTIME_JSON', Path.join(dir , 'runtime.json') );
NODE_CONFIG_PARSER = util.initParam('NODE_CONFIG_PARSER');
if (NODE_CONFIG_PARSER) {
try {
const parserModule = Path.isAbsolute(NODE_CONFIG_PARSER)
? NODE_CONFIG_PARSER
: Path.join(dir, NODE_CONFIG_PARSER);
Parser = require(parserModule);
}
catch (e) {
console.warn('Failed to load config parser from ' + NODE_CONFIG_PARSER);
console.log(e);
}
}
const HOST = util.initParam('HOST');
const HOSTNAME = util.initParam('HOSTNAME');
// Determine the host name from the OS module, $HOST, or $HOSTNAME
// Remove any . appendages, and default to null if not set
let hostName = HOST || HOSTNAME;
try {
if (!hostName) {
const OS = require('os');
hostName = OS.hostname();
}
} catch (e) {
hostName = '';
}
// Store the hostname that won.
env.HOSTNAME = hostName;
// Read each file in turn
const baseNames = ['default'].concat(NODE_ENV);
// #236: Also add full hostname when they are different.
if (hostName) {
const firstDomain = hostName.split('.')[0];
NODE_ENV.forEach(function(env) {
// Backward compatibility
baseNames.push(firstDomain, firstDomain + '-' + env);
// Add full hostname when it is not the same
if (hostName !== firstDomain) {
baseNames.push(hostName, hostName + '-' + env);
}
});
}
NODE_ENV.forEach(function(env) {
baseNames.push('local', 'local-' + env);
});
const allowedFiles = {};
let resolutionIndex = 1;
const extNames = Parser.getFilesOrder();
baseNames.forEach(function(baseName) {
const fileNames = [baseName];
if (APP_INSTANCE) {
fileNames.push(baseName + '-' + APP_INSTANCE);
}
fileNames.forEach(function(fileName) {
extNames.forEach(function(extName) {
allowedFiles[fileName + '.' + extName] = resolutionIndex++;
});
})
});
const locatedFiles = util.locateMatchingFiles(dir, allowedFiles);
locatedFiles.forEach(function(fullFilename) {
const configObj = util.parseFile(fullFilename, options);
if (configObj) {
util.extendDeep(config, configObj);
}
});
// Override configurations from the $NODE_CONFIG environment variable
// NODE_CONFIG only applies to the base config
if (!configDir) {
let envConfig = {};
CONFIG_DIR = dir;
if (process.env.NODE_CONFIG) {
try {
envConfig = JSON.parse(process.env.NODE_CONFIG);
} catch(e) {
console.error('The $NODE_CONFIG environment variable is malformed JSON');
}
util.extendDeep(config, envConfig);
const skipConfigSources = util.getOption(options,'skipConfigSources', false);
if (!skipConfigSources){
configSources.push({
name: "$NODE_CONFIG",
parsed: envConfig,
});
}
}
// Override configurations from the --NODE_CONFIG command line
let cmdLineConfig = util.getCmdLineArg('NODE_CONFIG');
if (cmdLineConfig) {
try {
cmdLineConfig = JSON.parse(cmdLineConfig);
} catch(e) {
console.error('The --NODE_CONFIG={json} command line argument is malformed JSON');
}
util.extendDeep(config, cmdLineConfig);
const skipConfigSources = util.getOption(options,'skipConfigSources', false);
if (!skipConfigSources){
configSources.push({
name: "--NODE_CONFIG argument",
parsed: cmdLineConfig,
});
}
}
// Place the mixed NODE_CONFIG into the environment
env['NODE_CONFIG'] = JSON.stringify(util.extendDeep(envConfig, cmdLineConfig, {}));
}
// Override with environment variables if there is a custom-environment-variables.EXT mapping file
const customEnvVars = util.getCustomEnvVars(dir, extNames);
util.extendDeep(config, customEnvVars);
// Extend the original config with the contents of runtime.json (backwards compatibility)
const runtimeJson = util.parseFile(runtimeFilename) || {};
util.extendDeep(config, runtimeJson);
util.resolveDeferredConfigs(config);
// Return the configuration object
return config;
};
/**
* Return a list of fullFilenames who exists in allowedFiles
* Ordered according to allowedFiles argument specifications
*
* @protected
* @method locateMatchingFiles
* @param configDirs {string} the config dir, or multiple dirs separated by a column (:)
* @param allowedFiles {object} an object. keys and supported filenames
* and values are the position in the resolution order
* @returns {string[]} fullFilenames - path + filename
*/
util.locateMatchingFiles = function(configDirs, allowedFiles) {
return configDirs.split(Path.delimiter)
.reduce(function(files, configDir) {
if (configDir) {
configDir = _toAbsolutePath(configDir);
try {
FileSystem.readdirSync(configDir).forEach(function(file) {
if (allowedFiles[file]) {
files.push([allowedFiles[file], Path.join(configDir, file)]);
}
});
}
catch(e) {}
return files;
}
}, [])
.sort(function(a, b) { return a[0] - b[0]; })
.map(function(file) { return file[1]; });
};
// Using basic recursion pattern, find all the deferred values and resolve them.
util.resolveDeferredConfigs = function (config) {
const deferred = [];
function _iterate (prop) {
// We put the properties we are going to look it in an array to keep the order predictable
const propsToSort = [];
// First step is to put the properties of interest in an array
for (const property in prop) {
if (Object.hasOwnProperty.call(prop, property) && prop[property] != null) {
propsToSort.push(property);
}
}
// Second step is to iterate of the elements in a predictable (sorted) order
propsToSort.sort().forEach(function (property) {
if (prop[property].constructor === Object) {
_iterate(prop[property]);
} else if (prop[property].constructor === Array) {
for (let i = 0; i < prop[property].length; i++) {
if (prop[property][i] instanceof DeferredConfig) {
deferred.push(prop[property][i].prepare(config, prop[property], i));
}
else {
_iterate(prop[property][i]);
}
}
} else {
if (prop[property] instanceof DeferredConfig) {
deferred.push(prop[property].prepare(config, prop, property));
}
// else: Nothing to do. Keep the property how it is.
}
});
}
_iterate(config);
deferred.forEach(function (defer) { defer.resolve(); });
};
/**
* Parse and return the specified configuration file.
*
* If the file exists in the application config directory, it will
* parse and return it as a JavaScript object.
*
* The file extension determines the parser to use.
*
* .js = File to run that has a module.exports containing the config object
* .coffee = File to run that has a module.exports with coffee-script containing the config object
* .iced = File to run that has a module.exports with iced-coffee-script containing the config object
* All other supported file types (yaml, toml, json, cson, hjson, json5, properties, xml)
* are parsed with util.parseString.
*
* If the file doesn't exist, a null will be returned. If the file can't be
* parsed, an exception will be thrown.
*
* This method performs synchronous file operations, and should not be called
* after synchronous module loading.
*
* @protected
* @method parseFile
* @param fullFilename {string} The full file path and name
* @param options { object | undefined } parsing options. Current supported option: skipConfigSources: true|false
* @return configObject {object|null} The configuration object parsed from the file
*/
util.parseFile = function(fullFilename, options) {
const t = this; // Initialize
let configObject = null;
let fileContent = null;
const stat = null;
// Note that all methods here are the Sync versions. This is appropriate during
// module loading (which is a synchronous operation), but not thereafter.
try {
// Try loading the file.
fileContent = FileSystem.readFileSync(fullFilename, 'utf-8');
fileContent = fileContent.replace(/^\uFEFF/, '');
}
catch (e2) {
if (e2.code !== 'ENOENT') {
throw new Error('Config file ' + fullFilename + ' cannot be read. Error code is: '+e2.code
+'. Error message is: '+e2.message);
}
return null; // file doesn't exists
}
// Parse the file based on extension
try {
// skip if it's a gitcrypt file and CONFIG_SKIP_GITCRYPT is true
if (CONFIG_SKIP_GITCRYPT) {
if (gitCryptTestRegex.test(fileContent)) {
console.error('WARNING: ' + fullFilename + ' is a git-crypt file and CONFIG_SKIP_GITCRYPT is set. skipping.');
return null;
}
}
configObject = Parser.parse(fullFilename, fileContent);
}
catch (e3) {
if (gitCryptTestRegex.test(fileContent)) {
console.error('ERROR: ' + fullFilename + ' is a git-crypt file and CONFIG_SKIP_GITCRYPT is not set.');
}
throw new Error("Cannot parse config file: '" + fullFilename + "': " + e3);
}
// Keep track of this configuration sources, including empty ones, unless the skipConfigSources flag is set to true in the options
const skipConfigSources = util.getOption(options,'skipConfigSources', false);
if (typeof configObject === 'object' && !skipConfigSources) {
configSources.push({
name: fullFilename,
original: fileContent,
parsed: configObject,
});
}
return configObject;
};
/**
* Parse and return the specified string with the specified format.
*
* The format determines the parser to use.
*
* json = File is parsed using JSON.parse()
* yaml (or yml) = Parsed with a YAML parser
* toml = Parsed with a TOML parser
* cson = Parsed with a CSON parser
* hjson = Parsed with a HJSON parser
* json5 = Parsed with a JSON5 parser
* properties = Parsed with the 'properties' node package
* xml = Parsed with a XML parser
*
* If the file doesn't exist, a null will be returned. If the file can't be
* parsed, an exception will be thrown.
*
* This method performs synchronous file operations, and should not be called
* after synchronous module loading.
*
* @protected
* @method parseString
* @param content {string} The full content
* @param format {string} The format to be parsed
* @return {configObject} The configuration object parsed from the string
*/
util.parseString = function (content, format) {
const parser = Parser.getParser(format);
if (typeof parser === 'function') {
return parser(null, content);
}
};
/**
* Attach the Config class prototype to all config objects recursively.
*
* <p>
* This allows you to do anything with CONFIG sub-objects as you can do with
* the top-level CONFIG object. It's so you can do this:
* </p>
*
* <pre>
* const CUST_CONFIG = require('config').Customer;
* CUST_CONFIG.get(...)
* </pre>
*
* @protected
* @method attachProtoDeep
* @param toObject
* @param depth
* @return toObject
*/
util.attachProtoDeep = function(toObject, depth) {
if (toObject instanceof RawConfig) {
return toObject;
}
// Recursion detection
const t = this;
depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth);
if (depth < 0) {
return toObject;
}
// Adding Config.prototype methods directly to toObject as hidden properties
// because adding to toObject.__proto__ exposes the function in toObject
for (const fnName in Config.prototype) {
if (!toObject[fnName]) {
util.makeHidden(toObject, fnName, Config.prototype[fnName]);
}
}
// Add prototypes to sub-objects
for (const prop in toObject) {
if (util.isObject(toObject[prop])) {
util.attachProtoDeep(toObject[prop], depth - 1);
}
}
// Return the original object
return toObject;
};
/**
* Return a deep copy of the specified object.
*
* This returns a new object with all elements copied from the specified
* object. Deep copies are made of objects and arrays so you can do anything
* with the returned object without affecting the input object.
*
* @protected
* @method cloneDeep
* @param parent {object} The original object to copy from
* @param [depth=20] {Integer} Maximum depth (default 20)
* @return {object} A new object with the elements copied from the copyFrom object
*
* This method is copied from https://github.com/pvorb/node-clone/blob/17eea36140d61d97a9954c53417d0e04a00525d9/clone.js
*
* Copyright © 2011-2014 Paul Vorbach and contributors.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the “Software”), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions: The above copyright notice and this permission