@spinajs/configuration 2.0.179 → 2.0.181

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,87 +1,87 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.AutoinjectService = exports.Config = void 0;
7
- const lodash_1 = __importDefault(require("lodash"));
8
- /* eslint-disable @typescript-eslint/no-explicit-any */
9
- const configuration_common_1 = require("@spinajs/configuration-common");
10
- const di_1 = require("@spinajs/di");
11
- /**
12
- * Injects configuration value to given class property
13
- *
14
- * @param path - path to configuration value eg. "app.dirs.stats"
15
- * @param dafaultValue - default value if path not exists
16
- * @returns
17
- */
18
- function Config(path, options) {
19
- return (target, key) => {
20
- let config = null;
21
- // register conf, so we can expose eg. in db if config is set
22
- di_1.DI.register({ path, options }).asValue('__configuration_property__');
23
- const getter = () => {
24
- if (!config) {
25
- config = di_1.DI.get(configuration_common_1.Configuration);
26
- }
27
- // try to return val
28
- return config.get(path, options ? options.defaultValue ?? undefined : undefined);
29
- };
30
- Object.defineProperty(target, key, {
31
- get: getter,
32
- enumerable: false,
33
- configurable: false,
34
- });
35
- };
36
- }
37
- exports.Config = Config;
38
- /**
39
- * Inject service based on configuration.
40
- * Configuration could be object or string containing service
41
- *
42
- * If array is provided in configuration, service is resolved by name
43
- * stored in 'service' property and returnes as Map\<serviceName, instance\>
44
- *
45
- * @param path - configuration path where service type is stored
46
- * @param type - if type is provided, it will override type obtain from reflection. Use it specific with arrays and maps, becouse ts reflection module cannot extract array and map type data
47
- */
48
- function AutoinjectService(path, type) {
49
- return (0, di_1.AddDependencyForProperty)((descriptor, target, propertyKey) => {
50
- const t = type ?? Reflect.getMetadata('design:type', target, propertyKey);
51
- descriptor.inject.push({
52
- autoinject: true,
53
- autoinjectKey: propertyKey,
54
- inject: t,
55
- data: path,
56
- mapFunc: (x) => {
57
- return x.ServiceName || x.constructor.name;
58
- },
59
- serviceFunc: (path, container) => {
60
- const cfg = container.get(configuration_common_1.Configuration);
61
- const cfgVal = cfg.get(path);
62
- if (!cfgVal) {
63
- throw new Error(`Configuration value ${path} is empty`);
64
- }
65
- if (lodash_1.default.isString(cfgVal)) {
66
- return {
67
- service: cfgVal,
68
- };
69
- }
70
- if (lodash_1.default.isArray(cfgVal)) {
71
- return cfgVal.map((x) => {
72
- return {
73
- service: x.service,
74
- options: x,
75
- };
76
- });
77
- }
78
- return {
79
- service: cfgVal.service,
80
- options: cfgVal,
81
- };
82
- },
83
- });
84
- });
85
- }
86
- exports.AutoinjectService = AutoinjectService;
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AutoinjectService = exports.Config = void 0;
7
+ const lodash_1 = __importDefault(require("lodash"));
8
+ /* eslint-disable @typescript-eslint/no-explicit-any */
9
+ const configuration_common_1 = require("@spinajs/configuration-common");
10
+ const di_1 = require("@spinajs/di");
11
+ /**
12
+ * Injects configuration value to given class property
13
+ *
14
+ * @param path - path to configuration value eg. "app.dirs.stats"
15
+ * @param dafaultValue - default value if path not exists
16
+ * @returns
17
+ */
18
+ function Config(path, options) {
19
+ return (target, key) => {
20
+ let config = null;
21
+ // register conf, so we can expose eg. in db if config is set
22
+ di_1.DI.register({ path, options }).asValue('__configuration_property__');
23
+ const getter = () => {
24
+ if (!config) {
25
+ config = di_1.DI.get(configuration_common_1.Configuration);
26
+ }
27
+ // try to return val
28
+ return config.get(path, options ? options.defaultValue ?? undefined : undefined);
29
+ };
30
+ Object.defineProperty(target, key, {
31
+ get: getter,
32
+ enumerable: false,
33
+ configurable: false,
34
+ });
35
+ };
36
+ }
37
+ exports.Config = Config;
38
+ /**
39
+ * Inject service based on configuration.
40
+ * Configuration could be object or string containing service
41
+ *
42
+ * If array is provided in configuration, service is resolved by name
43
+ * stored in 'service' property and returnes as Map\<serviceName, instance\>
44
+ *
45
+ * @param path - configuration path where service type is stored
46
+ * @param type - if type is provided, it will override type obtain from reflection. Use it specific with arrays and maps, becouse ts reflection module cannot extract array and map type data
47
+ */
48
+ function AutoinjectService(path, type) {
49
+ return (0, di_1.AddDependencyForProperty)((descriptor, target, propertyKey) => {
50
+ const t = type ?? Reflect.getMetadata('design:type', target, propertyKey);
51
+ descriptor.inject.push({
52
+ autoinject: true,
53
+ autoinjectKey: propertyKey,
54
+ inject: t,
55
+ data: path,
56
+ mapFunc: (x) => {
57
+ return x.ServiceName || x.constructor.name;
58
+ },
59
+ serviceFunc: (path, container) => {
60
+ const cfg = container.get(configuration_common_1.Configuration);
61
+ const cfgVal = cfg.get(path);
62
+ if (!cfgVal) {
63
+ throw new Error(`Configuration value ${path} is empty`);
64
+ }
65
+ if (lodash_1.default.isString(cfgVal)) {
66
+ return {
67
+ service: cfgVal,
68
+ };
69
+ }
70
+ if (lodash_1.default.isArray(cfgVal)) {
71
+ return cfgVal.map((x) => {
72
+ return {
73
+ service: x.service,
74
+ options: x,
75
+ };
76
+ });
77
+ }
78
+ return {
79
+ service: cfgVal.service,
80
+ options: cfgVal,
81
+ };
82
+ },
83
+ });
84
+ });
85
+ }
86
+ exports.AutoinjectService = AutoinjectService;
87
87
  //# sourceMappingURL=decorators.js.map
@@ -1,6 +1,6 @@
1
- import { ErrorObject } from 'ajv';
2
- export declare class InvalidConfiguration extends Error {
3
- validationExceptions?: ErrorObject[];
4
- constructor(message: string, validationExceptions?: ErrorObject[]);
5
- }
1
+ import { ErrorObject } from 'ajv';
2
+ export declare class InvalidConfiguration extends Error {
3
+ validationExceptions?: ErrorObject[];
4
+ constructor(message: string, validationExceptions?: ErrorObject[]);
5
+ }
6
6
  //# sourceMappingURL=exception.d.ts.map
@@ -1,11 +1,11 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.InvalidConfiguration = void 0;
4
- class InvalidConfiguration extends Error {
5
- constructor(message, validationExceptions) {
6
- super(message);
7
- this.validationExceptions = validationExceptions;
8
- }
9
- }
10
- exports.InvalidConfiguration = InvalidConfiguration;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InvalidConfiguration = void 0;
4
+ class InvalidConfiguration extends Error {
5
+ constructor(message, validationExceptions) {
6
+ super(message);
7
+ this.validationExceptions = validationExceptions;
8
+ }
9
+ }
10
+ exports.InvalidConfiguration = InvalidConfiguration;
11
11
  //# sourceMappingURL=exception.js.map
@@ -1,10 +1,10 @@
1
- /**
2
- * Reexport for simplicity, we dont need to import configuration-common
3
- * and remember all this packages :)
4
- */
5
- export * from '@spinajs/configuration-common';
6
- export * from './sources.js';
7
- export * from './decorators.js';
8
- export * from './configuration.js';
9
- export * from './exception.js';
1
+ /**
2
+ * Reexport for simplicity, we dont need to import configuration-common
3
+ * and remember all this packages :)
4
+ */
5
+ export * from '@spinajs/configuration-common';
6
+ export * from './sources.js';
7
+ export * from './decorators.js';
8
+ export * from './configuration.js';
9
+ export * from './exception.js';
10
10
  //# sourceMappingURL=index.d.ts.map
package/lib/cjs/index.js CHANGED
@@ -1,26 +1,26 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- /**
18
- * Reexport for simplicity, we dont need to import configuration-common
19
- * and remember all this packages :)
20
- */
21
- __exportStar(require("@spinajs/configuration-common"), exports);
22
- __exportStar(require("./sources.js"), exports);
23
- __exportStar(require("./decorators.js"), exports);
24
- __exportStar(require("./configuration.js"), exports);
25
- __exportStar(require("./exception.js"), exports);
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ /**
18
+ * Reexport for simplicity, we dont need to import configuration-common
19
+ * and remember all this packages :)
20
+ */
21
+ __exportStar(require("@spinajs/configuration-common"), exports);
22
+ __exportStar(require("./sources.js"), exports);
23
+ __exportStar(require("./decorators.js"), exports);
24
+ __exportStar(require("./configuration.js"), exports);
25
+ __exportStar(require("./exception.js"), exports);
26
26
  //# sourceMappingURL=index.js.map
@@ -1,22 +1,22 @@
1
- import { Configuration, ConfigurationSource, IConfigLike } from '@spinajs/configuration-common';
2
- export declare abstract class BaseFileSource extends ConfigurationSource {
3
- protected RunApp?: string;
4
- protected CustomConfigPaths?: string[];
5
- protected appBaseDir?: string;
6
- /**
7
- * Configuration base dir, where to look for app config
8
- */
9
- BaseDir: string;
10
- protected CommonDirs: string[];
11
- protected BasePath: string;
12
- get Order(): number;
13
- constructor(RunApp?: string, CustomConfigPaths?: string[], appBaseDir?: string);
14
- protected load(extension: string, callback: (file: string) => Promise<unknown>): Promise<{}>;
15
- }
16
- export declare class JsFileSource extends BaseFileSource {
17
- Load(config: Configuration): Promise<IConfigLike>;
18
- }
19
- export declare class JsonFileSource extends BaseFileSource {
20
- Load(config: Configuration): Promise<IConfigLike>;
21
- }
1
+ import { Configuration, ConfigurationSource, IConfigLike } from '@spinajs/configuration-common';
2
+ export declare abstract class BaseFileSource extends ConfigurationSource {
3
+ protected RunApp?: string;
4
+ protected CustomConfigPaths?: string[];
5
+ protected appBaseDir?: string;
6
+ /**
7
+ * Configuration base dir, where to look for app config
8
+ */
9
+ BaseDir: string;
10
+ protected CommonDirs: string[];
11
+ protected BasePath: string;
12
+ get Order(): number;
13
+ constructor(RunApp?: string, CustomConfigPaths?: string[], appBaseDir?: string);
14
+ protected load(extension: string, callback: (file: string) => Promise<unknown>): Promise<{}>;
15
+ }
16
+ export declare class JsFileSource extends BaseFileSource {
17
+ Load(config: Configuration): Promise<IConfigLike>;
18
+ }
19
+ export declare class JsonFileSource extends BaseFileSource {
20
+ Load(config: Configuration): Promise<IConfigLike>;
21
+ }
22
22
  //# sourceMappingURL=sources.d.ts.map
@@ -1,156 +1,156 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
- return c > 3 && r && Object.defineProperty(target, key, r), r;
23
- };
24
- var __importStar = (this && this.__importStar) || function (mod) {
25
- if (mod && mod.__esModule) return mod;
26
- var result = {};
27
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
28
- __setModuleDefault(result, mod);
29
- return result;
30
- };
31
- var __importDefault = (this && this.__importDefault) || function (mod) {
32
- return (mod && mod.__esModule) ? mod : { "default": mod };
33
- };
34
- Object.defineProperty(exports, "__esModule", { value: true });
35
- exports.JsonFileSource = exports.JsFileSource = exports.BaseFileSource = void 0;
36
- const di_1 = require("@spinajs/di");
37
- const glob_1 = __importDefault(require("glob"));
38
- const lodash_1 = __importDefault(require("lodash"));
39
- const path_1 = require("path");
40
- const util_js_1 = require("./util.js");
41
- const fs = __importStar(require("fs"));
42
- const path = __importStar(require("path"));
43
- const internal_logger_1 = require("@spinajs/internal-logger");
44
- const configuration_common_1 = require("@spinajs/configuration-common");
45
- class BaseFileSource extends configuration_common_1.ConfigurationSource {
46
- get Order() {
47
- return 1;
48
- }
49
- constructor(RunApp, CustomConfigPaths, appBaseDir) {
50
- super();
51
- this.RunApp = RunApp;
52
- this.CustomConfigPaths = CustomConfigPaths;
53
- this.appBaseDir = appBaseDir;
54
- /**
55
- * Configuration base dir, where to look for app config
56
- */
57
- this.BaseDir = './';
58
- this.CommonDirs = [];
59
- this.BasePath = '';
60
- const isESMMode = di_1.DI.get('__esmMode__');
61
- this.CommonDirs = [
62
- // for tests, in src dir
63
- (0, path_1.normalize)((0, path_1.join)((0, path_1.resolve)(process.cwd()), 'src', '/config')),
64
- // other @spinajs modules paths
65
- (0, path_1.normalize)((0, path_1.join)((0, path_1.resolve)(process.cwd()), isESMMode ? 'node_modules/@spinajs/*/lib/mjs/config' : 'node_modules/@spinajs/*/lib/cjs/config')),
66
- // project paths - last to allow overwrite @spinajs conf
67
- (0, path_1.normalize)((0, path_1.join)((0, path_1.resolve)(process.cwd()), 'lib/config')),
68
- (0, path_1.normalize)((0, path_1.join)((0, path_1.resolve)(process.cwd()), 'dist/config')),
69
- (0, path_1.normalize)((0, path_1.join)((0, path_1.resolve)(process.cwd()), 'build/config')),
70
- (0, path_1.normalize)((0, path_1.join)((0, path_1.resolve)(process.cwd()), 'config')),
71
- ];
72
- // try to find root folder with node_modules
73
- // on server environment
74
- const bPath = (0, util_js_1.findBasePath)(process.cwd());
75
- // if we cannot find node_modules folders and base path
76
- // assume that process working dir is base path
77
- // eg. on electron environment
78
- this.BasePath = bPath === null ? process.cwd() : bPath;
79
- if (this.RunApp) {
80
- this.CommonDirs = this.CommonDirs.concat([(0, path_1.join)(this.appBaseDir, `/${this.RunApp}/config`)]);
81
- }
82
- if (this.CustomConfigPaths) {
83
- this.CommonDirs = this.CommonDirs.concat(this.CustomConfigPaths);
84
- }
85
- }
86
- async load(extension, callback) {
87
- const config = {};
88
- const toResolve = this.CommonDirs.map((f) => (path.isAbsolute(f) ? f : (0, path_1.join)(this.BasePath, f)))
89
- // get all config files
90
- .map((d) => {
91
- return glob_1.default.sync(path.join(d, `/**/${extension}`).replace(/\\/g, '/'));
92
- })
93
- // flatten files
94
- .reduce((prev, current) => {
95
- return prev.concat(lodash_1.default.flattenDeep(current));
96
- }, [])
97
- // normalize & resolve paths to be sure
98
- .map((f) => (0, path_1.normalize)((0, path_1.resolve)(f)))
99
- .filter((f, index, self) => self.indexOf(f) === index)
100
- .map(callback);
101
- const result = await Promise.all(toResolve);
102
- result
103
- .filter((v) => v !== undefined && v !== null)
104
- // load & merge configs
105
- .map((c) => lodash_1.default.mergeWith(config, c.default ?? c, util_js_1.mergeArrays));
106
- return config;
107
- }
108
- }
109
- exports.BaseFileSource = BaseFileSource;
110
- let JsFileSource = class JsFileSource extends BaseFileSource {
111
- async Load(config) {
112
- const common = await this.load('!(*.dev|*.prod).{cjs,js}', _load);
113
- const env = config.get('process.env.APP_ENV', 'production');
114
- const fExt = env === 'development' ? '*.dev.{cjs,js}' : '*.prod.{cjs,js}';
115
- const cfg = await this.load(fExt, _load);
116
- return lodash_1.default.mergeWith(common, cfg, util_js_1.mergeArrays);
117
- async function _load(file) {
118
- try {
119
- internal_logger_1.InternalLogger.trace(`Trying to load file ${file}`, 'Configuration');
120
- return await di_1.DI.__spinajs_require__(file);
121
- }
122
- catch (err) {
123
- internal_logger_1.InternalLogger.error(err, `error loading configuration file ${file}`, 'configuration');
124
- return null;
125
- }
126
- }
127
- }
128
- };
129
- JsFileSource = __decorate([
130
- (0, di_1.Injectable)(configuration_common_1.ConfigurationSource)
131
- ], JsFileSource);
132
- exports.JsFileSource = JsFileSource;
133
- let JsonFileSource = class JsonFileSource extends BaseFileSource {
134
- async Load(config) {
135
- const common = await this.load('!(*.dev|*.prod).json', _load);
136
- const env = config.get('process.env.APP_ENV', 'production');
137
- const fExt = env === 'development' ? '*.dev.json' : '*.prod.json';
138
- const cfg = await this.load(fExt, _load);
139
- return lodash_1.default.mergeWith(common, cfg, util_js_1.mergeArrays);
140
- function _load(file) {
141
- try {
142
- internal_logger_1.InternalLogger.trace(`Trying to load file ${file}`, 'Configuration');
143
- return Promise.resolve(JSON.parse(fs.readFileSync(file, 'utf-8')));
144
- }
145
- catch (err) {
146
- console.error(`error loading configuration file ${file}, reasoun: ${err.message}`);
147
- return null;
148
- }
149
- }
150
- }
151
- };
152
- JsonFileSource = __decorate([
153
- (0, di_1.Injectable)(configuration_common_1.ConfigurationSource)
154
- ], JsonFileSource);
155
- exports.JsonFileSource = JsonFileSource;
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || function (mod) {
25
+ if (mod && mod.__esModule) return mod;
26
+ var result = {};
27
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
28
+ __setModuleDefault(result, mod);
29
+ return result;
30
+ };
31
+ var __importDefault = (this && this.__importDefault) || function (mod) {
32
+ return (mod && mod.__esModule) ? mod : { "default": mod };
33
+ };
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ exports.JsonFileSource = exports.JsFileSource = exports.BaseFileSource = void 0;
36
+ const di_1 = require("@spinajs/di");
37
+ const glob_1 = __importDefault(require("glob"));
38
+ const lodash_1 = __importDefault(require("lodash"));
39
+ const path_1 = require("path");
40
+ const util_js_1 = require("./util.js");
41
+ const fs = __importStar(require("fs"));
42
+ const path = __importStar(require("path"));
43
+ const internal_logger_1 = require("@spinajs/internal-logger");
44
+ const configuration_common_1 = require("@spinajs/configuration-common");
45
+ class BaseFileSource extends configuration_common_1.ConfigurationSource {
46
+ get Order() {
47
+ return 1;
48
+ }
49
+ constructor(RunApp, CustomConfigPaths, appBaseDir) {
50
+ super();
51
+ this.RunApp = RunApp;
52
+ this.CustomConfigPaths = CustomConfigPaths;
53
+ this.appBaseDir = appBaseDir;
54
+ /**
55
+ * Configuration base dir, where to look for app config
56
+ */
57
+ this.BaseDir = './';
58
+ this.CommonDirs = [];
59
+ this.BasePath = '';
60
+ const isESMMode = di_1.DI.get('__esmMode__');
61
+ this.CommonDirs = [
62
+ // for tests, in src dir
63
+ (0, path_1.normalize)((0, path_1.join)((0, path_1.resolve)(process.cwd()), 'src', '/config')),
64
+ // other @spinajs modules paths
65
+ (0, path_1.normalize)((0, path_1.join)((0, path_1.resolve)(process.cwd()), isESMMode ? 'node_modules/@spinajs/*/lib/mjs/config' : 'node_modules/@spinajs/*/lib/cjs/config')),
66
+ // project paths - last to allow overwrite @spinajs conf
67
+ (0, path_1.normalize)((0, path_1.join)((0, path_1.resolve)(process.cwd()), 'lib/config')),
68
+ (0, path_1.normalize)((0, path_1.join)((0, path_1.resolve)(process.cwd()), 'dist/config')),
69
+ (0, path_1.normalize)((0, path_1.join)((0, path_1.resolve)(process.cwd()), 'build/config')),
70
+ (0, path_1.normalize)((0, path_1.join)((0, path_1.resolve)(process.cwd()), 'config')),
71
+ ];
72
+ // try to find root folder with node_modules
73
+ // on server environment
74
+ const bPath = (0, util_js_1.findBasePath)(process.cwd());
75
+ // if we cannot find node_modules folders and base path
76
+ // assume that process working dir is base path
77
+ // eg. on electron environment
78
+ this.BasePath = bPath === null ? process.cwd() : bPath;
79
+ if (this.RunApp) {
80
+ this.CommonDirs = this.CommonDirs.concat([(0, path_1.join)(this.appBaseDir, `/${this.RunApp}/config`)]);
81
+ }
82
+ if (this.CustomConfigPaths) {
83
+ this.CommonDirs = this.CommonDirs.concat(this.CustomConfigPaths);
84
+ }
85
+ }
86
+ async load(extension, callback) {
87
+ const config = {};
88
+ const toResolve = this.CommonDirs.map((f) => (path.isAbsolute(f) ? f : (0, path_1.join)(this.BasePath, f)))
89
+ // get all config files
90
+ .map((d) => {
91
+ return glob_1.default.sync(path.join(d, `/**/${extension}`).replace(/\\/g, '/'));
92
+ })
93
+ // flatten files
94
+ .reduce((prev, current) => {
95
+ return prev.concat(lodash_1.default.flattenDeep(current));
96
+ }, [])
97
+ // normalize & resolve paths to be sure
98
+ .map((f) => (0, path_1.normalize)((0, path_1.resolve)(f)))
99
+ .filter((f, index, self) => self.indexOf(f) === index)
100
+ .map(callback);
101
+ const result = await Promise.all(toResolve);
102
+ result
103
+ .filter((v) => v !== undefined && v !== null)
104
+ // load & merge configs
105
+ .map((c) => lodash_1.default.mergeWith(config, c.default ?? c, util_js_1.mergeArrays));
106
+ return config;
107
+ }
108
+ }
109
+ exports.BaseFileSource = BaseFileSource;
110
+ let JsFileSource = class JsFileSource extends BaseFileSource {
111
+ async Load(config) {
112
+ const common = await this.load('!(*.dev|*.prod).{cjs,js}', _load);
113
+ const env = config.get('process.env.APP_ENV', 'production');
114
+ const fExt = env === 'development' ? '*.dev.{cjs,js}' : '*.prod.{cjs,js}';
115
+ const cfg = await this.load(fExt, _load);
116
+ return lodash_1.default.mergeWith(common, cfg, util_js_1.mergeArrays);
117
+ async function _load(file) {
118
+ try {
119
+ internal_logger_1.InternalLogger.trace(`Trying to load file ${file}`, 'Configuration');
120
+ return await di_1.DI.__spinajs_require__(file);
121
+ }
122
+ catch (err) {
123
+ internal_logger_1.InternalLogger.error(err, `error loading configuration file ${file}`, 'configuration');
124
+ return null;
125
+ }
126
+ }
127
+ }
128
+ };
129
+ exports.JsFileSource = JsFileSource;
130
+ exports.JsFileSource = JsFileSource = __decorate([
131
+ (0, di_1.Injectable)(configuration_common_1.ConfigurationSource)
132
+ ], JsFileSource);
133
+ let JsonFileSource = class JsonFileSource extends BaseFileSource {
134
+ async Load(config) {
135
+ const common = await this.load('!(*.dev|*.prod).json', _load);
136
+ const env = config.get('process.env.APP_ENV', 'production');
137
+ const fExt = env === 'development' ? '*.dev.json' : '*.prod.json';
138
+ const cfg = await this.load(fExt, _load);
139
+ return lodash_1.default.mergeWith(common, cfg, util_js_1.mergeArrays);
140
+ function _load(file) {
141
+ try {
142
+ internal_logger_1.InternalLogger.trace(`Trying to load file ${file}`, 'Configuration');
143
+ return Promise.resolve(JSON.parse(fs.readFileSync(file, 'utf-8')));
144
+ }
145
+ catch (err) {
146
+ console.error(`error loading configuration file ${file}, reasoun: ${err.message}`);
147
+ return null;
148
+ }
149
+ }
150
+ }
151
+ };
152
+ exports.JsonFileSource = JsonFileSource;
153
+ exports.JsonFileSource = JsonFileSource = __decorate([
154
+ (0, di_1.Injectable)(configuration_common_1.ConfigurationSource)
155
+ ], JsonFileSource);
156
156
  //# sourceMappingURL=sources.js.map