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