@catbee/utils 0.0.4 → 0.0.6
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/LICENSE +21 -201
- package/README.md +911 -242
- package/build/esm/config.d.ts +108 -8
- package/build/esm/config.js +122 -6
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +6 -0
- package/build/esm/index.js +29 -0
- package/build/esm/index.js.map +1 -1
- package/build/esm/servers/server.builder.d.ts +625 -0
- package/build/esm/servers/server.builder.js +722 -0
- package/build/esm/servers/server.builder.js.map +1 -0
- package/build/esm/servers/server.d.ts +256 -0
- package/build/esm/servers/server.js +1211 -0
- package/build/esm/servers/server.js.map +1 -0
- package/build/esm/types/api-response.d.ts +5 -7
- package/build/esm/types/api-response.js +23 -0
- package/build/esm/types/api-response.js.map +1 -1
- package/build/esm/types/index.d.ts +125 -0
- package/build/esm/types/index.js +25 -0
- package/build/esm/types/index.js.map +1 -0
- package/build/esm/types/server.d.ts +285 -0
- package/build/esm/types/server.js +25 -0
- package/build/esm/types/server.js.map +1 -0
- package/build/esm/utils/array.utils.js +23 -0
- package/build/esm/utils/array.utils.js.map +1 -1
- package/build/esm/utils/async.utils.js +23 -0
- package/build/esm/utils/async.utils.js.map +1 -1
- package/build/esm/utils/cache.utils.js +39 -16
- package/build/esm/utils/cache.utils.js.map +1 -1
- package/build/esm/utils/context-store.utils.d.ts +1 -1
- package/build/esm/utils/context-store.utils.js +24 -1
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.js +26 -2
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/decorators.utils.d.ts +291 -0
- package/build/esm/utils/decorators.utils.js +395 -41
- package/build/esm/utils/decorators.utils.js.map +1 -1
- package/build/esm/utils/dir.utils.js +23 -0
- package/build/esm/utils/dir.utils.js.map +1 -1
- package/build/esm/utils/env.utils.d.ts +186 -23
- package/build/esm/utils/env.utils.js +517 -91
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/exception.utils.js +31 -8
- package/build/esm/utils/exception.utils.js.map +1 -1
- package/build/esm/utils/fs.utils.js +23 -0
- package/build/esm/utils/fs.utils.js.map +1 -1
- package/build/esm/utils/http-status-codes.js +23 -0
- package/build/esm/utils/http-status-codes.js.map +1 -1
- package/build/esm/utils/id.utils.js +23 -0
- package/build/esm/utils/id.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +118 -0
- package/build/esm/utils/logger.utils.js +251 -15
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +29 -7
- package/build/esm/utils/middleware.utils.js +81 -55
- package/build/esm/utils/middleware.utils.js.map +1 -1
- package/build/esm/utils/obj.utils.d.ts +10 -3
- package/build/esm/utils/obj.utils.js +225 -15
- package/build/esm/utils/obj.utils.js.map +1 -1
- package/build/esm/utils/request.utils.d.ts +77 -0
- package/build/esm/utils/request.utils.js +196 -0
- package/build/esm/utils/request.utils.js.map +1 -0
- package/build/esm/utils/response.utils.d.ts +15 -1
- package/build/esm/utils/response.utils.js +55 -4
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esm/utils/string.utils.js +23 -0
- package/build/esm/utils/string.utils.js.map +1 -1
- package/build/esm/utils/url.utils.js +23 -0
- package/build/esm/utils/url.utils.js.map +1 -1
- package/build/esm/utils/validate.utils.d.ts +7 -0
- package/build/esm/utils/validate.utils.js +35 -2
- package/build/esm/utils/validate.utils.js.map +1 -1
- package/build/esnext/config.d.ts +108 -8
- package/build/esnext/config.js +122 -6
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +6 -0
- package/build/esnext/index.js +29 -0
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/servers/server.builder.d.ts +625 -0
- package/build/esnext/servers/server.builder.js +677 -0
- package/build/esnext/servers/server.builder.js.map +1 -0
- package/build/esnext/servers/server.d.ts +256 -0
- package/build/esnext/servers/server.js +918 -0
- package/build/esnext/servers/server.js.map +1 -0
- package/build/esnext/types/api-response.d.ts +5 -7
- package/build/esnext/types/api-response.js +23 -0
- package/build/esnext/types/api-response.js.map +1 -1
- package/build/esnext/types/index.d.ts +125 -0
- package/build/esnext/types/index.js +25 -0
- package/build/esnext/types/index.js.map +1 -0
- package/build/esnext/types/server.d.ts +285 -0
- package/build/esnext/types/server.js +25 -0
- package/build/esnext/types/server.js.map +1 -0
- package/build/esnext/utils/array.utils.js +23 -0
- package/build/esnext/utils/array.utils.js.map +1 -1
- package/build/esnext/utils/async.utils.js +23 -0
- package/build/esnext/utils/async.utils.js.map +1 -1
- package/build/esnext/utils/cache.utils.js +39 -16
- package/build/esnext/utils/cache.utils.js.map +1 -1
- package/build/esnext/utils/context-store.utils.d.ts +1 -1
- package/build/esnext/utils/context-store.utils.js +24 -1
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.js +26 -2
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/decorators.utils.d.ts +291 -0
- package/build/esnext/utils/decorators.utils.js +371 -22
- package/build/esnext/utils/decorators.utils.js.map +1 -1
- package/build/esnext/utils/dir.utils.js +23 -0
- package/build/esnext/utils/dir.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.d.ts +186 -23
- package/build/esnext/utils/env.utils.js +468 -77
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/exception.utils.js +30 -7
- package/build/esnext/utils/exception.utils.js.map +1 -1
- package/build/esnext/utils/fs.utils.js +23 -0
- package/build/esnext/utils/fs.utils.js.map +1 -1
- package/build/esnext/utils/http-status-codes.js +23 -0
- package/build/esnext/utils/http-status-codes.js.map +1 -1
- package/build/esnext/utils/id.utils.js +23 -0
- package/build/esnext/utils/id.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +118 -0
- package/build/esnext/utils/logger.utils.js +222 -15
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +29 -7
- package/build/esnext/utils/middleware.utils.js +77 -55
- package/build/esnext/utils/middleware.utils.js.map +1 -1
- package/build/esnext/utils/obj.utils.d.ts +10 -3
- package/build/esnext/utils/obj.utils.js +176 -12
- package/build/esnext/utils/obj.utils.js.map +1 -1
- package/build/esnext/utils/request.utils.d.ts +77 -0
- package/build/esnext/utils/request.utils.js +168 -0
- package/build/esnext/utils/request.utils.js.map +1 -0
- package/build/esnext/utils/response.utils.d.ts +15 -1
- package/build/esnext/utils/response.utils.js +55 -4
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/esnext/utils/string.utils.js +23 -0
- package/build/esnext/utils/string.utils.js.map +1 -1
- package/build/esnext/utils/url.utils.js +23 -0
- package/build/esnext/utils/url.utils.js.map +1 -1
- package/build/esnext/utils/validate.utils.d.ts +7 -0
- package/build/esnext/utils/validate.utils.js +33 -0
- package/build/esnext/utils/validate.utils.js.map +1 -1
- package/build/src/config.d.ts +108 -8
- package/build/src/config.js +125 -7
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +6 -0
- package/build/src/index.js +32 -0
- package/build/src/index.js.map +1 -1
- package/build/src/servers/server.builder.d.ts +625 -0
- package/build/src/servers/server.builder.js +681 -0
- package/build/src/servers/server.builder.js.map +1 -0
- package/build/src/servers/server.d.ts +256 -0
- package/build/src/servers/server.js +958 -0
- package/build/src/servers/server.js.map +1 -0
- package/build/src/types/api-response.d.ts +5 -7
- package/build/src/types/api-response.js +23 -0
- package/build/src/types/api-response.js.map +1 -1
- package/build/src/types/index.d.ts +125 -0
- package/build/src/types/index.js +26 -0
- package/build/src/types/index.js.map +1 -0
- package/build/src/types/server.d.ts +285 -0
- package/build/src/types/server.js +26 -0
- package/build/src/types/server.js.map +1 -0
- package/build/src/utils/array.utils.js +23 -0
- package/build/src/utils/array.utils.js.map +1 -1
- package/build/src/utils/async.utils.js +23 -0
- package/build/src/utils/async.utils.js.map +1 -1
- package/build/src/utils/cache.utils.js +38 -15
- package/build/src/utils/cache.utils.js.map +1 -1
- package/build/src/utils/context-store.utils.d.ts +1 -1
- package/build/src/utils/context-store.utils.js +24 -1
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.js +25 -1
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/decorators.utils.d.ts +291 -0
- package/build/src/utils/decorators.utils.js +373 -22
- package/build/src/utils/decorators.utils.js.map +1 -1
- package/build/src/utils/dir.utils.js +23 -0
- package/build/src/utils/dir.utils.js.map +1 -1
- package/build/src/utils/env.utils.d.ts +186 -23
- package/build/src/utils/env.utils.js +467 -76
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/exception.utils.js +30 -7
- package/build/src/utils/exception.utils.js.map +1 -1
- package/build/src/utils/fs.utils.js +23 -0
- package/build/src/utils/fs.utils.js.map +1 -1
- package/build/src/utils/http-status-codes.js +23 -0
- package/build/src/utils/http-status-codes.js.map +1 -1
- package/build/src/utils/id.utils.js +23 -0
- package/build/src/utils/id.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +118 -0
- package/build/src/utils/logger.utils.js +228 -15
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +29 -7
- package/build/src/utils/middleware.utils.js +76 -54
- package/build/src/utils/middleware.utils.js.map +1 -1
- package/build/src/utils/obj.utils.d.ts +10 -3
- package/build/src/utils/obj.utils.js +177 -12
- package/build/src/utils/obj.utils.js.map +1 -1
- package/build/src/utils/request.utils.d.ts +77 -0
- package/build/src/utils/request.utils.js +175 -0
- package/build/src/utils/request.utils.js.map +1 -0
- package/build/src/utils/response.utils.d.ts +15 -1
- package/build/src/utils/response.utils.js +56 -4
- package/build/src/utils/response.utils.js.map +1 -1
- package/build/src/utils/string.utils.js +23 -0
- package/build/src/utils/string.utils.js.map +1 -1
- package/build/src/utils/url.utils.js +23 -0
- package/build/src/utils/url.utils.js.map +1 -1
- package/build/src/utils/validate.utils.d.ts +7 -0
- package/build/src/utils/validate.utils.js +36 -2
- package/build/src/utils/validate.utils.js.map +1 -1
- package/package.json +40 -9
|
@@ -1,5 +1,28 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies
|
|
5
|
+
*
|
|
6
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
* in the Software without restriction, including without limitation the rights
|
|
9
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
* furnished to do so, subject to the following conditions:
|
|
12
|
+
*
|
|
13
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
* copies or substantial portions of the Software.
|
|
15
|
+
*
|
|
16
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
* SOFTWARE.
|
|
23
|
+
*/
|
|
1
24
|
/* eslint-disable n/no-process-env */
|
|
2
|
-
import { existsSync } from 'fs';
|
|
25
|
+
import { existsSync, readFileSync } from 'fs';
|
|
3
26
|
import { isAbsolute, resolve } from 'path';
|
|
4
27
|
/**
|
|
5
28
|
* Enum representing valid application environments.
|
|
@@ -30,7 +53,7 @@ export class Env {
|
|
|
30
53
|
* @returns {boolean} `true` if NODE_ENV is 'production', else `false`.
|
|
31
54
|
*/
|
|
32
55
|
static isProd() {
|
|
33
|
-
return Env.get('NODE_ENV') === Environment.PRODUCTION;
|
|
56
|
+
return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.PRODUCTION;
|
|
34
57
|
}
|
|
35
58
|
/**
|
|
36
59
|
* Checks if the current NODE_ENV is 'testing'.
|
|
@@ -38,7 +61,7 @@ export class Env {
|
|
|
38
61
|
* @returns {boolean} `true` if NODE_ENV is 'testing', else `false`.
|
|
39
62
|
*/
|
|
40
63
|
static isTest() {
|
|
41
|
-
return Env.get('NODE_ENV') === Environment.TESTING;
|
|
64
|
+
return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.TESTING;
|
|
42
65
|
}
|
|
43
66
|
/**
|
|
44
67
|
* Checks if the current NODE_ENV is 'staging'.
|
|
@@ -46,7 +69,7 @@ export class Env {
|
|
|
46
69
|
* @returns {boolean} `true` if NODE_ENV is 'staging', else `false`.
|
|
47
70
|
*/
|
|
48
71
|
static isStaging() {
|
|
49
|
-
return Env.get('NODE_ENV') === Environment.STAGING;
|
|
72
|
+
return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.STAGING;
|
|
50
73
|
}
|
|
51
74
|
/**
|
|
52
75
|
* Sets an environment variable (only affects runtime memory).
|
|
@@ -56,6 +79,13 @@ export class Env {
|
|
|
56
79
|
*/
|
|
57
80
|
static set(key, value) {
|
|
58
81
|
process.env[key] = value;
|
|
82
|
+
// Clear all cached values for this key with any prefix
|
|
83
|
+
this.cache.delete(key);
|
|
84
|
+
for (const cacheKey of [...this.cache.keys()]) {
|
|
85
|
+
if (cacheKey.includes(`:${key}`)) {
|
|
86
|
+
this.cache.delete(cacheKey);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
59
89
|
}
|
|
60
90
|
/**
|
|
61
91
|
* Returns all environment variables as an object.
|
|
@@ -67,14 +97,28 @@ export class Env {
|
|
|
67
97
|
}
|
|
68
98
|
/**
|
|
69
99
|
* Retrieves a string environment variable with a fallback default.
|
|
100
|
+
* Supports variable expansion with ${VAR_NAME} syntax.
|
|
70
101
|
*
|
|
71
102
|
* @param {string} key - The environment variable key.
|
|
72
103
|
* @param {string} [defaultValue] - Value to return if the key is missing.
|
|
73
|
-
* @returns {string
|
|
104
|
+
* @returns {string} The env value or the fallback.
|
|
105
|
+
*
|
|
106
|
+
* @example
|
|
107
|
+
* // If DATABASE_URL is "postgres://localhost:5432/${DB_NAME}"
|
|
108
|
+
* // and DB_NAME is "myapp"
|
|
109
|
+
* const url = Env.get('DATABASE_URL', ''); // "postgres://localhost:5432/myapp"
|
|
74
110
|
*/
|
|
75
111
|
static get(key, defaultValue) {
|
|
76
112
|
var _a;
|
|
77
|
-
|
|
113
|
+
let value = (_a = process.env[key]) !== null && _a !== void 0 ? _a : defaultValue;
|
|
114
|
+
// Expand ${VAR} references
|
|
115
|
+
if (value && value.includes('${')) {
|
|
116
|
+
value = value.replace(/\${([A-Za-z0-9_]+)}/g, (_, varName) => {
|
|
117
|
+
var _a;
|
|
118
|
+
return (_a = process.env[varName]) !== null && _a !== void 0 ? _a : '';
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
return value;
|
|
78
122
|
}
|
|
79
123
|
/**
|
|
80
124
|
* Retrieves a string environment variable and throws if it's missing.
|
|
@@ -86,9 +130,29 @@ export class Env {
|
|
|
86
130
|
static getRequired(key) {
|
|
87
131
|
const value = process.env[key];
|
|
88
132
|
if (value === undefined) {
|
|
89
|
-
throw new Error(`Required
|
|
133
|
+
throw new Error(`Required environment variable '${key}' is missing`);
|
|
90
134
|
}
|
|
91
|
-
return
|
|
135
|
+
return Env.get(key, ''); // Use get to handle variable expansion
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Retrieves a value using a default generating function if the key doesn't exist.
|
|
139
|
+
* Useful for expensive default calculations.
|
|
140
|
+
*
|
|
141
|
+
* @param {string} key - The environment variable key.
|
|
142
|
+
* @param {() => string} defaultFn - Function that generates default value.
|
|
143
|
+
* @returns {string} The environment value or generated default.
|
|
144
|
+
*
|
|
145
|
+
* @example
|
|
146
|
+
* const hostname = Env.getWithDefault('HOSTNAME', () => {
|
|
147
|
+
* // Only called if HOSTNAME is not set
|
|
148
|
+
* return require('os').hostname();
|
|
149
|
+
* });
|
|
150
|
+
*/
|
|
151
|
+
static getWithDefault(key, defaultFn) {
|
|
152
|
+
if (Env.has(key)) {
|
|
153
|
+
return Env.get(key, '');
|
|
154
|
+
}
|
|
155
|
+
return defaultFn();
|
|
92
156
|
}
|
|
93
157
|
/**
|
|
94
158
|
* Retrieves an environment variable as a number, or returns a default.
|
|
@@ -99,12 +163,18 @@ export class Env {
|
|
|
99
163
|
* @throws {Error} If the value is not a valid number.
|
|
100
164
|
*/
|
|
101
165
|
static getNumber(key, defaultValue) {
|
|
102
|
-
|
|
103
|
-
|
|
166
|
+
if (this.cache.has(`number:${key}`)) {
|
|
167
|
+
return this.cache.get(`number:${key}`);
|
|
168
|
+
}
|
|
169
|
+
const value = process.env[key];
|
|
170
|
+
if (value === undefined) {
|
|
171
|
+
return defaultValue;
|
|
172
|
+
}
|
|
104
173
|
const numberValue = Number(value);
|
|
105
174
|
if (isNaN(numberValue)) {
|
|
106
|
-
throw new Error(`
|
|
175
|
+
throw new Error(`Environment variable '${key}' is not a valid number, got: "${value}"`);
|
|
107
176
|
}
|
|
177
|
+
this.cache.set(`number:${key}`, numberValue);
|
|
108
178
|
return numberValue;
|
|
109
179
|
}
|
|
110
180
|
/**
|
|
@@ -117,13 +187,37 @@ export class Env {
|
|
|
117
187
|
static getNumberRequired(key) {
|
|
118
188
|
const value = process.env[key];
|
|
119
189
|
if (value === undefined) {
|
|
120
|
-
throw new Error(`Required
|
|
190
|
+
throw new Error(`Required environment variable '${key}' is missing`);
|
|
121
191
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
192
|
+
return Env.getNumber(key, 0); // The default is ignored since we know the key exists
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Retrieves an integer environment variable and validates it.
|
|
196
|
+
*
|
|
197
|
+
* @param {string} key - The environment variable key.
|
|
198
|
+
* @param {number} defaultValue - Fallback number if key is not present.
|
|
199
|
+
* @param {object} [options] - Validation options.
|
|
200
|
+
* @param {number} [options.min] - Minimum allowed value.
|
|
201
|
+
* @param {number} [options.max] - Maximum allowed value.
|
|
202
|
+
* @returns {number} The parsed integer.
|
|
203
|
+
*
|
|
204
|
+
* @example
|
|
205
|
+
* // Require PORT to be between 1000 and 9999
|
|
206
|
+
* const port = Env.getInteger('PORT', 3000, { min: 1000, max: 9999 });
|
|
207
|
+
*/
|
|
208
|
+
static getInteger(key, defaultValue, options = {}) {
|
|
209
|
+
const num = Env.getNumber(key, defaultValue);
|
|
210
|
+
const intValue = Math.floor(num);
|
|
211
|
+
if (intValue !== num) {
|
|
212
|
+
throw new Error(`Environment variable '${key}' must be an integer, got: ${num}`);
|
|
125
213
|
}
|
|
126
|
-
|
|
214
|
+
if (options.min !== undefined && intValue < options.min) {
|
|
215
|
+
throw new Error(`Environment variable '${key}' must be at least ${options.min}, got: ${intValue}`);
|
|
216
|
+
}
|
|
217
|
+
if (options.max !== undefined && intValue > options.max) {
|
|
218
|
+
throw new Error(`Environment variable '${key}' must be at most ${options.max}, got: ${intValue}`);
|
|
219
|
+
}
|
|
220
|
+
return intValue;
|
|
127
221
|
}
|
|
128
222
|
/**
|
|
129
223
|
* Retrieves an environment variable as a boolean.
|
|
@@ -133,15 +227,29 @@ export class Env {
|
|
|
133
227
|
* @param {boolean} [defaultValue=false] - Optional fallback value if key is missing.
|
|
134
228
|
* @returns {boolean} Parsed boolean.
|
|
135
229
|
* @throws {Error} If the value is not a recognized boolean string.
|
|
230
|
+
*
|
|
231
|
+
* @example
|
|
232
|
+
* // If DEBUG=yes
|
|
233
|
+
* const isDebug = Env.getBoolean('DEBUG', false); // true
|
|
136
234
|
*/
|
|
137
235
|
static getBoolean(key, defaultValue = false) {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
236
|
+
if (this.cache.has(`bool:${key}`)) {
|
|
237
|
+
return this.cache.get(`bool:${key}`);
|
|
238
|
+
}
|
|
239
|
+
const value = process.env[key];
|
|
240
|
+
if (value === undefined) {
|
|
241
|
+
return defaultValue;
|
|
242
|
+
}
|
|
243
|
+
const lowerValue = value.toLowerCase();
|
|
244
|
+
if (['true', '1', 'yes', 'on'].includes(lowerValue)) {
|
|
245
|
+
this.cache.set(`bool:${key}`, true);
|
|
141
246
|
return true;
|
|
142
|
-
|
|
247
|
+
}
|
|
248
|
+
if (['false', '0', 'no', 'off'].includes(lowerValue)) {
|
|
249
|
+
this.cache.set(`bool:${key}`, false);
|
|
143
250
|
return false;
|
|
144
|
-
|
|
251
|
+
}
|
|
252
|
+
throw new Error(`Environment variable '${key}' is not a valid boolean, got: "${value}". Use true/false, yes/no, 1/0, or on/off.`);
|
|
145
253
|
}
|
|
146
254
|
/**
|
|
147
255
|
* Retrieves a required environment variable as a boolean.
|
|
@@ -153,9 +261,9 @@ export class Env {
|
|
|
153
261
|
static getBooleanRequired(key) {
|
|
154
262
|
const value = process.env[key];
|
|
155
263
|
if (value === undefined) {
|
|
156
|
-
throw new Error(`Required
|
|
264
|
+
throw new Error(`Required environment variable '${key}' is missing`);
|
|
157
265
|
}
|
|
158
|
-
return
|
|
266
|
+
return Env.getBoolean(key);
|
|
159
267
|
}
|
|
160
268
|
/**
|
|
161
269
|
* Parses a stringified JSON object from an environment variable.
|
|
@@ -165,18 +273,28 @@ export class Env {
|
|
|
165
273
|
* @param {T} defaultValue - Value to return if key is missing.
|
|
166
274
|
* @returns {T} Parsed object or default.
|
|
167
275
|
* @throws {Error} If the value is not valid JSON.
|
|
276
|
+
*
|
|
277
|
+
* @example
|
|
278
|
+
* // If CONFIG='{"debug":true,"api":{"url":"https://api.example.com"}}'
|
|
279
|
+
* const config = Env.getJSON('CONFIG', { debug: false });
|
|
280
|
+
* // { debug: true, api: { url: "https://api.example.com" }}
|
|
168
281
|
*/
|
|
169
282
|
static getJSON(key, defaultValue) {
|
|
283
|
+
if (this.cache.has(`json:${key}`)) {
|
|
284
|
+
return this.cache.get(`json:${key}`);
|
|
285
|
+
}
|
|
170
286
|
const v = process.env[key];
|
|
171
|
-
if (v
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
287
|
+
if (v === undefined) {
|
|
288
|
+
return defaultValue;
|
|
289
|
+
}
|
|
290
|
+
try {
|
|
291
|
+
const parsed = JSON.parse(v);
|
|
292
|
+
this.cache.set(`json:${key}`, parsed);
|
|
293
|
+
return parsed;
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
throw new Error(`Environment variable '${key}' is not valid JSON: ${error.message}`);
|
|
178
297
|
}
|
|
179
|
-
return defaultValue;
|
|
180
298
|
}
|
|
181
299
|
/**
|
|
182
300
|
* Parses a comma-separated string as an array.
|
|
@@ -185,17 +303,65 @@ export class Env {
|
|
|
185
303
|
* @param {string} key - The environment variable key.
|
|
186
304
|
* @param {T[]} [defaultValue=[]] - Array to return if value is empty or missing.
|
|
187
305
|
* @param {string} [splitter=','] - Delimiter to split on.
|
|
188
|
-
* @
|
|
306
|
+
* @param {(item: string) => T} [transform] - Optional function to transform each item.
|
|
307
|
+
* @returns {T[]} An array of items.
|
|
308
|
+
*
|
|
309
|
+
* @example
|
|
310
|
+
* // If ALLOWED_IPS=127.0.0.1,192.168.1.1,10.0.0.1
|
|
311
|
+
* const ips = Env.getArray('ALLOWED_IPS');
|
|
312
|
+
* // ["127.0.0.1", "192.168.1.1", "10.0.0.1"]
|
|
313
|
+
*
|
|
314
|
+
* // With transformation function
|
|
315
|
+
* const ports = Env.getArray('PORTS', [], ',', (p) => parseInt(p, 10));
|
|
189
316
|
*/
|
|
190
|
-
static getArray(key, defaultValue = [], splitter = ',') {
|
|
317
|
+
static getArray(key, defaultValue = [], splitter = ',', transform) {
|
|
318
|
+
const cacheKey = `array:${key}:${splitter}:${transform ? 'transformed' : 'raw'}`;
|
|
319
|
+
if (this.cache.has(cacheKey)) {
|
|
320
|
+
return this.cache.get(cacheKey);
|
|
321
|
+
}
|
|
191
322
|
const value = process.env[key];
|
|
192
323
|
if (!value || value.trim() === '') {
|
|
193
324
|
return defaultValue;
|
|
194
325
|
}
|
|
195
|
-
|
|
326
|
+
const items = value
|
|
196
327
|
.split(splitter)
|
|
197
328
|
.map(item => item.trim())
|
|
198
329
|
.filter(item => item.length > 0);
|
|
330
|
+
if (transform) {
|
|
331
|
+
try {
|
|
332
|
+
const result = items.map(transform);
|
|
333
|
+
this.cache.set(cacheKey, result);
|
|
334
|
+
return result;
|
|
335
|
+
}
|
|
336
|
+
catch (error) {
|
|
337
|
+
throw new Error(`Failed to transform items in '${key}': ${error.message}`);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
const result = items;
|
|
341
|
+
this.cache.set(cacheKey, result);
|
|
342
|
+
return result;
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Parses a comma-separated list of numbers.
|
|
346
|
+
*
|
|
347
|
+
* @param {string} key - The environment variable key.
|
|
348
|
+
* @param {number[]} [defaultValue=[]] - Default value if not present.
|
|
349
|
+
* @param {string} [splitter=','] - Delimiter to split on.
|
|
350
|
+
* @returns {number[]} Array of parsed numbers.
|
|
351
|
+
*
|
|
352
|
+
* @example
|
|
353
|
+
* // If ALLOWED_PORTS=80,443,3000,8080
|
|
354
|
+
* const ports = Env.getNumberArray('ALLOWED_PORTS');
|
|
355
|
+
* // [80, 443, 3000, 8080]
|
|
356
|
+
*/
|
|
357
|
+
static getNumberArray(key, defaultValue = [], splitter = ',') {
|
|
358
|
+
return Env.getArray(key, defaultValue, splitter, item => {
|
|
359
|
+
const num = Number(item);
|
|
360
|
+
if (isNaN(num)) {
|
|
361
|
+
throw new Error(`Value "${item}" in array '${key}' is not a valid number`);
|
|
362
|
+
}
|
|
363
|
+
return num;
|
|
364
|
+
});
|
|
199
365
|
}
|
|
200
366
|
/**
|
|
201
367
|
* Retrieves an enum-like environment variable value, validating against allowed values.
|
|
@@ -206,12 +372,38 @@ export class Env {
|
|
|
206
372
|
* @param {T} [defaultValue] - Optional fallback value.
|
|
207
373
|
* @returns {T} The validated environment value.
|
|
208
374
|
* @throws {Error} If missing or invalid.
|
|
375
|
+
*
|
|
376
|
+
* @example
|
|
377
|
+
* // If LOG_LEVEL=debug
|
|
378
|
+
* const level = Env.getEnum('LOG_LEVEL', ['debug', 'info', 'warn', 'error'] as const, 'info');
|
|
379
|
+
* // 'debug' (typed as 'debug' | 'info' | 'warn' | 'error')
|
|
209
380
|
*/
|
|
210
381
|
static getEnum(key, allowedValues, defaultValue) {
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
382
|
+
const value = process.env[key];
|
|
383
|
+
if (!value) {
|
|
384
|
+
return defaultValue;
|
|
385
|
+
}
|
|
386
|
+
if (!allowedValues.includes(value)) {
|
|
387
|
+
throw new Error(`Environment variable '${key}' must be one of: ${allowedValues.join(', ')}. Received: "${value}"`);
|
|
388
|
+
}
|
|
389
|
+
return value;
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Retrieves an enum-like numeric environment variable.
|
|
393
|
+
*
|
|
394
|
+
* @param {string} key - The environment variable key.
|
|
395
|
+
* @param {number[]} allowedValues - Array of accepted values.
|
|
396
|
+
* @param {number} defaultValue - Default value if not present.
|
|
397
|
+
* @returns {number} The validated value.
|
|
398
|
+
*
|
|
399
|
+
* @example
|
|
400
|
+
* // If NODE_VERSION=16
|
|
401
|
+
* const version = Env.getNumberEnum('NODE_VERSION', [14, 16, 18], 16);
|
|
402
|
+
*/
|
|
403
|
+
static getNumberEnum(key, allowedValues, defaultValue) {
|
|
404
|
+
const value = Env.getNumber(key, defaultValue);
|
|
405
|
+
if (!allowedValues.includes(value)) {
|
|
406
|
+
throw new Error(`Environment variable '${key}' must be one of: ${allowedValues.join(', ')}. Received: ${value}`);
|
|
215
407
|
}
|
|
216
408
|
return value;
|
|
217
409
|
}
|
|
@@ -220,41 +412,66 @@ export class Env {
|
|
|
220
412
|
*
|
|
221
413
|
* @param {string} key - The environment variable key.
|
|
222
414
|
* @param {string} [defaultValue] - Optional fallback value.
|
|
223
|
-
* @param {
|
|
224
|
-
* @param {string[]} [options.protocols] - Allowed protocols.
|
|
225
|
-
* @param {boolean} [options.requireTld=true] - Whether TLD is required.
|
|
415
|
+
* @param {UrlOptions} [options] - Validation options.
|
|
226
416
|
* @returns {string} The validated URL.
|
|
227
417
|
* @throws {Error} If URL is invalid.
|
|
418
|
+
*
|
|
419
|
+
* @example
|
|
420
|
+
* // Validate API URL requires HTTPS
|
|
421
|
+
* const apiUrl = Env.getUrl('API_URL', 'https://api.example.com', {
|
|
422
|
+
* protocols: ['https'],
|
|
423
|
+
* requireTld: true,
|
|
424
|
+
* allowIp: false
|
|
425
|
+
* });
|
|
228
426
|
*/
|
|
229
427
|
static getUrl(key, defaultValue, options = {}) {
|
|
428
|
+
const cacheKey = `url:${key}:${JSON.stringify(options)}`;
|
|
429
|
+
if (this.cache.has(cacheKey)) {
|
|
430
|
+
return this.cache.get(cacheKey);
|
|
431
|
+
}
|
|
230
432
|
const value = Env.get(key, defaultValue);
|
|
231
433
|
if (!value) {
|
|
232
|
-
throw new Error(`
|
|
434
|
+
throw new Error(`URL environment variable '${key}' is missing or empty`);
|
|
233
435
|
}
|
|
234
436
|
let url;
|
|
235
437
|
try {
|
|
236
438
|
url = new URL(value);
|
|
237
439
|
}
|
|
238
440
|
catch (_a) {
|
|
239
|
-
throw new Error(`
|
|
441
|
+
throw new Error(`Environment variable '${key}' is not a valid URL: "${value}"`);
|
|
240
442
|
}
|
|
443
|
+
// Validate protocol
|
|
241
444
|
if (options.protocols && options.protocols.length > 0) {
|
|
242
445
|
const protocol = url.protocol.replace(':', '');
|
|
243
446
|
if (!options.protocols.includes(protocol)) {
|
|
244
|
-
throw new Error(`
|
|
447
|
+
throw new Error(`Environment variable '${key}' must use one of the protocols: ${options.protocols.join(', ')}. Got: ${protocol}`);
|
|
245
448
|
}
|
|
246
449
|
}
|
|
450
|
+
// Validate hostname
|
|
451
|
+
const { hostname } = url;
|
|
452
|
+
const isIp = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/.test(hostname);
|
|
453
|
+
const isLocalhost = hostname === 'localhost';
|
|
454
|
+
// Check if hostname is an IP address when not allowed
|
|
455
|
+
if (isIp && options.allowIp === false) {
|
|
456
|
+
throw new Error(`Environment variable '${key}' cannot be an IP address: "${hostname}"`);
|
|
457
|
+
}
|
|
458
|
+
// Check if hostname is localhost when not allowed
|
|
459
|
+
if (isLocalhost && options.allowLocalhost === false) {
|
|
460
|
+
throw new Error(`Environment variable '${key}' cannot be localhost`);
|
|
461
|
+
}
|
|
462
|
+
// Check for TLD requirement - include localhost in check if requireTld is true and allowLocalhost is false
|
|
247
463
|
if (options.requireTld === true) {
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
if (
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
throw new Error(`
|
|
464
|
+
if (isLocalhost && options.allowLocalhost !== false) {
|
|
465
|
+
// Localhost is allowed, so no TLD check needed for it
|
|
466
|
+
}
|
|
467
|
+
else if (isIp && options.allowIp !== false) {
|
|
468
|
+
// IP is allowed, so no TLD check needed for it
|
|
469
|
+
}
|
|
470
|
+
else if (!hostname.includes('.') || hostname.endsWith('.')) {
|
|
471
|
+
throw new Error(`Environment variable '${key}' must have a valid host with TLD: "${hostname}"`);
|
|
256
472
|
}
|
|
257
473
|
}
|
|
474
|
+
this.cache.set(cacheKey, value);
|
|
258
475
|
return value;
|
|
259
476
|
}
|
|
260
477
|
/**
|
|
@@ -264,20 +481,27 @@ export class Env {
|
|
|
264
481
|
* @param {string} [defaultValue] - Optional fallback value.
|
|
265
482
|
* @returns {string} The validated email address.
|
|
266
483
|
* @throws {Error} If email is invalid.
|
|
484
|
+
*
|
|
485
|
+
* @example
|
|
486
|
+
* const supportEmail = Env.getEmail('SUPPORT_EMAIL', 'support@example.com');
|
|
267
487
|
*/
|
|
268
488
|
static getEmail(key, defaultValue) {
|
|
489
|
+
if (this.cache.has(`email:${key}`)) {
|
|
490
|
+
return this.cache.get(`email:${key}`);
|
|
491
|
+
}
|
|
269
492
|
const value = Env.get(key, defaultValue);
|
|
270
493
|
if (!value) {
|
|
271
494
|
if (defaultValue === undefined) {
|
|
272
|
-
throw new Error(`Email
|
|
495
|
+
throw new Error(`Email environment variable '${key}' is missing`);
|
|
273
496
|
}
|
|
274
497
|
return defaultValue;
|
|
275
498
|
}
|
|
276
|
-
//
|
|
277
|
-
const emailRegex = /^[a-zA-Z0-9
|
|
499
|
+
// More comprehensive email validation regex
|
|
500
|
+
const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
|
|
278
501
|
if (!emailRegex.test(value)) {
|
|
279
|
-
throw new Error(`
|
|
502
|
+
throw new Error(`Environment variable '${key}' is not a valid email address: "${value}"`);
|
|
280
503
|
}
|
|
504
|
+
this.cache.set(`email:${key}`, value);
|
|
281
505
|
return value;
|
|
282
506
|
}
|
|
283
507
|
/**
|
|
@@ -285,75 +509,140 @@ export class Env {
|
|
|
285
509
|
*
|
|
286
510
|
* @param {string} key - The environment variable key.
|
|
287
511
|
* @param {string} [defaultValue] - Optional fallback value.
|
|
288
|
-
* @param {
|
|
289
|
-
* @param {boolean} [options.mustExist=false] - Whether path must exist.
|
|
290
|
-
* @param {boolean} [options.makeAbsolute=true] - Convert relative paths to absolute.
|
|
512
|
+
* @param {PathOptions} [options] - Validation options.
|
|
291
513
|
* @returns {string} The validated path.
|
|
292
514
|
* @throws {Error} If path is invalid.
|
|
515
|
+
*
|
|
516
|
+
* @example
|
|
517
|
+
* // Require that the path exists and is a .json file
|
|
518
|
+
* const configPath = Env.getPath('CONFIG_PATH', './config.json', {
|
|
519
|
+
* mustExist: true,
|
|
520
|
+
* allowedExtensions: ['.json', '.yaml']
|
|
521
|
+
* });
|
|
293
522
|
*/
|
|
294
523
|
static getPath(key, defaultValue, options = {}) {
|
|
524
|
+
const cacheKey = `path:${key}:${JSON.stringify(options)}`;
|
|
525
|
+
if (this.cache.has(cacheKey)) {
|
|
526
|
+
return this.cache.get(cacheKey);
|
|
527
|
+
}
|
|
295
528
|
const value = Env.get(key, defaultValue);
|
|
296
529
|
if (!value) {
|
|
297
530
|
if (defaultValue === undefined) {
|
|
298
|
-
throw new Error(`Path
|
|
531
|
+
throw new Error(`Path environment variable '${key}' is missing`);
|
|
299
532
|
}
|
|
300
533
|
return defaultValue;
|
|
301
534
|
}
|
|
302
535
|
const path = options.makeAbsolute !== false && !isAbsolute(value) ? resolve(process.cwd(), value) : value;
|
|
536
|
+
// Validate path exists if required
|
|
303
537
|
if (options.mustExist && !existsSync(path)) {
|
|
304
|
-
throw new Error(`Path in
|
|
538
|
+
throw new Error(`Path in environment variable '${key}' does not exist: "${path}"`);
|
|
539
|
+
}
|
|
540
|
+
// Validate file extension if specified
|
|
541
|
+
if (options.allowedExtensions && options.allowedExtensions.length > 0) {
|
|
542
|
+
const hasValidExtension = options.allowedExtensions.some(ext => path.toLowerCase().endsWith(ext.toLowerCase()));
|
|
543
|
+
if (!hasValidExtension) {
|
|
544
|
+
throw new Error(`Path in environment variable '${key}' must have one of these extensions: ${options.allowedExtensions.join(', ')}. Got: "${path}"`);
|
|
545
|
+
}
|
|
305
546
|
}
|
|
547
|
+
this.cache.set(cacheKey, path);
|
|
306
548
|
return path;
|
|
307
549
|
}
|
|
308
550
|
/**
|
|
309
551
|
* Retrieves a port environment variable and validates it.
|
|
310
552
|
*
|
|
311
553
|
* @param {string} key - The environment variable key.
|
|
312
|
-
* @param {number} [defaultValue
|
|
554
|
+
* @param {number} [defaultValue] - Optional fallback value.
|
|
313
555
|
* @returns {number} The validated port number.
|
|
314
556
|
* @throws {Error} If port is invalid.
|
|
557
|
+
*
|
|
558
|
+
* @example
|
|
559
|
+
* const serverPort = Env.getPort('PORT', 3000);
|
|
315
560
|
*/
|
|
316
|
-
static getPort(key, defaultValue
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
561
|
+
static getPort(key, defaultValue) {
|
|
562
|
+
try {
|
|
563
|
+
return Env.getInteger(key, defaultValue, { min: 0, max: 65535 });
|
|
564
|
+
}
|
|
565
|
+
catch (error) {
|
|
566
|
+
// Rewrite the error message to match the expected pattern
|
|
567
|
+
if (error.message.includes('must be at most 65535')) {
|
|
568
|
+
throw new Error(`Environment variable '${key}' must be a valid port number (0-65535)`);
|
|
569
|
+
}
|
|
570
|
+
throw error;
|
|
320
571
|
}
|
|
321
|
-
return port;
|
|
322
572
|
}
|
|
323
573
|
/**
|
|
324
|
-
* Retrieves
|
|
574
|
+
* Retrieves an ISO date string and converts it to a Date object.
|
|
575
|
+
*
|
|
576
|
+
* @param {string} key - The environment variable key.
|
|
577
|
+
* @param {string|Date} [defaultValue] - Optional fallback value.
|
|
578
|
+
* @returns {Date} The parsed Date object.
|
|
579
|
+
*
|
|
580
|
+
* @example
|
|
581
|
+
* // If EXPIRY_DATE=2023-12-31T23:59:59Z
|
|
582
|
+
* const expiryDate = Env.getDate('EXPIRY_DATE', new Date());
|
|
583
|
+
*/
|
|
584
|
+
static getDate(key, defaultValue = new Date()) {
|
|
585
|
+
const value = Env.get(key, defaultValue instanceof Date ? defaultValue.toISOString() : defaultValue);
|
|
586
|
+
if (!value) {
|
|
587
|
+
return defaultValue instanceof Date ? defaultValue : new Date();
|
|
588
|
+
}
|
|
589
|
+
const date = new Date(value);
|
|
590
|
+
if (isNaN(date.getTime())) {
|
|
591
|
+
throw new Error(`Environment variable '${key}' is not a valid date: "${value}"`);
|
|
592
|
+
}
|
|
593
|
+
return date;
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Retrieves a duration string and converts it to milliseconds.
|
|
325
597
|
* Supports formats like "1d", "2h", "30m", "45s", "100ms" or combinations like "1h30m".
|
|
326
598
|
*
|
|
327
599
|
* @param {string} key - The environment variable key.
|
|
328
600
|
* @param {string|number} [defaultValue='0'] - Optional fallback value.
|
|
329
601
|
* @returns {number} The duration in milliseconds.
|
|
330
602
|
* @throws {Error} If duration format is invalid.
|
|
603
|
+
*
|
|
604
|
+
* @example
|
|
605
|
+
* // If CACHE_TTL=2h30m
|
|
606
|
+
* const cacheTtlMs = Env.getDuration('CACHE_TTL', '1h');
|
|
607
|
+
* // 9000000 (2.5 hours in milliseconds)
|
|
331
608
|
*/
|
|
332
609
|
static getDuration(key, defaultValue = '0') {
|
|
610
|
+
const cacheKey = `duration:${key}`;
|
|
611
|
+
if (this.cache.has(cacheKey)) {
|
|
612
|
+
return this.cache.get(cacheKey);
|
|
613
|
+
}
|
|
333
614
|
const value = Env.get(key, String(defaultValue));
|
|
334
615
|
if (!value)
|
|
335
616
|
return 0;
|
|
336
617
|
// Handle plain number input (assume milliseconds)
|
|
337
618
|
if (/^\d+$/.test(value)) {
|
|
338
|
-
|
|
619
|
+
const ms = parseInt(value, 10);
|
|
620
|
+
this.cache.set(cacheKey, ms);
|
|
621
|
+
return ms;
|
|
339
622
|
}
|
|
340
|
-
//
|
|
341
|
-
const durationRegex =
|
|
623
|
+
// Enhanced duration parsing with more precise regex
|
|
624
|
+
const durationRegex = /^(?:(\d+)y)?(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?(?:(\d+)ms)?$/;
|
|
342
625
|
const matches = value.match(durationRegex);
|
|
343
626
|
if (!matches || matches[0] === '') {
|
|
344
|
-
throw new Error(`
|
|
627
|
+
throw new Error(`Environment variable '${key}' has invalid duration format: "${value}". ` +
|
|
628
|
+
`Use formats like 1y, 2w, 3d, 4h, 5m, 6s, or 7ms.`);
|
|
345
629
|
}
|
|
346
630
|
let ms = 0;
|
|
347
631
|
if (matches[1])
|
|
348
|
-
ms += parseInt(matches[1], 10) *
|
|
632
|
+
ms += parseInt(matches[1], 10) * 31536000000; // years (approximate)
|
|
349
633
|
if (matches[2])
|
|
350
|
-
ms += parseInt(matches[2], 10) *
|
|
634
|
+
ms += parseInt(matches[2], 10) * 604800000; // weeks
|
|
351
635
|
if (matches[3])
|
|
352
|
-
ms += parseInt(matches[3], 10) *
|
|
636
|
+
ms += parseInt(matches[3], 10) * 86400000; // days
|
|
353
637
|
if (matches[4])
|
|
354
|
-
ms += parseInt(matches[4], 10) *
|
|
638
|
+
ms += parseInt(matches[4], 10) * 3600000; // hours
|
|
355
639
|
if (matches[5])
|
|
356
|
-
ms += parseInt(matches[5], 10); //
|
|
640
|
+
ms += parseInt(matches[5], 10) * 60000; // minutes
|
|
641
|
+
if (matches[6])
|
|
642
|
+
ms += parseInt(matches[6], 10) * 1000; // seconds
|
|
643
|
+
if (matches[7])
|
|
644
|
+
ms += parseInt(matches[7], 10); // milliseconds
|
|
645
|
+
this.cache.set(cacheKey, ms);
|
|
357
646
|
return ms;
|
|
358
647
|
}
|
|
359
648
|
/**
|
|
@@ -361,6 +650,10 @@ export class Env {
|
|
|
361
650
|
*
|
|
362
651
|
* @param {string[]} [sensitiveKeys=['password', 'secret', 'key', 'token', 'auth']] - Keys to mask.
|
|
363
652
|
* @returns {Record<string, string>} Environment variables with sensitive values masked.
|
|
653
|
+
*
|
|
654
|
+
* @example
|
|
655
|
+
* console.log(Env.getSafeEnv(['password', 'secret', 'key']));
|
|
656
|
+
* // { DATABASE_URL: "postgres://...", API_KEY: "******", ... }
|
|
364
657
|
*/
|
|
365
658
|
static getSafeEnv(sensitiveKeys = ['password', 'secret', 'key', 'token', 'auth']) {
|
|
366
659
|
const safeEnv = {};
|
|
@@ -372,6 +665,88 @@ export class Env {
|
|
|
372
665
|
}
|
|
373
666
|
return safeEnv;
|
|
374
667
|
}
|
|
668
|
+
/**
|
|
669
|
+
* Loads environment variables from a .env file.
|
|
670
|
+
* Does not override existing variables.
|
|
671
|
+
*
|
|
672
|
+
* @param {string} [path='.env'] - Path to the .env file.
|
|
673
|
+
* @returns {Record<string, string>} Loaded environment variables.
|
|
674
|
+
*
|
|
675
|
+
* @example
|
|
676
|
+
* // Load variables from .env.development
|
|
677
|
+
* Env.loadFromFile('.env.development');
|
|
678
|
+
*/
|
|
679
|
+
static loadFromFile(path = '.env') {
|
|
680
|
+
if (!existsSync(path)) {
|
|
681
|
+
throw new Error(`Environment file not found: "${path}"`);
|
|
682
|
+
}
|
|
683
|
+
const content = readFileSync(path, 'utf8');
|
|
684
|
+
const variables = {};
|
|
685
|
+
const lines = content.split(/\r?\n/);
|
|
686
|
+
let i = 0;
|
|
687
|
+
while (i < lines.length) {
|
|
688
|
+
let line = lines[i].trim();
|
|
689
|
+
// Skip empty lines or comment-only lines
|
|
690
|
+
if (!line || line.startsWith('#')) {
|
|
691
|
+
i++;
|
|
692
|
+
continue;
|
|
693
|
+
}
|
|
694
|
+
const match = line.match(/^([^=]+)=(.*)$/);
|
|
695
|
+
if (!match) {
|
|
696
|
+
i++;
|
|
697
|
+
continue;
|
|
698
|
+
}
|
|
699
|
+
const key = match[1].trim();
|
|
700
|
+
let value = match[2].trim();
|
|
701
|
+
// Remove inline comment for unquoted values
|
|
702
|
+
if (!/^['"]/.test(value)) {
|
|
703
|
+
const hashIndex = value.indexOf(' #');
|
|
704
|
+
if (hashIndex !== -1) {
|
|
705
|
+
value = value.slice(0, hashIndex).trim();
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
// Handle quoted values
|
|
709
|
+
if ((value.startsWith('"') || value.startsWith("'")) && value.length > 1) {
|
|
710
|
+
const quote = value[0];
|
|
711
|
+
if (!value.endsWith(quote) || value.length === 1) {
|
|
712
|
+
// multiline quoted
|
|
713
|
+
let multilineValue = value.slice(1);
|
|
714
|
+
i++;
|
|
715
|
+
while (i < lines.length) {
|
|
716
|
+
const nextLine = lines[i];
|
|
717
|
+
if (nextLine.endsWith(quote)) {
|
|
718
|
+
multilineValue += '\n' + nextLine.slice(0, -1);
|
|
719
|
+
break;
|
|
720
|
+
}
|
|
721
|
+
else {
|
|
722
|
+
multilineValue += '\n' + nextLine;
|
|
723
|
+
}
|
|
724
|
+
i++;
|
|
725
|
+
}
|
|
726
|
+
value = multilineValue;
|
|
727
|
+
}
|
|
728
|
+
else {
|
|
729
|
+
// single-line quoted
|
|
730
|
+
value = value.slice(1, -1);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
else {
|
|
734
|
+
// Handle unquoted multiline: continue collecting until next key=value or empty line
|
|
735
|
+
i++;
|
|
736
|
+
while (i < lines.length && !lines[i].includes('=') && lines[i].trim() !== '') {
|
|
737
|
+
value += '\n' + lines[i];
|
|
738
|
+
i++;
|
|
739
|
+
}
|
|
740
|
+
i--; // adjust for outer loop
|
|
741
|
+
}
|
|
742
|
+
if (!process.env[key]) {
|
|
743
|
+
process.env[key] = value;
|
|
744
|
+
variables[key] = value;
|
|
745
|
+
}
|
|
746
|
+
i++;
|
|
747
|
+
}
|
|
748
|
+
return variables;
|
|
749
|
+
}
|
|
375
750
|
/**
|
|
376
751
|
* Checks whether the specified environment variable exists.
|
|
377
752
|
*
|
|
@@ -389,6 +764,22 @@ export class Env {
|
|
|
389
764
|
*/
|
|
390
765
|
static delete(key) {
|
|
391
766
|
delete process.env[key];
|
|
767
|
+
this.cache.delete(key);
|
|
768
|
+
// Also clear all cached variations of this key
|
|
769
|
+
for (const cacheKey of this.cache.keys()) {
|
|
770
|
+
if (cacheKey.includes(`:${key}`)) {
|
|
771
|
+
this.cache.delete(cacheKey);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Clears the internal cache of parsed environment values.
|
|
777
|
+
* Useful for testing or when environment variables might change.
|
|
778
|
+
*/
|
|
779
|
+
static clearCache() {
|
|
780
|
+
this.cache.clear();
|
|
392
781
|
}
|
|
393
782
|
}
|
|
783
|
+
// Cache for parsed values to avoid repeated parsing of complex values
|
|
784
|
+
Env.cache = new Map();
|
|
394
785
|
//# sourceMappingURL=env.utils.js.map
|