@scaleway/configuration-loader 0.0.2-alpha.0

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.
package/.npmignore ADDED
@@ -0,0 +1,6 @@
1
+ **/__tests__/**
2
+ examples/
3
+ src
4
+ .eslintrc.cjs
5
+ !.npmignore
6
+ CHANGELOG.md
package/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ https://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2019 Scaleway.
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ https://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,62 @@
1
+ import { env } from 'process';
2
+ import { EnvironmentKey } from './env.js';
3
+ import { resolveConfigurationFilePath } from './path-resolver.js';
4
+ import { loadConfigurationFromFile } from './yml-loader.js';
5
+
6
+ /**
7
+ * Loads profile from environment values.
8
+ *
9
+ * @returns The profile filled with values found in the environment
10
+ *
11
+ * @public
12
+ */
13
+
14
+ const loadProfileFromEnvironmentValues = () => ({
15
+ accessKey: env[EnvironmentKey.ScwAccessKey],
16
+ apiURL: env[EnvironmentKey.ScwAPIURL],
17
+ defaultOrganizationId: env[EnvironmentKey.ScwDefaultOrganizationId],
18
+ defaultProjectId: env[EnvironmentKey.ScwDefaultProjectId],
19
+ defaultRegion: env[EnvironmentKey.ScwDefaultRegion],
20
+ defaultZone: env[EnvironmentKey.ScwDefaultZone],
21
+ secretKey: env[EnvironmentKey.ScwSecretKey]
22
+ });
23
+ /**
24
+ * Loads profile from configuration file.
25
+ *
26
+ * @param params - The parameters to load the profile
27
+ * @returns The profile filled with values found in the configuration profile
28
+ *
29
+ * @throws Error
30
+ * Thrown if the configuration file couldn't be found,
31
+ * or if the specified profile can't be found.
32
+ *
33
+ * @public
34
+ */
35
+
36
+ const loadProfileFromConfigurationFile = params => {
37
+ const filePath = (params == null ? void 0 : params.filepath) ?? resolveConfigurationFilePath();
38
+
39
+ if (typeof filePath !== 'string' || filePath.length === 0) {
40
+ throw new Error('Could not find the path to the configuration file.');
41
+ }
42
+
43
+ const configs = loadConfigurationFromFile(filePath);
44
+ const profileName = (params == null ? void 0 : params.profileName) ?? 'default';
45
+ const profileMap = configs[profileName];
46
+
47
+ if (typeof profileMap !== 'object') {
48
+ throw new Error(`Could not find the desired profile '${profileName}' in the configuration file.`);
49
+ }
50
+
51
+ return {
52
+ accessKey: profileMap.access_key,
53
+ apiURL: profileMap.api_url,
54
+ defaultOrganizationId: profileMap.default_organization_id,
55
+ defaultProjectId: profileMap.default_project_id,
56
+ defaultRegion: profileMap.default_region,
57
+ defaultZone: profileMap.default_zone,
58
+ secretKey: profileMap.secret_key
59
+ };
60
+ };
61
+
62
+ export { loadProfileFromConfigurationFile, loadProfileFromEnvironmentValues };
package/dist/env.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Environment Key.
3
+ */
4
+ let EnvironmentKey;
5
+
6
+ (function (EnvironmentKey) {
7
+ EnvironmentKey["ScwConfigPath"] = "SCW_CONFIG_PATH";
8
+ EnvironmentKey["ScwAccessKey"] = "SCW_ACCESS_KEY";
9
+ EnvironmentKey["ScwSecretKey"] = "SCW_SECRET_KEY";
10
+ EnvironmentKey["ScwAPIURL"] = "SCW_API_URL";
11
+ EnvironmentKey["ScwDefaultOrganizationId"] = "SCW_DEFAULT_ORGANIZATION_ID";
12
+ EnvironmentKey["ScwDefaultProjectId"] = "SCW_DEFAULT_PROJECT_ID";
13
+ EnvironmentKey["ScwDefaultRegion"] = "SCW_DEFAULT_REGION";
14
+ EnvironmentKey["ScwDefaultZone"] = "SCW_DEFAULT_ZONE";
15
+ })(EnvironmentKey || (EnvironmentKey = {}));
16
+
17
+ export { EnvironmentKey };
package/dist/index.cjs ADDED
@@ -0,0 +1,200 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var process = require('process');
6
+ var os = require('os');
7
+ var path = require('path');
8
+ var fs = require('fs');
9
+
10
+ function _interopNamespace(e) {
11
+ if (e && e.__esModule) return e;
12
+ var n = Object.create(null);
13
+ if (e) {
14
+ Object.keys(e).forEach(function (k) {
15
+ if (k !== 'default') {
16
+ var d = Object.getOwnPropertyDescriptor(e, k);
17
+ Object.defineProperty(n, k, d.get ? d : {
18
+ enumerable: true,
19
+ get: function () { return e[k]; }
20
+ });
21
+ }
22
+ });
23
+ }
24
+ n["default"] = e;
25
+ return Object.freeze(n);
26
+ }
27
+
28
+ var path__namespace = /*#__PURE__*/_interopNamespace(path);
29
+
30
+ /**
31
+ * Environment Key.
32
+ */
33
+ let EnvironmentKey;
34
+
35
+ (function (EnvironmentKey) {
36
+ EnvironmentKey["ScwConfigPath"] = "SCW_CONFIG_PATH";
37
+ EnvironmentKey["ScwAccessKey"] = "SCW_ACCESS_KEY";
38
+ EnvironmentKey["ScwSecretKey"] = "SCW_SECRET_KEY";
39
+ EnvironmentKey["ScwAPIURL"] = "SCW_API_URL";
40
+ EnvironmentKey["ScwDefaultOrganizationId"] = "SCW_DEFAULT_ORGANIZATION_ID";
41
+ EnvironmentKey["ScwDefaultProjectId"] = "SCW_DEFAULT_PROJECT_ID";
42
+ EnvironmentKey["ScwDefaultRegion"] = "SCW_DEFAULT_REGION";
43
+ EnvironmentKey["ScwDefaultZone"] = "SCW_DEFAULT_ZONE";
44
+ })(EnvironmentKey || (EnvironmentKey = {}));
45
+
46
+ /**
47
+ * Gets the Scaleway directory.
48
+ *
49
+ * @returns The path to the Scaleway diretory
50
+ *
51
+ * @internal
52
+ */
53
+
54
+ const getScwConfigurationDirectory = () => {
55
+ const xdgConfigPath = process.env.XDG_CONFIG_HOME;
56
+ if (typeof xdgConfigPath === 'string' && xdgConfigPath.length > 0) return path__namespace.join(xdgConfigPath, 'scw');
57
+ return path__namespace.join(os.homedir(), '.config', 'scw');
58
+ };
59
+ /**
60
+ * Gets the configuration file path.
61
+ *
62
+ * @returns The path to the configuration file
63
+ *
64
+ * @internal
65
+ */
66
+
67
+ const resolveConfigurationFilePath = () => {
68
+ // Try path defined by user in env variables
69
+ const envFilePath = process.env[EnvironmentKey.ScwConfigPath];
70
+ if (typeof envFilePath === 'string' && envFilePath.length > 0) return envFilePath; // or fallback on the default path
71
+
72
+ return path__namespace.join(getScwConfigurationDirectory(), 'config.yaml');
73
+ };
74
+
75
+ const STRIP_COMMENT_REGEX = /(^|\s)[;#]/;
76
+ const DETECT_SECTION_REGEX = /^\s*([^]+):\s*$/;
77
+ const DETECT_ITEM_REGEX = /^\s*(.+?)\s*:\s*(.+?)\s*$/;
78
+ /**
79
+ * Converts Yaml to configuration map.
80
+ *
81
+ * @param input - Yaml string
82
+ * @returns The configuration map
83
+ *
84
+ * @internal
85
+ */
86
+
87
+ const convertYamlToConfiguration = input => {
88
+ let foundProfilesKey = false;
89
+ let currentSection = 'default';
90
+ const map = {};
91
+
92
+ if (typeof input !== 'string') {
93
+ return map;
94
+ }
95
+
96
+ input.split(/\r?\n/).forEach(rawLine => {
97
+ // remove comments
98
+ const line = rawLine.split(STRIP_COMMENT_REGEX)[0]; // parse sections
99
+
100
+ const newSection = DETECT_SECTION_REGEX.exec(line);
101
+
102
+ if (newSection) {
103
+ currentSection = undefined;
104
+
105
+ if (newSection[1] === 'profiles') {
106
+ foundProfilesKey = true;
107
+ } else if (foundProfilesKey === true) {
108
+ [, currentSection] = newSection;
109
+ }
110
+ } // parse items
111
+ else if (currentSection) {
112
+ const item = DETECT_ITEM_REGEX.exec(line);
113
+
114
+ if (item) {
115
+ if (typeof map[currentSection] !== 'object') {
116
+ map[currentSection] = {};
117
+ }
118
+ [,, map[currentSection][item[1]]] = item;
119
+ }
120
+ }
121
+ });
122
+ return map;
123
+ };
124
+ /**
125
+ * Loads configuration from a file.
126
+ *
127
+ * @param filePath - Path to the configuration file
128
+ * @returns The configuration
129
+ *
130
+ * @throws Error
131
+ * Thrown if the file doesn't exist.
132
+ *
133
+ * @internal
134
+ */
135
+
136
+ const loadConfigurationFromFile = filePath => {
137
+ // `readFileSync` returns a string when encoding option is specified.
138
+ // {@link https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options}
139
+ const fileContent = fs.readFileSync(filePath, 'utf-8');
140
+ return convertYamlToConfiguration(fileContent);
141
+ };
142
+
143
+ /**
144
+ * Loads profile from environment values.
145
+ *
146
+ * @returns The profile filled with values found in the environment
147
+ *
148
+ * @public
149
+ */
150
+
151
+ const loadProfileFromEnvironmentValues = () => ({
152
+ accessKey: process.env[EnvironmentKey.ScwAccessKey],
153
+ apiURL: process.env[EnvironmentKey.ScwAPIURL],
154
+ defaultOrganizationId: process.env[EnvironmentKey.ScwDefaultOrganizationId],
155
+ defaultProjectId: process.env[EnvironmentKey.ScwDefaultProjectId],
156
+ defaultRegion: process.env[EnvironmentKey.ScwDefaultRegion],
157
+ defaultZone: process.env[EnvironmentKey.ScwDefaultZone],
158
+ secretKey: process.env[EnvironmentKey.ScwSecretKey]
159
+ });
160
+ /**
161
+ * Loads profile from configuration file.
162
+ *
163
+ * @param params - The parameters to load the profile
164
+ * @returns The profile filled with values found in the configuration profile
165
+ *
166
+ * @throws Error
167
+ * Thrown if the configuration file couldn't be found,
168
+ * or if the specified profile can't be found.
169
+ *
170
+ * @public
171
+ */
172
+
173
+ const loadProfileFromConfigurationFile = params => {
174
+ const filePath = (params == null ? void 0 : params.filepath) ?? resolveConfigurationFilePath();
175
+
176
+ if (typeof filePath !== 'string' || filePath.length === 0) {
177
+ throw new Error('Could not find the path to the configuration file.');
178
+ }
179
+
180
+ const configs = loadConfigurationFromFile(filePath);
181
+ const profileName = (params == null ? void 0 : params.profileName) ?? 'default';
182
+ const profileMap = configs[profileName];
183
+
184
+ if (typeof profileMap !== 'object') {
185
+ throw new Error(`Could not find the desired profile '${profileName}' in the configuration file.`);
186
+ }
187
+
188
+ return {
189
+ accessKey: profileMap.access_key,
190
+ apiURL: profileMap.api_url,
191
+ defaultOrganizationId: profileMap.default_organization_id,
192
+ defaultProjectId: profileMap.default_project_id,
193
+ defaultRegion: profileMap.default_region,
194
+ defaultZone: profileMap.default_zone,
195
+ secretKey: profileMap.secret_key
196
+ };
197
+ };
198
+
199
+ exports.loadProfileFromConfigurationFile = loadProfileFromConfigurationFile;
200
+ exports.loadProfileFromEnvironmentValues = loadProfileFromEnvironmentValues;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Profile contains information to help instanciating the Scaleway client.
3
+ *
4
+ * @public
5
+ */
6
+ declare type Profile = {
7
+ /**
8
+ * You need an access key and a secret key to connect to Scaleway API.
9
+ * Generate your token at the following address: {@link https://console.scaleway.com/project/credentials}
10
+ */
11
+ accessKey?: string;
12
+ /**
13
+ * APIURL overrides the API URL of the Scaleway API to the given URL.
14
+ * Change that if you want to direct requests to a different endpoint.
15
+ *
16
+ * @defaultValue `https://api.scaleway.com`
17
+ */
18
+ apiURL?: string;
19
+ /**
20
+ * Your organization ID is the identifier of your account inside Scaleway infrastructure.
21
+ */
22
+ defaultOrganizationId?: string;
23
+ /**
24
+ * Your project ID is the identifier of the project your resources are attached to.
25
+ */
26
+ defaultProjectId?: string;
27
+ /**
28
+ * A region is represented as a geographical area such as France (Paris) or the Netherlands (Amsterdam).
29
+ * It can contain multiple availability zones.
30
+ *
31
+ * Examples: fr-par, nl-ams.
32
+ */
33
+ defaultRegion?: string;
34
+ /**
35
+ * A region can be split into many availability zones (AZ).
36
+ * Latency between multiple AZ of the same region are low as they have a common network layer.
37
+ *
38
+ * Examples: fr-par-1, nl-ams-1
39
+ */
40
+ defaultZone?: string;
41
+ /**
42
+ * The secret key is the value that can be used to authenticate against the API (the value used in X-Auth-Token HTTP-header).
43
+ * The secret key MUST remain secret and not given to anyone or published online.
44
+ */
45
+ secretKey?: string;
46
+ };
47
+ /** Parameters to load the profile from the configuration file */
48
+ declare type ProfileFromFileParams = {
49
+ /**
50
+ * The path at which to locate the configuration file.
51
+ *
52
+ * Defaults to the value of the `SCW_CONFIG_PATH` environment variable
53
+ * or `~/.scw/config` otherwise.
54
+ */
55
+ filepath?: string;
56
+ /**
57
+ * Name of the profile to load.
58
+ *
59
+ * @defaultValue `default`
60
+ * */
61
+ profileName?: 'default' | string;
62
+ };
63
+
64
+ /**
65
+ * Loads profile from environment values.
66
+ *
67
+ * @returns The profile filled with values found in the environment
68
+ *
69
+ * @public
70
+ */
71
+ declare const loadProfileFromEnvironmentValues: () => Profile;
72
+ /**
73
+ * Loads profile from configuration file.
74
+ *
75
+ * @param params - The parameters to load the profile
76
+ * @returns The profile filled with values found in the configuration profile
77
+ *
78
+ * @throws Error
79
+ * Thrown if the configuration file couldn't be found,
80
+ * or if the specified profile can't be found.
81
+ *
82
+ * @public
83
+ */
84
+ declare const loadProfileFromConfigurationFile: (params?: Readonly<ProfileFromFileParams> | undefined) => Profile;
85
+
86
+ export { ProfileFromFileParams, loadProfileFromConfigurationFile, loadProfileFromEnvironmentValues };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { loadProfileFromConfigurationFile, loadProfileFromEnvironmentValues } from './config-loader.js';
@@ -0,0 +1,35 @@
1
+ import { homedir } from 'os';
2
+ import * as path from 'path';
3
+ import { env } from 'process';
4
+ import { EnvironmentKey } from './env.js';
5
+
6
+ /**
7
+ * Gets the Scaleway directory.
8
+ *
9
+ * @returns The path to the Scaleway diretory
10
+ *
11
+ * @internal
12
+ */
13
+
14
+ const getScwConfigurationDirectory = () => {
15
+ const xdgConfigPath = env.XDG_CONFIG_HOME;
16
+ if (typeof xdgConfigPath === 'string' && xdgConfigPath.length > 0) return path.join(xdgConfigPath, 'scw');
17
+ return path.join(homedir(), '.config', 'scw');
18
+ };
19
+ /**
20
+ * Gets the configuration file path.
21
+ *
22
+ * @returns The path to the configuration file
23
+ *
24
+ * @internal
25
+ */
26
+
27
+ const resolveConfigurationFilePath = () => {
28
+ // Try path defined by user in env variables
29
+ const envFilePath = env[EnvironmentKey.ScwConfigPath];
30
+ if (typeof envFilePath === 'string' && envFilePath.length > 0) return envFilePath; // or fallback on the default path
31
+
32
+ return path.join(getScwConfigurationDirectory(), 'config.yaml');
33
+ };
34
+
35
+ export { getScwConfigurationDirectory, resolveConfigurationFilePath };
@@ -0,0 +1,71 @@
1
+ import { readFileSync } from 'fs';
2
+
3
+ const STRIP_COMMENT_REGEX = /(^|\s)[;#]/;
4
+ const DETECT_SECTION_REGEX = /^\s*([^]+):\s*$/;
5
+ const DETECT_ITEM_REGEX = /^\s*(.+?)\s*:\s*(.+?)\s*$/;
6
+ /**
7
+ * Converts Yaml to configuration map.
8
+ *
9
+ * @param input - Yaml string
10
+ * @returns The configuration map
11
+ *
12
+ * @internal
13
+ */
14
+
15
+ const convertYamlToConfiguration = input => {
16
+ let foundProfilesKey = false;
17
+ let currentSection = 'default';
18
+ const map = {};
19
+
20
+ if (typeof input !== 'string') {
21
+ return map;
22
+ }
23
+
24
+ input.split(/\r?\n/).forEach(rawLine => {
25
+ // remove comments
26
+ const line = rawLine.split(STRIP_COMMENT_REGEX)[0]; // parse sections
27
+
28
+ const newSection = DETECT_SECTION_REGEX.exec(line);
29
+
30
+ if (newSection) {
31
+ currentSection = undefined;
32
+
33
+ if (newSection[1] === 'profiles') {
34
+ foundProfilesKey = true;
35
+ } else if (foundProfilesKey === true) {
36
+ [, currentSection] = newSection;
37
+ }
38
+ } // parse items
39
+ else if (currentSection) {
40
+ const item = DETECT_ITEM_REGEX.exec(line);
41
+
42
+ if (item) {
43
+ if (typeof map[currentSection] !== 'object') {
44
+ map[currentSection] = {};
45
+ }
46
+ [,, map[currentSection][item[1]]] = item;
47
+ }
48
+ }
49
+ });
50
+ return map;
51
+ };
52
+ /**
53
+ * Loads configuration from a file.
54
+ *
55
+ * @param filePath - Path to the configuration file
56
+ * @returns The configuration
57
+ *
58
+ * @throws Error
59
+ * Thrown if the file doesn't exist.
60
+ *
61
+ * @internal
62
+ */
63
+
64
+ const loadConfigurationFromFile = filePath => {
65
+ // `readFileSync` returns a string when encoding option is specified.
66
+ // {@link https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options}
67
+ const fileContent = readFileSync(filePath, 'utf-8');
68
+ return convertYamlToConfiguration(fileContent);
69
+ };
70
+
71
+ export { convertYamlToConfiguration, loadConfigurationFromFile };
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@scaleway/configuration-loader",
3
+ "version": "0.0.2-alpha.0",
4
+ "license": "Apache-2.0",
5
+ "description": "Load configuration via file or environment for NodeJS.",
6
+ "main": "dist/index.cjs",
7
+ "module": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "publishConfig": {
10
+ "access": "public"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "directory": "packages/configuration-loader"
15
+ },
16
+ "engines": {
17
+ "node": ">=14.x"
18
+ },
19
+ "type": "module",
20
+ "gitHead": "348ef780f8af12baa19e8c5b3c02f3087bcf0964"
21
+ }