@catbee/utils 1.1.0 → 2.0.0-next.1

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