@catbee/utils 0.0.3 → 0.0.5

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